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: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } Commit Message: sg_start_req(): make sure that there's not too many elements in iovec unfortunately, allowing an arbitrary 16bit value means a possibility of overflow in the calculation of total number of pages in bio_map_user_iov() - we rely on there being no more than PAGE_SIZE members of sum in the first loop there. If that sum wraps around, we end up allocating too small array of pointers to pages and it's easy to overflow it in the second loop. X-Coverup: TINC (and there's no lumber cartel either) Cc: [email protected] # way, way back Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: bool IsTabFrozen(content::WebContents* content) { const LifecycleUnitState state = static_cast<TabLifecycleUnitSource::TabLifecycleUnit*>( TabLifecycleUnitExternal::FromWebContents(content)) ->GetState(); return state == LifecycleUnitState::PENDING_FREEZE || state == LifecycleUnitState::FROZEN; } 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: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 TestRenderWidgetHostView::HasAcceleratedSurface( const gfx::Size& desired_size) { return false; } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; } Commit Message: A DWARF related section marked SHT_NOBITS (elf section type) is an error in the elf object. Now detected. dwarf_elf_access.c CWE ID: CWE-476 Target: 1 Example 2: Code: void ChromeContentBrowserClientExtensionsPart::OverrideWebkitPrefs( RenderViewHost* rvh, WebPreferences* web_prefs) { const ExtensionRegistry* registry = ExtensionRegistry::Get(rvh->GetProcess()->GetBrowserContext()); if (!registry) return; const GURL& site_url = rvh->GetSiteInstance()->GetSiteURL(); if (!site_url.SchemeIs(kExtensionScheme)) return; WebContents* web_contents = WebContents::FromRenderViewHost(rvh); ViewType view_type = GetViewType(web_contents); const Extension* extension = registry->enabled_extensions().GetByID(site_url.host()); extension_webkit_preferences::SetPreferences(extension, view_type, web_prefs); } Commit Message: [Extensions] Update navigations across hypothetical extension extents Update code to treat navigations across hypothetical extension extents (e.g. for nonexistent extensions) the same as we do for navigations crossing installed extension extents. Bug: 598265 Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b Reviewed-on: https://chromium-review.googlesource.com/617180 Commit-Queue: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#495779} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int dsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8) { const unsigned char *p, *pm; int pklen, pmlen; int ptype; void *pval; ASN1_STRING *pstr; X509_ALGOR *palg; ASN1_INTEGER *privkey = NULL; BN_CTX *ctx = NULL; STACK_OF(ASN1_TYPE) *ndsa = NULL; DSA *dsa = NULL; if (!PKCS8_pkey_get0(NULL, &p, &pklen, &palg, p8)) return 0; X509_ALGOR_get0(NULL, &ptype, &pval, palg); if (*p == (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) { ASN1_TYPE *t1, *t2; if (!(ndsa = d2i_ASN1_SEQUENCE_ANY(NULL, &p, pklen))) goto decerr; if (sk_ASN1_TYPE_num(ndsa) != 2) goto decerr; /*- * Handle Two broken types: * SEQUENCE {parameters, priv_key} * SEQUENCE {pub_key, priv_key} */ t1 = sk_ASN1_TYPE_value(ndsa, 0); t2 = sk_ASN1_TYPE_value(ndsa, 1); if (t1->type == V_ASN1_SEQUENCE) { p8->broken = PKCS8_EMBEDDED_PARAM; pval = t1->value.ptr; } else if (ptype == V_ASN1_SEQUENCE) p8->broken = PKCS8_NS_DB; else goto decerr; if (t2->type != V_ASN1_INTEGER) goto decerr; privkey = t2->value.integer; } else { const unsigned char *q = p; if (!(privkey = d2i_ASN1_INTEGER(NULL, &p, pklen))) goto decerr; if (privkey->type == V_ASN1_NEG_INTEGER) { p8->broken = PKCS8_NEG_PRIVKEY; ASN1_STRING_clear_free(privkey); if (!(privkey = d2i_ASN1_UINTEGER(NULL, &q, pklen))) goto decerr; } if (ptype != V_ASN1_SEQUENCE) goto decerr; } pstr = pval; pm = pstr->data; pmlen = pstr->length; if (!(dsa = d2i_DSAparams(NULL, &pm, pmlen))) goto decerr; /* We have parameters now set private key */ if (!(dsa->priv_key = ASN1_INTEGER_to_BN(privkey, NULL))) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } /* Calculate public key */ if (!(dsa->pub_key = BN_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!(ctx = BN_CTX_new())) { DSAerr(DSA_F_DSA_PRIV_DECODE, ERR_R_MALLOC_FAILURE); goto dsaerr; } if (!BN_mod_exp(dsa->pub_key, dsa->g, dsa->priv_key, dsa->p, ctx)) { DSAerr(DSA_F_DSA_PRIV_DECODE, DSA_R_BN_ERROR); goto dsaerr; } } Commit Message: CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int bochs_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVBochsState *s = bs->opaque; uint32_t i; struct bochs_header bochs; int ret; bs->read_only = 1; // no write support yet ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs)); if (ret < 0) { return ret; } if (strcmp(bochs.magic, HEADER_MAGIC) || strcmp(bochs.type, REDOLOG_TYPE) || strcmp(bochs.subtype, GROWING_TYPE) || ((le32_to_cpu(bochs.version) != HEADER_VERSION) && (le32_to_cpu(bochs.version) != HEADER_V1))) { error_setg(errp, "Image not in Bochs format"); return -EINVAL; } if (le32_to_cpu(bochs.version) == HEADER_V1) { bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512; } else { bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512; } s->catalog_size = le32_to_cpu(bochs.catalog); s->catalog_bitmap = g_malloc(s->catalog_size * 4); ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap, s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4); s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512; s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512; s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; fail: s->extent_size = le32_to_cpu(bochs.extent); qemu_co_mutex_init(&s->lock); return 0; extent_index = offset / s->extent_size; extent_offset = (offset % s->extent_size) / 512; if (s->catalog_bitmap[extent_index] == 0xffffffff) { return -1; /* not allocated */ } bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] * (s->extent_blocks + s->bitmap_blocks)); /* read in bitmap for current extent */ if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8), &bitmap_entry, 1) != 1) { return -1; } if (!((bitmap_entry >> (extent_offset % 8)) & 1)) { return -1; /* not allocated */ } return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset)); } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: void LayerTreeHostQt::layerFlushTimerFired(Timer<LayerTreeHostQt>*) { performScheduledLayerFlush(); } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: std::unique_ptr<NavigationRequest> NavigationRequest::CreateBrowserInitiated( FrameTreeNode* frame_tree_node, const GURL& dest_url, const Referrer& dest_referrer, const FrameNavigationEntry& frame_entry, const NavigationEntryImpl& entry, FrameMsg_Navigate_Type::Value navigation_type, PreviewsState previews_state, bool is_same_document_history_load, bool is_history_navigation_in_new_child, const scoped_refptr<network::ResourceRequestBody>& post_body, base::TimeTicks navigation_start, NavigationControllerImpl* controller, std::unique_ptr<NavigationUIData> navigation_ui_data, base::TimeTicks input_start) { scoped_refptr<network::ResourceRequestBody> request_body; std::string post_content_type; if (post_body) { request_body = post_body; } else if (frame_entry.method() == "POST") { request_body = frame_entry.GetPostData(&post_content_type); post_content_type = base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL) .as_string(); } bool is_form_submission = !!request_body; base::Optional<url::Origin> initiator = frame_tree_node->IsMainFrame() ? base::Optional<url::Origin>() : base::Optional<url::Origin>( frame_tree_node->frame_tree()->root()->current_origin()); bool browser_initiated = !entry.is_renderer_initiated(); CommonNavigationParams common_params = entry.ConstructCommonNavigationParams( frame_entry, request_body, dest_url, dest_referrer, navigation_type, previews_state, navigation_start, input_start); RequestNavigationParams request_params = entry.ConstructRequestNavigationParams( frame_entry, common_params.url, common_params.method, is_history_navigation_in_new_child, entry.GetSubframeUniqueNames(frame_tree_node), controller->GetPendingEntryIndex() == -1, controller->GetIndexOfEntry(&entry), controller->GetLastCommittedEntryIndex(), controller->GetEntryCount()); request_params.post_content_type = post_content_type; std::unique_ptr<NavigationRequest> navigation_request(new NavigationRequest( frame_tree_node, common_params, mojom::BeginNavigationParams::New( entry.extra_headers(), net::LOAD_NORMAL, false /* skip_service_worker */, REQUEST_CONTEXT_TYPE_LOCATION, blink::WebMixedContentContextType::kBlockable, is_form_submission, GURL() /* searchable_form_url */, std::string() /* searchable_form_encoding */, initiator, GURL() /* client_side_redirect_url */, base::nullopt /* devtools_initiator_info */), request_params, browser_initiated, false /* from_begin_navigation */, &frame_entry, &entry, std::move(navigation_ui_data), nullptr)); navigation_request->blob_url_loader_factory_ = frame_entry.blob_url_loader_factory(); return navigation_request; } Commit Message: Use an opaque URL rather than an empty URL for request's site for cookies. Apparently this makes a big difference to the cookie settings backend. Bug: 881715 Change-Id: Id87fa0c6a858bae6a3f8fff4d6af3f974b00d5e4 Reviewed-on: https://chromium-review.googlesource.com/1212846 Commit-Queue: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#589512} 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: const Cluster* Segment::GetNext(const Cluster* pCurr) { assert(pCurr); assert(pCurr != &m_eos); assert(m_clusters); long idx = pCurr->m_index; if (idx >= 0) { assert(m_clusterCount > 0); assert(idx < m_clusterCount); assert(pCurr == m_clusters[idx]); ++idx; if (idx >= m_clusterCount) return &m_eos; //caller will LoadCluster as desired Cluster* const pNext = m_clusters[idx]; assert(pNext); assert(pNext->m_index >= 0); assert(pNext->m_index == idx); return pNext; } assert(m_clusterPreloadCount > 0); long long pos = pCurr->m_element_start; assert(m_size >= 0); //TODO const long long stop = m_start + m_size; //end of segment { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); //TODO if (result != 0) return NULL; const long long id = ReadUInt(m_pReader, pos, len); assert(id == 0x0F43B675); //Cluster ID if (id != 0x0F43B675) return NULL; pos += len; //consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); //TODO assert((pos + len) <= stop); //TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size > 0); //TODO pos += len; //consume length of size of element assert((pos + size) <= stop); //TODO pos += size; //consume payload } long long off_next = 0; while (pos < stop) { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); //TODO if (result != 0) return NULL; const long long idpos = pos; //pos of next (potential) cluster const long long id = ReadUInt(m_pReader, idpos, len); assert(id > 0); //TODO pos += len; //consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); //TODO assert((pos + len) <= stop); //TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size >= 0); //TODO pos += len; //consume length of size of element assert((pos + size) <= stop); //TODO if (size == 0) //weird continue; if (id == 0x0F43B675) //Cluster ID { const long long off_next_ = idpos - m_start; long long pos_; long len_; const long status = Cluster::HasBlockEntries( this, off_next_, pos_, len_); assert(status >= 0); if (status > 0) { off_next = off_next_; break; } } pos += size; //consume payload } if (off_next <= 0) return 0; Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else return pNext; } assert(i == j); Cluster* const pNext = Cluster::Create(this, -1, off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; //insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); return pNext; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: struct fib6_node * fib6_lookup(struct fib6_node *root, const struct in6_addr *daddr, const struct in6_addr *saddr) { struct fib6_node *fn; struct lookup_args args[] = { { .offset = offsetof(struct rt6_info, rt6i_dst), .addr = daddr, }, #ifdef CONFIG_IPV6_SUBTREES { .offset = offsetof(struct rt6_info, rt6i_src), .addr = saddr, }, #endif { .offset = 0, /* sentinel */ } }; fn = fib6_lookup_1(root, daddr ? args : args + 1); if (!fn || fn->fn_flags & RTN_TL_ROOT) fn = root; return fn; } Commit Message: net: fib: fib6_add: fix potential NULL pointer dereference When the kernel is compiled with CONFIG_IPV6_SUBTREES, and we return with an error in fn = fib6_add_1(), then error codes are encoded into the return pointer e.g. ERR_PTR(-ENOENT). In such an error case, we write the error code into err and jump to out, hence enter the if(err) condition. Now, if CONFIG_IPV6_SUBTREES is enabled, we check for: if (pn != fn && pn->leaf == rt) ... if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) ... Since pn is NULL and fn is f.e. ERR_PTR(-ENOENT), then pn != fn evaluates to true and causes a NULL-pointer dereference on further checks on pn. Fix it, by setting both NULL in error case, so that pn != fn already evaluates to false and no further dereference takes place. This was first correctly implemented in 4a287eba2 ("IPv6 routing, NLM_F_* flag support: REPLACE and EXCL flags support, warn about missing CREATE flag"), but the bug got later on introduced by 188c517a0 ("ipv6: return errno pointers consistently for fib6_add_1()"). Signed-off-by: Daniel Borkmann <[email protected]> Cc: Lin Ming <[email protected]> Cc: Matti Vaittinen <[email protected]> Cc: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Acked-by: Matti Vaittinen <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PaymentRequest::DidStartMainFrameNavigationToDifferentDocument( bool is_user_initiated) { RecordFirstAbortReason(is_user_initiated ? JourneyLogger::ABORT_REASON_USER_NAVIGATION : JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, 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 vorbis_book_decodevv_add(codebook *book,ogg_int32_t **a, long offset,int ch, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); long i,j; int chptr=0; if (!v) return -1; for(i=offset;i<offset+n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++){ a[chptr++][i]+=v[j]; if(chptr==ch){ chptr=0; i++; } } } } return 0; } 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 Target: 1 Example 2: Code: exsltDateYearFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *dt = NULL; double ret; if ((nargs < 0) || (nargs > 1)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 1) { dt = xmlXPathPopString(ctxt); if (xmlXPathCheckError(ctxt)) { xmlXPathSetTypeError(ctxt); return; } } ret = exsltDateYear(dt); if (dt != NULL) xmlFree(dt); xmlXPathReturnNumber(ctxt, ret); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void btif_av_event_deep_copy(uint16_t event, char* p_dest, char* p_src) { BTIF_TRACE_DEBUG("%s", __func__); tBTA_AV* av_src = (tBTA_AV*)p_src; tBTA_AV* av_dest = (tBTA_AV*)p_dest; maybe_non_aligned_memcpy(av_dest, av_src, sizeof(*av_src)); switch (event) { case BTA_AV_META_MSG_EVT: if (av_src->meta_msg.p_data && av_src->meta_msg.len) { av_dest->meta_msg.p_data = (uint8_t*)osi_calloc(av_src->meta_msg.len); memcpy(av_dest->meta_msg.p_data, av_src->meta_msg.p_data, av_src->meta_msg.len); } if (av_src->meta_msg.p_msg) { av_dest->meta_msg.p_msg = (tAVRC_MSG*)osi_calloc(sizeof(tAVRC_MSG)); memcpy(av_dest->meta_msg.p_msg, av_src->meta_msg.p_msg, sizeof(tAVRC_MSG)); tAVRC_MSG* p_msg_src = av_src->meta_msg.p_msg; tAVRC_MSG* p_msg_dest = av_dest->meta_msg.p_msg; if ((p_msg_src->hdr.opcode == AVRC_OP_VENDOR) && (p_msg_src->vendor.p_vendor_data && p_msg_src->vendor.vendor_len)) { p_msg_dest->vendor.p_vendor_data = (uint8_t*)osi_calloc(p_msg_src->vendor.vendor_len); memcpy(p_msg_dest->vendor.p_vendor_data, p_msg_src->vendor.p_vendor_data, p_msg_src->vendor.vendor_len); } } break; default: break; } } Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy p_msg_src->browse.p_browse_data is not copied, but used after the original pointer is freed Bug: 109699112 Test: manual Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e (cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b) 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 WebMediaPlayerImpl::HasSingleSecurityOrigin() const { if (data_source_) return data_source_->HasSingleOrigin(); return true; } Commit Message: Fix HasSingleSecurityOrigin for HLS HLS manifests can request segments from a different origin than the original manifest's origin. We do not inspect HLS manifests within Chromium, and instead delegate to Android's MediaPlayer. This means we need to be conservative, and always assume segments might come from a different origin. HasSingleSecurityOrigin should always return false when decoding HLS. Bug: 864283 Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef Reviewed-on: https://chromium-review.googlesource.com/1142691 Reviewed-by: Dale Curtis <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Commit-Queue: Thomas Guilbert <[email protected]> Cr-Commit-Position: refs/heads/master@{#576378} CWE ID: CWE-346 Target: 1 Example 2: Code: int vm_brk(unsigned long addr, unsigned long len) { return vm_brk_flags(addr, len, 0); } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG (printf ("Reading gd2 header info\n")); for (i = 0; i < 4; i++) { ch = gdGetC (in); if (ch == EOF) { goto fail1; }; id[i] = ch; }; id[4] = 0; GD2_DBG (printf ("Got file code: %s\n", id)); /* Equiv. of 'magick'. */ if (strcmp (id, GD2_ID) != 0) { GD2_DBG (printf ("Not a valid gd2 file\n")); goto fail1; }; /* Version */ if (gdGetWord (vers, in) != 1) { goto fail1; }; GD2_DBG (printf ("Version: %d\n", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG (printf ("Bad version: %d\n", *vers)); goto fail1; }; /* Image Size */ if (!gdGetWord (sx, in)) { GD2_DBG (printf ("Could not get x-size\n")); goto fail1; } if (!gdGetWord (sy, in)) { GD2_DBG (printf ("Could not get y-size\n")); goto fail1; } GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord (cs, in) != 1) { goto fail1; }; GD2_DBG (printf ("ChunkSize: %d\n", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG (printf ("Bad chunk size: %d\n", *cs)); goto fail1; }; /* Data Format */ if (gdGetWord (fmt, in) != 1) { goto fail1; }; GD2_DBG (printf ("Format: %d\n", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG (printf ("Bad data format: %d\n", *fmt)); goto fail1; }; /* # of chunks wide */ if (gdGetWord (ncx, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks Wide\n", *ncx)); /* # of chunks high */ if (gdGetWord (ncy, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks vertically\n", *ncy)); if (gd2_compressed (*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG (printf ("Reading %d chunk index entries\n", nc)); if (overflow2(sizeof(t_chunk_info), nc)) { goto fail1; } sidx = sizeof (t_chunk_info) * nc; if (sidx <= 0) { goto fail1; } cidx = gdCalloc (sidx, 1); if (cidx == NULL) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt (&cidx[i].offset, in) != 1) { goto fail2; }; if (gdGetInt (&cidx[i].size, in) != 1) { goto fail2; }; if (cidx[i].offset < 0 || cidx[i].size < 0) goto fail2; }; *chunkIdx = cidx; }; GD2_DBG (printf ("gd2 header complete\n")); return 1; fail2: gdFree(cidx); fail1: return 0; } Commit Message: Fix #354: Signed Integer Overflow gd_io.c GD2 stores the number of horizontal and vertical chunks as words (i.e. 2 byte unsigned). These values are multiplied and assigned to an int when reading the image, what can cause integer overflows. We have to avoid that, and also make sure that either chunk count is actually greater than zero. If illegal chunk counts are detected, we bail out from reading the image. 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: bool WebGLImageConversion::ExtractTextureData(unsigned width, unsigned height, GLenum format, GLenum type, unsigned unpack_alignment, bool flip_y, bool premultiply_alpha, const void* pixels, Vector<uint8_t>& data) { DataFormat source_data_format = GetDataFormat(format, type); if (source_data_format == kDataFormatNumFormats) return false; unsigned int components_per_pixel, bytes_per_component; if (!ComputeFormatAndTypeParameters(format, type, &components_per_pixel, &bytes_per_component)) return false; unsigned bytes_per_pixel = components_per_pixel * bytes_per_component; data.resize(width * height * bytes_per_pixel); if (!PackPixels(static_cast<const uint8_t*>(pixels), source_data_format, width, height, IntRect(0, 0, width, height), 1, unpack_alignment, 0, format, type, (premultiply_alpha ? kAlphaDoPremultiply : kAlphaDoNothing), data.data(), flip_y)) return false; return true; } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125 Target: 1 Example 2: Code: _exsltDateParseGDay (exsltDateValDatePtr dt, const xmlChar **str) { const xmlChar *cur = *str; int ret = 0; PARSE_2_DIGITS(dt->day, cur, VALID_DAY, ret); if (ret != 0) return ret; *str = cur; #ifdef DEBUG_EXSLT_DATE xsltGenericDebug(xsltGenericDebugContext, "Parsed day %02i\n", dt->day); #endif return 0; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: seamless_process(STREAM s) { unsigned int pkglen; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &seamless_rest, seamless_line_handler, NULL); xfree(buf); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb, char *mount_data_global, const char *devname) { int rc; int xid; struct smb_vol *volume_info; struct cifsSesInfo *pSesInfo; struct cifsTconInfo *tcon; struct TCP_Server_Info *srvTcp; char *full_path; char *mount_data = mount_data_global; struct tcon_link *tlink; #ifdef CONFIG_CIFS_DFS_UPCALL struct dfs_info3_param *referrals = NULL; unsigned int num_referrals = 0; int referral_walks_count = 0; try_mount_again: #endif rc = 0; tcon = NULL; pSesInfo = NULL; srvTcp = NULL; full_path = NULL; tlink = NULL; xid = GetXid(); volume_info = kzalloc(sizeof(struct smb_vol), GFP_KERNEL); if (!volume_info) { rc = -ENOMEM; goto out; } if (cifs_parse_mount_options(mount_data, devname, volume_info)) { rc = -EINVAL; goto out; } if (volume_info->nullauth) { cFYI(1, "null user"); volume_info->username = ""; } else if (volume_info->username) { /* BB fixme parse for domain name here */ cFYI(1, "Username: %s", volume_info->username); } else { cifserror("No username specified"); /* In userspace mount helper we can get user name from alternate locations such as env variables and files on disk */ rc = -EINVAL; goto out; } /* this is needed for ASCII cp to Unicode converts */ if (volume_info->iocharset == NULL) { /* load_nls_default cannot return null */ volume_info->local_nls = load_nls_default(); } else { volume_info->local_nls = load_nls(volume_info->iocharset); if (volume_info->local_nls == NULL) { cERROR(1, "CIFS mount error: iocharset %s not found", volume_info->iocharset); rc = -ELIBACC; goto out; } } cifs_sb->local_nls = volume_info->local_nls; /* get a reference to a tcp session */ srvTcp = cifs_get_tcp_session(volume_info); if (IS_ERR(srvTcp)) { rc = PTR_ERR(srvTcp); goto out; } /* get a reference to a SMB session */ pSesInfo = cifs_get_smb_ses(srvTcp, volume_info); if (IS_ERR(pSesInfo)) { rc = PTR_ERR(pSesInfo); pSesInfo = NULL; goto mount_fail_check; } setup_cifs_sb(volume_info, cifs_sb); if (pSesInfo->capabilities & CAP_LARGE_FILES) sb->s_maxbytes = MAX_LFS_FILESIZE; else sb->s_maxbytes = MAX_NON_LFS; /* BB FIXME fix time_gran to be larger for LANMAN sessions */ sb->s_time_gran = 100; /* search for existing tcon to this server share */ tcon = cifs_get_tcon(pSesInfo, volume_info); if (IS_ERR(tcon)) { rc = PTR_ERR(tcon); tcon = NULL; goto remote_path_check; } /* do not care if following two calls succeed - informational */ if (!tcon->ipc) { CIFSSMBQFSDeviceInfo(xid, tcon); CIFSSMBQFSAttributeInfo(xid, tcon); } /* tell server which Unix caps we support */ if (tcon->ses->capabilities & CAP_UNIX) /* reset of caps checks mount to see if unix extensions disabled for just this mount */ reset_cifs_unix_caps(xid, tcon, sb, volume_info); else tcon->unix_ext = 0; /* server does not support them */ /* convert forward to back slashes in prepath here if needed */ if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0) convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb)); if ((tcon->unix_ext == 0) && (cifs_sb->rsize > (1024 * 127))) { cifs_sb->rsize = 1024 * 127; cFYI(DBG2, "no very large read support, rsize now 127K"); } if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X)) cifs_sb->wsize = min(cifs_sb->wsize, (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE)); if (!(tcon->ses->capabilities & CAP_LARGE_READ_X)) cifs_sb->rsize = min(cifs_sb->rsize, (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE)); remote_path_check: /* check if a whole path (including prepath) is not remote */ if (!rc && cifs_sb->prepathlen && tcon) { /* build_path_to_root works only when we have a valid tcon */ full_path = cifs_build_path_to_root(cifs_sb, tcon); if (full_path == NULL) { rc = -ENOMEM; goto mount_fail_check; } rc = is_path_accessible(xid, tcon, cifs_sb, full_path); if (rc != 0 && rc != -EREMOTE) { kfree(full_path); goto mount_fail_check; } kfree(full_path); } /* get referral if needed */ if (rc == -EREMOTE) { #ifdef CONFIG_CIFS_DFS_UPCALL if (referral_walks_count > MAX_NESTED_LINKS) { /* * BB: when we implement proper loop detection, * we will remove this check. But now we need it * to prevent an indefinite loop if 'DFS tree' is * misconfigured (i.e. has loops). */ rc = -ELOOP; goto mount_fail_check; } /* convert forward to back slashes in prepath here if needed */ if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0) convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb)); full_path = build_unc_path_to_root(volume_info, cifs_sb); if (IS_ERR(full_path)) { rc = PTR_ERR(full_path); goto mount_fail_check; } cFYI(1, "Getting referral for: %s", full_path); rc = get_dfs_path(xid, pSesInfo , full_path + 1, cifs_sb->local_nls, &num_referrals, &referrals, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (!rc && num_referrals > 0) { char *fake_devname = NULL; if (mount_data != mount_data_global) kfree(mount_data); mount_data = cifs_compose_mount_options( cifs_sb->mountdata, full_path + 1, referrals, &fake_devname); free_dfs_info_array(referrals, num_referrals); kfree(fake_devname); kfree(full_path); if (IS_ERR(mount_data)) { rc = PTR_ERR(mount_data); mount_data = NULL; goto mount_fail_check; } if (tcon) cifs_put_tcon(tcon); else if (pSesInfo) cifs_put_smb_ses(pSesInfo); cleanup_volume_info(&volume_info); referral_walks_count++; FreeXid(xid); goto try_mount_again; } #else /* No DFS support, return error on mount */ rc = -EOPNOTSUPP; #endif } if (rc) goto mount_fail_check; /* now, hang the tcon off of the superblock */ tlink = kzalloc(sizeof *tlink, GFP_KERNEL); if (tlink == NULL) { rc = -ENOMEM; goto mount_fail_check; } tlink->tl_uid = pSesInfo->linux_uid; tlink->tl_tcon = tcon; tlink->tl_time = jiffies; set_bit(TCON_LINK_MASTER, &tlink->tl_flags); set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags); cifs_sb->master_tlink = tlink; spin_lock(&cifs_sb->tlink_tree_lock); tlink_rb_insert(&cifs_sb->tlink_tree, tlink); spin_unlock(&cifs_sb->tlink_tree_lock); queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks, TLINK_IDLE_EXPIRE); mount_fail_check: /* on error free sesinfo and tcon struct if needed */ if (rc) { if (mount_data != mount_data_global) kfree(mount_data); /* If find_unc succeeded then rc == 0 so we can not end */ /* up accidentally freeing someone elses tcon struct */ if (tcon) cifs_put_tcon(tcon); else if (pSesInfo) cifs_put_smb_ses(pSesInfo); else cifs_put_tcp_session(srvTcp); goto out; } /* volume_info->password is freed above when existing session found (in which case it is not needed anymore) but when new sesion is created the password ptr is put in the new session structure (in which case the password will be freed at unmount time) */ out: /* zero out password before freeing */ cleanup_volume_info(&volume_info); FreeXid(xid); return rc; } Commit Message: cifs: always do is_path_accessible check in cifs_mount Currently, we skip doing the is_path_accessible check in cifs_mount if there is no prefixpath. I have a report of at least one server however that allows a TREE_CONNECT to a share that has a DFS referral at its root. The reporter in this case was using a UNC that had no prefixpath, so the is_path_accessible check was not triggered and the box later hit a BUG() because we were chasing a DFS referral on the root dentry for the mount. This patch fixes this by removing the check for a zero-length prefixpath. That should make the is_path_accessible check be done in this situation and should allow the client to chase the DFS referral at mount time instead. Cc: [email protected] Reported-and-Tested-by: Yogesh Sharma <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->min_is_white=min_is_white; } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/110 CWE ID: CWE-369 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void ComputePrincipleComponent(const float *covariance, DDSVector3 *principle) { DDSVector4 row0, row1, row2, v; register ssize_t i; row0.x = covariance[0]; row0.y = covariance[1]; row0.z = covariance[2]; row0.w = 0.0f; row1.x = covariance[1]; row1.y = covariance[3]; row1.z = covariance[4]; row1.w = 0.0f; row2.x = covariance[2]; row2.y = covariance[4]; row2.z = covariance[5]; row2.w = 0.0f; VectorInit(v,1.0f); for (i=0; i < 8; i++) { DDSVector4 w; float a; w.x = row0.x * v.x; w.y = row0.y * v.x; w.z = row0.z * v.x; w.w = row0.w * v.x; w.x = (row1.x * v.y) + w.x; w.y = (row1.y * v.y) + w.y; w.z = (row1.z * v.y) + w.z; w.w = (row1.w * v.y) + w.w; w.x = (row2.x * v.z) + w.x; w.y = (row2.y * v.z) + w.y; w.z = (row2.z * v.z) + w.z; w.w = (row2.w * v.z) + w.w; a = 1.0f / MaxF(w.x,MaxF(w.y,w.z)); v.x = w.x * a; v.y = w.y * a; v.z = w.z * a; v.w = w.w * a; } VectorCopy43(v,principle); } Commit Message: Added extra EOF check and some minor refactoring. 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: on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler ? handler->opaque : NULL; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476 Target: 1 Example 2: Code: bgp_attr_check (struct peer *peer, struct attr *attr) { u_char type = 0; if (! CHECK_FLAG (attr->flag, ATTR_FLAG_BIT (BGP_ATTR_ORIGIN))) type = BGP_ATTR_ORIGIN; if (! CHECK_FLAG (attr->flag, ATTR_FLAG_BIT (BGP_ATTR_AS_PATH))) type = BGP_ATTR_AS_PATH; if (! CHECK_FLAG (attr->flag, ATTR_FLAG_BIT (BGP_ATTR_NEXT_HOP))) type = BGP_ATTR_NEXT_HOP; if (peer_sort (peer) == BGP_PEER_IBGP && ! CHECK_FLAG (attr->flag, ATTR_FLAG_BIT (BGP_ATTR_LOCAL_PREF))) type = BGP_ATTR_LOCAL_PREF; if (type) { zlog (peer->log, LOG_WARNING, "%s Missing well-known attribute %d.", peer->host, type); bgp_notify_send_with_data (peer, BGP_NOTIFY_UPDATE_ERR, BGP_NOTIFY_UPDATE_MISS_ATTR, &type, 1); return BGP_ATTR_PARSE_ERROR; } return BGP_ATTR_PARSE_PROCEED; } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } } Commit Message: CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { AllocatePixelCachePixels(cache_info); if (cache_info->pixels == (PixelPacket *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s %s, %.20gx%.20g %s)",cache_info->filename, cache_info->mapped != MagickFalse ? "Anonymous" : "Heap", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; return(MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->pixels=source_info.pixels; cache_info->type=DiskCache; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(MagickTrue); } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=2&t=28946 CWE ID: CWE-399 Target: 1 Example 2: Code: static void __perf_event_exit_context(void *__info) { struct perf_event_context *ctx = __info; struct perf_event *event, *tmp; perf_pmu_rotate_stop(ctx->pmu); list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry) __perf_remove_from_context(event); list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry) __perf_remove_from_context(event); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: compare_sids(const struct cifs_sid *ctsid, const struct cifs_sid *cwsid) { int i; int num_subauth, num_sat, num_saw; if ((!ctsid) || (!cwsid)) return 1; /* compare the revision */ if (ctsid->revision != cwsid->revision) { if (ctsid->revision > cwsid->revision) return 1; else return -1; } /* compare all of the six auth values */ for (i = 0; i < NUM_AUTHS; ++i) { if (ctsid->authority[i] != cwsid->authority[i]) { if (ctsid->authority[i] > cwsid->authority[i]) return 1; else return -1; } } /* compare all of the subauth values if any */ num_sat = ctsid->num_subauth; num_saw = cwsid->num_subauth; num_subauth = num_sat < num_saw ? num_sat : num_saw; if (num_subauth) { for (i = 0; i < num_subauth; ++i) { if (ctsid->sub_auth[i] != cwsid->sub_auth[i]) { if (le32_to_cpu(ctsid->sub_auth[i]) > le32_to_cpu(cwsid->sub_auth[i])) return 1; else return -1; } } } return 0; /* sids compare/match */ } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, 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 MaybeStopInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value) && enable_auto_ime_shutdown_) { StopInputMethodDaemon(); } } 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 spl_heap_it_rewind(zend_object_iterator *iter TSRMLS_DC) /* {{{ */ { /* do nothing, the iterator always points to the top element */ } /* }}} */ Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TextTrackCue::setId(const AtomicString& id) { if (id_ == id) return; CueWillChange(); id_ = id; CueDidChange(); } Commit Message: Support negative timestamps of TextTrackCue Ensure proper behaviour for negative timestamps of TextTrackCue. 1. Cues with negative startTime should become active from 0s. 2. Cues with negative startTime and endTime should never be active. Bug: 314032 Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d Reviewed-on: https://chromium-review.googlesource.com/863270 Commit-Queue: srirama chandra sekhar <[email protected]> Reviewed-by: Fredrik Söderquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#529012} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int fill_autodev(const struct lxc_rootfs *rootfs) { int ret; char path[MAXPATHLEN]; int i; mode_t cmask; INFO("Creating initial consoles under container /dev"); ret = snprintf(path, MAXPATHLEN, "%s/dev", rootfs->path ? rootfs->mount : ""); if (ret < 0 || ret >= MAXPATHLEN) { ERROR("Error calculating container /dev location"); return -1; } if (!dir_exists(path)) // ignore, just don't try to fill in return 0; INFO("Populating container /dev"); cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH); for (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) { const struct lxc_devs *d = &lxc_devs[i]; ret = snprintf(path, MAXPATHLEN, "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; ret = mknod(path, d->mode, makedev(d->maj, d->min)); if (ret && errno != EEXIST) { char hostpath[MAXPATHLEN]; FILE *pathfile; ret = snprintf(hostpath, MAXPATHLEN, "/dev/%s", d->name); if (ret < 0 || ret >= MAXPATHLEN) return -1; pathfile = fopen(path, "wb"); if (!pathfile) { SYSERROR("Failed to create device mount target '%s'", path); return -1; } fclose(pathfile); if (mount(hostpath, path, 0, MS_BIND, NULL) != 0) { SYSERROR("Failed bind mounting device %s from host into container", d->name); return -1; } } } umask(cmask); INFO("Populated container /dev"); return 0; } 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: 1 Example 2: Code: ModuleExport size_t RegisterTIFFImage(void) { #define TIFFDescription "Tagged Image File Format" char version[MagickPathExtent]; MagickInfo *entry; #if defined(MAGICKCORE_TIFF_DELEGATE) if (tiff_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&tiff_semaphore); LockSemaphoreInfo(tiff_semaphore); if (instantiate_key == MagickFalse) { if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); error_handler=TIFFSetErrorHandler(TIFFErrors); warning_handler=TIFFSetWarningHandler(TIFFWarnings); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) tag_extender=TIFFSetTagExtender(TIFFTagExtender); #endif instantiate_key=MagickTrue; } UnlockSemaphoreInfo(tiff_semaphore); #endif *version='\0'; #if defined(TIFF_VERSION) (void) FormatLocaleString(version,MagickPathExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MagickPathExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=AcquireMagickInfo("TIFF","GROUP4","Raw CCITT Group4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->flags|=CoderRawSupportFlag; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; entry->format_type=ImplicitFormatType; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","PTIF","Pyramid encoded TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags|=CoderStealthFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF",TIFFDescription); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("TIFF","TIFF64","Tagged Image File Format (64-bit)"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->flags|=CoderEndianSupportFlag; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderUseExtensionFlag; if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1602 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: int __sys_listen(int fd, int backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } Commit Message: socket: close race condition between sock_close() and sockfs_setattr() fchownat() doesn't even hold refcnt of fd until it figures out fd is really needed (otherwise is ignored) and releases it after it resolves the path. This means sock_close() could race with sockfs_setattr(), which leads to a NULL pointer dereference since typically we set sock->sk to NULL in ->release(). As pointed out by Al, this is unique to sockfs. So we can fix this in socket layer by acquiring inode_lock in sock_close() and checking against NULL in sockfs_setattr(). sock_release() is called in many places, only the sock_close() path matters here. And fortunately, this should not affect normal sock_close() as it is only called when the last fd refcnt is gone. It only affects sock_close() with a parallel sockfs_setattr() in progress, which is not common. Fixes: 86741ec25462 ("net: core: Add a UID field to struct sock.") Reported-by: shankarapailoor <[email protected]> Cc: Tetsuo Handa <[email protected]> Cc: Lorenzo Colitti <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int link_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, i = 0, nbuf; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } /* * If we have iterated all input buffers or ran out of * output room, break. */ if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) break; ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1)); nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); obuf = opipe->bufs + nbuf; *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; if (obuf->len > len) obuf->len = len; opipe->nrbufs++; ret += obuf->len; len -= obuf->len; i++; } while (len); /* * return EAGAIN if we have the potential of some data in the * future, otherwise just return 0 */ if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK)) ret = -EAGAIN; pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); return ret; } Commit Message: fs: prevent page refcount overflow in pipe_buf_get Change pipe_buf_get() to return a bool indicating whether it succeeded in raising the refcount of the page (if the thing in the pipe is a page). This removes another mechanism for overflowing the page refcount. All callers converted to handle a failure. Reported-by: Jann Horn <[email protected]> Signed-off-by: Matthew Wilcox <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: void SendNoContentResponse(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { std::string response = "HTTP/1.1 204 No Content\r\n" "Content-Length:0\r\n" "\r\n"; mg_write(connection, response.data(), response.length()); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 IsBackForwardLoadType(FrameLoadType type) { return type == kFrameLoadTypeBackForward || type == kFrameLoadTypeInitialHistoryLoad; } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ikev2_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { const struct ikev2_n *p; struct ikev2_n n; const u_char *cp; u_char showspi, showdata, showsomedata; const char *notify_name; uint32_t type; p = (const struct ikev2_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical); showspi = 1; showdata = 0; showsomedata=0; notify_name=NULL; ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id))); type = ntohs(n.type); /* notify space is annoying sparse */ switch(type) { case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD: notify_name = "unsupported_critical_payload"; showspi = 0; break; case IV2_NOTIFY_INVALID_IKE_SPI: notify_name = "invalid_ike_spi"; showspi = 1; break; case IV2_NOTIFY_INVALID_MAJOR_VERSION: notify_name = "invalid_major_version"; showspi = 0; break; case IV2_NOTIFY_INVALID_SYNTAX: notify_name = "invalid_syntax"; showspi = 1; break; case IV2_NOTIFY_INVALID_MESSAGE_ID: notify_name = "invalid_message_id"; showspi = 1; break; case IV2_NOTIFY_INVALID_SPI: notify_name = "invalid_spi"; showspi = 1; break; case IV2_NOTIFY_NO_PROPOSAL_CHOSEN: notify_name = "no_protocol_chosen"; showspi = 1; break; case IV2_NOTIFY_INVALID_KE_PAYLOAD: notify_name = "invalid_ke_payload"; showspi = 1; break; case IV2_NOTIFY_AUTHENTICATION_FAILED: notify_name = "authentication_failed"; showspi = 1; break; case IV2_NOTIFY_SINGLE_PAIR_REQUIRED: notify_name = "single_pair_required"; showspi = 1; break; case IV2_NOTIFY_NO_ADDITIONAL_SAS: notify_name = "no_additional_sas"; showspi = 0; break; case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE: notify_name = "internal_address_failure"; showspi = 0; break; case IV2_NOTIFY_FAILED_CP_REQUIRED: notify_name = "failed:cp_required"; showspi = 0; break; case IV2_NOTIFY_INVALID_SELECTORS: notify_name = "invalid_selectors"; showspi = 0; break; case IV2_NOTIFY_INITIAL_CONTACT: notify_name = "initial_contact"; showspi = 0; break; case IV2_NOTIFY_SET_WINDOW_SIZE: notify_name = "set_window_size"; showspi = 0; break; case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE: notify_name = "additional_ts_possible"; showspi = 0; break; case IV2_NOTIFY_IPCOMP_SUPPORTED: notify_name = "ipcomp_supported"; showspi = 0; break; case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP: notify_name = "nat_detection_source_ip"; showspi = 1; break; case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP: notify_name = "nat_detection_destination_ip"; showspi = 1; break; case IV2_NOTIFY_COOKIE: notify_name = "cookie"; showspi = 1; showsomedata= 1; showdata= 0; break; case IV2_NOTIFY_USE_TRANSPORT_MODE: notify_name = "use_transport_mode"; showspi = 0; break; case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED: notify_name = "http_cert_lookup_supported"; showspi = 0; break; case IV2_NOTIFY_REKEY_SA: notify_name = "rekey_sa"; showspi = 1; break; case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED: notify_name = "tfc_padding_not_supported"; showspi = 0; break; case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO: notify_name = "non_first_fragment_also"; showspi = 0; break; default: if (type < 8192) { notify_name="error"; } else if(type < 16384) { notify_name="private-error"; } else if(type < 40960) { notify_name="status"; } else { notify_name="private-status"; } } if(notify_name) { ND_PRINT((ndo," type=%u(%s)", type, notify_name)); } if (showspi && n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; if(3 < ndo->ndo_vflag) { showdata = 1; } if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else if(showsomedata && cp < ep) { if(!ike_show_somedata(ndo, cp, ep)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data. The closest thing to a specification for the contents of the payload data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it is ever a complete ISAKMP message, so don't dissect types we don't have specific code for as a complete ISAKMP message. While we're at it, fix a comment, and clean up printing of V1 Nonce, V2 Authentication payloads, and v2 Notice payloads. This fixes an infinite loop 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-835 Target: 1 Example 2: Code: base::string16 ExtensionInstallPrompt::Prompt::GetRetainedFile(size_t index) const { CHECK_LT(index, retained_files_.size()); return retained_files_[index].AsUTF16Unsafe(); } Commit Message: Make the webstore inline install dialog be tab-modal Also clean up a few minor lint errors while I'm in here. BUG=550047 Review URL: https://codereview.chromium.org/1496033003 Cr-Commit-Position: refs/heads/master@{#363925} 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: static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb) { to_vmcb->save.fs = from_vmcb->save.fs; to_vmcb->save.gs = from_vmcb->save.gs; to_vmcb->save.tr = from_vmcb->save.tr; to_vmcb->save.ldtr = from_vmcb->save.ldtr; to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base; to_vmcb->save.star = from_vmcb->save.star; to_vmcb->save.lstar = from_vmcb->save.lstar; to_vmcb->save.cstar = from_vmcb->save.cstar; to_vmcb->save.sfmask = from_vmcb->save.sfmask; to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs; to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp; to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip; } Commit Message: KVM: x86: Check non-canonical addresses upon WRMSR Upon WRMSR, the CPU should inject #GP if a non-canonical value (address) is written to certain MSRs. The behavior is "almost" identical for AMD and Intel (ignoring MSRs that are not implemented in either architecture since they would anyhow #GP). However, IA32_SYSENTER_ESP and IA32_SYSENTER_EIP cause #GP if non-canonical address is written on Intel but not on AMD (which ignores the top 32-bits). Accordingly, this patch injects a #GP on the MSRs which behave identically on Intel and AMD. To eliminate the differences between the architecutres, the value which is written to IA32_SYSENTER_ESP and IA32_SYSENTER_EIP is turned to canonical value before writing instead of injecting a #GP. Some references from Intel and AMD manuals: According to Intel SDM description of WRMSR instruction #GP is expected on WRMSR "If the source register contains a non-canonical address and ECX specifies one of the following MSRs: IA32_DS_AREA, IA32_FS_BASE, IA32_GS_BASE, IA32_KERNEL_GS_BASE, IA32_LSTAR, IA32_SYSENTER_EIP, IA32_SYSENTER_ESP." According to AMD manual instruction manual: LSTAR/CSTAR (SYSCALL): "The WRMSR instruction loads the target RIP into the LSTAR and CSTAR registers. If an RIP written by WRMSR is not in canonical form, a general-protection exception (#GP) occurs." IA32_GS_BASE and IA32_FS_BASE (WRFSBASE/WRGSBASE): "The address written to the base field must be in canonical form or a #GP fault will occur." IA32_KERNEL_GS_BASE (SWAPGS): "The address stored in the KernelGSbase MSR must be in canonical form." This patch fixes CVE-2014-3610. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[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: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); return map->FindProcess(site); } Commit Message: Check for appropriate bindings in process-per-site mode. BUG=174059 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12188025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: virtual int DoIOPending(SocketStreamEvent* event) { io_test_callback_.callback().Run(OK); return ERR_IO_PENDING; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 OMXNodeInstance::sendCommand( OMX_COMMANDTYPE cmd, OMX_S32 param) { if (cmd == OMX_CommandStateSet) { mSailed = true; } const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && cmd == OMX_CommandStateSet) { if (param == OMX_StateIdle) { bufferSource->omxIdle(); } else if (param == OMX_StateLoaded) { bufferSource->omxLoaded(); setGraphicBufferSource(NULL); } } Mutex::Autolock autoLock(mLock); { Mutex::Autolock _l(mDebugLock); bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */); } const char *paramString = cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param); CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL); CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param); return StatusFromOMXError(err); } Commit Message: IOMX: allow configuration after going to loaded state This was disallowed recently but we still use it as MediaCodcec.stop only goes to loaded state, and does not free component. Bug: 31450460 Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d (cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b) 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 DevToolsSession::ReceivedBadMessage() { MojoConnectionDestroyed(); if (process_) { bad_message::ReceivedBadMessage( process_, bad_message::RFH_INCONSISTENT_DEVTOOLS_MESSAGE); } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 1 Example 2: Code: static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd) { int bytes; struct ip_udp_dhcp_packet packet; uint16_t check; unsigned char cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))]; struct iovec iov; struct msghdr msg; struct cmsghdr *cmsg; /* used to use just safe_read(fd, &packet, sizeof(packet)) * but we need to check for TP_STATUS_CSUMNOTREADY :( */ iov.iov_base = &packet; iov.iov_len = sizeof(packet); memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof(cmsgbuf); for (;;) { bytes = recvmsg(fd, &msg, 0); if (bytes < 0) { if (errno == EINTR) continue; log1("Packet read error, ignoring"); /* NB: possible down interface, etc. Caller should pause. */ return bytes; /* returns -1 */ } break; } if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) { log1("Packet is too short, ignoring"); return -2; } if (bytes < ntohs(packet.ip.tot_len)) { /* packet is bigger than sizeof(packet), we did partial read */ log1("Oversized packet, ignoring"); return -2; } /* ignore any extra garbage bytes */ bytes = ntohs(packet.ip.tot_len); /* make sure its the right packet for us, and that it passes sanity checks */ if (packet.ip.protocol != IPPROTO_UDP || packet.ip.version != IPVERSION || packet.ip.ihl != (sizeof(packet.ip) >> 2) || packet.udp.dest != htons(CLIENT_PORT) /* || bytes > (int) sizeof(packet) - can't happen */ || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip)) ) { log1("Unrelated/bogus packet, ignoring"); return -2; } /* verify IP checksum */ check = packet.ip.check; packet.ip.check = 0; if (check != inet_cksum((uint16_t *)&packet.ip, sizeof(packet.ip))) { log1("Bad IP header checksum, ignoring"); return -2; } for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (cmsg->cmsg_level == SOL_PACKET && cmsg->cmsg_type == PACKET_AUXDATA ) { /* some VMs don't checksum UDP and TCP data * they send to the same physical machine, * here we detect this case: */ struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg); if (aux->tp_status & TP_STATUS_CSUMNOTREADY) goto skip_udp_sum_check; } } /* verify UDP checksum. IP header has to be modified for this */ memset(&packet.ip, 0, offsetof(struct iphdr, protocol)); /* ip.xx fields which are not memset: protocol, check, saddr, daddr */ packet.ip.tot_len = packet.udp.len; /* yes, this is needed */ check = packet.udp.check; packet.udp.check = 0; if (check && check != inet_cksum((uint16_t *)&packet, bytes)) { log1("Packet with bad UDP checksum received, ignoring"); return -2; } skip_udp_sum_check: if (packet.data.cookie != htonl(DHCP_MAGIC)) { bb_info_msg("Packet with bad magic, ignoring"); return -2; } log1("Received a packet"); udhcp_dump_packet(&packet.data); bytes -= sizeof(packet.ip) + sizeof(packet.udp); memcpy(dhcp_pkt, &packet.data, bytes); return bytes; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Segment::ParseCues( long long off, long long& pos, long& len) { if (m_pCues) return 0; //success if (off < 0) return -1; long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = m_start + off; if ((total < 0) || (pos >= total)) return 1; //don't bother parsing cues const long long element_start = pos; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id != 0x0C53BB6B) //Cues ID return E_FILE_FORMAT_INVALID; pos += len; //consume ID assert((segment_stop < 0) || (pos <= segment_stop)); if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); if (size == 0) //weird, although technically not illegal return 1; //done pos += len; //consume length of size of element assert((segment_stop < 0) || (pos <= segment_stop)); const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (element_stop > total)) return 1; //don't bother parsing anymore len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; const long long element_size = element_stop - element_start; m_pCues = new (std::nothrow) Cues( this, pos, size, element_start, element_size); assert(m_pCues); //TODO return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SensorCreated(scoped_refptr<PlatformSensor> sensor) { if (!result_callback_) { return; } if (!sensor) { std::move(result_callback_).Run(nullptr); return; } mojom::SensorType type = sensor->GetType(); sources_map_[type] = std::move(sensor); if (sources_map_.size() == fusion_algorithm_->source_types().size()) { scoped_refptr<PlatformSensor> fusion_sensor(new PlatformSensorFusion( std::move(mapping_), provider_, std::move(fusion_algorithm_), std::move(sources_map_))); std::move(result_callback_).Run(fusion_sensor); } } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: int dns_packet_read_key(DnsPacket *p, DnsResourceKey **ret, bool *ret_cache_flush, size_t *start) { _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder; _cleanup_free_ char *name = NULL; bool cache_flush = false; uint16_t class, type; DnsResourceKey *key; int r; assert(p); assert(ret); INIT_REWINDER(rewinder, p); r = dns_packet_read_name(p, &name, true, NULL); if (r < 0) return r; r = dns_packet_read_uint16(p, &type, NULL); if (r < 0) return r; r = dns_packet_read_uint16(p, &class, NULL); if (r < 0) return r; if (p->protocol == DNS_PROTOCOL_MDNS) { /* See RFC6762, Section 10.2 */ if (type != DNS_TYPE_OPT && (class & MDNS_RR_CACHE_FLUSH)) { class &= ~MDNS_RR_CACHE_FLUSH; cache_flush = true; } } key = dns_resource_key_new_consume(class, type, name); if (!key) return -ENOMEM; name = NULL; *ret = key; if (ret_cache_flush) *ret_cache_flush = cache_flush; if (start) *start = rewinder.saved_rindex; CANCEL_REWINDER(rewinder); return 0; } Commit Message: resolved: bugfix of null pointer p->question dereferencing (#6020) See https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1621396 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: RenderBlock* RenderBlock::blockElementContinuation() const { RenderBoxModelObject* currentContinuation = continuation(); if (!currentContinuation || currentContinuation->isInline()) return 0; RenderBlock* nextContinuation = toRenderBlock(currentContinuation); if (nextContinuation->isAnonymousBlock()) return nextContinuation->blockElementContinuation(); return nextContinuation; } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, 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 P2PQuicStreamImpl::Finish() { DCHECK(!fin_sent()); quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284 Target: 1 Example 2: Code: void NuPlayer::GenericSource::onMessageReceived(const sp<AMessage> &msg) { switch (msg->what()) { case kWhatPrepareAsync: { onPrepareAsync(); break; } case kWhatFetchSubtitleData: { fetchTextData(kWhatSendSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); break; } case kWhatFetchTimedTextData: { fetchTextData(kWhatSendTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); break; } case kWhatSendSubtitleData: { sendTextData(kWhatSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); break; } case kWhatSendTimedTextData: { sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); break; } case kWhatChangeAVSource: { int32_t trackIndex; CHECK(msg->findInt32("trackIndex", &trackIndex)); const sp<MediaSource> source = mSources.itemAt(trackIndex); Track* track; const char *mime; media_track_type trackType, counterpartType; sp<MetaData> meta = source->getFormat(); meta->findCString(kKeyMIMEType, &mime); if (!strncasecmp(mime, "audio/", 6)) { track = &mAudioTrack; trackType = MEDIA_TRACK_TYPE_AUDIO; counterpartType = MEDIA_TRACK_TYPE_VIDEO;; } else { CHECK(!strncasecmp(mime, "video/", 6)); track = &mVideoTrack; trackType = MEDIA_TRACK_TYPE_VIDEO; counterpartType = MEDIA_TRACK_TYPE_AUDIO;; } if (track->mSource != NULL) { track->mSource->stop(); } track->mSource = source; track->mSource->start(); track->mIndex = trackIndex; int64_t timeUs, actualTimeUs; const bool formatChange = true; if (trackType == MEDIA_TRACK_TYPE_AUDIO) { timeUs = mAudioLastDequeueTimeUs; } else { timeUs = mVideoLastDequeueTimeUs; } readBuffer(trackType, timeUs, &actualTimeUs, formatChange); readBuffer(counterpartType, -1, NULL, formatChange); ALOGV("timeUs %lld actualTimeUs %lld", (long long)timeUs, (long long)actualTimeUs); break; } case kWhatStart: case kWhatResume: { restartPollBuffering(); break; } case kWhatPollBuffering: { int32_t generation; CHECK(msg->findInt32("generation", &generation)); if (generation == mPollBufferingGeneration) { onPollBuffering(); } break; } case kWhatGetFormat: { onGetFormatMeta(msg); break; } case kWhatGetSelectedTrack: { onGetSelectedTrack(msg); break; } case kWhatSelectTrack: { onSelectTrack(msg); break; } case kWhatSeek: { onSeek(msg); break; } case kWhatReadBuffer: { onReadBuffer(msg); break; } case kWhatSecureDecodersInstantiated: { int32_t err; CHECK(msg->findInt32("err", &err)); onSecureDecodersInstantiated(err); break; } case kWhatStopWidevine: { mStopRead = true; if (mVideoTrack.mSource != NULL) { mVideoTrack.mPackets->clear(); } sp<AMessage> response = new AMessage; sp<AReplyToken> replyID; CHECK(msg->senderAwaitsResponse(&replyID)); response->postReply(replyID); break; } default: Source::onMessageReceived(msg); break; } } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock) { int version; int r; struct pvclock_wall_clock wc; struct timespec boot; if (!wall_clock) return; r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version)); if (r) return; if (version & 1) ++version; /* first time write, random junk */ ++version; kvm_write_guest(kvm, wall_clock, &version, sizeof(version)); /* * The guest calculates current wall clock time by adding * system time (updated by kvm_guest_time_update below) to the * wall clock specified here. guest system time equals host * system time for us, thus we must fill in host boot time here. */ getboottime(&boot); if (kvm->arch.kvmclock_offset) { struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset); boot = timespec_sub(boot, ts); } wc.sec = boot.tv_sec; wc.nsec = boot.tv_nsec; wc.version = version; kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc)); version++; kvm_write_guest(kvm, wall_clock, &version, sizeof(version)); } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag "Equalize/Image" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); } Commit Message: Evaluate lazy pixel cache morphology to prevent buffer overflow (bug report from Ibrahim M. El-Sayed) CWE ID: CWE-125 Target: 1 Example 2: Code: PassRefPtr<Comment> Document::createComment(const String& data) { return Comment::create(*this, data); } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none [email protected], abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MaxTextExtent], text[MaxTextExtent]; Image *image; IndexPacket *indexes; long x_offset, y_offset; MagickBooleanType status; MagickPixelPacket pixel; QuantumAny range; register ssize_t i, x; register PixelPacket *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) if (depth >= 64) break; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->matte=MagickFalse; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->matte=MagickTrue; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->colorspace=(ColorspaceType) type; (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); (void) SetImageBackgroundColor(image); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, index, opacity, red; red=0.0; green=0.0; blue=0.0; index=0.0; opacity=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&opacity); green=red; blue=red; break; } (void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->matte != MagickFalse) { (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&index,&opacity); break; } (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&index); break; } default: { if (image->matte != MagickFalse) { (void) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&opacity); break; } (void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; index*=0.01*range; opacity*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5), range); pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+ 0.5),range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (PixelPacket *) NULL) continue; SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->colorspace == CMYKColorspace) { indexes=GetAuthenticIndexQueue(image); SetPixelIndex(indexes,pixel.index); } if (image->matte != MagickFalse) SetPixelAlpha(q,pixel.opacity); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/713 CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); builder.SetIsHandleVisible(true); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 1 Example 2: Code: skb_zerocopy(struct sk_buff *to, const struct sk_buff *from, int len, int hlen) { int i, j = 0; int plen = 0; /* length of skb->head fragment */ struct page *page; unsigned int offset; BUG_ON(!from->head_frag && !hlen); /* dont bother with small payloads */ if (len <= skb_tailroom(to)) { skb_copy_bits(from, 0, skb_put(to, len), len); return; } if (hlen) { skb_copy_bits(from, 0, skb_put(to, hlen), hlen); len -= hlen; } else { plen = min_t(int, skb_headlen(from), len); if (plen) { page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); __skb_fill_page_desc(to, 0, page, offset, plen); get_page(page); j = 1; len -= plen; } } to->truesize += len + plen; to->len += len + plen; to->data_len += len + plen; for (i = 0; i < skb_shinfo(from)->nr_frags; i++) { if (!len) break; skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i]; skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len); len -= skb_shinfo(to)->frags[j].size; skb_frag_ref(to, j); j++; } skb_shinfo(to)->nr_frags = j; } Commit Message: skbuff: skb_segment: orphan frags before copying skb_segment copies frags around, so we need to copy them carefully to avoid accessing user memory after reporting completion to userspace through a callback. skb_segment doesn't normally happen on datapath: TSO needs to be disabled - so disabling zero copy in this case does not look like a big deal. Signed-off-by: Michael S. Tsirkin <[email protected]> Acked-by: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) { int name_end = -1; int j = *idx; int ptr_count = 0; #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0) #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0) #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0) char *cp = name_out; const char *const end = name_out + name_out_len; /* Normally, names are a series of length prefixed strings terminated */ /* with a length of 0 (the lengths are u8's < 63). */ /* However, the length can start with a pair of 1 bits and that */ /* means that the next 14 bits are a pointer within the current */ /* packet. */ for (;;) { u8 label_len; if (j >= length) return -1; GET8(label_len); if (!label_len) break; if (label_len & 0xc0) { u8 ptr_low; GET8(ptr_low); if (name_end < 0) name_end = j; j = (((int)label_len & 0x3f) << 8) + ptr_low; /* Make sure that the target offset is in-bounds. */ if (j < 0 || j >= length) return -1; /* If we've jumped more times than there are characters in the * message, we must have a loop. */ if (++ptr_count > length) return -1; continue; } if (label_len > 63) return -1; if (cp != name_out) { if (cp + 1 >= end) return -1; *cp++ = '.'; } if (cp + label_len >= end) return -1; memcpy(cp, packet + j, label_len); cp += label_len; j += label_len; } if (cp >= end) return -1; *cp = '\0'; if (name_end < 0) *idx = j; else *idx = name_end; return 0; err: return -1; } Commit Message: evdns: name_parse(): fix remote stack overread @asn-the-goblin-slayer: "the name_parse() function in libevent's DNS code is vulnerable to a buffer overread. 971 if (cp != name_out) { 972 if (cp + 1 >= end) return -1; 973 *cp++ = '.'; 974 } 975 if (cp + label_len >= end) return -1; 976 memcpy(cp, packet + j, label_len); 977 cp += label_len; 978 j += label_len; No check is made against length before the memcpy occurs. This was found through the Tor bug bounty program and the discovery should be credited to 'Guido Vranken'." Reproducer for gdb (https://gist.github.com/azat/e4fcf540e9b89ab86d02): set $PROT_NONE=0x0 set $PROT_READ=0x1 set $PROT_WRITE=0x2 set $MAP_ANONYMOUS=0x20 set $MAP_SHARED=0x01 set $MAP_FIXED=0x10 set $MAP_32BIT=0x40 start set $length=202 # overread set $length=2 # allocate with mmap to have a seg fault on page boundary set $l=(1<<20)*2 p mmap(0, $l, $PROT_READ|$PROT_WRITE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_32BIT, -1, 0) set $packet=(char *)$1+$l-$length # hack the packet set $packet[0]=63 set $packet[1]='/' p malloc(sizeof(int)) set $idx=(int *)$2 set $idx[0]=0 set $name_out_len=202 p malloc($name_out_len) set $name_out=$3 # have WRITE only mapping to fail on read set $end=$1+$l p (void *)mmap($end, 1<<12, $PROT_NONE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_FIXED|$MAP_32BIT, -1, 0) set $m=$4 p name_parse($packet, $length, $idx, $name_out, $name_out_len) x/2s (char *)$name_out Before this patch: $ gdb -ex 'source gdb' dns-example $1 = 1073741824 $2 = (void *) 0x633010 $3 = (void *) 0x633030 $4 = (void *) 0x40200000 Program received signal SIGSEGV, Segmentation fault. __memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:33 After this patch: $ gdb -ex 'source gdb' dns-example $1 = 1073741824 $2 = (void *) 0x633010 $3 = (void *) 0x633030 $4 = (void *) 0x40200000 $5 = -1 0x633030: "/" 0x633032: "" (gdb) p $m $6 = (void *) 0x40200000 (gdb) p $1 $7 = 1073741824 (gdb) p/x $1 $8 = 0x40000000 (gdb) quit P.S. plus drop one condition duplicate. Fixes: #317 CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned short get_ushort(const unsigned char *data) { unsigned short val = *(const unsigned short *)data; #ifdef OPJ_BIG_ENDIAN val = ((val & 0xffU) << 8) | (val >> 8); #endif return val; } Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995) CWE ID: CWE-787 Target: 1 Example 2: Code: void DownloadManagerImpl::DetermineDownloadTarget( DownloadItemImpl* item, const DownloadTargetCallback& callback) { if (!delegate_ || !delegate_->DetermineDownloadTarget(item, callback)) { base::FilePath target_path = item->GetForcedFilePath(); callback.Run(target_path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, target_path, DOWNLOAD_INTERRUPT_REASON_NONE); } } Commit Message: Downloads : Fixed an issue of opening incorrect download file When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download. Bug: 793620 Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8 Reviewed-on: https://chromium-review.googlesource.com/826477 Reviewed-by: David Trainor <[email protected]> Reviewed-by: Xing Liu <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Commit-Queue: Shakti Sahu <[email protected]> Cr-Commit-Position: refs/heads/master@{#525810} 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 cac_read_binary(sc_card_t *card, unsigned int idx, unsigned char *buf, size_t count, unsigned long flags) { cac_private_data_t * priv = CAC_DATA(card); int r = 0; u8 *tl = NULL, *val = NULL; u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start; u8 *cert_ptr; size_t tl_len, val_len, tlv_len; size_t len, tl_head_len, cert_len; u8 cert_type, tag; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* if we didn't return it all last time, return the remainder */ if (priv->cached) { sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (idx > priv->cache_buf_len) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED); } len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len); } sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u", idx, count); if (priv->cache_buf) { free(priv->cache_buf); priv->cache_buf = NULL; priv->cache_buf_len = 0; } if (priv->object_type <= 0) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL); r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len); if (r < 0) { goto done; } r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len); if (r < 0) goto done; switch (priv->object_type) { case CAC_OBJECT_TYPE_TLV_FILE: tlv_len = tl_len + val_len; priv->cache_buf = malloc(tlv_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = tlv_len; for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf; tl_len >= 2 && tlv_len > 0; val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) { /* get the tag and the length */ tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = (tl_ptr - tl_start); sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr); tlv_len -= tl_head_len; tl_len -= tl_head_len; /* don't crash on bad data */ if (val_len < len) { len = val_len; } /* if we run out of return space, truncate */ if (tlv_len < len) { len = tlv_len; } memcpy(tlv_ptr, val_ptr, len); } break; case CAC_OBJECT_TYPE_CERT: /* read file */ sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)", val_len, val_len); cert_len = 0; cert_ptr = NULL; cert_type = 0; for (tl_ptr = tl, val_ptr=val; tl_len >= 2; val_len -= len, val_ptr += len, tl_len -= tl_head_len) { tl_start = tl_ptr; if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS) break; tl_head_len = tl_ptr - tl_start; if (tag == CAC_TAG_CERTIFICATE) { cert_len = len; cert_ptr = val_ptr; } if (tag == CAC_TAG_CERTINFO) { if ((len >= 1) && (val_len >=1)) { cert_type = *val_ptr; } } if (tag == CAC_TAG_MSCUID) { sc_log_hex(card->ctx, "MSCUID", val_ptr, len); } if ((val_len < len) || (tl_len < tl_head_len)) { break; } } /* if the info byte is 1, then the cert is compressed, decompress it */ if ((cert_type & 0x3) == 1) { #ifdef ENABLE_ZLIB r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len, cert_ptr, cert_len, COMPRESSION_AUTO); #else sc_log(card->ctx, "CAC compression not supported, no zlib"); r = SC_ERROR_NOT_SUPPORTED; #endif if (r) goto done; } else if (cert_len > 0) { priv->cache_buf = malloc(cert_len); if (priv->cache_buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; goto done; } priv->cache_buf_len = cert_len; memcpy(priv->cache_buf, cert_ptr, cert_len); } else { sc_log(card->ctx, "Can't read zero-length certificate"); goto done; } break; case CAC_OBJECT_TYPE_GENERIC: /* TODO * We have some two buffers in unknown encoding that we * need to present in PKCS#15 layer. */ default: /* Unknown object type */ sc_log(card->ctx, "Unknown object type: %x", priv->object_type); r = SC_ERROR_INTERNAL; goto done; } /* OK we've read the data, now copy the required portion out to the callers buffer */ priv->cached = 1; len = MIN(count, priv->cache_buf_len-idx); memcpy(buf, &priv->cache_buf[idx], len); r = len; done: if (tl) free(tl); if (val) free(val); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 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 su3000_power_ctrl(struct dvb_usb_device *d, int i) { struct dw2102_state *state = (struct dw2102_state *)d->priv; u8 obuf[] = {0xde, 0}; info("%s: %d, initialized %d", __func__, i, state->initialized); if (i && !state->initialized) { state->initialized = 1; /* reset board */ return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0); } return 0; } Commit Message: [media] dw2102: don't do DMA on stack On Kernel 4.9, WARNINGs about doing DMA on stack are hit at the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach(). Both were due to the use of buffers on the stack as parameters to dvb_usb_generic_rw() and the resulting attempt to do DMA with them. The device was non-functional as a result. So, switch this driver over to use a buffer within the device state structure, as has been done with other DVB-USB drivers. Tested with TechnoTrend TT-connect S2-4600. [[email protected]: fixed a warning at su3000_i2c_transfer() that state var were dereferenced before check 'd'] Signed-off-by: Jonathan McDowell <[email protected]> Cc: <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: file_continue(i_ctx_t *i_ctx_p) { os_ptr op = osp; es_ptr pscratch = esp - 2; file_enum *pfen = r_ptr(esp - 1, file_enum); int devlen = esp[-3].value.intval; gx_io_device *iodev = r_ptr(esp - 4, gx_io_device); uint len = r_size(pscratch); uint code; if (len < devlen) return_error(gs_error_rangecheck); /* not even room for device len */ do { memcpy((char *)pscratch->value.bytes, iodev->dname, devlen); code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen, len - devlen); if (code == ~(uint) 0) { /* all done */ esp -= 5; /* pop proc, pfen, devlen, iodev , mark */ return o_pop_estack; } else if (code > len) /* overran string */ return_error(gs_error_rangecheck); else if (iodev != iodev_default(imemory) || (check_file_permissions_reduced(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, "PermitFileReading")) == 0) { push(1); ref_assign(op, pscratch); r_set_size(op, code + devlen); push_op_estack(file_continue); /* come again */ *++esp = pscratch[2]; /* proc */ return o_push_estack; } } while(1); } 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: void DataReductionProxySettings::AddDataReductionProxySettingsObserver( DataReductionProxySettingsObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); observers_.AddObserver(observer); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, 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 perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); for (;;) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } } Commit Message: powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH (currently 127), but we forgot to do the same for 64bit backtraces. Cc: [email protected] Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Michael Ellerman <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static inline void tg3_netif_stop(struct tg3 *tp) { tp->dev->trans_start = jiffies; /* prevent tx timeout */ tg3_napi_disable(tp); netif_carrier_off(tp->dev); netif_tx_disable(tp->dev); } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <[email protected]> Reported-by: Oded Horovitz <[email protected]> Reported-by: Brad Spengler <[email protected]> Cc: [email protected] Cc: Matt Carlson <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available; long status = pReader->Length(&total, &available); if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; assert(len > 0); assert(len <= 8); if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } assert(pos == end); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; } Commit Message: * libtiff/tif_predic.c: fix memory leaks in error code paths added in previous commit (fix for MSVR 35105) CWE ID: CWE-119 Target: 1 Example 2: Code: unsigned char lodepng_chunk_private(const unsigned char* chunk) { return((chunk[6] & 32) != 0); } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ext4_xattr_ibody_list(struct dentry *dentry, char *buffer, size_t buffer_size) { struct inode *inode = d_inode(dentry); struct ext4_xattr_ibody_header *header; struct ext4_inode *raw_inode; struct ext4_iloc iloc; void *end; int error; if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR)) return 0; error = ext4_get_inode_loc(inode, &iloc); if (error) return error; raw_inode = ext4_raw_inode(&iloc); header = IHDR(inode, raw_inode); end = (void *)raw_inode + EXT4_SB(inode->i_sb)->s_inode_size; error = ext4_xattr_check_names(IFIRST(header), end, IFIRST(header)); if (error) goto cleanup; error = ext4_xattr_list_entries(dentry, IFIRST(header), buffer, buffer_size); cleanup: brelse(iloc.bh); return error; } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only 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 buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: TEE_Result syscall_asymm_operate(unsigned long state, const struct utee_attribute *usr_params, size_t num_params, const void *src_data, size_t src_len, void *dst_data, uint64_t *dst_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; uint64_t dlen64; size_t dlen; struct tee_obj *o; void *label = NULL; size_t label_len = 0; size_t n; int salt_len; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) src_data, src_len); if (res != TEE_SUCCESS) return res; res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64)); if (res != TEE_SUCCESS) return res; dlen = dlen64; res = tee_mmu_check_access_rights( utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) dst_data, dlen); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * num_params); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, num_params, params); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, cs->key1, &o); if (res != TEE_SUCCESS) goto out; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) { res = TEE_ERROR_GENERIC; goto out; } switch (cs->algo) { case TEE_ALG_RSA_NOPAD: if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsanopad_encrypt(o->attr, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsanopad_decrypt(o->attr, src_data, src_len, dst_data, &dlen); } else { /* * We will panic because "the mode is not compatible * with the function" */ res = TEE_ERROR_GENERIC; } break; case TEE_ALG_RSAES_PKCS1_V1_5: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384: case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512: for (n = 0; n < num_params; n++) { if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) { label = params[n].content.ref.buffer; label_len = params[n].content.ref.length; break; } } if (cs->mode == TEE_MODE_ENCRYPT) { res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else if (cs->mode == TEE_MODE_DECRYPT) { res = crypto_acipher_rsaes_decrypt( cs->algo, o->attr, label, label_len, src_data, src_len, dst_data, &dlen); } else { res = TEE_ERROR_BAD_PARAMETERS; } break; #if defined(CFG_CRYPTO_RSASSA_NA1) case TEE_ALG_RSASSA_PKCS1_V1_5: #endif case TEE_ALG_RSASSA_PKCS1_V1_5_MD5: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384: case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384: case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512: if (cs->mode != TEE_MODE_SIGN) { res = TEE_ERROR_BAD_PARAMETERS; break; } salt_len = pkcs1_get_salt_len(params, num_params, src_len); res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_DSA_SHA1: case TEE_ALG_DSA_SHA224: case TEE_ALG_DSA_SHA256: res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; case TEE_ALG_ECDSA_P192: case TEE_ALG_ECDSA_P224: case TEE_ALG_ECDSA_P256: case TEE_ALG_ECDSA_P384: case TEE_ALG_ECDSA_P521: res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data, src_len, dst_data, &dlen); break; default: res = TEE_ERROR_BAD_PARAMETERS; break; } out: free(params); if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) { TEE_Result res2; dlen64 = dlen; res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len)); if (res2 != TEE_SUCCESS) return res2; } return res; } Commit Message: svc: check for allocation overflow in crypto calls part 2 Without checking for overflow there is a risk of allocating a buffer with size smaller than anticipated and as a consequence of that it might lead to a heap based overflow with attacker controlled data written outside the boundaries of the buffer. Fixes: OP-TEE-2018-0011: "Integer overflow in crypto system calls (x2)" Signed-off-by: Joakim Bech <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Jens Wiklander <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: ~ExtensionConfig() { } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool lockdep_softirq_start(void) { bool in_hardirq = false; if (trace_hardirq_context(current)) { in_hardirq = true; trace_hardirq_exit(); } lockdep_softirq_enter(); return in_hardirq; } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GF_Err tenc_dump(GF_Box *a, FILE * trace) { GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a; if (!a) return GF_BAD_PARAM; gf_isom_box_dump_start(a, "TrackEncryptionBox", trace); fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected); if (ptr->Per_Sample_IV_Size) fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size); else { fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size); dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size); fprintf(trace, "\" KID=\""); } dump_data_hex(trace, (char *) ptr->KID, 16); if (ptr->version) fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block); fprintf(trace, "\">\n"); gf_isom_box_dump_done("TrackEncryptionBox", a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 1 Example 2: Code: static inline int get_duration(AVIStream *ast, int len) { if (ast->sample_size) return len; else if (ast->dshow_block_align) return (len + ast->dshow_block_align - 1) / ast->dshow_block_align; else return 1; } Commit Message: avformat/avidec: Limit formats in gab2 to srt and ass/ssa This prevents part of one exploit leading to an information leak Found-by: Emil Lerner and Pavel Cheremushkin Reported-by: Thierry Foucu <[email protected]> Signed-off-by: Michael Niedermayer <[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: BGD_DECLARE(void) gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); if (out == NULL) { return; } gdImageWebpCtx(im, out, -1); out->gd_free(out); } Commit Message: Fix double-free in gdImageWebPtr() The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and the other WebP output functions to do the real work) does not return whether it succeeded or failed, so this is not checked in gdImageWebpPtr() and the function wrongly assumes everything is okay, which is not, in this case, because there is a size limitation for WebP, namely that the width and height must by less than 16383. We can't change the signature of gdImageWebpCtx() for API compatibility reasons, so we introduce the static helper _gdImageWebpCtx() which returns success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can check the return value. We leave it solely to libwebp for now to report warnings regarding the failing write. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6912 CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void UpdateProperty(const ImePropertyList& prop_list) { for (size_t i = 0; i < prop_list.size(); ++i) { FindAndUpdateProperty(prop_list[i], &current_ime_properties_); } FOR_EACH_OBSERVER(Observer, observers_, PropertyListChanged(this, current_ime_properties_)); } 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: ShelfAlignment LauncherView::GetShelfAlignment() const { return alignment_; } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: streamNACK *streamCreateNACK(streamConsumer *consumer) { streamNACK *nack = zmalloc(sizeof(*nack)); nack->delivery_time = mstime(); nack->delivery_count = 1; nack->consumer = consumer; return nack; } Commit Message: Abort in XGROUP if the key is not a stream 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: status_t BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: HDCP: buffer over flow check -- DO NOT MERGE bug: 20222489 Change-Id: I3a64a5999d68ea243d187f12ec7717b7f26d93a3 (cherry picked from commit 532cd7b86a5fdc7b9a30a45d8ae2d16ef7660a72) CWE ID: CWE-189 Target: 1 Example 2: Code: void btm_sec_update_clock_offset (UINT16 handle, UINT16 clock_offset) { tBTM_SEC_DEV_REC *p_dev_rec; tBTM_INQ_INFO *p_inq_info; if ((p_dev_rec = btm_find_dev_by_handle (handle)) == NULL) return; p_dev_rec->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; if ((p_inq_info = BTM_InqDbRead(p_dev_rec->bd_addr)) == NULL) return; p_inq_info->results.clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID; } Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround Bug: 26551752 Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1 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 tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct tun_struct *tun; struct tun_file *tfile = file->private_data; struct net_device *dev; int err; if (tfile->detached) return -EINVAL; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != !!(tun->flags & IFF_MULTI_QUEUE)) return -EINVAL; if (tun_not_capable(tun)) return -EPERM; err = security_tun_dev_open(tun->security); if (err < 0) return err; err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); if (err < 0) return err; if (tun->flags & IFF_MULTI_QUEUE && (tun->numqueues + tun->numdisabled > 1)) { /* One or more queue has already been attached, no need * to initialize the device again. */ return 0; } } else { char *name; unsigned long flags = 0; int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? MAX_TAP_QUEUES : 1; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= IFF_TUN; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= IFF_TAP; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, NET_NAME_UNKNOWN, tun_setup, queues, queues); if (!dev) return -ENOMEM; err = dev_get_valid_name(net, dev, name); if (err) goto err_free_dev; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; dev->ifindex = tfile->ifindex; dev->sysfs_groups[0] = &tun_attr_group; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); tun->align = NET_SKB_PAD; tun->filter_attached = false; tun->sndbuf = tfile->socket.sk->sk_sndbuf; tun->rx_batched = 0; tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); if (!tun->pcpu_stats) { err = -ENOMEM; goto err_free_dev; } spin_lock_init(&tun->lock); err = security_tun_dev_alloc_security(&tun->security); if (err < 0) goto err_free_stat; tun_net_init(dev); tun_flow_init(tun); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX; dev->features = dev->hw_features | NETIF_F_LLTX; dev->vlan_features = dev->features & ~(NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX); INIT_LIST_HEAD(&tun->disabled); err = tun_attach(tun, file, false); if (err < 0) goto err_free_flow; err = register_netdevice(tun->dev); if (err < 0) goto err_detach; } netif_carrier_on(tun->dev); tun_debug(KERN_INFO, tun, "tun_set_iff\n"); tun->flags = (tun->flags & ~TUN_FEATURES) | (ifr->ifr_flags & TUN_FEATURES); /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_tx_wake_all_queues(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_detach: tun_detach_all(dev); /* register_netdevice() already called tun_free_netdev() */ goto err_free_dev; err_free_flow: tun_flow_uninit(tun); security_tun_dev_free_security(tun->security); err_free_stat: free_percpu(tun->pcpu_stats); err_free_dev: free_netdev(dev); return err; } Commit Message: tun: allow positive return values on dev_get_valid_name() call If the name argument of dev_get_valid_name() contains "%d", it will try to assign it a unit number in __dev__alloc_name() and return either the unit number (>= 0) or an error code (< 0). Considering positive values as error values prevent tun device creations relying this mechanism, therefor we should only consider negative values as errors here. Signed-off-by: Julien Gomes <[email protected]> Acked-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); return; } PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); if (!data_bytes || !data_bytes->size()) return; print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); print_preview_ui->OnPreviewDataIsAvailable( params.expected_pages_count, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254 Target: 1 Example 2: Code: static MagickBooleanType InsertRow(int bpp,unsigned char *p,ssize_t y, Image *image) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); indexes=GetAuthenticIndexQueue(image); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { if ((image->storage_class != PseudoClass) || (indexes == (IndexPacket *) NULL)) break; for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); if (index < image->colors) SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1599 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame) { if (!targetFrame) return false; const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal(); for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) { Document* ancestorDocument = ancestorFrame->document(); if (!ancestorDocument) return true; const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin(); if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin)) return true; if (isLocalActiveOrigin && ancestorSecurityOrigin->isLocal()) return true; } return false; } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none [email protected], abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: seamless_process_line(const char *line, void *data) { UNUSED(data); char *p, *l; char *tok1, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8; unsigned long id, flags; char *endptr; l = xstrdup(line); p = l; logger(Core, Debug, "seamless_process_line(), got '%s'", p); tok1 = seamless_get_token(&p); (void) seamless_get_token(&p); tok3 = seamless_get_token(&p); tok4 = seamless_get_token(&p); tok5 = seamless_get_token(&p); tok6 = seamless_get_token(&p); tok7 = seamless_get_token(&p); tok8 = seamless_get_token(&p); if (!strcmp("CREATE", tok1)) { unsigned long group, parent; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; group = strtoul(tok4, &endptr, 0); if (*endptr) return False; parent = strtoul(tok5, &endptr, 0); if (*endptr) return False; flags = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_create_window(id, group, parent, flags); } else if (!strcmp("DESTROY", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_window(id, flags); } else if (!strcmp("DESTROYGRP", tok1)) { if (!tok4) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok4, &endptr, 0); if (*endptr) return False; ui_seamless_destroy_group(id, flags); } else if (!strcmp("SETICON", tok1)) { int chunk, width, height, len; char byte[3]; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; chunk = strtoul(tok4, &endptr, 0); if (*endptr) return False; width = strtoul(tok6, &endptr, 0); if (*endptr) return False; height = strtoul(tok7, &endptr, 0); if (*endptr) return False; byte[2] = '\0'; len = 0; while (*tok8 != '\0') { byte[0] = *tok8; tok8++; if (*tok8 == '\0') return False; byte[1] = *tok8; tok8++; icon_buf[len] = strtol(byte, NULL, 16); len++; } ui_seamless_seticon(id, tok5, width, height, chunk, icon_buf, len); } else if (!strcmp("DELICON", tok1)) { int width, height; if (!tok6) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; width = strtoul(tok5, &endptr, 0); if (*endptr) return False; height = strtoul(tok6, &endptr, 0); if (*endptr) return False; ui_seamless_delicon(id, tok4, width, height); } else if (!strcmp("POSITION", tok1)) { int x, y, width, height; if (!tok8) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; x = strtol(tok4, &endptr, 0); if (*endptr) return False; y = strtol(tok5, &endptr, 0); if (*endptr) return False; width = strtol(tok6, &endptr, 0); if (*endptr) return False; height = strtol(tok7, &endptr, 0); if (*endptr) return False; flags = strtoul(tok8, &endptr, 0); if (*endptr) return False; ui_seamless_move_window(id, x, y, width, height, flags); } else if (!strcmp("ZCHANGE", tok1)) { unsigned long behind; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; behind = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_restack_window(id, behind, flags); } else if (!strcmp("TITLE", tok1)) { if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_settitle(id, tok4, flags); } else if (!strcmp("STATE", tok1)) { unsigned int state; if (!tok5) return False; id = strtoul(tok3, &endptr, 0); if (*endptr) return False; state = strtoul(tok4, &endptr, 0); if (*endptr) return False; flags = strtoul(tok5, &endptr, 0); if (*endptr) return False; ui_seamless_setstate(id, state, flags); } else if (!strcmp("DEBUG", tok1)) { logger(Core, Debug, "seamless_process_line(), %s", line); } else if (!strcmp("SYNCBEGIN", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_syncbegin(flags); } else if (!strcmp("SYNCEND", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; /* do nothing, currently */ } else if (!strcmp("HELLO", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_begin(! !(flags & SEAMLESSRDP_HELLO_HIDDEN)); } else if (!strcmp("ACK", tok1)) { unsigned int serial; serial = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_ack(serial); } else if (!strcmp("HIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_hide_desktop(); } else if (!strcmp("UNHIDE", tok1)) { if (!tok3) return False; flags = strtoul(tok3, &endptr, 0); if (*endptr) return False; ui_seamless_unhide_desktop(); } xfree(l); return 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: 1 Example 2: Code: void Editor::RemoveFormattingAndStyle() { DCHECK(GetFrame().GetDocument()); RemoveFormatCommand::Create(*GetFrame().GetDocument())->Apply(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_get_objs (MyObject *obj, GPtrArray **objs, GError **error) { *objs = g_ptr_array_new (); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject")); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); 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: SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } } dPath = new SplashPath(); while (i < path->length) { for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; newPath = gTrue; for (k = i; k < j; ++k) { x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static int nfs4_delay(struct rpc_clnt *clnt, long *timeout) { int res = 0; might_sleep(); if (*timeout <= 0) *timeout = NFS4_POLL_RETRY_MIN; if (*timeout > NFS4_POLL_RETRY_MAX) *timeout = NFS4_POLL_RETRY_MAX; freezable_schedule_timeout_killable(*timeout); if (fatal_signal_pending(current)) res = -ERESTARTSYS; *timeout <<= 1; return res; } Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached _copy_from_pages() used to copy data from the temporary buffer to the user passed buffer is passed the wrong size parameter when copying data. res.acl_len contains both the bitmap and acl lenghts while acl_len contains the acl length after adjusting for the bitmap size. Signed-off-by: Sachin Prabhu <[email protected]> Signed-off-by: Trond Myklebust <[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: Browser* Browser::CreateForPopup(Type type, Profile* profile, TabContents* new_contents, const gfx::Rect& initial_bounds) { DCHECK(type & TYPE_POPUP); Browser* browser = new Browser(type, profile); browser->set_override_bounds(initial_bounds); browser->InitBrowserWindow(); TabContentsWrapper* wrapper = new TabContentsWrapper(new_contents); browser->tabstrip_model()->AppendTabContents(wrapper, true); return browser; } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, 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 bpf_jit_compile(struct sk_filter *fp) { u8 temp[64]; u8 *prog; unsigned int proglen, oldproglen = 0; int ilen, i; int t_offset, f_offset; u8 t_op, f_op, seen = 0, pass; u8 *image = NULL; u8 *func; int pc_ret0 = -1; /* bpf index of first RET #0 instruction (if any) */ unsigned int cleanup_addr; /* epilogue code offset */ unsigned int *addrs; const struct sock_filter *filter = fp->insns; int flen = fp->len; if (!bpf_jit_enable) return; addrs = kmalloc(flen * sizeof(*addrs), GFP_KERNEL); if (addrs == NULL) return; /* Before first pass, make a rough estimation of addrs[] * each bpf instruction is translated to less than 64 bytes */ for (proglen = 0, i = 0; i < flen; i++) { proglen += 64; addrs[i] = proglen; } cleanup_addr = proglen; /* epilogue address */ for (pass = 0; pass < 10; pass++) { /* no prologue/epilogue for trivial filters (RET something) */ proglen = 0; prog = temp; if (seen) { EMIT4(0x55, 0x48, 0x89, 0xe5); /* push %rbp; mov %rsp,%rbp */ EMIT4(0x48, 0x83, 0xec, 96); /* subq $96,%rsp */ /* note : must save %rbx in case bpf_error is hit */ if (seen & (SEEN_XREG | SEEN_DATAREF)) EMIT4(0x48, 0x89, 0x5d, 0xf8); /* mov %rbx, -8(%rbp) */ if (seen & SEEN_XREG) CLEAR_X(); /* make sure we dont leek kernel memory */ /* * If this filter needs to access skb data, * loads r9 and r8 with : * r9 = skb->len - skb->data_len * r8 = skb->data */ if (seen & SEEN_DATAREF) { if (offsetof(struct sk_buff, len) <= 127) /* mov off8(%rdi),%r9d */ EMIT4(0x44, 0x8b, 0x4f, offsetof(struct sk_buff, len)); else { /* mov off32(%rdi),%r9d */ EMIT3(0x44, 0x8b, 0x8f); EMIT(offsetof(struct sk_buff, len), 4); } if (is_imm8(offsetof(struct sk_buff, data_len))) /* sub off8(%rdi),%r9d */ EMIT4(0x44, 0x2b, 0x4f, offsetof(struct sk_buff, data_len)); else { EMIT3(0x44, 0x2b, 0x8f); EMIT(offsetof(struct sk_buff, data_len), 4); } if (is_imm8(offsetof(struct sk_buff, data))) /* mov off8(%rdi),%r8 */ EMIT4(0x4c, 0x8b, 0x47, offsetof(struct sk_buff, data)); else { /* mov off32(%rdi),%r8 */ EMIT3(0x4c, 0x8b, 0x87); EMIT(offsetof(struct sk_buff, data), 4); } } } switch (filter[0].code) { case BPF_S_RET_K: case BPF_S_LD_W_LEN: case BPF_S_ANC_PROTOCOL: case BPF_S_ANC_IFINDEX: case BPF_S_ANC_MARK: case BPF_S_ANC_RXHASH: case BPF_S_ANC_CPU: case BPF_S_ANC_QUEUE: case BPF_S_LD_W_ABS: case BPF_S_LD_H_ABS: case BPF_S_LD_B_ABS: /* first instruction sets A register (or is RET 'constant') */ break; default: /* make sure we dont leak kernel information to user */ CLEAR_A(); /* A = 0 */ } for (i = 0; i < flen; i++) { unsigned int K = filter[i].k; switch (filter[i].code) { case BPF_S_ALU_ADD_X: /* A += X; */ seen |= SEEN_XREG; EMIT2(0x01, 0xd8); /* add %ebx,%eax */ break; case BPF_S_ALU_ADD_K: /* A += K; */ if (!K) break; if (is_imm8(K)) EMIT3(0x83, 0xc0, K); /* add imm8,%eax */ else EMIT1_off32(0x05, K); /* add imm32,%eax */ break; case BPF_S_ALU_SUB_X: /* A -= X; */ seen |= SEEN_XREG; EMIT2(0x29, 0xd8); /* sub %ebx,%eax */ break; case BPF_S_ALU_SUB_K: /* A -= K */ if (!K) break; if (is_imm8(K)) EMIT3(0x83, 0xe8, K); /* sub imm8,%eax */ else EMIT1_off32(0x2d, K); /* sub imm32,%eax */ break; case BPF_S_ALU_MUL_X: /* A *= X; */ seen |= SEEN_XREG; EMIT3(0x0f, 0xaf, 0xc3); /* imul %ebx,%eax */ break; case BPF_S_ALU_MUL_K: /* A *= K */ if (is_imm8(K)) EMIT3(0x6b, 0xc0, K); /* imul imm8,%eax,%eax */ else { EMIT2(0x69, 0xc0); /* imul imm32,%eax */ EMIT(K, 4); } break; case BPF_S_ALU_DIV_X: /* A /= X; */ seen |= SEEN_XREG; EMIT2(0x85, 0xdb); /* test %ebx,%ebx */ if (pc_ret0 != -1) EMIT_COND_JMP(X86_JE, addrs[pc_ret0] - (addrs[i] - 4)); else { EMIT_COND_JMP(X86_JNE, 2 + 5); CLEAR_A(); EMIT1_off32(0xe9, cleanup_addr - (addrs[i] - 4)); /* jmp .+off32 */ } EMIT4(0x31, 0xd2, 0xf7, 0xf3); /* xor %edx,%edx; div %ebx */ break; case BPF_S_ALU_DIV_K: /* A = reciprocal_divide(A, K); */ EMIT3(0x48, 0x69, 0xc0); /* imul imm32,%rax,%rax */ EMIT(K, 4); EMIT4(0x48, 0xc1, 0xe8, 0x20); /* shr $0x20,%rax */ break; case BPF_S_ALU_AND_X: seen |= SEEN_XREG; EMIT2(0x21, 0xd8); /* and %ebx,%eax */ break; case BPF_S_ALU_AND_K: if (K >= 0xFFFFFF00) { EMIT2(0x24, K & 0xFF); /* and imm8,%al */ } else if (K >= 0xFFFF0000) { EMIT2(0x66, 0x25); /* and imm16,%ax */ EMIT2(K, 2); } else { EMIT1_off32(0x25, K); /* and imm32,%eax */ } break; case BPF_S_ALU_OR_X: seen |= SEEN_XREG; EMIT2(0x09, 0xd8); /* or %ebx,%eax */ break; case BPF_S_ALU_OR_K: if (is_imm8(K)) EMIT3(0x83, 0xc8, K); /* or imm8,%eax */ else EMIT1_off32(0x0d, K); /* or imm32,%eax */ break; case BPF_S_ALU_LSH_X: /* A <<= X; */ seen |= SEEN_XREG; EMIT4(0x89, 0xd9, 0xd3, 0xe0); /* mov %ebx,%ecx; shl %cl,%eax */ break; case BPF_S_ALU_LSH_K: if (K == 0) break; else if (K == 1) EMIT2(0xd1, 0xe0); /* shl %eax */ else EMIT3(0xc1, 0xe0, K); break; case BPF_S_ALU_RSH_X: /* A >>= X; */ seen |= SEEN_XREG; EMIT4(0x89, 0xd9, 0xd3, 0xe8); /* mov %ebx,%ecx; shr %cl,%eax */ break; case BPF_S_ALU_RSH_K: /* A >>= K; */ if (K == 0) break; else if (K == 1) EMIT2(0xd1, 0xe8); /* shr %eax */ else EMIT3(0xc1, 0xe8, K); break; case BPF_S_ALU_NEG: EMIT2(0xf7, 0xd8); /* neg %eax */ break; case BPF_S_RET_K: if (!K) { if (pc_ret0 == -1) pc_ret0 = i; CLEAR_A(); } else { EMIT1_off32(0xb8, K); /* mov $imm32,%eax */ } /* fallinto */ case BPF_S_RET_A: if (seen) { if (i != flen - 1) { EMIT_JMP(cleanup_addr - addrs[i]); break; } if (seen & SEEN_XREG) EMIT4(0x48, 0x8b, 0x5d, 0xf8); /* mov -8(%rbp),%rbx */ EMIT1(0xc9); /* leaveq */ } EMIT1(0xc3); /* ret */ break; case BPF_S_MISC_TAX: /* X = A */ seen |= SEEN_XREG; EMIT2(0x89, 0xc3); /* mov %eax,%ebx */ break; case BPF_S_MISC_TXA: /* A = X */ seen |= SEEN_XREG; EMIT2(0x89, 0xd8); /* mov %ebx,%eax */ break; case BPF_S_LD_IMM: /* A = K */ if (!K) CLEAR_A(); else EMIT1_off32(0xb8, K); /* mov $imm32,%eax */ break; case BPF_S_LDX_IMM: /* X = K */ seen |= SEEN_XREG; if (!K) CLEAR_X(); else EMIT1_off32(0xbb, K); /* mov $imm32,%ebx */ break; case BPF_S_LD_MEM: /* A = mem[K] : mov off8(%rbp),%eax */ seen |= SEEN_MEM; EMIT3(0x8b, 0x45, 0xf0 - K*4); break; case BPF_S_LDX_MEM: /* X = mem[K] : mov off8(%rbp),%ebx */ seen |= SEEN_XREG | SEEN_MEM; EMIT3(0x8b, 0x5d, 0xf0 - K*4); break; case BPF_S_ST: /* mem[K] = A : mov %eax,off8(%rbp) */ seen |= SEEN_MEM; EMIT3(0x89, 0x45, 0xf0 - K*4); break; case BPF_S_STX: /* mem[K] = X : mov %ebx,off8(%rbp) */ seen |= SEEN_XREG | SEEN_MEM; EMIT3(0x89, 0x5d, 0xf0 - K*4); break; case BPF_S_LD_W_LEN: /* A = skb->len; */ BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4); if (is_imm8(offsetof(struct sk_buff, len))) /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, len)); else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, len), 4); } break; case BPF_S_LDX_W_LEN: /* X = skb->len; */ seen |= SEEN_XREG; if (is_imm8(offsetof(struct sk_buff, len))) /* mov off8(%rdi),%ebx */ EMIT3(0x8b, 0x5f, offsetof(struct sk_buff, len)); else { EMIT2(0x8b, 0x9f); EMIT(offsetof(struct sk_buff, len), 4); } break; case BPF_S_ANC_PROTOCOL: /* A = ntohs(skb->protocol); */ BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2); if (is_imm8(offsetof(struct sk_buff, protocol))) { /* movzwl off8(%rdi),%eax */ EMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, protocol)); } else { EMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */ EMIT(offsetof(struct sk_buff, protocol), 4); } EMIT2(0x86, 0xc4); /* ntohs() : xchg %al,%ah */ break; case BPF_S_ANC_IFINDEX: if (is_imm8(offsetof(struct sk_buff, dev))) { /* movq off8(%rdi),%rax */ EMIT4(0x48, 0x8b, 0x47, offsetof(struct sk_buff, dev)); } else { EMIT3(0x48, 0x8b, 0x87); /* movq off32(%rdi),%rax */ EMIT(offsetof(struct sk_buff, dev), 4); } EMIT3(0x48, 0x85, 0xc0); /* test %rax,%rax */ EMIT_COND_JMP(X86_JE, cleanup_addr - (addrs[i] - 6)); BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4); EMIT2(0x8b, 0x80); /* mov off32(%rax),%eax */ EMIT(offsetof(struct net_device, ifindex), 4); break; case BPF_S_ANC_MARK: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4); if (is_imm8(offsetof(struct sk_buff, mark))) { /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, mark)); } else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, mark), 4); } break; case BPF_S_ANC_RXHASH: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, rxhash) != 4); if (is_imm8(offsetof(struct sk_buff, rxhash))) { /* mov off8(%rdi),%eax */ EMIT3(0x8b, 0x47, offsetof(struct sk_buff, rxhash)); } else { EMIT2(0x8b, 0x87); EMIT(offsetof(struct sk_buff, rxhash), 4); } break; case BPF_S_ANC_QUEUE: BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2); if (is_imm8(offsetof(struct sk_buff, queue_mapping))) { /* movzwl off8(%rdi),%eax */ EMIT4(0x0f, 0xb7, 0x47, offsetof(struct sk_buff, queue_mapping)); } else { EMIT3(0x0f, 0xb7, 0x87); /* movzwl off32(%rdi),%eax */ EMIT(offsetof(struct sk_buff, queue_mapping), 4); } break; case BPF_S_ANC_CPU: #ifdef CONFIG_SMP EMIT4(0x65, 0x8b, 0x04, 0x25); /* mov %gs:off32,%eax */ EMIT((u32)(unsigned long)&cpu_number, 4); /* A = smp_processor_id(); */ #else CLEAR_A(); #endif break; case BPF_S_LD_W_ABS: func = sk_load_word; common_load: seen |= SEEN_DATAREF; if ((int)K < 0) goto out; t_offset = func - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call */ break; case BPF_S_LD_H_ABS: func = sk_load_half; goto common_load; case BPF_S_LD_B_ABS: func = sk_load_byte; goto common_load; case BPF_S_LDX_B_MSH: if ((int)K < 0) { if (pc_ret0 != -1) { EMIT_JMP(addrs[pc_ret0] - addrs[i]); break; } CLEAR_A(); EMIT_JMP(cleanup_addr - addrs[i]); break; } seen |= SEEN_DATAREF | SEEN_XREG; t_offset = sk_load_byte_msh - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call sk_load_byte_msh */ break; case BPF_S_LD_W_IND: func = sk_load_word_ind; common_load_ind: seen |= SEEN_DATAREF | SEEN_XREG; t_offset = func - (image + addrs[i]); EMIT1_off32(0xbe, K); /* mov imm32,%esi */ EMIT1_off32(0xe8, t_offset); /* call sk_load_xxx_ind */ break; case BPF_S_LD_H_IND: func = sk_load_half_ind; goto common_load_ind; case BPF_S_LD_B_IND: func = sk_load_byte_ind; goto common_load_ind; case BPF_S_JMP_JA: t_offset = addrs[i + K] - addrs[i]; EMIT_JMP(t_offset); break; COND_SEL(BPF_S_JMP_JGT_K, X86_JA, X86_JBE); COND_SEL(BPF_S_JMP_JGE_K, X86_JAE, X86_JB); COND_SEL(BPF_S_JMP_JEQ_K, X86_JE, X86_JNE); COND_SEL(BPF_S_JMP_JSET_K,X86_JNE, X86_JE); COND_SEL(BPF_S_JMP_JGT_X, X86_JA, X86_JBE); COND_SEL(BPF_S_JMP_JGE_X, X86_JAE, X86_JB); COND_SEL(BPF_S_JMP_JEQ_X, X86_JE, X86_JNE); COND_SEL(BPF_S_JMP_JSET_X,X86_JNE, X86_JE); cond_branch: f_offset = addrs[i + filter[i].jf] - addrs[i]; t_offset = addrs[i + filter[i].jt] - addrs[i]; /* same targets, can avoid doing the test :) */ if (filter[i].jt == filter[i].jf) { EMIT_JMP(t_offset); break; } switch (filter[i].code) { case BPF_S_JMP_JGT_X: case BPF_S_JMP_JGE_X: case BPF_S_JMP_JEQ_X: seen |= SEEN_XREG; EMIT2(0x39, 0xd8); /* cmp %ebx,%eax */ break; case BPF_S_JMP_JSET_X: seen |= SEEN_XREG; EMIT2(0x85, 0xd8); /* test %ebx,%eax */ break; case BPF_S_JMP_JEQ_K: if (K == 0) { EMIT2(0x85, 0xc0); /* test %eax,%eax */ break; } case BPF_S_JMP_JGT_K: case BPF_S_JMP_JGE_K: if (K <= 127) EMIT3(0x83, 0xf8, K); /* cmp imm8,%eax */ else EMIT1_off32(0x3d, K); /* cmp imm32,%eax */ break; case BPF_S_JMP_JSET_K: if (K <= 0xFF) EMIT2(0xa8, K); /* test imm8,%al */ else if (!(K & 0xFFFF00FF)) EMIT3(0xf6, 0xc4, K >> 8); /* test imm8,%ah */ else if (K <= 0xFFFF) { EMIT2(0x66, 0xa9); /* test imm16,%ax */ EMIT(K, 2); } else { EMIT1_off32(0xa9, K); /* test imm32,%eax */ } break; } if (filter[i].jt != 0) { if (filter[i].jf) t_offset += is_near(f_offset) ? 2 : 6; EMIT_COND_JMP(t_op, t_offset); if (filter[i].jf) EMIT_JMP(f_offset); break; } EMIT_COND_JMP(f_op, f_offset); break; default: /* hmm, too complex filter, give up with jit compiler */ goto out; } ilen = prog - temp; if (image) { if (unlikely(proglen + ilen > oldproglen)) { pr_err("bpb_jit_compile fatal error\n"); kfree(addrs); module_free(NULL, image); return; } memcpy(image + proglen, temp, ilen); } proglen += ilen; addrs[i] = proglen; prog = temp; } /* last bpf instruction is always a RET : * use it to give the cleanup instruction(s) addr */ cleanup_addr = proglen - 1; /* ret */ if (seen) cleanup_addr -= 1; /* leaveq */ if (seen & SEEN_XREG) cleanup_addr -= 4; /* mov -8(%rbp),%rbx */ if (image) { WARN_ON(proglen != oldproglen); break; } if (proglen == oldproglen) { image = module_alloc(max_t(unsigned int, proglen, sizeof(struct work_struct))); if (!image) goto out; } oldproglen = proglen; } if (bpf_jit_enable > 1) pr_err("flen=%d proglen=%u pass=%d image=%p\n", flen, proglen, pass, image); if (image) { if (bpf_jit_enable > 1) print_hex_dump(KERN_ERR, "JIT code: ", DUMP_PREFIX_ADDRESS, 16, 1, image, proglen, false); bpf_flush_icache(image, image + proglen); fp->bpf_func = (void *)image; } out: kfree(addrs); return; } Commit Message: net: bpf_jit: fix an off-one bug in x86_64 cond jump target x86 jump instruction size is 2 or 5 bytes (near/long jump), not 2 or 6 bytes. In case a conditional jump is followed by a long jump, conditional jump target is one byte past the start of target instruction. Signed-off-by: Markus Kötter <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: void WebGLRenderingContextBase::vertexAttrib2f(GLuint index, GLfloat v0, GLfloat v1) { if (isContextLost()) return; ContextGL()->VertexAttrib2f(index, v0, v1); SetVertexAttribType(index, kFloat32ArrayType); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; uint32_t hot_age; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtoul(tokens[4].value, &hot_age) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0) { out_string(c, "ERROR cold age factor must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_age = hot_age; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 3 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 3 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } 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 Output:
0
Here are some example code snippets. Analyze the following code, 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 *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ 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. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(long algo) { /* {{{ */ switch (algo) { #ifndef OPENSSL_NO_RC2 case PHP_OPENSSL_CIPHER_RC2_40: return EVP_rc2_40_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_64: return EVP_rc2_64_cbc(); break; case PHP_OPENSSL_CIPHER_RC2_128: return EVP_rc2_cbc(); break; #endif #ifndef OPENSSL_NO_DES case PHP_OPENSSL_CIPHER_DES: return EVP_des_cbc(); break; case PHP_OPENSSL_CIPHER_3DES: return EVP_des_ede3_cbc(); break; #endif default: return NULL; break; } } /* }}} */ Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int print_udev_ambivalent(blkid_probe pr) { char *val = NULL; size_t valsz = 0; int count = 0, rc = -1; while (!blkid_do_probe(pr)) { const char *usage_txt = NULL, *type = NULL, *version = NULL; char enc[256]; blkid_probe_lookup_value(pr, "USAGE", &usage_txt, NULL); blkid_probe_lookup_value(pr, "TYPE", &type, NULL); blkid_probe_lookup_value(pr, "VERSION", &version, NULL); if (!usage_txt || !type) continue; blkid_encode_string(usage_txt, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, ":")) goto done; blkid_encode_string(type, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, version ? ":" : " ")) goto done; if (version) { blkid_encode_string(version, enc, sizeof(enc)); if (append_str(&val, &valsz, enc, " ")) goto done; } count++; } if (count > 1) { *(val + valsz - 1) = '\0'; /* rem tailing whitespace */ printf("ID_FS_AMBIVALENT=%s\n", val); rc = 0; } done: free(val); return rc; } Commit Message: libblkid: care about unsafe chars in cache The high-level libblkid API uses /run/blkid/blkid.tab cache to store probing results. The cache format is <device NAME="value" ...>devname</device> and unfortunately the cache code does not escape quotation marks: # mkfs.ext4 -L 'AAA"BBB' # cat /run/blkid/blkid.tab ... <device ... LABEL="AAA"BBB" ...>/dev/sdb1</device> such string is later incorrectly parsed and blkid(8) returns nonsenses. And for use-cases like # eval $(blkid -o export /dev/sdb1) it's also insecure. Note that mount, udevd and blkid -p are based on low-level libblkid API, it bypass the cache and directly read data from the devices. The current udevd upstream does not depend on blkid(8) output at all, it's directly linked with the library and all unsafe chars are encoded by \x<hex> notation. # mkfs.ext4 -L 'X"`/tmp/foo` "' /dev/sdb1 # udevadm info --export-db | grep LABEL ... E: ID_FS_LABEL=X__/tmp/foo___ E: ID_FS_LABEL_ENC=X\x22\x60\x2ftmp\x2ffoo\x60\x20\x22 Signed-off-by: Karel Zak <[email protected]> CWE ID: CWE-77 Output:
0
Here are some example code snippets. Analyze the following code, 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 GpuVideoDecodeAccelerator::OnDecode( base::SharedMemoryHandle handle, int32 id, int32 size) { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size)); } Commit Message: Sizes going across an IPC should be uint32. BUG=164946 Review URL: https://chromiumcodereview.appspot.com/11472038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: void Document::SetReadyState(DocumentReadyState ready_state) { if (ready_state == ready_state_) return; switch (ready_state) { case kLoading: if (document_timing_.DomLoading().is_null()) { document_timing_.MarkDomLoading(); } break; case kInteractive: if (document_timing_.DomInteractive().is_null()) document_timing_.MarkDomInteractive(); break; case kComplete: if (document_timing_.DomComplete().is_null()) document_timing_.MarkDomComplete(); break; } ready_state_ = ready_state; DispatchEvent(Event::Create(EventTypeNames::readystatechange)); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int get_ip_port(char *iface, char *ip, const int ipsize) { char *host; char *ptr; int port = -1; struct in_addr addr; host = strdup(iface); if (!host) return -1; ptr = strchr(host, ':'); if (!ptr) goto out; *ptr++ = 0; if (!inet_aton(host, &addr)) goto out; /* XXX resolve hostname */ assert(strlen(host) <= 15); strncpy(ip, host, ipsize); port = atoi(ptr); out: free(host); return port; } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: connection_exit_begin_conn(cell_t *cell, circuit_t *circ) { edge_connection_t *n_stream; relay_header_t rh; char *address = NULL; uint16_t port = 0; or_circuit_t *or_circ = NULL; const or_options_t *options = get_options(); begin_cell_t bcell; int rv; uint8_t end_reason=0; assert_circuit_ok(circ); if (!CIRCUIT_IS_ORIGIN(circ)) or_circ = TO_OR_CIRCUIT(circ); relay_header_unpack(&rh, cell->payload); if (rh.length > RELAY_PAYLOAD_SIZE) return -END_CIRC_REASON_TORPROTOCOL; /* Note: we have to use relay_send_command_from_edge here, not * connection_edge_end or connection_edge_send_command, since those require * that we have a stream connected to a circuit, and we don't connect to a * circuit until we have a pending/successful resolve. */ if (!server_mode(options) && circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay begin cell at non-server. Closing."); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_EXITPOLICY, NULL); return 0; } rv = begin_cell_parse(cell, &bcell, &end_reason); if (rv < -1) { return -END_CIRC_REASON_TORPROTOCOL; } else if (rv == -1) { tor_free(bcell.address); relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL); return 0; } if (! bcell.is_begindir) { /* Steal reference */ address = bcell.address; port = bcell.port; if (or_circ && or_circ->p_chan) { if (!options->AllowSingleHopExits && (or_circ->is_first_hop || (!connection_or_digest_is_known_relay( or_circ->p_chan->identity_digest) && should_refuse_unknown_exits(options)))) { /* Don't let clients use us as a single-hop proxy, unless the user * has explicitly allowed that in the config. It attracts attackers * and users who'd be better off with, well, single-hop proxies. */ log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Attempt by %s to open a stream %s. Closing.", safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)), or_circ->is_first_hop ? "on first hop of circuit" : "from unknown relay"); relay_send_end_cell_from_edge(rh.stream_id, circ, or_circ->is_first_hop ? END_STREAM_REASON_TORPROTOCOL : END_STREAM_REASON_MISC, NULL); tor_free(address); return 0; } } } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) { if (!directory_permits_begindir_requests(options) || circ->purpose != CIRCUIT_PURPOSE_OR) { relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_NOTDIRECTORY, NULL); return 0; } /* Make sure to get the 'real' address of the previous hop: the * caller might want to know whether the remote IP address has changed, * and we might already have corrected base_.addr[ess] for the relay's * canonical IP address. */ if (or_circ && or_circ->p_chan) address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan)); else address = tor_strdup("127.0.0.1"); port = 1; /* XXXX This value is never actually used anywhere, and there * isn't "really" a connection here. But we * need to set it to something nonzero. */ } else { log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_INTERNAL, NULL); return 0; } if (! options->IPv6Exit) { /* I don't care if you prefer IPv6; I can't give you any. */ bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED; /* If you don't want IPv4, I can't help. */ if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) { tor_free(address); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_EXITPOLICY, NULL); return 0; } } log_debug(LD_EXIT,"Creating new exit connection."); /* The 'AF_INET' here is temporary; we might need to change it later in * connection_exit_connect(). */ n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET); /* Remember the tunneled request ID in the new edge connection, so that * we can measure download times. */ n_stream->dirreq_id = circ->dirreq_id; n_stream->base_.purpose = EXIT_PURPOSE_CONNECT; n_stream->begincell_flags = bcell.flags; n_stream->stream_id = rh.stream_id; n_stream->base_.port = port; /* leave n_stream->s at -1, because it's not yet valid */ n_stream->package_window = STREAMWINDOW_START; n_stream->deliver_window = STREAMWINDOW_START; if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) { origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ); log_info(LD_REND,"begin is for rendezvous. configuring stream."); n_stream->base_.address = tor_strdup("(rendezvous)"); n_stream->base_.state = EXIT_CONN_STATE_CONNECTING; n_stream->rend_data = rend_data_dup(origin_circ->rend_data); tor_assert(connection_edge_is_rendezvous_stream(n_stream)); assert_circuit_ok(circ); const int r = rend_service_set_connection_addr_port(n_stream, origin_circ); if (r < 0) { log_info(LD_REND,"Didn't find rendezvous service (port %d)", n_stream->base_.port); /* Send back reason DONE because we want to make hidden service port * scanning harder thus instead of returning that the exit policy * didn't match, which makes it obvious that the port is closed, * return DONE and kill the circuit. That way, a user (malicious or * not) needs one circuit per bad port unless it matches the policy of * the hidden service. */ relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_DONE, origin_circ->cpath->prev); connection_free(TO_CONN(n_stream)); tor_free(address); /* Drop the circuit here since it might be someone deliberately * scanning the hidden service ports. Note that this mitigates port * scanning by adding more work on the attacker side to successfully * scan but does not fully solve it. */ if (r < -1) return END_CIRC_AT_ORIGIN; else return 0; } assert_circuit_ok(circ); log_debug(LD_REND,"Finished assigning addr/port"); n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */ /* add it into the linked list of p_streams on this circuit */ n_stream->next_stream = origin_circ->p_streams; n_stream->on_circuit = circ; origin_circ->p_streams = n_stream; assert_circuit_ok(circ); origin_circ->rend_data->nr_streams++; connection_exit_connect(n_stream); /* For path bias: This circuit was used successfully */ pathbias_mark_use_success(origin_circ); tor_free(address); return 0; } tor_strlower(address); n_stream->base_.address = address; n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED; /* default to failed, change in dns_resolve if it turns out not to fail */ if (we_are_hibernating()) { relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_HIBERNATING, NULL); connection_free(TO_CONN(n_stream)); return 0; } n_stream->on_circuit = circ; if (rh.command == RELAY_COMMAND_BEGIN_DIR) { tor_addr_t tmp_addr; tor_assert(or_circ); if (or_circ->p_chan && channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) { tor_addr_copy(&n_stream->base_.addr, &tmp_addr); } return connection_exit_connect_dir(n_stream); } log_debug(LD_EXIT,"about to start the dns_resolve()."); /* send it off to the gethostbyname farm */ switch (dns_resolve(n_stream)) { case 1: /* resolve worked; now n_stream is attached to circ. */ assert_circuit_ok(circ); log_debug(LD_EXIT,"about to call connection_exit_connect()."); connection_exit_connect(n_stream); return 0; case -1: /* resolve failed */ relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_RESOLVEFAILED, NULL); /* n_stream got freed. don't touch it. */ break; case 0: /* resolve added to pending list */ assert_circuit_ok(circ); break; } return 0; } Commit Message: TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_ This fixes an assertion failure in relay_send_end_cell_from_edge_() when an origin circuit and a cpath_layer = NULL were passed. A service rendezvous circuit could do such a thing when a malformed BEGIN cell is received but shouldn't in the first place because the service needs to send an END cell on the circuit for which it can not do without a cpath_layer. Fixes #22493 Reported-by: Roger Dingledine <[email protected]> Signed-off-by: David Goulet <[email protected]> CWE ID: CWE-617 Target: 1 Example 2: Code: LocalSiteCharacteristicsWebContentsObserver( content::WebContents* web_contents) : content::WebContentsObserver(web_contents) { if (!g_skip_observer_registration_for_testing) { DCHECK(PageSignalReceiver::IsEnabled()); TabLoadTracker::Get()->AddObserver(this); PageSignalReceiver::GetInstance()->AddObserver(this); } } 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: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 LayoutSVGViewportContainer::calculateLocalTransform() { if (!m_needsTransformUpdate) return false; m_localToParentTransform = AffineTransform::translation(m_viewport.x(), m_viewport.y()) * viewportTransform(); m_needsTransformUpdate = false; return true; } Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers Currently, SVG containers in the LayoutObject hierarchy force layout of their children if the transform changes. The main reason for this is to trigger paint invalidation of the subtree. In some cases - changes to the scale factor - there are other reasons to trigger layout, like computing a new scale factor for <text> or re-layout nodes with non-scaling stroke. Compute a "scale-factor change" in addition to the "transform change" already computed, then use this new signal to determine if layout should be forced for the subtree. Trigger paint invalidation using the LayoutObject flags instead. The downside to this is that paint invalidation will walk into "hidden" containers which rarely require repaint (since they are not technically visible). This will hopefully be rectified in a follow-up CL. For the testcase from 603850, this essentially eliminates the cost of layout (from ~350ms to ~0ms on authors machine; layout cost is related to text metrics recalculation), bumping frame rate significantly. BUG=603956,603850 Review-Url: https://codereview.chromium.org/1996543002 Cr-Commit-Position: refs/heads/master@{#400950} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void nsc_rle_decompress_data(NSC_CONTEXT* context) { UINT16 i; BYTE* rle; UINT32 planeSize; UINT32 originalSize; rle = context->Planes; for (i = 0; i < 4; i++) { originalSize = context->OrgByteCount[i]; planeSize = context->PlaneByteCount[i]; if (planeSize == 0) FillMemory(context->priv->PlaneBuffers[i], originalSize, 0xFF); else if (planeSize < originalSize) nsc_rle_decode(rle, context->priv->PlaneBuffers[i], originalSize); else CopyMemory(context->priv->PlaneBuffers[i], rle, originalSize); rle += planeSize; } } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787 Target: 1 Example 2: Code: static long kvm_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; struct kvm_fpu *fpu = NULL; struct kvm_sregs *kvm_sregs = NULL; if (vcpu->kvm->mm != current->mm) return -EIO; #if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS) /* * Special cases: vcpu ioctls that are asynchronous to vcpu execution, * so vcpu_load() would break it. */ if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT) return kvm_arch_vcpu_ioctl(filp, ioctl, arg); #endif r = vcpu_load(vcpu); if (r) return r; switch (ioctl) { case KVM_RUN: r = -EINVAL; if (arg) goto out; r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run); trace_kvm_userspace_exit(vcpu->run->exit_reason, r); break; case KVM_GET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); if (!kvm_regs) goto out; r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); if (r) goto out_free1; r = -EFAULT; if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) goto out_free1; r = 0; out_free1: kfree(kvm_regs); break; } case KVM_SET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = memdup_user(argp, sizeof(*kvm_regs)); if (IS_ERR(kvm_regs)) { r = PTR_ERR(kvm_regs); goto out; } r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); kfree(kvm_regs); break; } case KVM_GET_SREGS: { kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); r = -ENOMEM; if (!kvm_sregs) goto out; r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) goto out; r = 0; break; } case KVM_SET_SREGS: { kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs)); if (IS_ERR(kvm_sregs)) { r = PTR_ERR(kvm_sregs); kvm_sregs = NULL; goto out; } r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); break; } case KVM_GET_MP_STATE: { struct kvm_mp_state mp_state; r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &mp_state, sizeof mp_state)) goto out; r = 0; break; } case KVM_SET_MP_STATE: { struct kvm_mp_state mp_state; r = -EFAULT; if (copy_from_user(&mp_state, argp, sizeof mp_state)) goto out; r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); break; } case KVM_TRANSLATE: { struct kvm_translation tr; r = -EFAULT; if (copy_from_user(&tr, argp, sizeof tr)) goto out; r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tr, sizeof tr)) goto out; r = 0; break; } case KVM_SET_GUEST_DEBUG: { struct kvm_guest_debug dbg; r = -EFAULT; if (copy_from_user(&dbg, argp, sizeof dbg)) goto out; r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); break; } case KVM_SET_SIGNAL_MASK: { struct kvm_signal_mask __user *sigmask_arg = argp; struct kvm_signal_mask kvm_sigmask; sigset_t sigset, *p; p = NULL; if (argp) { r = -EFAULT; if (copy_from_user(&kvm_sigmask, argp, sizeof kvm_sigmask)) goto out; r = -EINVAL; if (kvm_sigmask.len != sizeof sigset) goto out; r = -EFAULT; if (copy_from_user(&sigset, sigmask_arg->sigset, sizeof sigset)) goto out; p = &sigset; } r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); break; } case KVM_GET_FPU: { fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); r = -ENOMEM; if (!fpu) goto out; r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) goto out; r = 0; break; } case KVM_SET_FPU: { fpu = memdup_user(argp, sizeof(*fpu)); if (IS_ERR(fpu)) { r = PTR_ERR(fpu); fpu = NULL; goto out; } r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); break; } default: r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); } out: vcpu_put(vcpu); kfree(fpu); kfree(kvm_sregs); return r; } Commit Message: KVM: Improve create VCPU parameter (CVE-2013-4587) In multiple functions the vcpu_id is used as an offset into a bitfield. Ag malicious user could specify a vcpu_id greater than 255 in order to set or clear bits in kernel memory. This could be used to elevate priveges in the kernel. This patch verifies that the vcpu_id provided is less than 255. The api documentation already specifies that the vcpu_id must be less than max_vcpus, but this is currently not checked. Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: StatisticsRecorderTest() : use_persistent_histogram_allocator_(GetParam()) { PersistentHistogramAllocator::GetCreateHistogramResultHistogram(); InitializeStatisticsRecorder(); if (use_persistent_histogram_allocator_) { GlobalHistogramAllocator::CreateWithLocalMemory(kAllocatorMemorySize, 0, "StatisticsRecorderTest"); } } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: CoordinatorImpl::CoordinatorImpl(service_manager::Connector* connector) : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)) { process_map_ = std::make_unique<ProcessMap>(connector); DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( mojom::kServiceTracingProcessId); tracing_observer_ = std::make_unique<TracingObserver>( base::trace_event::TraceLog::GetInstance(), nullptr); } 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 Target: 1 Example 2: Code: static void dump_error_msg(struct nl_msg *msg, FILE *ofd) { struct nlmsghdr *hdr = nlmsg_hdr(msg); struct nlmsgerr *err = nlmsg_data(hdr); fprintf(ofd, " [ERRORMSG] %zu octets\n", sizeof(*err)); if (nlmsg_len(hdr) >= sizeof(*err)) { struct nl_msg *errmsg; fprintf(ofd, " .error = %d \"%s\"\n", err->error, nl_strerror_l(-err->error)); fprintf(ofd, " [ORIGINAL MESSAGE] %zu octets\n", sizeof(*hdr)); errmsg = nlmsg_inherit(&err->msg); print_hdr(ofd, errmsg); nlmsg_free(errmsg); } } Commit Message: 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: getHTTPResponse(int s, int * size) { char buf[2048]; int n; int endofheaders = 0; int chunked = 0; int content_length = -1; unsigned int chunksize = 0; unsigned int bytestocopy = 0; /* buffers : */ char * header_buf; unsigned int header_buf_len = 2048; unsigned int header_buf_used = 0; char * content_buf; unsigned int content_buf_len = 2048; unsigned int content_buf_used = 0; char chunksize_buf[32]; unsigned int chunksize_buf_index; header_buf = malloc(header_buf_len); content_buf = malloc(content_buf_len); chunksize_buf[0] = '\0'; chunksize_buf_index = 0; while((n = receivedata(s, buf, 2048, 5000, NULL)) > 0) { if(endofheaders == 0) { int i; int linestart=0; int colon=0; int valuestart=0; if(header_buf_used + n > header_buf_len) { header_buf = realloc(header_buf, header_buf_used + n); header_buf_len = header_buf_used + n; } memcpy(header_buf + header_buf_used, buf, n); header_buf_used += n; /* search for CR LF CR LF (end of headers) * recognize also LF LF */ i = 0; while(i < ((int)header_buf_used-1) && (endofheaders == 0)) { if(header_buf[i] == '\r') { i++; if(header_buf[i] == '\n') { i++; if(i < (int)header_buf_used && header_buf[i] == '\r') { i++; if(i < (int)header_buf_used && header_buf[i] == '\n') { endofheaders = i+1; } } } } else if(header_buf[i] == '\n') { i++; if(header_buf[i] == '\n') { endofheaders = i+1; } } i++; } if(endofheaders == 0) continue; /* parse header lines */ for(i = 0; i < endofheaders - 1; i++) { if(colon <= linestart && header_buf[i]==':') { colon = i; while(i < (endofheaders-1) && (header_buf[i+1] == ' ' || header_buf[i+1] == '\t')) i++; valuestart = i + 1; } /* detecting end of line */ else if(header_buf[i]=='\r' || header_buf[i]=='\n') { if(colon > linestart && valuestart > colon) { #ifdef DEBUG printf("header='%.*s', value='%.*s'\n", colon-linestart, header_buf+linestart, i-valuestart, header_buf+valuestart); #endif if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart)) { content_length = atoi(header_buf+valuestart); #ifdef DEBUG printf("Content-Length: %d\n", content_length); #endif } else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart) && 0==strncasecmp(header_buf+valuestart, "chunked", 7)) { #ifdef DEBUG printf("chunked transfer-encoding!\n"); #endif chunked = 1; } } while(header_buf[i]=='\r' || header_buf[i] == '\n') i++; linestart = i; colon = linestart; valuestart = 0; } } /* copy the remaining of the received data back to buf */ n = header_buf_used - endofheaders; memcpy(buf, header_buf + endofheaders, n); /* if(headers) */ } if(endofheaders) { /* content */ if(chunked) { int i = 0; while(i < n) { if(chunksize == 0) { /* reading chunk size */ if(chunksize_buf_index == 0) { /* skipping any leading CR LF */ if(i<n && buf[i] == '\r') i++; if(i<n && buf[i] == '\n') i++; } while(i<n && isxdigit(buf[i]) && chunksize_buf_index < (sizeof(chunksize_buf)-1)) { chunksize_buf[chunksize_buf_index++] = buf[i]; chunksize_buf[chunksize_buf_index] = '\0'; i++; } while(i<n && buf[i] != '\r' && buf[i] != '\n') i++; /* discarding chunk-extension */ if(i<n && buf[i] == '\r') i++; if(i<n && buf[i] == '\n') { unsigned int j; for(j = 0; j < chunksize_buf_index; j++) { if(chunksize_buf[j] >= '0' && chunksize_buf[j] <= '9') chunksize = (chunksize << 4) + (chunksize_buf[j] - '0'); else chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10); } chunksize_buf[0] = '\0'; chunksize_buf_index = 0; i++; } else { /* not finished to get chunksize */ continue; } #ifdef DEBUG printf("chunksize = %u (%x)\n", chunksize, chunksize); #endif if(chunksize == 0) { #ifdef DEBUG printf("end of HTTP content - %d %d\n", i, n); /*printf("'%.*s'\n", n-i, buf+i);*/ #endif goto end_of_stream; } } bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i); if((content_buf_used + bytestocopy) > content_buf_len) { if(content_length >= (int)(content_buf_used + bytestocopy)) { content_buf_len = content_length; } else { content_buf_len = content_buf_used + bytestocopy; } content_buf = (char *)realloc((void *)content_buf, content_buf_len); } memcpy(content_buf + content_buf_used, buf + i, bytestocopy); content_buf_used += bytestocopy; i += bytestocopy; chunksize -= bytestocopy; } } else { /* not chunked */ if(content_length > 0 && (int)(content_buf_used + n) > content_length) { /* skipping additional bytes */ n = content_length - content_buf_used; } if(content_buf_used + n > content_buf_len) { if(content_length >= (int)(content_buf_used + n)) { content_buf_len = content_length; } else { content_buf_len = content_buf_used + n; } content_buf = (char *)realloc((void *)content_buf, content_buf_len); } memcpy(content_buf + content_buf_used, buf, n); content_buf_used += n; } } /* use the Content-Length header value if available */ if(content_length > 0 && (int)content_buf_used >= content_length) { #ifdef DEBUG printf("End of HTTP content\n"); #endif break; } } end_of_stream: free(header_buf); header_buf = NULL; *size = content_buf_used; if(content_buf_used == 0) { free(content_buf); content_buf = NULL; } return content_buf; } Commit Message: miniwget.c: fixed potential buffer overrun 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 gdImageWBMPCtx (gdImagePtr image, int fg, gdIOCtx * out) { int x, y, pos; Wbmp *wbmp; /* create the WBMP */ if ((wbmp = createwbmp (gdImageSX (image), gdImageSY (image), WBMP_WHITE)) == NULL) { gd_error("Could not create WBMP"); return; } /* fill up the WBMP structure */ pos = 0; for (y = 0; y < gdImageSY(image); y++) { for (x = 0; x < gdImageSX(image); x++) { if (gdImageGetPixel (image, x, y) == fg) { wbmp->bitmap[pos] = WBMP_BLACK; } pos++; } } /* write the WBMP to a gd file descriptor */ if (writewbmp (wbmp, &gd_putout, out)) { gd_error("Could not save WBMP"); } /* des submitted this bugfix: gdFree the memory. */ freewbmp(wbmp); } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415 Target: 1 Example 2: Code: bool Plugin::HasProperty(const nacl::string& prop_name) { PLUGIN_PRINTF(("Plugin::HasProperty (prop_name=%s)\n", prop_name.c_str())); return property_getters_[prop_name] != NULL; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int limiting_can_increase_treesame(const struct rev_info *revs) { /* * TREESAME is irrelevant unless prune && dense; * if simplify_history is set, we can't have a mixture of TREESAME and * !TREESAME INTERESTING parents (and we don't have treesame[] * decoration anyway); * if first_parent_only is set, then the TREESAME flag is locked * against the first parent (and again we lack treesame[] decoration). */ return revs->prune && revs->dense && !revs->simplify_history && !revs->first_parent_only; } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ssl_scan_serverhello_tlsext(SSL *s, PACKET *pkt, int *al) { unsigned int length, type, size; int tlsext_servername = 0; int renegotiate_seen = 0; #ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; #endif s->tlsext_ticket_expected = 0; OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; #ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_DTLSEXT_HB_ENABLED | SSL_DTLSEXT_HB_DONT_SEND_REQUESTS); #endif s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC; s->s3->flags &= ~TLS1_FLAGS_RECEIVED_EXTMS; if (!PACKET_get_net_2(pkt, &length)) goto ri_check; if (PACKET_remaining(pkt) != length) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!tls1_check_duplicate_extensions(pkt)) { *al = SSL_AD_DECODE_ERROR; return 0; } while (PACKET_get_net_2(pkt, &type) && PACKET_get_net_2(pkt, &size)) { const unsigned char *data; PACKET spkt; if (!PACKET_get_sub_packet(pkt, &spkt, size) || !PACKET_peek_bytes(&spkt, &data, size)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, &spkt, al)) return 0; renegotiate_seen = 1; } else if (s->version == SSL3_VERSION) { } else if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } #ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned int ecpointformatlist_length; if (!PACKET_get_1(&spkt, &ecpointformatlist_length) || ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; if (!PACKET_copy_bytes(&spkt, s->session->tlsext_ecpointformatlist, ecpointformatlist_length)) { *al = TLS1_AD_DECODE_ERROR; return 0; } } } #endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if (!tls_use_ticket(s) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } #ifndef OPENSSL_NO_CT /* * Only take it if we asked for it - i.e if there is no CT validation * callback set, then a custom extension MAY be processing it, so we * need to let control continue to flow to that. */ else if (type == TLSEXT_TYPE_signed_certificate_timestamp && s->ct_validation_callback != NULL) { /* Simply copy it off for later processing */ if (s->tlsext_scts != NULL) { OPENSSL_free(s->tlsext_scts); s->tlsext_scts = NULL; } s->tlsext_scts_len = size; if (size > 0) { s->tlsext_scts = OPENSSL_malloc(size); if (s->tlsext_scts == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->tlsext_scts, data, size); } } #endif #ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(&spkt)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s-> ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } /* * Could be non-NULL if server has sent multiple NPN extensions in * a single Serverhello */ OPENSSL_free(s->next_proto_negotiated); s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (s->next_proto_negotiated == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } #endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->s3->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ if (!PACKET_get_net_2(&spkt, &len) || PACKET_remaining(&spkt) != len || !PACKET_get_1(&spkt, &len) || PACKET_remaining(&spkt) != len) { *al = TLS1_AD_DECODE_ERROR; return 0; } OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (s->s3->alpn_selected == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if (!PACKET_copy_bytes(&spkt, s->s3->alpn_selected, len)) { *al = TLS1_AD_DECODE_ERROR; return 0; } s->s3->alpn_selected_len = len; } #ifndef OPENSSL_NO_HEARTBEATS else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_heartbeat) { unsigned int hbtype; if (!PACKET_get_1(&spkt, &hbtype)) { *al = SSL_AD_DECODE_ERROR; return 0; } switch (hbtype) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_DTLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_DTLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } #endif #ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, &spkt, al)) return 0; } #endif else if (type == TLSEXT_TYPE_encrypt_then_mac) { /* Ignore if inappropriate ciphersuite */ if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD && s->s3->tmp.new_cipher->algorithm_enc != SSL_RC4) s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC; } else if (type == TLSEXT_TYPE_extended_master_secret) { s->s3->flags |= TLS1_FLAGS_RECEIVED_EXTMS; if (!s->hit) s->session->flags |= SSL_SESS_FLAG_EXTMS; } /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; } if (PACKET_remaining(pkt) != 0) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = OPENSSL_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } if (s->hit) { /* * Check extended master secret extension is consistent with * original session. */ if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) != !(s->session->flags & SSL_SESS_FLAG_EXTMS)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_INCONSISTENT_EXTMS); return 0; } } return 1; } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void SimulateNetworkServiceCrash() { CHECK(base::FeatureList::IsEnabled(network::features::kNetworkService)); CHECK(!IsNetworkServiceRunningInProcess()) << "Can't crash the network service if it's running in-process!"; network::mojom::NetworkServiceTestPtr network_service_test; ServiceManagerConnection::GetForProcess()->GetConnector()->BindInterface( mojom::kNetworkServiceName, &network_service_test); base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed); network_service_test.set_connection_error_handler(run_loop.QuitClosure()); network_service_test->SimulateCrash(); run_loop.Run(); FlushNetworkServiceInstanceForTesting(); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } fclose(fp); return true; } Commit Message: ccpp: fix symlink race conditions Fix copy & chown race conditions Related: #1211835 Signed-off-by: Jakub Filak <[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: void AddChunk(const TransformPaintPropertyNode* t, const ClipPaintPropertyNode* c, const EffectPaintPropertyNode* e, const FloatRect& bounds = FloatRect(0, 0, 100, 100)) { auto record = sk_make_sp<PaintRecord>(); record->push<cc::DrawRectOp>(bounds, cc::PaintFlags()); AddChunk(std::move(record), t, c, e, bounds); } 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 int napi_poll(struct napi_struct *n, struct list_head *repoll) { void *have; int work, weight; list_del_init(&n->poll_list); have = netpoll_poll_lock(n); weight = n->weight; /* This NAPI_STATE_SCHED test is for avoiding a race * with netpoll's poll_napi(). Only the entity which * obtains the lock and sees NAPI_STATE_SCHED set will * actually make the ->poll() call. Therefore we avoid * accidentally calling ->poll() when NAPI is not scheduled. */ work = 0; if (test_bit(NAPI_STATE_SCHED, &n->state)) { work = n->poll(n, weight); trace_napi_poll(n); } WARN_ON_ONCE(work > weight); if (likely(work < weight)) goto out_unlock; /* Drivers must not modify the NAPI state if they * consume the entire weight. In such cases this code * still "owns" the NAPI instance and therefore can * move the instance around on the list at-will. */ if (unlikely(napi_disable_pending(n))) { napi_complete(n); goto out_unlock; } if (n->gro_list) { /* flush too old packets * If HZ < 1000, flush all packets. */ napi_gro_flush(n, HZ >= 1000); } /* Some drivers may have called napi_schedule * prior to exhausting their budget. */ if (unlikely(!list_empty(&n->poll_list))) { pr_warn_once("%s: Budget exhausted after napi rescheduled\n", n->dev ? n->dev->name : "backlog"); goto out_unlock; } list_add_tail(&n->poll_list, repoll); out_unlock: netpoll_poll_unlock(have); return work; } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[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 int _server_handle_qTfV(libgdbr_t *g, int (*cmd_cb) (void*, const char*, char*, size_t), void *core_ptr) { if (send_ack (g) < 0) { return -1; } return send_msg (g, ""); } Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void setup_format_params(int track) { int n; int il; int count; int head_shift; int track_shift; struct fparm { unsigned char track, head, sect, size; } *here = (struct fparm *)floppy_track_buffer; raw_cmd = &default_raw_cmd; raw_cmd->track = track; raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK); raw_cmd->rate = _floppy->rate & 0x43; raw_cmd->cmd_count = NR_F; COMMAND = FM_MODE(_floppy, FD_FORMAT); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head); F_SIZECODE = FD_SIZECODE(_floppy); F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE; F_GAP = _floppy->fmt_gap; F_FILL = FD_FILL_BYTE; raw_cmd->kernel_data = floppy_track_buffer; raw_cmd->length = 4 * F_SECT_PER_TRACK; /* allow for about 30ms for data transport per track */ head_shift = (F_SECT_PER_TRACK + 5) / 6; /* a ``cylinder'' is two tracks plus a little stepping time */ track_shift = 2 * head_shift + 3; /* position of logical sector 1 on this track */ n = (track_shift * format_req.track + head_shift * format_req.head) % F_SECT_PER_TRACK; /* determine interleave */ il = 1; if (_floppy->fmt_gap < 0x22) il++; /* initialize field */ for (count = 0; count < F_SECT_PER_TRACK; ++count) { here[count].track = format_req.track; here[count].head = format_req.head; here[count].sect = 0; here[count].size = F_SIZECODE; } /* place logical sectors */ for (count = 1; count <= F_SECT_PER_TRACK; ++count) { here[n].sect = count; n = (n + il) % F_SECT_PER_TRACK; if (here[n].sect) { /* sector busy, find next free sector */ ++n; if (n >= F_SECT_PER_TRACK) { n -= F_SECT_PER_TRACK; while (here[n].sect) ++n; } } } if (_floppy->stretch & FD_SECTBASEMASK) { for (count = 0; count < F_SECT_PER_TRACK; count++) here[count].sect += FD_SECTBASE(_floppy) - 1; } } Commit Message: floppy: fix div-by-zero in setup_format_params This fixes a divide by zero error in the setup_format_params function of the floppy driver. Two consecutive ioctls can trigger the bug: The first one should set the drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK to become zero. Next, the floppy format operation should be called. A floppy disk is not required to be inserted. An unprivileged user could trigger the bug if the device is accessible. The patch checks F_SECT_PER_TRACK for a non-zero value in the set_geometry function. The proper check should involve a reasonable upper limit for the .sect and .rate fields, but it could change the UAPI. The patch also checks F_SECT_PER_TRACK in the setup_format_params, and cancels the formatting operation in case of zero. The bug was found by syzkaller. Signed-off-by: Denis Efremov <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-369 Target: 1 Example 2: Code: static inline void ne2000_dma_update(NE2000State *s, int len) { s->rsar += len; /* wrap */ /* XXX: check what to do if rsar > stop */ if (s->rsar == s->stop) s->rsar = s->start; if (s->rcnt <= len) { s->rcnt = 0; /* signal end of transfer */ s->isr |= ENISR_RDC; ne2000_update_irq(s); } else { s->rcnt -= len; } } 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: ExtensionsAPIClient::CreateMimeHandlerViewGuestDelegate( MimeHandlerViewGuest* guest) const { return std::unique_ptr<MimeHandlerViewGuestDelegate>(); } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} 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: InputMethodLibraryImpl() : input_method_status_connection_(NULL), should_launch_ime_(false), ime_connected_(false), defer_ime_startup_(false), enable_auto_ime_shutdown_(true), ibus_daemon_process_handle_(base::kNullProcessHandle), #if !defined(TOUCH_UI) initialized_successfully_(false), candidate_window_controller_(NULL) { #else initialized_successfully_(false) { #endif notification_registrar_.Add(this, NotificationType::APP_TERMINATING, NotificationService::AllSources()); } bool Init() { DCHECK(!initialized_successfully_) << "Already initialized"; if (!CrosLibrary::Get()->EnsureLoaded()) return false; input_method_status_connection_ = chromeos::MonitorInputMethodStatus( this, &InputMethodChangedHandler, &RegisterPropertiesHandler, &UpdatePropertyHandler, &ConnectionChangeHandler); if (!input_method_status_connection_) return false; initialized_successfully_ = true; return true; } virtual ~InputMethodLibraryImpl() { } virtual void AddObserver(Observer* observer) { if (!observers_.size()) { observer->FirstObserverIsAdded(this); } observers_.AddObserver(observer); } virtual void RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } virtual InputMethodDescriptors* GetActiveInputMethods() { chromeos::InputMethodDescriptors* result = new chromeos::InputMethodDescriptors; for (size_t i = 0; i < active_input_method_ids_.size(); ++i) { const std::string& input_method_id = active_input_method_ids_[i]; const InputMethodDescriptor* descriptor = chromeos::input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { result->push_back(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } } if (result->empty()) { LOG(WARNING) << "No active input methods found."; result->push_back(input_method::GetFallbackInputMethodDescriptor()); } return result; } virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); return input_methods->size(); } virtual InputMethodDescriptors* GetSupportedInputMethods() { if (!initialized_successfully_) { InputMethodDescriptors* result = new InputMethodDescriptors; result->push_back(input_method::GetFallbackInputMethodDescriptor()); return result; } return chromeos::GetSupportedInputMethodDescriptors(); } virtual void ChangeInputMethod(const std::string& input_method_id) { tentative_current_input_method_id_ = input_method_id; if (ibus_daemon_process_handle_ == base::kNullProcessHandle && chromeos::input_method::IsKeyboardLayout(input_method_id)) { ChangeCurrentInputMethodFromId(input_method_id); } else { StartInputMethodDaemon(); if (!ChangeInputMethodViaIBus(input_method_id)) { VLOG(1) << "Failed to change the input method to " << input_method_id << " (deferring)"; } } } virtual void SetImePropertyActivated(const std::string& key, bool activated) { if (!initialized_successfully_) return; DCHECK(!key.empty()); chromeos::SetImePropertyActivated( input_method_status_connection_, key.c_str(), activated); } virtual bool InputMethodIsActivated(const std::string& input_method_id) { scoped_ptr<InputMethodDescriptors> active_input_method_descriptors( GetActiveInputMethods()); for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) { if (active_input_method_descriptors->at(i).id == input_method_id) { return true; } } return false; } virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } virtual InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; } virtual InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; } virtual const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) { if (!initialized_successfully_) return ""; return chromeos::GetKeyboardOverlayId(input_method_id); } virtual void SendHandwritingStroke(const HandwritingStroke& stroke) { if (!initialized_successfully_) return; chromeos::SendHandwritingStroke(input_method_status_connection_, stroke); } virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; chromeos::CancelHandwriting(input_method_status_connection_, stroke_count); } private: bool ContainOnlyOneKeyboardLayout( const ImeConfigValue& value) { return (value.type == ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && chromeos::input_method::IsKeyboardLayout( value.string_list_value[0])); } void MaybeStartInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList && !value.string_list_value.empty()) { if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) { return; } const bool just_started = StartInputMethodDaemon(); if (!just_started) { return; } if (tentative_current_input_method_id_.empty()) { tentative_current_input_method_id_ = current_input_method_.id; } if (std::find(value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_) == value.string_list_value.end()) { tentative_current_input_method_id_.clear(); } } } void MaybeStopInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value) && enable_auto_ime_shutdown_) { StopInputMethodDaemon(); } } void MaybeChangeCurrentKeyboardLayout(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } } bool ChangeInputMethodViaIBus(const std::string& input_method_id) { if (!initialized_successfully_) return false; std::string input_method_id_to_switch = input_method_id; if (!InputMethodIsActivated(input_method_id)) { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); DCHECK(!input_methods->empty()); if (!input_methods->empty()) { input_method_id_to_switch = input_methods->at(0).id; LOG(INFO) << "Can't change the current input method to " << input_method_id << " since the engine is not preloaded. " << "Switch to " << input_method_id_to_switch << " instead."; } } if (chromeos::ChangeInputMethod(input_method_status_connection_, input_method_id_to_switch.c_str())) { return true; } LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch; return false; } void FlushImeConfig() { if (!initialized_successfully_) return; bool active_input_methods_are_changed = false; InputMethodConfigRequests::iterator iter = pending_config_requests_.begin(); while (iter != pending_config_requests_.end()) { const std::string& section = iter->first.first; const std::string& config_name = iter->first.second; ImeConfigValue& value = iter->second; if (config_name == language_prefs::kPreloadEnginesConfigName && !tentative_current_input_method_id_.empty()) { std::vector<std::string>::iterator engine_iter = std::find( value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_); if (engine_iter != value.string_list_value.end()) { std::rotate(value.string_list_value.begin(), engine_iter, // this becomes the new first element value.string_list_value.end()); } else { LOG(WARNING) << tentative_current_input_method_id_ << " is not in preload_engines: " << value.ToString(); } tentative_current_input_method_id_.erase(); } if (chromeos::SetImeConfig(input_method_status_connection_, section.c_str(), config_name.c_str(), value)) { if (config_name == language_prefs::kPreloadEnginesConfigName) { active_input_methods_are_changed = true; VLOG(1) << "Updated preload_engines: " << value.ToString(); } pending_config_requests_.erase(iter++); } else { break; } } if (active_input_methods_are_changed) { const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, ActiveInputMethodsChanged(this, current_input_method_, num_active_input_methods)); } } static void InputMethodChangedHandler( void* object, const chromeos::InputMethodDescriptor& current_input_method) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->ChangeCurrentInputMethod(current_input_method); } static void RegisterPropertiesHandler( void* object, const ImePropertyList& prop_list) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->RegisterProperties(prop_list); } static void UpdatePropertyHandler( void* object, const ImePropertyList& prop_list) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->UpdateProperty(prop_list); } static void ConnectionChangeHandler(void* object, bool connected) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->ime_connected_ = connected; if (connected) { input_method_library->pending_config_requests_.clear(); input_method_library->pending_config_requests_.insert( input_method_library->current_config_values_.begin(), input_method_library->current_config_values_.end()); input_method_library->FlushImeConfig(); input_method_library->ChangeInputMethod( input_method_library->previous_input_method().id); input_method_library->ChangeInputMethod( input_method_library->current_input_method().id); } } void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<Observer>::Iterator it(observers_); Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); } void ChangeCurrentInputMethodFromId(const std::string& input_method_id) { const chromeos::InputMethodDescriptor* descriptor = chromeos::input_method::GetInputMethodDescriptorFromId( input_method_id); if (descriptor) { ChangeCurrentInputMethod(*descriptor); } else { LOG(ERROR) << "Descriptor is not found for: " << input_method_id; } } void RegisterProperties(const ImePropertyList& prop_list) { current_ime_properties_ = prop_list; FOR_EACH_OBSERVER(Observer, observers_, PropertyListChanged(this, current_ime_properties_)); } bool StartInputMethodDaemon() { should_launch_ime_ = true; return MaybeLaunchInputMethodDaemon(); } void UpdateProperty(const ImePropertyList& prop_list) { for (size_t i = 0; i < prop_list.size(); ++i) { FindAndUpdateProperty(prop_list[i], &current_ime_properties_); } FOR_EACH_OBSERVER(Observer, observers_, PropertyListChanged(this, current_ime_properties_)); } bool LaunchInputMethodProcess(const std::string& command_line, base::ProcessHandle* process_handle) { std::vector<std::string> argv; base::file_handle_mapping_vector fds_to_remap; base::ProcessHandle handle = base::kNullProcessHandle; base::SplitString(command_line, ' ', &argv); const bool result = base::LaunchApp(argv, fds_to_remap, // no remapping false, // wait &handle); if (!result) { LOG(ERROR) << "Could not launch: " << command_line; return false; } const base::ProcessId pid = base::GetProcId(handle); g_child_watch_add(pid, reinterpret_cast<GChildWatchFunc>(OnImeShutdown), this); *process_handle = handle; VLOG(1) << command_line << " (PID=" << pid << ") is started"; return true; } bool MaybeLaunchInputMethodDaemon() { if (!initialized_successfully_) return false; if (!should_launch_ime_) { return false; } #if !defined(TOUCH_UI) if (!candidate_window_controller_.get()) { candidate_window_controller_.reset(new CandidateWindowController); if (!candidate_window_controller_->Init()) { LOG(WARNING) << "Failed to initialize the candidate window controller"; } } #endif if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { return false; // ibus-daemon is already running. } const std::string ibus_daemon_command_line = StringPrintf("%s --panel=disable --cache=none --restart --replace", kIBusDaemonPath); if (!LaunchInputMethodProcess( ibus_daemon_command_line, &ibus_daemon_process_handle_)) { LOG(ERROR) << "Failed to launch " << ibus_daemon_command_line; return false; } return true; } static void OnImeShutdown(GPid pid, gint status, InputMethodLibraryImpl* library) { if (library->ibus_daemon_process_handle_ != base::kNullProcessHandle && base::GetProcId(library->ibus_daemon_process_handle_) == pid) { library->ibus_daemon_process_handle_ = base::kNullProcessHandle; } library->MaybeLaunchInputMethodDaemon(); } void StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } } void SetDeferImeStartup(bool defer) { VLOG(1) << "Setting DeferImeStartup to " << defer; defer_ime_startup_ = defer; } void SetEnableAutoImeShutdown(bool enable) { enable_auto_ime_shutdown_ = enable; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type.value == NotificationType::APP_TERMINATING) { notification_registrar_.RemoveAll(); StopInputMethodDaemon(); #if !defined(TOUCH_UI) candidate_window_controller_.reset(NULL); #endif } } InputMethodStatusConnection* input_method_status_connection_; ObserverList<Observer> observers_; InputMethodDescriptor previous_input_method_; InputMethodDescriptor current_input_method_; ImePropertyList current_ime_properties_; typedef std::pair<std::string, std::string> ConfigKeyType; typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests; InputMethodConfigRequests pending_config_requests_; InputMethodConfigRequests current_config_values_; NotificationRegistrar notification_registrar_; bool should_launch_ime_; bool ime_connected_; bool defer_ime_startup_; bool enable_auto_ime_shutdown_; std::string tentative_current_input_method_id_; base::ProcessHandle ibus_daemon_process_handle_; bool initialized_successfully_; #if !defined(TOUCH_UI) scoped_ptr<CandidateWindowController> candidate_window_controller_; #endif std::vector<std::string> active_input_method_ids_; DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl); }; Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int bond_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *event_dev = (struct net_device *)ptr; pr_debug("event_dev: %s, event: %lx\n", event_dev ? event_dev->name : "None", event); if (!(event_dev->priv_flags & IFF_BONDING)) return NOTIFY_DONE; if (event_dev->flags & IFF_MASTER) { pr_debug("IFF_MASTER\n"); return bond_master_netdev_event(event, event_dev); } if (event_dev->flags & IFF_SLAVE) { pr_debug("IFF_SLAVE\n"); return bond_slave_netdev_event(event, event_dev); } return NOTIFY_DONE; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DisconnectWindowLinux::Hide() { NOTIMPLEMENTED(); } Commit Message: Initial implementation of DisconnectWindow on Linux. BUG=None TEST=Manual Review URL: http://codereview.chromium.org/7089016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const double bias, ExceptionInfo *exception) { #define AdaptiveThresholdImageTag "AdaptiveThreshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickSizeType number_pixels; ssize_t y; /* Initialize threshold image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (width == 0) return(threshold_image); status=SetImageStorageClass(threshold_image,DirectClass,exception); if (status == MagickFalse) { threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Threshold image. */ status=MagickTrue; progress=0; number_pixels=(MagickSizeType) width*height; image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double channel_bias[MaxPixelChannels], channel_sum[MaxPixelChannels]; register const Quantum *magick_restrict p, *magick_restrict pixels; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t center, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (height/2L),image->columns+width,height,exception); q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+ GetPixelChannels(image)*(width/2); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } pixels=p; channel_bias[channel]=0.0; channel_sum[channel]=0.0; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) channel_bias[channel]+=pixels[i]; channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double mean; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image, channel); if ((traits == UndefinedPixelTrait) || (threshold_traits == UndefinedPixelTrait)) continue; if ((threshold_traits & CopyPixelTrait) != 0) { SetPixelChannel(threshold_image,channel,p[center+i],q); continue; } channel_sum[channel]-=channel_bias[channel]; channel_bias[channel]=0.0; pixels=p; for (v=0; v < (ssize_t) height; v++) { channel_bias[channel]+=pixels[i]; pixels+=(width-1)*GetPixelChannels(image); channel_sum[channel]+=pixels[i]; pixels+=GetPixelChannels(image)*(image->columns+1); } mean=(double) (channel_sum[channel]/number_pixels+bias); SetPixelChannel(threshold_image,channel,(Quantum) ((double) p[center+i] <= mean ? 0 : QuantumRange),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(threshold_image); } if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_image->type=image->type; threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609 CWE ID: CWE-125 Target: 1 Example 2: Code: DXVAVideoDecodeAccelerator::PendingSampleInfo::~PendingSampleInfo() {} Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void EditorClientBlackBerry::getGuessesForWord(const String&, const String&, Vector<String>&) { notImplemented(); } Commit Message: [BlackBerry] Prevent text selection inside Colour and Date/Time input fields https://bugs.webkit.org/show_bug.cgi?id=111733 Reviewed by Rob Buis. PR 305194. Prevent selection for popup input fields as they are buttons. Informally Reviewed Gen Mak. * WebCoreSupport/EditorClientBlackBerry.cpp: (WebCore::EditorClientBlackBerry::shouldChangeSelectedRange): git-svn-id: svn://svn.chromium.org/blink/trunk@145121 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(doc->ctx); samples[0] = 1; samples[1] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); profile = strchr(buf, ' '); if (!profile) { fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string); return; } p = strchr(profile, ' '); p = strchr(profile, ' '); if (!p) { fz_warn(doc->ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; i = 0; while (i < n) { p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; default: *csp = fz_device_gray(doc->ctx); break; } } } for (i = 0; i < colorspace->n; i++) doc->color[i] = samples[i + 1]; doc->alpha = samples[0] * doc->opacity[doc->opacity_top]; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: e1000e_core_reset(E1000ECore *core) { int i; timer_del(core->autoneg_timer); e1000e_intrmgr_reset(core); memset(core->phy, 0, sizeof core->phy); memmove(core->phy, e1000e_phy_reg_init, sizeof e1000e_phy_reg_init); memset(core->mac, 0, sizeof core->mac); memmove(core->mac, e1000e_mac_reg_init, sizeof e1000e_mac_reg_init); core->rxbuf_min_shift = 1 + E1000_RING_DESC_LEN_SHIFT; if (qemu_get_queue(core->owner_nic)->link_down) { e1000e_link_down(core); } e1000x_reset_mac_addr(core->owner_nic, core->mac, core->permanent_mac); for (i = 0; i < ARRAY_SIZE(core->tx); i++) { net_tx_pkt_reset(core->tx[i].tx_pkt); memset(&core->tx[i].props, 0, sizeof(core->tx[i].props)); core->tx[i].skip_cp = false; } } Commit Message: CWE ID: CWE-835 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: asmlinkage void __kprobes do_page_fault(struct pt_regs *regs, unsigned long writeaccess, unsigned long address) { unsigned long vec; struct task_struct *tsk; struct mm_struct *mm; struct vm_area_struct * vma; int si_code; int fault; siginfo_t info; tsk = current; mm = tsk->mm; si_code = SEGV_MAPERR; vec = lookup_exception_vector(); /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. */ if (unlikely(fault_in_kernel_space(address))) { if (vmalloc_fault(address) >= 0) return; if (notify_page_fault(regs, vec)) return; goto bad_area_nosemaphore; } if (unlikely(notify_page_fault(regs, vec))) return; /* Only enable interrupts if they were on before the fault */ if ((regs->sr & SR_IMASK) != SR_IMASK) local_irq_enable(); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); /* * If we're in an interrupt, have no user context or are running * in an atomic region then we must not take the fault: */ if (in_atomic() || !mm) goto no_context; down_read(&mm->mmap_sem); vma = find_vma(mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if (expand_stack(vma, address)) goto bad_area; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: si_code = SEGV_ACCERR; if (writeaccess) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; } else { if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))) goto bad_area; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(mm, vma, address, writeaccess ? FAULT_FLAG_WRITE : 0); if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (fault & VM_FAULT_MAJOR) { tsk->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); } else { tsk->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } up_read(&mm->mmap_sem); return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: if (user_mode(regs)) { info.si_signo = SIGSEGV; info.si_errno = 0; info.si_code = si_code; info.si_addr = (void *) address; force_sig_info(SIGSEGV, &info, tsk); return; } no_context: /* Are we prepared to handle this kernel fault? */ if (fixup_exception(regs)) return; if (handle_trapped_io(regs, address)) return; /* * Oops. The kernel tried to access some bad page. We'll have to * terminate things with extreme prejudice. * */ bust_spinlocks(1); if (oops_may_print()) { unsigned long page; if (address < PAGE_SIZE) printk(KERN_ALERT "Unable to handle kernel NULL " "pointer dereference"); else printk(KERN_ALERT "Unable to handle kernel paging " "request"); printk(" at virtual address %08lx\n", address); printk(KERN_ALERT "pc = %08lx\n", regs->pc); page = (unsigned long)get_TTB(); if (page) { page = ((__typeof__(page) *)page)[address >> PGDIR_SHIFT]; printk(KERN_ALERT "*pde = %08lx\n", page); if (page & _PAGE_PRESENT) { page &= PAGE_MASK; address &= 0x003ff000; page = ((__typeof__(page) *) __va(page))[address >> PAGE_SHIFT]; printk(KERN_ALERT "*pte = %08lx\n", page); } } } die("Oops", regs, writeaccess); bust_spinlocks(0); do_exit(SIGKILL); /* * We ran out of memory, or some other thing happened to us that made * us unable to handle the page fault gracefully. */ out_of_memory: up_read(&mm->mmap_sem); if (!user_mode(regs)) goto no_context; pagefault_out_of_memory(); return; do_sigbus: up_read(&mm->mmap_sem); /* * Send a sigbus, regardless of whether we were in kernel * or user mode. */ info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void *)address; force_sig_info(SIGBUS, &info, tsk); /* Kernel mode? Handle exceptions or die */ if (!user_mode(regs)) goto no_context; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
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: GDataRootDirectory::GDataRootDirectory() : ALLOW_THIS_IN_INITIALIZER_LIST(GDataDirectory(NULL, this)), fake_search_directory_(new GDataDirectory(NULL, NULL)), largest_changestamp_(0), serialized_size_(0) { title_ = kGDataRootDirectory; SetFileNameFromTitle(); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: ChromeExtensionsAPIClient::CreateContentRulesRegistry( content::BrowserContext* browser_context, RulesCacheDelegate* cache_delegate) const { return scoped_refptr<ContentRulesRegistry>( new ChromeContentRulesRegistry( browser_context, cache_delegate, base::Bind(&CreateDefaultContentPredicateEvaluators, base::Unretained(browser_context)))); } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} 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 sctp_process_param(struct sctp_association *asoc, union sctp_params param, const union sctp_addr *peer_addr, gfp_t gfp) { struct net *net = sock_net(asoc->base.sk); union sctp_addr addr; int i; __u16 sat; int retval = 1; sctp_scope_t scope; time_t stale; struct sctp_af *af; union sctp_addr_param *addr_param; struct sctp_transport *t; struct sctp_endpoint *ep = asoc->ep; /* We maintain all INIT parameters in network byte order all the * time. This allows us to not worry about whether the parameters * came from a fresh INIT, and INIT ACK, or were stored in a cookie. */ switch (param.p->type) { case SCTP_PARAM_IPV6_ADDRESS: if (PF_INET6 != asoc->base.sk->sk_family) break; goto do_addr_param; case SCTP_PARAM_IPV4_ADDRESS: /* v4 addresses are not allowed on v6-only socket */ if (ipv6_only_sock(asoc->base.sk)) break; do_addr_param: af = sctp_get_af_specific(param_type2af(param.p->type)); af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0); scope = sctp_scope(peer_addr); if (sctp_in_scope(net, &addr, scope)) if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED)) return 0; break; case SCTP_PARAM_COOKIE_PRESERVATIVE: if (!net->sctp.cookie_preserve_enable) break; stale = ntohl(param.life->lifespan_increment); /* Suggested Cookie Life span increment's unit is msec, * (1/1000sec). */ asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale); break; case SCTP_PARAM_HOST_NAME_ADDRESS: pr_debug("%s: unimplemented SCTP_HOST_NAME_ADDRESS\n", __func__); break; case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES: /* Turn off the default values first so we'll know which * ones are really set by the peer. */ asoc->peer.ipv4_address = 0; asoc->peer.ipv6_address = 0; /* Assume that peer supports the address family * by which it sends a packet. */ if (peer_addr->sa.sa_family == AF_INET6) asoc->peer.ipv6_address = 1; else if (peer_addr->sa.sa_family == AF_INET) asoc->peer.ipv4_address = 1; /* Cycle through address types; avoid divide by 0. */ sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t); if (sat) sat /= sizeof(__u16); for (i = 0; i < sat; ++i) { switch (param.sat->types[i]) { case SCTP_PARAM_IPV4_ADDRESS: asoc->peer.ipv4_address = 1; break; case SCTP_PARAM_IPV6_ADDRESS: if (PF_INET6 == asoc->base.sk->sk_family) asoc->peer.ipv6_address = 1; break; case SCTP_PARAM_HOST_NAME_ADDRESS: asoc->peer.hostname_address = 1; break; default: /* Just ignore anything else. */ break; } } break; case SCTP_PARAM_STATE_COOKIE: asoc->peer.cookie_len = ntohs(param.p->length) - sizeof(sctp_paramhdr_t); asoc->peer.cookie = param.cookie->body; break; case SCTP_PARAM_HEARTBEAT_INFO: /* Would be odd to receive, but it causes no problems. */ break; case SCTP_PARAM_UNRECOGNIZED_PARAMETERS: /* Rejected during verify stage. */ break; case SCTP_PARAM_ECN_CAPABLE: asoc->peer.ecn_capable = 1; break; case SCTP_PARAM_ADAPTATION_LAYER_IND: asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind); break; case SCTP_PARAM_SET_PRIMARY: if (!net->sctp.addip_enable) goto fall_through; addr_param = param.v + sizeof(sctp_addip_param_t); af = sctp_get_af_specific(param_type2af(param.p->type)); af->from_addr_param(&addr, addr_param, htons(asoc->peer.port), 0); /* if the address is invalid, we can't process it. * XXX: see spec for what to do. */ if (!af->addr_valid(&addr, NULL, NULL)) break; t = sctp_assoc_lookup_paddr(asoc, &addr); if (!t) break; sctp_assoc_set_primary(asoc, t); break; case SCTP_PARAM_SUPPORTED_EXT: sctp_process_ext_param(asoc, param); break; case SCTP_PARAM_FWD_TSN_SUPPORT: if (net->sctp.prsctp_enable) { asoc->peer.prsctp_capable = 1; break; } /* Fall Through */ goto fall_through; case SCTP_PARAM_RANDOM: if (!ep->auth_enable) goto fall_through; /* Save peer's random parameter */ asoc->peer.peer_random = kmemdup(param.p, ntohs(param.p->length), gfp); if (!asoc->peer.peer_random) { retval = 0; break; } break; case SCTP_PARAM_HMAC_ALGO: if (!ep->auth_enable) goto fall_through; /* Save peer's HMAC list */ asoc->peer.peer_hmacs = kmemdup(param.p, ntohs(param.p->length), gfp); if (!asoc->peer.peer_hmacs) { retval = 0; break; } /* Set the default HMAC the peer requested*/ sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo); break; case SCTP_PARAM_CHUNKS: if (!ep->auth_enable) goto fall_through; asoc->peer.peer_chunks = kmemdup(param.p, ntohs(param.p->length), gfp); if (!asoc->peer.peer_chunks) retval = 0; break; fall_through: default: /* Any unrecognized parameters should have been caught * and handled by sctp_verify_param() which should be * called prior to this routine. Simply log the error * here. */ pr_debug("%s: ignoring param:%d for association:%p.\n", __func__, ntohs(param.p->type), asoc); break; } return retval; } Commit Message: net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet An SCTP server doing ASCONF will panic on malformed INIT ping-of-death in the form of: ------------ INIT[PARAM: SET_PRIMARY_IP] ------------> While the INIT chunk parameter verification dissects through many things in order to detect malformed input, it misses to actually check parameters inside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary IP address' parameter in ASCONF, which has as a subparameter an address parameter. So an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS or SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0 and thus sctp_get_af_specific() returns NULL, too, which we then happily dereference unconditionally through af->from_addr_param(). The trace for the log: BUG: unable to handle kernel NULL pointer dereference at 0000000000000078 IP: [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp] PGD 0 Oops: 0000 [#1] SMP [...] Pid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs RIP: 0010:[<ffffffffa01e9c62>] [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp] [...] Call Trace: <IRQ> [<ffffffffa01f2add>] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp] [<ffffffffa01e1fcb>] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp] [<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp] [<ffffffffa01e5c09>] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp] [<ffffffffa01e61f6>] sctp_endpoint_bh_rcv+0x116/0x230 [sctp] [<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp] [<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp] [<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter] [<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [...] A minimal way to address this is to check for NULL as we do on all other such occasions where we know sctp_get_af_specific() could possibly return with NULL. Fixes: d6de3097592b ("[SCTP]: Add the handling of "Set Primary IP Address" parameter to INIT") Signed-off-by: Daniel Borkmann <[email protected]> Cc: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 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: secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); /* m1 = c ^ (d mod (p-1)) mod p */ mpi_sub_ui ( h, P, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m1, C, h, P ); /* m2 = c ^ (d mod (q-1)) mod q */ mpi_sub_ui ( h, Q, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m2, C, h, Q ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } } Commit Message: CWE ID: CWE-310 Target: 1 Example 2: Code: size_t tls12_copy_sigalgs(SSL *s, unsigned char *out, const unsigned char *psig, size_t psiglen) { unsigned char *tmpout = out; size_t i; for (i = 0; i < psiglen; i += 2, psig += 2) { if (tls12_sigalg_allowed(s, SSL_SECOP_SIGALG_SUPPORTED, psig)) { *tmpout++ = psig[0]; *tmpout++ = psig[1]; } } return tmpout - out; } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; } 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: xfs_attr3_leaf_lookup_int( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_entry *entries; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; xfs_dahash_t hashval; int probe; int span; trace_xfs_attr_leaf_lookup(args); leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); entries = xfs_attr3_leaf_entryp(leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); /* * Binary search. (note: small blocks will skip this loop) */ hashval = args->hashval; probe = span = ichdr.count / 2; for (entry = &entries[probe]; span > 4; entry = &entries[probe]) { span /= 2; if (be32_to_cpu(entry->hashval) < hashval) probe += span; else if (be32_to_cpu(entry->hashval) > hashval) probe -= span; else break; } ASSERT(probe >= 0 && (!ichdr.count || probe < ichdr.count)); ASSERT(span <= 4 || be32_to_cpu(entry->hashval) == hashval); /* * Since we may have duplicate hashval's, find the first matching * hashval in the leaf. */ while (probe > 0 && be32_to_cpu(entry->hashval) >= hashval) { entry--; probe--; } while (probe < ichdr.count && be32_to_cpu(entry->hashval) < hashval) { entry++; probe++; } if (probe == ichdr.count || be32_to_cpu(entry->hashval) != hashval) { args->index = probe; return XFS_ERROR(ENOATTR); } /* * Duplicate keys may be present, so search all of them for a match. */ for (; probe < ichdr.count && (be32_to_cpu(entry->hashval) == hashval); entry++, probe++) { /* * GROT: Add code to remove incomplete entries. */ /* * If we are looking for INCOMPLETE entries, show only those. * If we are looking for complete entries, show only those. */ if ((args->flags & XFS_ATTR_INCOMPLETE) != (entry->flags & XFS_ATTR_INCOMPLETE)) { continue; } if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, probe); if (name_loc->namelen != args->namelen) continue; if (memcmp(args->name, name_loc->nameval, args->namelen) != 0) continue; if (!xfs_attr_namesp_match(args->flags, entry->flags)) continue; args->index = probe; return XFS_ERROR(EEXIST); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, probe); if (name_rmt->namelen != args->namelen) continue; if (memcmp(args->name, name_rmt->name, args->namelen) != 0) continue; if (!xfs_attr_namesp_match(args->flags, entry->flags)) continue; args->index = probe; args->valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks( args->dp->i_mount, args->valuelen); return XFS_ERROR(EEXIST); } } args->index = probe; return XFS_ERROR(ENOATTR); } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: static void __exit au1100fb_unload(void) { platform_driver_unregister(&au1100fb_driver); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool hctx_may_queue(struct blk_mq_hw_ctx *hctx, struct blk_mq_bitmap_tags *bt) { unsigned int depth, users; if (!hctx || !(hctx->flags & BLK_MQ_F_TAG_SHARED)) return true; if (!test_bit(BLK_MQ_S_TAG_ACTIVE, &hctx->state)) return true; /* * Don't try dividing an ant */ if (bt->depth == 1) return true; users = atomic_read(&hctx->tags->active_queues); if (!users) return true; /* * Allow at least some tags */ depth = max((bt->depth + users - 1) / users, 4U); return atomic_read(&hctx->nr_active) < depth; } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec, nal_header_t *ps_nal) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 value; WORD32 i; WORD32 sps_id; pps_t *ps_pps; sps_t *ps_sps; slice_header_t *ps_slice_hdr; WORD32 disable_deblocking_filter_flag; bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; WORD32 idr_pic_flag; WORD32 pps_id; WORD32 first_slice_in_pic_flag; WORD32 no_output_of_prior_pics_flag = 0; WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type; WORD32 num_poc_total_curr = 0; WORD32 slice_address; if(ps_codec->i4_slice_error == 1) return ret; idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) || (NAL_IDR_N_LP == i1_nal_unit_type); BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1); if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1); } UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm); pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2); /* Get the current PPS structure */ ps_pps = ps_codec->s_parse.ps_pps_base + pps_id; if(0 == ps_pps->i1_pps_valid) { pps_t *ps_pps_ref = ps_codec->ps_pps_base; while(0 == ps_pps_ref->i1_pps_valid) ps_pps_ref++; if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1)) return IHEVCD_INVALID_HEADER; ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id); } /* Get SPS id for the current PPS */ sps_id = ps_pps->i1_sps_id; /* Get the current SPS structure */ ps_sps = ps_codec->s_parse.ps_sps_base + sps_id; /* When the current slice is the first in a pic, * check whether the previous frame is complete * If the previous frame is incomplete - * treat the remaining CTBs as skip */ if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) && first_slice_in_pic_flag) { if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } else { ps_codec->i4_slice_error = 0; } } if(first_slice_in_pic_flag) { ps_codec->s_parse.i4_cur_slice_idx = 0; } else { /* If the current slice is not the first slice in the pic, * but the first one to be parsed, set the current slice indx to 1 * Treat the first slice to be missing and copy the current slice header * to the first one */ if(0 == ps_codec->i4_pic_present) ps_codec->s_parse.i4_cur_slice_idx = 1; } ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); if((ps_pps->i1_dependent_slice_enabled_flag) && (!first_slice_in_pic_flag)) { BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1); /* If dependendent slice, copy slice header from previous slice */ if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0)) { ihevcd_copy_slice_hdr(ps_codec, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)), ((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1))); } ps_slice_hdr->i1_dependent_slice_flag = value; } else { ps_slice_hdr->i1_dependent_slice_flag = 0; } ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type; ps_slice_hdr->i1_pps_id = pps_id; ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag; ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1; if((NAL_BLA_W_LP <= i1_nal_unit_type) && (NAL_RSV_RAP_VCL23 >= i1_nal_unit_type)) { ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag; } ps_slice_hdr->i1_pps_id = pps_id; if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { WORD32 num_bits; /* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */ num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1); BITS_PARSE("slice_address", value, ps_bitstrm, num_bits); slice_address = value; /* If slice address is greater than the number of CTBs in a picture, * ignore the slice */ if(value >= ps_sps->i4_pic_size_in_ctb) return IHEVCD_IGNORE_SLICE; } else { slice_address = 0; } if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i1_pic_output_flag = 1; ps_slice_hdr->i4_pic_order_cnt_lsb = 0; ps_slice_hdr->i1_num_long_term_sps = 0; ps_slice_hdr->i1_num_long_term_pics = 0; for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++) { BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1); } UEV_PARSE("slice_type", value, ps_bitstrm); ps_slice_hdr->i1_slice_type = value; /* If the picture is IRAP, slice type must be equal to ISLICE */ if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) && (ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23)) ps_slice_hdr->i1_slice_type = ISLICE; if((ps_slice_hdr->i1_slice_type < 0) || (ps_slice_hdr->i1_slice_type > 2)) return IHEVCD_IGNORE_SLICE; if(ps_pps->i1_output_flag_present_flag) { BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_pic_output_flag = value; } ps_slice_hdr->i1_colour_plane_id = 0; if(1 == ps_sps->i1_separate_colour_plane_flag) { BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2); ps_slice_hdr->i1_colour_plane_id = value; } ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0; if(!idr_pic_flag) { WORD32 st_rps_idx; WORD32 num_neg_pics; WORD32 num_pos_pics; WORD8 *pi1_used; BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->i4_pic_order_cnt_lsb = value; BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value; if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag) { WORD32 numbits; ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0; if(ps_sps->i1_num_short_term_ref_pic_sets > 1) { numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1); BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits); ps_slice_hdr->i1_short_term_ref_pic_set_idx = value; } st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx; num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics; num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics; pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used; } else { ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, ps_sps->i1_num_short_term_ref_pic_sets, &ps_slice_hdr->s_stref_picset); st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets; num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics; num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics; pi1_used = ps_slice_hdr->s_stref_picset.ai1_used; } if(ps_sps->i1_long_term_ref_pics_present_flag) { if(ps_sps->i1_num_long_term_ref_pics_sps > 0) { UEV_PARSE("num_long_term_sps", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_sps = value; ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics); } UEV_PARSE("num_long_term_pics", value, ps_bitstrm); ps_slice_hdr->i1_num_long_term_pics = value; ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics, 0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics - ps_slice_hdr->i1_num_long_term_sps); for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics); i++) { if(i < ps_slice_hdr->i1_num_long_term_sps) { /* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */ WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps); BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits); ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value]; ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value]; } else { BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); ps_slice_hdr->ai4_poc_lsb_lt[i] = value; BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value; } BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1); ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value; ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0; if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]) { UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm); ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value; } if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps)) { ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1]; } } } for(i = 0; i < num_neg_pics + num_pos_pics; i++) { if(pi1_used[i]) { num_poc_total_curr++; } } for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++) { if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i]) { num_poc_total_curr++; } } if(ps_sps->i1_sps_temporal_mvp_enable_flag) { BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value; } } ps_slice_hdr->i1_slice_sao_luma_flag = 0; ps_slice_hdr->i1_slice_sao_chroma_flag = 0; if(ps_sps->i1_sample_adaptive_offset_enabled_flag) { BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_luma_flag = value; BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_sao_chroma_flag = value; } ps_slice_hdr->i1_max_num_merge_cand = 1; ps_slice_hdr->i1_cabac_init_flag = 0; ps_slice_hdr->i1_num_ref_idx_l0_active = 0; ps_slice_hdr->i1_num_ref_idx_l1_active = 0; ps_slice_hdr->i1_slice_cb_qp_offset = 0; ps_slice_hdr->i1_slice_cr_qp_offset = 0; if((PSLICE == ps_slice_hdr->i1_slice_type) || (BSLICE == ps_slice_hdr->i1_slice_type)) { BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_num_ref_idx_active_override_flag = value; if(ps_slice_hdr->i1_num_ref_idx_active_override_flag) { UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1; if(BSLICE == ps_slice_hdr->i1_slice_type) { UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm); ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1; } } else { ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active; if(BSLICE == ps_slice_hdr->i1_slice_type) { ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active; } } ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1); ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1); if(0 == num_poc_total_curr) return IHEVCD_IGNORE_SLICE; if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1)) { ihevcd_ref_pic_list_modification(ps_bitstrm, ps_slice_hdr, num_poc_total_curr); } else { ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0; ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0; } if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_mvd_l1_zero_flag = value; } ps_slice_hdr->i1_cabac_init_flag = 0; if(ps_pps->i1_cabac_init_present_flag) { BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_cabac_init_flag = value; } ps_slice_hdr->i1_collocated_from_l0_flag = 1; ps_slice_hdr->i1_collocated_ref_idx = 0; if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag) { if(BSLICE == ps_slice_hdr->i1_slice_type) { BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_collocated_from_l0_flag = value; } if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) || (!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1))) { UEV_PARSE("collocated_ref_idx", value, ps_bitstrm); ps_slice_hdr->i1_collocated_ref_idx = value; } } ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1); if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) || (ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type))) { ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr); } UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm); ps_slice_hdr->i1_max_num_merge_cand = 5 - value; } ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5); SEV_PARSE("slice_qp_delta", value, ps_bitstrm); ps_slice_hdr->i1_slice_qp_delta = value; if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag) { SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cb_qp_offset = value; SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm); ps_slice_hdr->i1_slice_cr_qp_offset = value; } ps_slice_hdr->i1_deblocking_filter_override_flag = 0; ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2; ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2; disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag; if(ps_pps->i1_deblocking_filter_control_present_flag) { if(ps_pps->i1_deblocking_filter_override_enabled_flag) { BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_deblocking_filter_override_flag = value; } if(ps_slice_hdr->i1_deblocking_filter_override_flag) { BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value; disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag; if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag) { SEV_PARSE("beta_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_beta_offset_div2 = value; SEV_PARSE("tc_offset_div2", value, ps_bitstrm); ps_slice_hdr->i1_tc_offset_div2 = value; } } } ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag; if(ps_pps->i1_loop_filter_across_slices_enabled_flag && (ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag)) { BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1); ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value; } } /* Check sanity of slice */ if((!first_slice_in_pic_flag) && (ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base; /* According to the standard, the above conditions must be satisfied - But for error resilience, * only the following conditions are checked */ if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) || (ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb)) { return IHEVCD_IGNORE_SLICE; } } if(0 == ps_codec->i4_pic_present) { ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb); } else { ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt; } if(!first_slice_in_pic_flag) { /* Check if the current slice belongs to the same pic (Pic being parsed) */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) { /* If the Next CTB's index is less than the slice address, * the previous slice is incomplete. * Indicate slice error, and treat the remaining CTBs as skip */ if(slice_address > ps_codec->s_parse.i4_next_ctb_indx) { if(ps_codec->i4_pic_present) { ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; return ret; } else { return IHEVCD_IGNORE_SLICE; } } /* If the slice address is less than the next CTB's index, * extra CTBs have been decoded in the previous slice. * Ignore the current slice. Treat it as incomplete */ else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx) { return IHEVCD_IGNORE_SLICE; } else { ps_codec->i4_slice_error = 0; } } /* The current slice does not belong to the pic that is being parsed */ else { /* The previous pic is incomplete. * Treat the remaining CTBs as skip */ if(ps_codec->i4_pic_present) { slice_header_t *ps_slice_hdr_next; ps_codec->i4_slice_error = 1; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; return ret; } /* If the previous pic is complete, * return if the current slice is dependant * otherwise, update the parse context's POC */ else { if(ps_slice_hdr->i1_dependent_slice_flag) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } } } /* If the slice is the first slice in the pic, update the parse context's POC */ else { /* If the first slice is repeated, ignore the second occurrence * If any other slice is repeated, the CTB addr will be greater than the slice addr, * and hence the second occurrence is ignored */ if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt) return IHEVCD_IGNORE_SLICE; ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt; } ps_slice_hdr->i4_num_entry_point_offsets = 0; if((ps_pps->i1_tiles_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag)) { UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm); ps_slice_hdr->i4_num_entry_point_offsets = value; { WORD32 max_num_entry_point_offsets; if((ps_pps->i1_tiles_enabled_flag) && (ps_pps->i1_entropy_coding_sync_enabled_flag)) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1); } else if(ps_pps->i1_tiles_enabled_flag) { max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows; } else { max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1); } ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets, 0, max_num_entry_point_offsets); } if(ps_slice_hdr->i4_num_entry_point_offsets > 0) { UEV_PARSE("offset_len_minus1", value, ps_bitstrm); ps_slice_hdr->i1_offset_len = value + 1; for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++) { BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len); /* TODO: pu4_entry_point_offset needs to be initialized */ } } } if(ps_pps->i1_slice_header_extension_present_flag) { UEV_PARSE("slice_header_extension_length", value, ps_bitstrm); ps_slice_hdr->i2_slice_header_extension_length = value; for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++) { BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8); } } ihevcd_bits_flush_to_byte_boundary(ps_bitstrm); { dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; WORD32 r_idx; if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) || (NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) || (0 == ps_codec->u4_pic_cnt)) { for(i = 0; i < MAX_DPB_BUFS; i++) { if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf) { pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf; mv_buf_t *ps_mv_buf; /* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */ ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc); /* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */ ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf; for(i = 0; i < BUF_MGR_MAX_CNT; i++) { if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc) { ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF); break; } ps_mv_buf++; } } } /* Initialize the reference lists to NULL * This is done to take care of the cases where the first pic is not IDR * but the reference list is not created for the first pic because * pic count is zero leaving the reference list uninitialised */ for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL; } } else { ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr); } } /* Fill the remaining entries of the reference lists with the nearest POC * This is done to handle cases where there is a corruption in the reference index */ if(ps_codec->i4_pic_present) { pic_buf_t *ps_pic_buf_ref; mv_buf_t *ps_mv_buf_ref; WORD32 r_idx; dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr; ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt); if(NULL == ps_pic_buf_ref) { ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic; ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf; } else { ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc); } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++) { if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++) { ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref; } } /* Update slice address in the header */ if(!ps_slice_hdr->i1_first_slice_in_pic_flag) { ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb; ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb; if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x; ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y; } } else { ps_slice_hdr->i2_ctb_x = 0; ps_slice_hdr->i2_ctb_y = 0; ps_slice_hdr->i2_independent_ctb_x = 0; ps_slice_hdr->i2_independent_ctb_y = 0; } /* If the first slice in the pic is missing, copy the current slice header to * the first slice's header */ if((!first_slice_in_pic_flag) && (0 == ps_codec->i4_pic_present)) { slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base; ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))); ps_codec->i4_slice_error = 1; ps_slice_hdr_prev->i2_ctb_x = 0; ps_slice_hdr_prev->i2_ctb_y = 0; ps_codec->s_parse.i4_ctb_x = 0; ps_codec->s_parse.i4_ctb_y = 0; ps_codec->s_parse.i4_cur_slice_idx = 0; if((ps_slice_hdr->i2_ctb_x == 0) && (ps_slice_hdr->i2_ctb_y == 0)) { ps_slice_hdr->i2_ctb_x++; } } { /* If skip B is enabled, * ignore pictures that are non-reference * TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is * sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/ if((i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0)) { if(IVD_SKIP_B == ps_codec->e_pic_skip_mode) return IHEVCD_IGNORE_SLICE; } /* If skip PB is enabled, * decode only I slices */ if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) && (ISLICE != ps_slice_hdr->i1_slice_type)) { return IHEVCD_IGNORE_SLICE; } } return ret; } Commit Message: Handle error return from ref list in slice hdr parsing The error returned by ref_list function was not handled by the caller parse_slice_header. Bug: 34672748 Change-Id: I55f6cb0e651746e77f7ff3375115894ec3964203 (cherry picked from commit 25206ffa6eeb25f32103e69f893287425ab1bd10) CWE ID: CWE-252 Target: 1 Example 2: Code: static void _php_pgsql_notice_handler(void *resource_id, const char *message) { php_pgsql_notice *notice; TSRMLS_FETCH(); if (! PGG(ignore_notices)) { notice = (php_pgsql_notice *)emalloc(sizeof(php_pgsql_notice)); notice->message = _php_pgsql_trim_message(message, (int *)&notice->len); if (PGG(log_notices)) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s", notice->message); } zend_hash_index_update(&PGG(notices), (ulong)resource_id, (void **)&notice, sizeof(php_pgsql_notice *), NULL); } } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FrameSelection::Clear() { granularity_ = TextGranularity::kCharacter; if (granularity_strategy_) granularity_strategy_->Clear(); SetSelection(SelectionInDOMTree()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 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: ip_printts(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; int hoplen; const char *type; if (length < 4) { ND_PRINT((ndo, "[bad length %u]", length)); return; } ND_PRINT((ndo, " TS{")); hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4; if ((length - 4) & (hoplen-1)) ND_PRINT((ndo, "[bad length %u]", length)); ptr = cp[2] - 1; len = 0; if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1) ND_PRINT((ndo, "[bad ptr %u]", cp[2])); switch (cp[3]&0xF) { case IPOPT_TS_TSONLY: ND_PRINT((ndo, "TSONLY")); break; case IPOPT_TS_TSANDADDR: ND_PRINT((ndo, "TS+ADDR")); break; /* * prespecified should really be 3, but some ones might send 2 * instead, and the IPOPT_TS_PRESPEC constant can apparently * have both values, so we have to hard-code it here. */ case 2: ND_PRINT((ndo, "PRESPEC2.0")); break; case 3: /* IPOPT_TS_PRESPEC */ ND_PRINT((ndo, "PRESPEC")); break; default: ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF)); goto done; } type = " "; for (len = 4; len < length; len += hoplen) { if (ptr == len) type = " ^ "; ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]), hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len]))); type = " "; } done: ND_PRINT((ndo, "%s", ptr == len ? " ^ " : "")); if (cp[3]>>4) ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4)); else ND_PRINT((ndo, "}")); Commit Message: CVE-2017-13037/IP: Add bounds checks when printing time stamp options. 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: bool readArrayBuffer(v8::Handle<v8::Value>* value) { RefPtr<ArrayBuffer> arrayBuffer = doReadArrayBuffer(); if (!arrayBuffer) return false; *value = toV8(arrayBuffer.release(), m_scriptState->context()->Global(), isolate()); return true; } 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: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } Commit Message: avformat/movenc: Do not pass AVCodecParameters in avpriv_request_sample Fixes: out of array read Fixes: ffmpeg_crash_8.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool GLES2DecoderImpl::SimulateAttrib0( const char* function_name, GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; GLuint size_needed = 0; if (num_vertices == 0 || !SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } PerformanceWarning( "Attribute 0 is disabled. This has signficant performance penalty"); CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_; if (new_buffer) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } } if (new_buffer || (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3])))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 1 Example 2: Code: XRecordCreateContext(Display *dpy, int datum_flags, XRecordClientSpec *clients, int nclients, XRecordRange **ranges, int nranges) { XExtDisplayInfo *info = find_display (dpy); register xRecordCreateContextReq *req; int clen = 4 * nclients; XRecordCheckExtension (dpy, info, 0); LockDisplay(dpy); GetReq(RecordCreateContext, req); req->reqType = info->codes->major_opcode; req->recordReqType = X_RecordCreateContext; req->context = XAllocID(dpy); req->length += (nclients * 4 + nranges * SIZEOF(xRecordRange)) >> 2; req->elementHeader = datum_flags; req->nClients = nclients; req->nRanges = nranges; Data32(dpy, (long *)clients, clen); SendRange(dpy, ranges, nranges); UnlockDisplay(dpy); SyncHandle(); return req->context; } 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 char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read 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: SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|sss", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 4: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry) { struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *sub_root = root; struct btrfs_key location; int index; int ret = 0; if (dentry->d_name.len > BTRFS_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); if (unlikely(d_need_lookup(dentry))) { memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key)); kfree(dentry->d_fsdata); dentry->d_fsdata = NULL; /* This thing is hashed, drop it for now */ d_drop(dentry); } else { ret = btrfs_inode_by_name(dir, dentry, &location); } if (ret < 0) return ERR_PTR(ret); if (location.objectid == 0) return NULL; if (location.type == BTRFS_INODE_ITEM_KEY) { inode = btrfs_iget(dir->i_sb, &location, root, NULL); return inode; } BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY); index = srcu_read_lock(&root->fs_info->subvol_srcu); ret = fixup_tree_root_location(root, dir, dentry, &location, &sub_root); if (ret < 0) { if (ret != -ENOENT) inode = ERR_PTR(ret); else inode = new_simple_dir(dir->i_sb, &location, sub_root); } else { inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL); } srcu_read_unlock(&root->fs_info->subvol_srcu, index); if (!IS_ERR(inode) && root != sub_root) { down_read(&root->fs_info->cleanup_work_sem); if (!(inode->i_sb->s_flags & MS_RDONLY)) ret = btrfs_orphan_cleanup(sub_root); up_read(&root->fs_info->cleanup_work_sem); if (ret) inode = ERR_PTR(ret); } return inode; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 AddObserverOnIDBThread() { DCHECK(context_->TaskRunner()->RunsTasksInCurrentSequence()); context_->AddObserver(this); } 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:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebGLObject::WebGLObject(WebGLRenderingContext* context) : m_object(0) , m_attachmentCount(0) , m_deleted(false) { } Commit Message: Unreviewed, build fix for unused argument warning after r104954. https://bugs.webkit.org/show_bug.cgi?id=75906 Also fixed up somebody's bad merge in Source/WebCore/ChangeLog. * html/canvas/WebGLObject.cpp: (WebCore::WebGLObject::WebGLObject): git-svn-id: svn://svn.chromium.org/blink/trunk@104959 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: void Con_Shutdown(void) { Cmd_RemoveCommand("toggleconsole"); Cmd_RemoveCommand("togglemenu"); Cmd_RemoveCommand("messagemode"); Cmd_RemoveCommand("messagemode2"); Cmd_RemoveCommand("messagemode3"); Cmd_RemoveCommand("messagemode4"); Cmd_RemoveCommand("clear"); Cmd_RemoveCommand("condump"); } Commit Message: Merge some file writing extension checks from OpenJK. Thanks Ensiform. https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0 https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176 CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void buffer_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; if (--ref->ref) return; ring_buffer_free_read_page(ref->buffer, ref->cpu, ref->page); kfree(ref); buf->private = 0; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type, int bit_depth, png_const_bytep gamma_table, double conv, unsigned int *colors) { png_uint_32 size_max = image_size_of_type(color_type, bit_depth, colors)-1; png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */ if (colors[0] == 0) switch (channels_of_type(color_type)) { /* 1 channel: a square image with a diamond, the least luminous colors are on * the edge of the image, the most luminous in the center. */ case 1: { png_uint_32 x; png_uint_32 base = 2*size_max - abs(2*y-size_max); for (x=0; x<=size_max; ++x) { png_uint_32 luma = base - abs(2*x-size_max); /* 'luma' is now in the range 0..2*size_max, we need * 0..depth_max */ luma = (luma*depth_max + size_max) / (2*size_max); set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv); } } break; /* 2 channels: the color channel increases in luminosity from top to bottom, * the alpha channel increases in opacity from left to right. */ case 2: { png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 2*x, bit_depth, (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table, conv); } } break; /* 3 channels: linear combinations of, from the top-left corner clockwise, * black, green, white, red. */ case 3: { /* x0: the black->red scale (the value of the red component) at the * start of the row (blue and green are 0). * x1: the green->white scale (the value of the red and blue * components at the end of the row; green is depth_max). */ png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; /* Interpolate x/depth_max from start to end: * * start end difference * red: Y Y 0 * green: 0 depth_max depth_max * blue: 0 Y Y */ for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y, gamma_table, conv); set_value(row, rowbytes, 3*x+1, bit_depth, /* green */ (depth_max * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */ (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); } } break; /* 4 channels: linear combinations of, from the top-left corner clockwise, * transparent, red, green, blue. */ case 4: { /* x0: the transparent->blue scale (the value of the blue and alpha * components) at the start of the row (red and green are 0). * x1: the red->green scale (the value of the red and green * components at the end of the row; blue is 0 and alpha is * depth_max). */ png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max); png_uint_32 x; /* Interpolate x/depth_max from start to end: * * start end difference * red: 0 depth_max-Y depth_max-Y * green: 0 Y Y * blue: Y 0 -Y * alpha: Y depth_max depth_max-Y */ for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 4*x+0, bit_depth, /* red */ ((depth_max-Y) * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+1, bit_depth, /* green */ (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */ Y - (Y * x * 2 + size_max) / (2 * size_max), gamma_table, conv); set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */ Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max), gamma_table, conv); } } break; default: fprintf(stderr, "makepng: internal bad channel count\n"); exit(2); } else if (color_type & PNG_COLOR_MASK_PALETTE) { /* Palette with fixed color: the image rows are all 0 and the image width * is 16. */ memset(row, 0, rowbytes); } else if (colors[0] == channels_of_type(color_type)) switch (channels_of_type(color_type)) { case 1: { const png_uint_32 luma = colors[1]; png_uint_32 x; for (x=0; x<=size_max; ++x) set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv); } break; case 2: { const png_uint_32 luma = colors[1]; const png_uint_32 alpha = colors[2]; png_uint_32 x; for (x=0; x<size_max; ++x) { set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table, conv); set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table, conv); } } break; case 3: { const png_uint_32 red = colors[1]; const png_uint_32 green = colors[2]; const png_uint_32 blue = colors[3]; png_uint_32 x; for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table, conv); set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table, conv); set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table, conv); } } break; case 4: { const png_uint_32 red = colors[1]; const png_uint_32 green = colors[2]; const png_uint_32 blue = colors[3]; const png_uint_32 alpha = colors[4]; png_uint_32 x; for (x=0; x<=size_max; ++x) { set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table, conv); set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table, conv); set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table, conv); set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table, conv); } } break; default: fprintf(stderr, "makepng: internal bad channel count\n"); exit(2); } else { fprintf(stderr, "makepng: --color: count(%u) does not match channels(%u)\n", colors[0], channels_of_type(color_type)); exit(1); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void BrowserView::FlashFrame(bool flash) { frame_->FlashFrame(flash); } 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 khugepaged_enter_vma_merge(struct vm_area_struct *vma) { unsigned long hstart, hend; if (!vma->anon_vma) /* * Not yet faulted in so we will register later in the * page fault if needed. */ return 0; if (vma->vm_file || vma->vm_ops) /* khugepaged not yet working on file or special mappings */ return 0; VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma)); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart < hend) return khugepaged_enter(vma); return 0; } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] 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: void GDataFileSystem::OnCopyDocumentCompleted( const FilePath& dir_path, const FileOperationCallback& callback, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); GDataFileError error = util::GDataToGDataFileError(status); if (error != GDATA_FILE_OK) { callback.Run(error); return; } scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (!doc_entry.get()) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } GDataEntry* entry = GDataEntry::FromDocumentEntry( NULL, doc_entry.get(), directory_service_.get()); if (!entry) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } directory_service_->root()->AddEntry(entry); MoveEntryFromRootDirectory(dir_path, callback, GDATA_FILE_OK, entry->GetFilePath()); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: status_t ACodec::setupFlacCodec( bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel) { if (encoder) { OMX_AUDIO_PARAM_FLACTYPE def; InitOMXParams(&def); def.nPortIndex = kPortIndexOutput; status_t err = mOMX->getParameter(mNode, OMX_IndexParamAudioFlac, &def, sizeof(def)); if (err != OK) { ALOGE("setupFlacCodec(): Error %d getting OMX_IndexParamAudioFlac parameter", err); return err; } def.nCompressionLevel = compressionLevel; err = mOMX->setParameter(mNode, OMX_IndexParamAudioFlac, &def, sizeof(def)); if (err != OK) { ALOGE("setupFlacCodec(): Error %d setting OMX_IndexParamAudioFlac parameter", err); return err; } } return setupRawAudioFormat( encoder ? kPortIndexInput : kPortIndexOutput, sampleRate, numChannels); } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg) { struct vivid_dev *dev = (struct vivid_dev *)info->par; switch (cmd) { case FBIOGET_VBLANK: { struct fb_vblank vblank; vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT | FB_VBLANK_HAVE_VSYNC; vblank.count = 0; vblank.vcount = 0; vblank.hcount = 0; if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank))) return -EFAULT; return 0; } default: dprintk(dev, 1, "Unknown ioctl %08x\n", cmd); return -EINVAL; } return 0; } Commit Message: [media] media/vivid-osd: fix info leak in ioctl The vivid_fb_ioctl() code fails to initialize the 16 _reserved bytes of struct fb_vblank after the ->hcount member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[email protected]> Signed-off-by: Hans Verkuil <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc, struct sctp_chunk *asconf) { sctp_addiphdr_t *hdr; union sctp_addr_param *addr_param; sctp_addip_param_t *asconf_param; struct sctp_chunk *asconf_ack; __be16 err_code; int length = 0; int chunk_len; __u32 serial; int all_param_pass = 1; chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t); hdr = (sctp_addiphdr_t *)asconf->skb->data; serial = ntohl(hdr->serial); /* Skip the addiphdr and store a pointer to address parameter. */ length = sizeof(sctp_addiphdr_t); addr_param = (union sctp_addr_param *)(asconf->skb->data + length); chunk_len -= length; /* Skip the address parameter and store a pointer to the first * asconf parameter. */ length = ntohs(addr_param->p.length); asconf_param = (void *)addr_param + length; chunk_len -= length; /* create an ASCONF_ACK chunk. * Based on the definitions of parameters, we know that the size of * ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF * parameters. */ asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4); if (!asconf_ack) goto done; /* Process the TLVs contained within the ASCONF chunk. */ while (chunk_len > 0) { err_code = sctp_process_asconf_param(asoc, asconf, asconf_param); /* ADDIP 4.1 A7) * If an error response is received for a TLV parameter, * all TLVs with no response before the failed TLV are * considered successful if not reported. All TLVs after * the failed response are considered unsuccessful unless * a specific success indication is present for the parameter. */ if (SCTP_ERROR_NO_ERROR != err_code) all_param_pass = 0; if (!all_param_pass) sctp_add_asconf_response(asconf_ack, asconf_param->crr_id, err_code, asconf_param); /* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add * an IP address sends an 'Out of Resource' in its response, it * MUST also fail any subsequent add or delete requests bundled * in the ASCONF. */ if (SCTP_ERROR_RSRC_LOW == err_code) goto done; /* Move to the next ASCONF param. */ length = ntohs(asconf_param->param_hdr.length); asconf_param = (void *)asconf_param + length; chunk_len -= length; } done: asoc->peer.addip_serial++; /* If we are sending a new ASCONF_ACK hold a reference to it in assoc * after freeing the reference to old asconf ack if any. */ if (asconf_ack) { sctp_chunk_hold(asconf_ack); list_add_tail(&asconf_ack->transmitted_list, &asoc->asconf_ack_list); } return asconf_ack; } Commit Message: net: sctp: fix skb_over_panic when receiving malformed ASCONF chunks Commit 6f4c618ddb0 ("SCTP : Add paramters validity check for ASCONF chunk") added basic verification of ASCONF chunks, however, it is still possible to remotely crash a server by sending a special crafted ASCONF chunk, even up to pre 2.6.12 kernels: skb_over_panic: text:ffffffffa01ea1c3 len:31056 put:30768 head:ffff88011bd81800 data:ffff88011bd81800 tail:0x7950 end:0x440 dev:<NULL> ------------[ cut here ]------------ kernel BUG at net/core/skbuff.c:129! [...] Call Trace: <IRQ> [<ffffffff8144fb1c>] skb_put+0x5c/0x70 [<ffffffffa01ea1c3>] sctp_addto_chunk+0x63/0xd0 [sctp] [<ffffffffa01eadaf>] sctp_process_asconf+0x1af/0x540 [sctp] [<ffffffff8152d025>] ? _read_unlock_bh+0x15/0x20 [<ffffffffa01e0038>] sctp_sf_do_asconf+0x168/0x240 [sctp] [<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp] [<ffffffff8147645d>] ? fib_rules_lookup+0xad/0xf0 [<ffffffffa01e6b22>] ? sctp_cmp_addr_exact+0x32/0x40 [sctp] [<ffffffffa01e8393>] sctp_assoc_bh_rcv+0xd3/0x180 [sctp] [<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp] [<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp] [<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter] [<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120 [<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff81496ded>] ip_local_deliver_finish+0xdd/0x2d0 [<ffffffff81497078>] ip_local_deliver+0x98/0xa0 [<ffffffff8149653d>] ip_rcv_finish+0x12d/0x440 [<ffffffff81496ac5>] ip_rcv+0x275/0x350 [<ffffffff8145c88b>] __netif_receive_skb+0x4ab/0x750 [<ffffffff81460588>] netif_receive_skb+0x58/0x60 This can be triggered e.g., through a simple scripted nmap connection scan injecting the chunk after the handshake, for example, ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ------------------ ASCONF; UNKNOWN ------------------> ... where ASCONF chunk of length 280 contains 2 parameters ... 1) Add IP address parameter (param length: 16) 2) Add/del IP address parameter (param length: 255) ... followed by an UNKNOWN chunk of e.g. 4 bytes. Here, the Address Parameter in the ASCONF chunk is even missing, too. This is just an example and similarly-crafted ASCONF chunks could be used just as well. The ASCONF chunk passes through sctp_verify_asconf() as all parameters passed sanity checks, and after walking, we ended up successfully at the chunk end boundary, and thus may invoke sctp_process_asconf(). Parameter walking is done with WORD_ROUND() to take padding into account. In sctp_process_asconf()'s TLV processing, we may fail in sctp_process_asconf_param() e.g., due to removal of the IP address that is also the source address of the packet containing the ASCONF chunk, and thus we need to add all TLVs after the failure to our ASCONF response to remote via helper function sctp_add_asconf_response(), which basically invokes a sctp_addto_chunk() adding the error parameters to the given skb. When walking to the next parameter this time, we proceed with ... length = ntohs(asconf_param->param_hdr.length); asconf_param = (void *)asconf_param + length; ... instead of the WORD_ROUND()'ed length, thus resulting here in an off-by-one that leads to reading the follow-up garbage parameter length of 12336, and thus throwing an skb_over_panic for the reply when trying to sctp_addto_chunk() next time, which implicitly calls the skb_put() with that length. Fix it by using sctp_walk_params() [ which is also used in INIT parameter processing ] macro in the verification *and* in ASCONF processing: it will make sure we don't spill over, that we walk parameters WORD_ROUND()'ed. Moreover, we're being more defensive and guard against unknown parameter types and missized addresses. Joint work with Vlad Yasevich. Fixes: b896b82be4ae ("[SCTP] ADDIP: Support for processing incoming ASCONF_ACK chunks.") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: smtp_alert(smtp_msg_t msg_type, void* data, const char *subject, const char *body) { smtp_t *smtp; #ifdef _WITH_VRRP_ vrrp_t *vrrp; vrrp_sgroup_t *vgroup; #endif #ifdef _WITH_LVS_ checker_t *checker; virtual_server_t *vs; smtp_rs *rs_info; #endif /* Only send mail if email specified */ if (LIST_ISEMPTY(global_data->email) || !global_data->smtp_server.ss_family) return; /* allocate & initialize smtp argument data structure */ smtp = (smtp_t *) MALLOC(sizeof(smtp_t)); smtp->subject = (char *) MALLOC(MAX_HEADERS_LENGTH); smtp->body = (char *) MALLOC(MAX_BODY_LENGTH); smtp->buffer = (char *) MALLOC(SMTP_BUFFER_MAX); smtp->email_to = (char *) MALLOC(SMTP_BUFFER_MAX); /* format subject if rserver is specified */ #ifdef _WITH_LVS_ if (msg_type == SMTP_MSG_RS) { checker = (checker_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(checker->rs, checker->vs), FMT_VS(checker->vs), checker->rs->alive ? "UP" : "DOWN"); } else if (msg_type == SMTP_MSG_VS) { vs = (virtual_server_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Virtualserver %s - %s", global_data->router_id, FMT_VS(vs), subject); } else if (msg_type == SMTP_MSG_RS_SHUT) { rs_info = (smtp_rs *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] Realserver %s of virtual server %s - %s", global_data->router_id, FMT_RS(rs_info->rs, rs_info->vs), FMT_VS(rs_info->vs), subject); } else #endif #ifdef _WITH_VRRP_ if (msg_type == SMTP_MSG_VRRP) { vrrp = (vrrp_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Instance %s - %s", global_data->router_id, vrrp->iname, subject); } else if (msg_type == SMTP_MSG_VGROUP) { vgroup = (vrrp_sgroup_t *)data; snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] VRRP Group %s - %s", global_data->router_id, vgroup->gname, subject); } else #endif if (global_data->router_id) snprintf(smtp->subject, MAX_HEADERS_LENGTH, "[%s] %s" , global_data->router_id , subject); else snprintf(smtp->subject, MAX_HEADERS_LENGTH, "%s", subject); strncpy(smtp->body, body, MAX_BODY_LENGTH - 1); smtp->body[MAX_BODY_LENGTH - 1]= '\0'; build_to_header_rcpt_addrs(smtp); #ifdef _SMTP_ALERT_DEBUG_ if (do_smtp_alert_debug) smtp_log_to_file(smtp); else #endif smtp_connect(smtp); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WebPresentationConnectionState PresentationConnection::getState() { return m_state; } Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures Add layout test. 1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead. BUG=697719 Review-Url: https://codereview.chromium.org/2730123003 Cr-Commit-Position: refs/heads/master@{#455225} 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: rtadv_read (struct thread *thread) { int sock; int len; u_char buf[RTADV_MSG_SIZE]; struct sockaddr_in6 from; ifindex_t ifindex = 0; int hoplimit = -1; struct zebra_vrf *zvrf = THREAD_ARG (thread); sock = THREAD_FD (thread); zvrf->rtadv.ra_read = NULL; /* Register myself. */ rtadv_event (zvrf, RTADV_READ, sock); len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit); if (len < 0) { zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno)); return len; } rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id); return 0; } Commit Message: zebra: stack overrun in IPv6 RA receive code (CVE-2016-1245) The IPv6 RA code also receives ICMPv6 RS and RA messages. Unfortunately, by bad coding practice, the buffer size specified on receiving such messages mixed up 2 constants that in fact have different values. The code itself has: #define RTADV_MSG_SIZE 4096 While BUFSIZ is system-dependent, in my case (x86_64 glibc): /usr/include/_G_config.h:#define _G_BUFSIZ 8192 /usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ /usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ FreeBSD, OpenBSD, NetBSD and Illumos are not affected, since all of them have BUFSIZ == 1024. As the latter is passed to the kernel on recvmsg(), it's possible to overwrite 4kB of stack -- with ICMPv6 packets that can be globally sent to any of the system's addresses (using fragmentation to get to 8k). (The socket has filters installed limiting this to RS and RA packets, but does not have a filter for source address or TTL.) Issue discovered by trying to test other stuff, which randomly caused the stack to be smaller than 8kB in that code location, which then causes the kernel to report EFAULT (Bad address). Signed-off-by: David Lamparter <[email protected]> Reviewed-by: Donald Sharp <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static __net_init int l2tp_eth_init_net(struct net *net) { struct l2tp_eth_net *pn = net_generic(net, l2tp_eth_net_id); INIT_LIST_HEAD(&pn->l2tp_eth_dev_list); spin_lock_init(&pn->l2tp_eth_lock); return 0; } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( const CompactHTMLToken& token, HTMLTokenizer* tokenizer) { SimulatedToken simulated_token = kOtherToken; if (token.GetType() == HTMLToken::kStartTag) { const String& tag_name = token.Data(); if (ThreadSafeMatch(tag_name, SVGNames::svgTag)) namespace_stack_.push_back(SVG); if (ThreadSafeMatch(tag_name, MathMLNames::mathTag)) namespace_stack_.push_back(kMathML); if (InForeignContent() && TokenExitsForeignContent(token)) namespace_stack_.pop_back(); if ((namespace_stack_.back() == SVG && TokenExitsSVG(token)) || (namespace_stack_.back() == kMathML && TokenExitsMath(token))) namespace_stack_.push_back(HTML); if (!InForeignContent()) { if (ThreadSafeMatch(tag_name, textareaTag) || ThreadSafeMatch(tag_name, titleTag)) { tokenizer->SetState(HTMLTokenizer::kRCDATAState); } else if (ThreadSafeMatch(tag_name, scriptTag)) { tokenizer->SetState(HTMLTokenizer::kScriptDataState); simulated_token = kScriptStart; } else if (ThreadSafeMatch(tag_name, linkTag)) { simulated_token = kLink; } else if (!in_select_insertion_mode_) { if (ThreadSafeMatch(tag_name, plaintextTag) && !in_select_insertion_mode_) { tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState); } else if (ThreadSafeMatch(tag_name, styleTag) || ThreadSafeMatch(tag_name, iframeTag) || ThreadSafeMatch(tag_name, xmpTag) || (ThreadSafeMatch(tag_name, noembedTag) && options_.plugins_enabled) || ThreadSafeMatch(tag_name, noframesTag) || (ThreadSafeMatch(tag_name, noscriptTag) && options_.script_enabled)) { tokenizer->SetState(HTMLTokenizer::kRAWTEXTState); } } if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = true; } else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) { in_select_insertion_mode_ = false; } } } if (token.GetType() == HTMLToken::kEndTag || (token.GetType() == HTMLToken::kStartTag && token.SelfClosing() && InForeignContent())) { const String& tag_name = token.Data(); if ((namespace_stack_.back() == SVG && ThreadSafeMatch(tag_name, SVGNames::svgTag)) || (namespace_stack_.back() == kMathML && ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || (namespace_stack_.Contains(SVG) && namespace_stack_.back() == HTML && TokenExitsSVG(token)) || (namespace_stack_.Contains(kMathML) && namespace_stack_.back() == HTML && TokenExitsMath(token))) { namespace_stack_.pop_back(); } if (ThreadSafeMatch(tag_name, scriptTag)) { if (!InForeignContent()) tokenizer->SetState(HTMLTokenizer::kDataState); return kScriptEnd; } else if (ThreadSafeMatch(tag_name, selectTag)) { in_select_insertion_mode_ = false; } if (ThreadSafeMatch(tag_name, styleTag)) simulated_token = kStyleEnd; } tokenizer->SetForceNullCharacterReplacement(InForeignContent()); tokenizer->SetShouldAllowCDATA(InForeignContent()); return simulated_token; } Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator. HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML integration point. This CL adds <annotation-xml>, <desc>, and SVG <title>. Bug: 805924 Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2 Reviewed-on: https://chromium-review.googlesource.com/964038 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Cr-Commit-Position: refs/heads/master@{#543634} CWE ID: CWE-79 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 nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) { if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0) memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data)); memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data)); switch (open_flags) { case FMODE_READ: set_bit(NFS_O_RDONLY_STATE, &state->flags); break; case FMODE_WRITE: set_bit(NFS_O_WRONLY_STATE, &state->flags); break; case FMODE_READ|FMODE_WRITE: set_bit(NFS_O_RDWR_STATE, &state->flags); } } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Target: 1 Example 2: Code: static inline int may_follow_link(struct path *link, struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = link->dentry->d_inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->path.dentry->d_inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; audit_log_link_denied("follow_link", link); path_put_conditional(link, nd); path_put(&nd->path); return -EACCES; } 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: on_response(void *data, krb5_error_code retval, otp_response response) { struct request_state rs = *(struct request_state *)data; free(data); if (retval == 0 && response != otp_response_success) retval = KRB5_PREAUTH_FAILED; rs.respond(rs.arg, retval, NULL, NULL, NULL); } Commit Message: Prevent requires_preauth bypass [CVE-2015-2694] In the OTP kdcpreauth module, don't set the TKT_FLG_PRE_AUTH bit until the request is successfully verified. In the PKINIT kdcpreauth module, don't respond with code 0 on empty input or an unconfigured realm. Together these bugs could cause the KDC preauth framework to erroneously treat a request as pre-authenticated. CVE-2015-2694: In MIT krb5 1.12 and later, when the KDC is configured with PKINIT support, an unauthenticated remote attacker can bypass the requires_preauth flag on a client principal and obtain a ciphertext encrypted in the principal's long-term key. This ciphertext could be used to conduct an off-line dictionary attack against the user's password. CVSSv2 Vector: AV:N/AC:M/Au:N/C:P/I:P/A:N/E:POC/RL:OF/RC:C ticket: 8160 (new) target_version: 1.13.2 tags: pullup subject: requires_preauth bypass in PKINIT-enabled KDC [CVE-2015-2694] 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: MagickExport int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l(c,c_locale)); #endif return(tolower(c)); } Commit Message: ... CWE ID: CWE-125 Target: 1 Example 2: Code: void esp_command_complete(SCSIRequest *req, uint32_t status, size_t resid) { ESPState *s = req->hba_private; trace_esp_command_complete(); if (s->ti_size != 0) { trace_esp_command_complete_unexpected(); } s->ti_size = 0; s->dma_left = 0; s->async_len = 0; if (status) { trace_esp_command_complete_fail(); } s->status = status; s->rregs[ESP_RSTAT] = STAT_ST; esp_dma_done(s); if (s->current_req) { scsi_req_unref(s->current_req); s->current_req = NULL; s->current_dev = NULL; } } Commit Message: CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadSCREENSHOTImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; 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=(Image *) NULL; #if defined(MAGICKCORE_WINGDI32_DELEGATE) { BITMAPINFO bmi; DISPLAY_DEVICE device; HBITMAP bitmap, bitmapOld; HDC bitmapDC, hDC; Image *screen; int i; register PixelPacket *q; register ssize_t x; RGBTRIPLE *p; ssize_t y; assert(image_info != (const ImageInfo *) NULL); i=0; device.cb = sizeof(device); image=(Image *) NULL; while(EnumDisplayDevices(NULL,i,&device,0) && ++i) { if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE) continue; hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL); if (hDC == (HDC) NULL) ThrowReaderException(CoderError,"UnableToCreateDC"); screen=AcquireImage(image_info); screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES); screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES); screen->storage_class=DirectClass; if (image == (Image *) NULL) image=screen; else AppendImageToList(&image,screen); bitmapDC=CreateCompatibleDC(hDC); if (bitmapDC == (HDC) NULL) { DeleteDC(hDC); ThrowReaderException(CoderError,"UnableToCreateDC"); } (void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO)); bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth=(LONG) screen->columns; bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows; bmi.bmiHeader.biPlanes=1; bmi.bmiHeader.biBitCount=24; bmi.bmiHeader.biCompression=BI_RGB; bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0); if (bitmap == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap); if (bitmapOld == (HBITMAP) NULL) { DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); ThrowReaderException(CoderError,"UnableToCreateBitmap"); } BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0, SRCCOPY); (void) SelectObject(bitmapDC,bitmapOld); for (y=0; y < (ssize_t) screen->rows; y++) { q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) screen->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed)); SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen)); SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue)); SetPixelOpacity(q,OpaqueOpacity); p++; q++; } if (SyncAuthenticPixels(screen,exception) == MagickFalse) break; } DeleteDC(hDC); DeleteDC(bitmapDC); DeleteObject(bitmap); } } #elif defined(MAGICKCORE_X11_DELEGATE) { const char *option; XImportInfo ximage_info; (void) exception; XGetImportInfo(&ximage_info); option=GetImageOption(image_info,"x:screen"); if (option != (const char *) NULL) ximage_info.screen=IsMagickTrue(option); option=GetImageOption(image_info,"x:silent"); if (option != (const char *) NULL) ximage_info.silent=IsMagickTrue(option); image=XImportImage(image_info,&ximage_info); } #endif return(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: cliprdr_process(STREAM s) { uint16 type, status; uint32 length, format; uint8 *data; in_uint16_le(s, type); in_uint16_le(s, status); in_uint32_le(s, length); data = s->p; logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status, length); if (status == CLIPRDR_ERROR) { switch (type) { case CLIPRDR_FORMAT_ACK: /* FIXME: We seem to get this when we send an announce while the server is still processing a paste. Try sending another announce. */ cliprdr_send_native_format_announce(last_formats, last_formats_length); break; case CLIPRDR_DATA_RESPONSE: ui_clip_request_failed(); break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled error (type=%d)", type); } return; } switch (type) { case CLIPRDR_CONNECT: ui_clip_sync(); break; case CLIPRDR_FORMAT_ANNOUNCE: ui_clip_format_announce(data, length); cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0); return; case CLIPRDR_FORMAT_ACK: break; case CLIPRDR_DATA_REQUEST: in_uint32_le(s, format); ui_clip_request_data(format); break; case CLIPRDR_DATA_RESPONSE: ui_clip_handle_data(data, length); break; case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */ break; default: logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d", type); } } 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: 1 Example 2: Code: static int __init file_caps_disable(char *str) { file_caps_enabled = 0; return 1; } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Dave Chinner <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: webrtc::MediaStreamTrackInterface* MediaStreamImpl::GetLocalMediaStreamTrack( const std::string& label) { DCHECK(CalledOnValidThread()); MediaStreamTrackPtrMap::iterator it = local_tracks_.find(label); if (it == local_tracks_.end()) return NULL; MediaStreamTrackPtr stream = it->second; return stream.get(); } Commit Message: Explicitly stopping thread in MediaStreamImpl dtor to avoid any racing issues. This may solve the below bugs. BUG=112408,111202 TEST=content_unittests Review URL: https://chromiumcodereview.appspot.com/9307058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120222 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: e1000e_write_packet_to_guest(E1000ECore *core, struct NetRxPkt *pkt, const E1000E_RxRing *rxr, const E1000E_RSSInfo *rss_info) { PCIDevice *d = core->owner; dma_addr_t base; uint8_t desc[E1000_MAX_RX_DESC_LEN]; size_t desc_size; size_t desc_offset = 0; size_t iov_ofs = 0; struct iovec *iov = net_rx_pkt_get_iovec(pkt); size_t size = net_rx_pkt_get_total_len(pkt); size_t total_size = size + e1000x_fcs_len(core->mac); const E1000E_RingInfo *rxi; size_t ps_hdr_len = 0; bool do_ps = e1000e_do_ps(core, pkt, &ps_hdr_len); bool is_first = true; rxi = rxr->i; do { hwaddr ba[MAX_PS_BUFFERS]; e1000e_ba_state bastate = { { 0 } }; bool is_last = false; desc_size = total_size - desc_offset; if (desc_size > core->rx_desc_buf_size) { desc_size = core->rx_desc_buf_size; desc_size = core->rx_desc_buf_size; } base = e1000e_ring_head_descr(core, rxi); pci_dma_read(d, base, &desc, core->rx_desc_len); if (ba[0]) { if (desc_offset < size) { static const uint32_t fcs_pad; size_t iov_copy; size_t copy_size = size - desc_offset; if (copy_size > core->rx_desc_buf_size) { copy_size = core->rx_desc_buf_size; } /* For PS mode copy the packet header first */ if (do_ps) { if (is_first) { size_t ps_hdr_copied = 0; do { iov_copy = MIN(ps_hdr_len - ps_hdr_copied, iov->iov_len - iov_ofs); e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate, iov->iov_base, iov_copy); copy_size -= iov_copy; ps_hdr_copied += iov_copy; iov_ofs += iov_copy; if (iov_ofs == iov->iov_len) { iov++; iov_ofs = 0; } } while (ps_hdr_copied < ps_hdr_len); is_first = false; } else { /* Leave buffer 0 of each descriptor except first */ /* empty as per spec 7.1.5.1 */ e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate, NULL, 0); } } /* Copy packet payload */ while (copy_size) { iov_copy = MIN(copy_size, iov->iov_len - iov_ofs); e1000e_write_to_rx_buffers(core, &ba, &bastate, iov->iov_base + iov_ofs, iov_copy); copy_size -= iov_copy; iov_ofs += iov_copy; if (iov_ofs == iov->iov_len) { iov++; iov_ofs = 0; } } if (desc_offset + desc_size >= total_size) { /* Simulate FCS checksum presence in the last descriptor */ e1000e_write_to_rx_buffers(core, &ba, &bastate, (const char *) &fcs_pad, e1000x_fcs_len(core->mac)); } } desc_offset += desc_size; if (desc_offset >= total_size) { is_last = true; } } else { /* as per intel docs; skip descriptors with null buf addr */ trace_e1000e_rx_null_descriptor(); } e1000e_write_rx_descr(core, desc, is_last ? core->rx_pkt : NULL, rss_info, do_ps ? ps_hdr_len : 0, &bastate.written); pci_dma_write(d, base, &desc, core->rx_desc_len); e1000e_ring_advance(core, rxi, core->rx_desc_len / E1000_MIN_RX_DESC_LEN); } while (desc_offset < total_size); e1000e_update_rx_stats(core, size, total_size); } Commit Message: CWE ID: CWE-835 Target: 1 Example 2: Code: static ssize_t proc_sessionid_read(struct file * file, char __user * buf, size_t count, loff_t *ppos) { struct inode * inode = file_inode(file); struct task_struct *task = get_proc_task(inode); ssize_t length; char tmpbuf[TMPBUFLEN]; if (!task) return -ESRCH; length = scnprintf(tmpbuf, TMPBUFLEN, "%u", audit_get_sessionid(task)); put_task_struct(task); return simple_read_from_buffer(buf, count, ppos, tmpbuf, length); } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <[email protected]> Cc: Emese Revfy <[email protected]> Cc: Pax Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Mateusz Guzik <[email protected]> Cc: Alexey Dobriyan <[email protected]> Cc: Cyrill Gorcunov <[email protected]> Cc: Jarod Wilson <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void writeDate(double numberValue) { append(DateTag); doWriteNumber(numberValue); } 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:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: std::string Experiment::NameForChoice(int index) const { DCHECK(type == Experiment::MULTI_VALUE || type == Experiment::ENABLE_DISABLE_VALUE); DCHECK_LT(index, num_choices); return std::string(internal_name) + testing::kMultiSeparator + base::IntToString(index); } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 DesktopWindowTreeHostX11::SetWindowTransparency() { compositor()->SetBackgroundColor(use_argb_visual_ ? SK_ColorTRANSPARENT : SK_ColorWHITE); window()->SetTransparent(use_argb_visual_); content_window()->SetTransparent(use_argb_visual_); } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char *argv[]) { int free_query_string = 0; int exit_status = SUCCESS; int cgi = 0, c, i, len; zend_file_handle file_handle; char *s; /* temporary locals */ int behavior = PHP_MODE_STANDARD; int no_headers = 0; int orig_optind = php_optind; char *orig_optarg = php_optarg; char *script_file = NULL; int ini_entries_len = 0; /* end of temporary locals */ #ifdef ZTS void ***tsrm_ls; #endif int max_requests = 500; int requests = 0; int fastcgi; char *bindpath = NULL; int fcgi_fd = 0; fcgi_request *request = NULL; int repeats = 1; int benchmark = 0; #if HAVE_GETTIMEOFDAY struct timeval start, end; #else time_t start, end; #endif #ifndef PHP_WIN32 int status = 0; #endif char *query_string; char *decoded_query_string; int skip_getopt = 0; #if 0 && defined(PHP_DEBUG) /* IIS is always making things more difficult. This allows * us to stop PHP and attach a debugger before much gets started */ { char szMessage [256]; wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]); MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION); } #endif #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! [email protected] 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); tsrm_ls = ts_resource(0); #endif sapi_startup(&cgi_sapi_module); fastcgi = fcgi_is_fastcgi(); cgi_sapi_module.php_ini_path_override = NULL; #ifdef PHP_WIN32 _fmode = _O_BINARY; /* sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif if (!fastcgi) { /* Make sure we detect we are a cgi - a bit redundancy here, * but the default case is that we have to check only the first one. */ if (getenv("SERVER_SOFTWARE") || getenv("SERVER_NAME") || getenv("GATEWAY_INTERFACE") || getenv("REQUEST_METHOD") ) { cgi = 1; } } if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) { /* we've got query string that has no = - apache CGI will pass it to command line */ unsigned char *p; decoded_query_string = strdup(query_string); php_url_decode(decoded_query_string, strlen(decoded_query_string)); for (p = decoded_query_string; *p && *p <= ' '; p++) { /* skip all leading spaces */ } if(*p == '-') { skip_getopt = 1; } free(decoded_query_string); } while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'c': if (cgi_sapi_module.php_ini_path_override) { free(cgi_sapi_module.php_ini_path_override); } cgi_sapi_module.php_ini_path_override = strdup(php_optarg); break; case 'n': cgi_sapi_module.php_ini_ignore = 1; break; case 'd': { /* define ini entries on command line */ int len = strlen(php_optarg); char *val; if ((val = strchr(php_optarg, '='))) { val++; if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg)); ini_entries_len += (val - php_optarg); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1); ini_entries_len++; memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg)); ini_entries_len += len - (val - php_optarg); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0")); ini_entries_len += sizeof("\n\0\"") - 2; } else { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len); memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0")); ini_entries_len += len + sizeof("\n\0") - 2; } } else { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len); memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0")); ini_entries_len += len + sizeof("=1\n\0") - 2; } break; } /* if we're started on command line, check to see if * we are being started as an 'external' fastcgi * server by accepting a bindpath parameter. */ case 'b': if (!fastcgi) { bindpath = strdup(php_optarg); } break; case 's': /* generate highlighted HTML from source */ behavior = PHP_MODE_HIGHLIGHT; break; } } php_optind = orig_optind; php_optarg = orig_optarg; if (fastcgi || bindpath) { /* Override SAPI callbacks */ cgi_sapi_module.ub_write = sapi_fcgi_ub_write; cgi_sapi_module.flush = sapi_fcgi_flush; cgi_sapi_module.read_post = sapi_fcgi_read_post; cgi_sapi_module.getenv = sapi_fcgi_getenv; cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies; } #ifdef ZTS SG(request_info).path_translated = NULL; #endif cgi_sapi_module.executable_location = argv[0]; if (!cgi && !fastcgi && !bindpath) { cgi_sapi_module.additional_functions = additional_functions; } /* startup after we get the above ini override se we get things right */ if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) { #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } /* check force_cgi after startup, so we have proper output */ if (cgi && CGIG(force_redirect)) { /* Apache will generate REDIRECT_STATUS, * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS. * redirect.so and installation instructions available from * http://www.koehntopp.de/php. * -- [email protected] */ if (!getenv("REDIRECT_STATUS") && !getenv ("HTTP_REDIRECT_STATUS") && /* this is to allow a different env var to be configured * in case some server does something different than above */ (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env))) ) { zend_try { SG(sapi_headers).http_response_code = 400; PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\ <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\ means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\ set, e.g. via an Apache Action directive.</p>\n\ <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\ manual page for CGI security</a>.</p>\n\ <p>For more information about changing this behaviour or re-enabling this webserver,\n\ consult the installation file that came with this distribution, or visit \n\ <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n"); } zend_catch { } zend_end_try(); #if defined(ZTS) && !defined(PHP_DEBUG) /* XXX we're crashing here in msvc6 debug builds at * php_message_handler_for_zend:839 because * SG(request_info).path_translated is an invalid pointer. * It still happens even though I set it to null, so something * weird is going on. */ tsrm_shutdown(); #endif return FAILURE; } } if (bindpath) { fcgi_fd = fcgi_listen(bindpath, 128); if (fcgi_fd < 0) { fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath); #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } fastcgi = fcgi_is_fastcgi(); } if (fastcgi) { /* How many times to run PHP scripts before dying */ if (getenv("PHP_FCGI_MAX_REQUESTS")) { max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS")); if (max_requests < 0) { fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n"); return FAILURE; } } /* make php call us to get _ENV vars */ php_php_import_environment_variables = php_import_environment_variables; php_import_environment_variables = cgi_php_import_environment_variables; /* library is already initialized, now init our request */ request = fcgi_init_request(fcgi_fd); #ifndef PHP_WIN32 /* Pre-fork, if required */ if (getenv("PHP_FCGI_CHILDREN")) { char * children_str = getenv("PHP_FCGI_CHILDREN"); children = atoi(children_str); if (children < 0) { fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n"); return FAILURE; } fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str)); /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */ fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str)); } else { fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1); fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1); } if (children) { int running = 0; pid_t pid; /* Create a process group for ourself & children */ setsid(); pgroup = getpgrp(); #ifdef DEBUG_FASTCGI fprintf(stderr, "Process group %d\n", pgroup); #endif /* Set up handler to kill children upon exit */ act.sa_flags = 0; act.sa_handler = fastcgi_cleanup; if (sigaction(SIGTERM, &act, &old_term) || sigaction(SIGINT, &act, &old_int) || sigaction(SIGQUIT, &act, &old_quit) ) { perror("Can't set signals"); exit(1); } if (fcgi_in_shutdown()) { goto parent_out; } while (parent) { do { #ifdef DEBUG_FASTCGI fprintf(stderr, "Forking, %d running\n", running); #endif pid = fork(); switch (pid) { case 0: /* One of the children. * Make sure we don't go round the * fork loop any more */ parent = 0; /* don't catch our signals */ sigaction(SIGTERM, &old_term, 0); sigaction(SIGQUIT, &old_quit, 0); sigaction(SIGINT, &old_int, 0); break; case -1: perror("php (pre-forking)"); exit(1); break; default: /* Fine */ running++; break; } } while (parent && (running < children)); if (parent) { #ifdef DEBUG_FASTCGI fprintf(stderr, "Wait for kids, pid %d\n", getpid()); #endif parent_waiting = 1; while (1) { if (wait(&status) >= 0) { running--; break; } else if (exit_signal) { break; } } if (exit_signal) { #if 0 while (running > 0) { while (wait(&status) < 0) { } running--; } #endif goto parent_out; } } } } else { parent = 0; } #endif /* WIN32 */ } zend_first_try { while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) { switch (c) { case 'T': benchmark = 1; repeats = atoi(php_optarg); #ifdef HAVE_GETTIMEOFDAY gettimeofday(&start, NULL); #else time(&start); #endif break; case 'h': case '?': if (request) { fcgi_destroy_request(request); } fcgi_shutdown(); no_headers = 1; SG(headers_sent) = 1; php_cgi_usage(argv[0]); php_output_end_all(TSRMLS_C); exit_status = 0; goto out; } } php_optind = orig_optind; php_optarg = orig_optarg; /* start of FAST CGI loop */ /* Initialise FastCGI request structure */ #ifdef PHP_WIN32 /* attempt to set security impersonation for fastcgi * will only happen on NT based OS, others will ignore it. */ if (fastcgi && CGIG(impersonate)) { fcgi_impersonate(); } #endif while (!fastcgi || fcgi_accept_request(request) >= 0) { SG(server_context) = fastcgi ? (void *) request : (void *) 1; init_request_info(request TSRMLS_CC); CG(interactive) = 0; if (!cgi && !fastcgi) { while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'a': /* interactive mode */ printf("Interactive mode enabled\n\n"); CG(interactive) = 1; break; case 'C': /* don't chdir to the script directory */ SG(options) |= SAPI_OPTION_NO_CHDIR; break; case 'e': /* enable extended info output */ CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; break; case 'f': /* parse file */ if (script_file) { efree(script_file); } script_file = estrdup(php_optarg); no_headers = 1; break; case 'i': /* php info & quit */ if (script_file) { efree(script_file); } if (php_request_startup(TSRMLS_C) == FAILURE) { SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } php_print_info(0xFFFFFFFF TSRMLS_CC); php_request_shutdown((void *) 0); fcgi_shutdown(); exit_status = 0; goto out; case 'l': /* syntax check mode */ no_headers = 1; behavior = PHP_MODE_LINT; break; case 'm': /* list compiled in modules */ if (script_file) { efree(script_file); } SG(headers_sent) = 1; php_printf("[PHP Modules]\n"); print_modules(TSRMLS_C); php_printf("\n[Zend Modules]\n"); print_extensions(TSRMLS_C); php_printf("\n"); php_output_end_all(TSRMLS_C); fcgi_shutdown(); exit_status = 0; goto out; #if 0 /* not yet operational, see also below ... */ case '': /* generate indented source mode*/ behavior=PHP_MODE_INDENT; break; #endif case 'q': /* do not generate HTTP headers */ no_headers = 1; break; case 'v': /* show php version & quit */ if (script_file) { efree(script_file); } no_headers = 1; if (php_request_startup(TSRMLS_C) == FAILURE) { SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } #if ZEND_DEBUG php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #else php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #endif php_request_shutdown((void *) 0); fcgi_shutdown(); exit_status = 0; goto out; case 'w': behavior = PHP_MODE_STRIP; break; case 'z': /* load extension file */ zend_load_extension(php_optarg); break; default: break; } } if (script_file) { /* override path_translated if -f on command line */ STR_FREE(SG(request_info).path_translated); SG(request_info).path_translated = script_file; /* before registering argv to module exchange the *new* argv[0] */ /* we can achieve this without allocating more memory */ SG(request_info).argc = argc - (php_optind - 1); SG(request_info).argv = &argv[php_optind - 1]; SG(request_info).argv[0] = script_file; } else if (argc > php_optind) { /* file is on command line, but not in -f opt */ STR_FREE(SG(request_info).path_translated); SG(request_info).path_translated = estrdup(argv[php_optind]); /* arguments after the file are considered script args */ SG(request_info).argc = argc - php_optind; SG(request_info).argv = &argv[php_optind]; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } /* all remaining arguments are part of the query string * this section of code concatenates all remaining arguments * into a single string, seperating args with a & * this allows command lines like: * * test.php v1=test v2=hello+world! * test.php "v1=test&v2=hello world!" * test.php v1=test "v2=hello world!" */ if (!SG(request_info).query_string && argc > php_optind) { int slen = strlen(PG(arg_separator).input); len = 0; for (i = php_optind; i < argc; i++) { if (i < (argc - 1)) { len += strlen(argv[i]) + slen; } else { len += strlen(argv[i]); } } len += 2; s = malloc(len); *s = '\0'; /* we are pretending it came from the environment */ for (i = php_optind; i < argc; i++) { strlcat(s, argv[i], len); if (i < (argc - 1)) { strlcat(s, PG(arg_separator).input, len); } } SG(request_info).query_string = s; free_query_string = 1; } } /* end !cgi && !fastcgi */ /* we never take stdin if we're (f)cgi, always rely on the web server giving us the info we need in the environment. */ if (SG(request_info).path_translated || cgi || fastcgi) { file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = SG(request_info).path_translated; file_handle.handle.fp = NULL; } else { file_handle.filename = "-"; file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = stdin; } file_handle.opened_path = NULL; file_handle.free_filename = 0; /* request startup only after we've done all we can to * get path_translated */ if (php_request_startup(TSRMLS_C) == FAILURE) { if (fastcgi) { fcgi_finish_request(request, 1); } SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } /* at this point path_translated will be set if: 1. we are running from shell and got filename was there 2. we are running as cgi or fastcgi */ if (cgi || fastcgi || SG(request_info).path_translated) { if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) { zend_try { if (errno == EACCES) { SG(sapi_headers).http_response_code = 403; PUTS("Access denied.\n"); } else { SG(sapi_headers).http_response_code = 404; PUTS("No input file specified.\n"); } } zend_catch { } zend_end_try(); /* we want to serve more requests if this is fastcgi * so cleanup and continue, request shutdown is * handled later */ if (fastcgi) { goto fastcgi_request_done; } STR_FREE(SG(request_info).path_translated); if (free_query_string && SG(request_info).query_string) { free(SG(request_info).query_string); SG(request_info).query_string = NULL; } php_request_shutdown((void *) 0); SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } } if (CGIG(check_shebang_line)) { /* #!php support */ switch (file_handle.type) { case ZEND_HANDLE_FD: if (file_handle.handle.fd < 0) { break; } file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb"); /* break missing intentionally */ case ZEND_HANDLE_FP: if (!file_handle.handle.fp || (file_handle.handle.fp == stdin)) { break; } c = fgetc(file_handle.handle.fp); if (c == '#') { while (c != '\n' && c != '\r' && c != EOF) { c = fgetc(file_handle.handle.fp); /* skip to end of line */ } /* handle situations where line is terminated by \r\n */ if (c == '\r') { if (fgetc(file_handle.handle.fp) != '\n') { long pos = ftell(file_handle.handle.fp); fseek(file_handle.handle.fp, pos - 1, SEEK_SET); } } CG(start_lineno) = 2; } else { rewind(file_handle.handle.fp); } break; case ZEND_HANDLE_STREAM: c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); if (c == '#') { while (c != '\n' && c != '\r' && c != EOF) { c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */ } /* handle situations where line is terminated by \r\n */ if (c == '\r') { if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') { long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle); php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET); } } CG(start_lineno) = 2; } else { php_stream_rewind((php_stream*)file_handle.handle.stream.handle); } break; case ZEND_HANDLE_MAPPED: if (file_handle.handle.stream.mmap.buf[0] == '#') { int i = 1; c = file_handle.handle.stream.mmap.buf[i++]; while (c != '\n' && c != '\r' && c != EOF) { c = file_handle.handle.stream.mmap.buf[i++]; } if (c == '\r') { if (file_handle.handle.stream.mmap.buf[i] == '\n') { i++; } } file_handle.handle.stream.mmap.buf += i; file_handle.handle.stream.mmap.len -= i; } } } switch (behavior) { case PHP_MODE_STANDARD: php_execute_script(&file_handle TSRMLS_CC); break; case PHP_MODE_LINT: PG(during_request_startup) = 0; exit_status = php_lint_script(&file_handle TSRMLS_CC); if (exit_status == SUCCESS) { zend_printf("No syntax errors detected in %s\n", file_handle.filename); } else { zend_printf("Errors parsing %s\n", file_handle.filename); } break; case PHP_MODE_STRIP: if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) { zend_strip(TSRMLS_C); zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); } return SUCCESS; break; case PHP_MODE_HIGHLIGHT: { zend_syntax_highlighter_ini syntax_highlighter_ini; if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) { php_get_highlight_struct(&syntax_highlighter_ini); zend_highlight(&syntax_highlighter_ini TSRMLS_CC); if (fastcgi) { goto fastcgi_request_done; } zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); } return SUCCESS; } break; #if 0 /* Zeev might want to do something with this one day */ case PHP_MODE_INDENT: open_file_for_scanning(&file_handle TSRMLS_CC); zend_indent(); zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); return SUCCESS; break; #endif } fastcgi_request_done: { STR_FREE(SG(request_info).path_translated); php_request_shutdown((void *) 0); if (exit_status == 0) { exit_status = EG(exit_status); } if (free_query_string && SG(request_info).query_string) { free(SG(request_info).query_string); SG(request_info).query_string = NULL; } } if (!fastcgi) { if (benchmark) { repeats--; if (repeats > 0) { script_file = NULL; php_optind = orig_optind; php_optarg = orig_optarg; continue; } } break; } /* only fastcgi will get here */ requests++; if (max_requests && (requests == max_requests)) { fcgi_finish_request(request, 1); if (bindpath) { free(bindpath); } if (max_requests != 1) { /* no need to return exit_status of the last request */ exit_status = 0; } break; } /* end of fastcgi loop */ } if (request) { fcgi_destroy_request(request); } fcgi_shutdown(); if (cgi_sapi_module.php_ini_path_override) { free(cgi_sapi_module.php_ini_path_override); } if (cgi_sapi_module.ini_entries) { free(cgi_sapi_module.ini_entries); } } zend_catch { exit_status = 255; } zend_end_try(); out: if (benchmark) { int sec; #ifdef HAVE_GETTIMEOFDAY int usec; gettimeofday(&end, NULL); sec = (int)(end.tv_sec - start.tv_sec); if (end.tv_usec >= start.tv_usec) { usec = (int)(end.tv_usec - start.tv_usec); } else { sec -= 1; usec = (int)(end.tv_usec + 1000000 - start.tv_usec); } fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec); #else time(&end); sec = (int)(end - start); fprintf(stderr, "\nElapsed time: %d sec\n", sec); #endif } #ifndef PHP_WIN32 parent_out: #endif SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif #if defined(PHP_WIN32) && ZEND_DEBUG && 0 _CrtDumpMemoryLeaks(); #endif return exit_status; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: NTSTATUS smb_register_vfs(int version, const char *name, const struct vfs_fn_pointers *fns) { struct vfs_init_function_entry *entry = backends; if ((version != SMB_VFS_INTERFACE_VERSION)) { DEBUG(0, ("Failed to register vfs module.\n" "The module was compiled against SMB_VFS_INTERFACE_VERSION %d,\n" "current SMB_VFS_INTERFACE_VERSION is %d.\n" "Please recompile against the current Samba Version!\n", version, SMB_VFS_INTERFACE_VERSION)); return NT_STATUS_OBJECT_TYPE_MISMATCH; } if (!name || !name[0]) { DEBUG(0,("smb_register_vfs() called with NULL pointer or empty name!\n")); return NT_STATUS_INVALID_PARAMETER; } if (vfs_find_backend_entry(name)) { DEBUG(0,("VFS module %s already loaded!\n", name)); return NT_STATUS_OBJECT_NAME_COLLISION; } entry = SMB_XMALLOC_P(struct vfs_init_function_entry); entry->name = smb_xstrdup(name); entry->fns = fns; DLIST_ADD(backends, entry); DEBUG(5, ("Successfully added vfs backend '%s'\n", name)); return NT_STATUS_OK; } Commit Message: CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int em_ret_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip, cs; u16 old_cs; int cpl = ctxt->ops->cpl(ctxt); struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS); rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; /* Outer-privilege level return is not implemented */ if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl) return X86EMUL_UNHANDLEABLE; rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl, X86_TRANSFER_RET, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, eip, &new_desc); if (rc != X86EMUL_CONTINUE) { WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64); ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS); } return rc; } Commit Message: KVM: x86: drop error recovery in em_jmp_far and em_ret_far em_jmp_far and em_ret_far assumed that setting IP can only fail in 64 bit mode, but syzkaller proved otherwise (and SDM agrees). Code segment was restored upon failure, but it was left uninitialized outside of long mode, which could lead to a leak of host kernel stack. We could have fixed that by always saving and restoring the CS, but we take a simpler approach and just break any guest that manages to fail as the error recovery is error-prone and modern CPUs don't need emulator for this. Found by syzkaller: WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480 Kernel panic - not syncing: panic_on_warn set ... CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 [...] Call Trace: [...] __dump_stack lib/dump_stack.c:15 [...] dump_stack+0xb3/0x118 lib/dump_stack.c:51 [...] panic+0x1b7/0x3a3 kernel/panic.c:179 [...] __warn+0x1c4/0x1e0 kernel/panic.c:542 [...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585 [...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217 [...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227 [...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294 [...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545 [...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116 [...] complete_emulated_io arch/x86/kvm/x86.c:6870 [...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934 [...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978 [...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557 [...] vfs_ioctl fs/ioctl.c:43 [...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679 [...] SYSC_ioctl fs/ioctl.c:694 [...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685 [...] entry_SYSCALL_64_fastpath+0x1f/0xc2 Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: d1442d85cc30 ("KVM: x86: Handle errors when RIP is set during far jumps") Signed-off-by: Radim Krčmář <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: VP8PictureToVaapiDecodeSurface(const scoped_refptr<VP8Picture>& pic) { VaapiVP8Picture* vaapi_pic = pic->AsVaapiVP8Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 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: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362 Target: 1 Example 2: Code: get_internet_likely_down_interval(void) { return networkstatus_get_param(NULL, "guard-internet-likely-down-interval", DFLT_INTERNET_LIKELY_DOWN_INTERVAL, 1, INT32_MAX); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: free_config_tinker( config_tree *ptree ) { FREE_ATTR_VAL_FIFO(ptree->tinker); } Commit Message: [Bug 1773] openssl not detected during ./configure. [Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL. 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: client_x11_display_valid(const char *display) { size_t i, dlen; dlen = strlen(display); for (i = 0; i < dlen; i++) { if (!isalnum((u_char)display[i]) && } } Commit Message: CWE ID: CWE-254 Target: 1 Example 2: Code: daemon_msg_err(SOCKET sockctrl, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; char remote_errbuf[PCAP_ERRBUF_SIZE]; if (plen >= PCAP_ERRBUF_SIZE) { /* * Message is too long; just read as much of it as we * can into the buffer provided, and discard the rest. */ if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } if (rpcapd_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1)) == -1) { return -1; } /* * Null-terminate it. */ remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0'; } else if (plen == 0) { /* Empty error string. */ remote_errbuf[0] = '\0'; } else { if (sock_recv(sockctrl, remote_errbuf, plen, SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE) == -1) { rpcapd_log(LOGPRIO_ERROR, "Read from client failed: %s", errbuf); return -1; } /* * Null-terminate it. */ remote_errbuf[plen] = '\0'; } rpcapd_log(LOGPRIO_ERROR, "Error from client: %s", remote_errbuf); return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 PPB_Widget_Impl::SetLocation(const PP_Rect* location) { location_ = *location; SetLocationInternal(location); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 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: void WebDevToolsAgentImpl::clearBrowserCookies() { m_client->clearBrowserCookies(); } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: lseg_parallel(PG_FUNCTION_ARGS) { LSEG *l1 = PG_GETARG_LSEG_P(0); LSEG *l2 = PG_GETARG_LSEG_P(1); #ifdef NOT_USED PG_RETURN_BOOL(FPeq(l1->m, l2->m)); #endif PG_RETURN_BOOL(FPeq(point_sl(&l1->p[0], &l1->p[1]), point_sl(&l2->p[0], &l2->p[1]))); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool) { if (valbool) sock_set_flag(sk, bit); else sock_reset_flag(sk, bit); } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int32 CommandBufferProxyImpl::CreateTransferBuffer( size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; scoped_ptr<base::SharedMemory> shm( channel_->factory()->AllocateSharedMemory(size)); if (!shm.get()) return -1; base::SharedMemoryHandle handle = shm->handle(); #if defined(OS_POSIX) DCHECK(!handle.auto_close); #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_, handle, size, id_request, &id))) { return -1; } return id; } 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: static void add_capability(uint32_t **caps, int *num_caps, uint32_t cap) { int nbefore, n; nbefore = *num_caps; n = cap / 32; *num_caps = MAX(*num_caps, n + 1); *caps = spice_renew(uint32_t, *caps, *num_caps); memset(*caps + nbefore, 0, (*num_caps - nbefore) * sizeof(uint32_t)); (*caps)[n] |= (1 << (cap % 32)); } Commit Message: CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int do_mathemu(struct pt_regs *regs, struct fpustate *f) { unsigned long pc = regs->tpc; unsigned long tstate = regs->tstate; u32 insn = 0; int type = 0; /* ftt tells which ftt it may happen in, r is rd, b is rs2 and a is rs1. The *u arg tells whether the argument should be packed/unpacked (0 - do not unpack/pack, 1 - unpack/pack) non-u args tells the size of the argument (0 - no argument, 1 - single, 2 - double, 3 - quad */ #define TYPE(ftt, r, ru, b, bu, a, au) type = (au << 2) | (a << 0) | (bu << 5) | (b << 3) | (ru << 8) | (r << 6) | (ftt << 9) int freg; static u64 zero[2] = { 0L, 0L }; int flags; FP_DECL_EX; FP_DECL_S(SA); FP_DECL_S(SB); FP_DECL_S(SR); FP_DECL_D(DA); FP_DECL_D(DB); FP_DECL_D(DR); FP_DECL_Q(QA); FP_DECL_Q(QB); FP_DECL_Q(QR); int IR; long XR, xfsr; if (tstate & TSTATE_PRIV) die_if_kernel("unfinished/unimplemented FPop from kernel", regs); perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); if (test_thread_flag(TIF_32BIT)) pc = (u32)pc; if (get_user(insn, (u32 __user *) pc) != -EFAULT) { if ((insn & 0xc1f80000) == 0x81a00000) /* FPOP1 */ { switch ((insn >> 5) & 0x1ff) { /* QUAD - ftt == 3 */ case FMOVQ: case FNEGQ: case FABSQ: TYPE(3,3,0,3,0,0,0); break; case FSQRTQ: TYPE(3,3,1,3,1,0,0); break; case FADDQ: case FSUBQ: case FMULQ: case FDIVQ: TYPE(3,3,1,3,1,3,1); break; case FDMULQ: TYPE(3,3,1,2,1,2,1); break; case FQTOX: TYPE(3,2,0,3,1,0,0); break; case FXTOQ: TYPE(3,3,1,2,0,0,0); break; case FQTOS: TYPE(3,1,1,3,1,0,0); break; case FQTOD: TYPE(3,2,1,3,1,0,0); break; case FITOQ: TYPE(3,3,1,1,0,0,0); break; case FSTOQ: TYPE(3,3,1,1,1,0,0); break; case FDTOQ: TYPE(3,3,1,2,1,0,0); break; case FQTOI: TYPE(3,1,0,3,1,0,0); break; /* We can get either unimplemented or unfinished * for these cases. Pre-Niagara systems generate * unfinished fpop for SUBNORMAL cases, and Niagara * always gives unimplemented fpop for fsqrt{s,d}. */ case FSQRTS: { unsigned long x = current_thread_info()->xfsr[0]; x = (x >> 14) & 0xf; TYPE(x,1,1,1,1,0,0); break; } case FSQRTD: { unsigned long x = current_thread_info()->xfsr[0]; x = (x >> 14) & 0xf; TYPE(x,2,1,2,1,0,0); break; } /* SUBNORMAL - ftt == 2 */ case FADDD: case FSUBD: case FMULD: case FDIVD: TYPE(2,2,1,2,1,2,1); break; case FADDS: case FSUBS: case FMULS: case FDIVS: TYPE(2,1,1,1,1,1,1); break; case FSMULD: TYPE(2,2,1,1,1,1,1); break; case FSTOX: TYPE(2,2,0,1,1,0,0); break; case FDTOX: TYPE(2,2,0,2,1,0,0); break; case FDTOS: TYPE(2,1,1,2,1,0,0); break; case FSTOD: TYPE(2,2,1,1,1,0,0); break; case FSTOI: TYPE(2,1,0,1,1,0,0); break; case FDTOI: TYPE(2,1,0,2,1,0,0); break; /* Only Ultra-III generates these */ case FXTOS: TYPE(2,1,1,2,0,0,0); break; case FXTOD: TYPE(2,2,1,2,0,0,0); break; #if 0 /* Optimized inline in sparc64/kernel/entry.S */ case FITOS: TYPE(2,1,1,1,0,0,0); break; #endif case FITOD: TYPE(2,2,1,1,0,0,0); break; } } else if ((insn & 0xc1f80000) == 0x81a80000) /* FPOP2 */ { IR = 2; switch ((insn >> 5) & 0x1ff) { case FCMPQ: TYPE(3,0,0,3,1,3,1); break; case FCMPEQ: TYPE(3,0,0,3,1,3,1); break; /* Now the conditional fmovq support */ case FMOVQ0: case FMOVQ1: case FMOVQ2: case FMOVQ3: /* fmovq %fccX, %fY, %fZ */ if (!((insn >> 11) & 3)) XR = current_thread_info()->xfsr[0] >> 10; else XR = current_thread_info()->xfsr[0] >> (30 + ((insn >> 10) & 0x6)); XR &= 3; IR = 0; switch ((insn >> 14) & 0x7) { /* case 0: IR = 0; break; */ /* Never */ case 1: if (XR) IR = 1; break; /* Not Equal */ case 2: if (XR == 1 || XR == 2) IR = 1; break; /* Less or Greater */ case 3: if (XR & 1) IR = 1; break; /* Unordered or Less */ case 4: if (XR == 1) IR = 1; break; /* Less */ case 5: if (XR & 2) IR = 1; break; /* Unordered or Greater */ case 6: if (XR == 2) IR = 1; break; /* Greater */ case 7: if (XR == 3) IR = 1; break; /* Unordered */ } if ((insn >> 14) & 8) IR ^= 1; break; case FMOVQI: case FMOVQX: /* fmovq %[ix]cc, %fY, %fZ */ XR = regs->tstate >> 32; if ((insn >> 5) & 0x80) XR >>= 4; XR &= 0xf; IR = 0; freg = ((XR >> 2) ^ XR) & 2; switch ((insn >> 14) & 0x7) { /* case 0: IR = 0; break; */ /* Never */ case 1: if (XR & 4) IR = 1; break; /* Equal */ case 2: if ((XR & 4) || freg) IR = 1; break; /* Less or Equal */ case 3: if (freg) IR = 1; break; /* Less */ case 4: if (XR & 5) IR = 1; break; /* Less or Equal Unsigned */ case 5: if (XR & 1) IR = 1; break; /* Carry Set */ case 6: if (XR & 8) IR = 1; break; /* Negative */ case 7: if (XR & 2) IR = 1; break; /* Overflow Set */ } if ((insn >> 14) & 8) IR ^= 1; break; case FMOVQZ: case FMOVQLE: case FMOVQLZ: case FMOVQNZ: case FMOVQGZ: case FMOVQGE: freg = (insn >> 14) & 0x1f; if (!freg) XR = 0; else if (freg < 16) XR = regs->u_regs[freg]; else if (test_thread_flag(TIF_32BIT)) { struct reg_window32 __user *win32; flushw_user (); win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP])); get_user(XR, &win32->locals[freg - 16]); } else { struct reg_window __user *win; flushw_user (); win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS); get_user(XR, &win->locals[freg - 16]); } IR = 0; switch ((insn >> 10) & 3) { case 1: if (!XR) IR = 1; break; /* Register Zero */ case 2: if (XR <= 0) IR = 1; break; /* Register Less Than or Equal to Zero */ case 3: if (XR < 0) IR = 1; break; /* Register Less Than Zero */ } if ((insn >> 10) & 4) IR ^= 1; break; } if (IR == 0) { /* The fmov test was false. Do a nop instead */ current_thread_info()->xfsr[0] &= ~(FSR_CEXC_MASK); regs->tpc = regs->tnpc; regs->tnpc += 4; return 1; } else if (IR == 1) { /* Change the instruction into plain fmovq */ insn = (insn & 0x3e00001f) | 0x81a00060; TYPE(3,3,0,3,0,0,0); } } } if (type) { argp rs1 = NULL, rs2 = NULL, rd = NULL; freg = (current_thread_info()->xfsr[0] >> 14) & 0xf; if (freg != (type >> 9)) goto err; current_thread_info()->xfsr[0] &= ~0x1c000; freg = ((insn >> 14) & 0x1f); switch (type & 0x3) { case 3: if (freg & 2) { current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */; goto err; } case 2: freg = ((freg & 1) << 5) | (freg & 0x1e); case 1: rs1 = (argp)&f->regs[freg]; flags = (freg < 32) ? FPRS_DL : FPRS_DU; if (!(current_thread_info()->fpsaved[0] & flags)) rs1 = (argp)&zero; break; } switch (type & 0x7) { case 7: FP_UNPACK_QP (QA, rs1); break; case 6: FP_UNPACK_DP (DA, rs1); break; case 5: FP_UNPACK_SP (SA, rs1); break; } freg = (insn & 0x1f); switch ((type >> 3) & 0x3) { case 3: if (freg & 2) { current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */; goto err; } case 2: freg = ((freg & 1) << 5) | (freg & 0x1e); case 1: rs2 = (argp)&f->regs[freg]; flags = (freg < 32) ? FPRS_DL : FPRS_DU; if (!(current_thread_info()->fpsaved[0] & flags)) rs2 = (argp)&zero; break; } switch ((type >> 3) & 0x7) { case 7: FP_UNPACK_QP (QB, rs2); break; case 6: FP_UNPACK_DP (DB, rs2); break; case 5: FP_UNPACK_SP (SB, rs2); break; } freg = ((insn >> 25) & 0x1f); switch ((type >> 6) & 0x3) { case 3: if (freg & 2) { current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */; goto err; } case 2: freg = ((freg & 1) << 5) | (freg & 0x1e); case 1: rd = (argp)&f->regs[freg]; flags = (freg < 32) ? FPRS_DL : FPRS_DU; if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) { current_thread_info()->fpsaved[0] = FPRS_FEF; current_thread_info()->gsr[0] = 0; } if (!(current_thread_info()->fpsaved[0] & flags)) { if (freg < 32) memset(f->regs, 0, 32*sizeof(u32)); else memset(f->regs+32, 0, 32*sizeof(u32)); } current_thread_info()->fpsaved[0] |= flags; break; } switch ((insn >> 5) & 0x1ff) { /* + */ case FADDS: FP_ADD_S (SR, SA, SB); break; case FADDD: FP_ADD_D (DR, DA, DB); break; case FADDQ: FP_ADD_Q (QR, QA, QB); break; /* - */ case FSUBS: FP_SUB_S (SR, SA, SB); break; case FSUBD: FP_SUB_D (DR, DA, DB); break; case FSUBQ: FP_SUB_Q (QR, QA, QB); break; /* * */ case FMULS: FP_MUL_S (SR, SA, SB); break; case FSMULD: FP_CONV (D, S, 1, 1, DA, SA); FP_CONV (D, S, 1, 1, DB, SB); case FMULD: FP_MUL_D (DR, DA, DB); break; case FDMULQ: FP_CONV (Q, D, 2, 1, QA, DA); FP_CONV (Q, D, 2, 1, QB, DB); case FMULQ: FP_MUL_Q (QR, QA, QB); break; /* / */ case FDIVS: FP_DIV_S (SR, SA, SB); break; case FDIVD: FP_DIV_D (DR, DA, DB); break; case FDIVQ: FP_DIV_Q (QR, QA, QB); break; /* sqrt */ case FSQRTS: FP_SQRT_S (SR, SB); break; case FSQRTD: FP_SQRT_D (DR, DB); break; case FSQRTQ: FP_SQRT_Q (QR, QB); break; /* mov */ case FMOVQ: rd->q[0] = rs2->q[0]; rd->q[1] = rs2->q[1]; break; case FABSQ: rd->q[0] = rs2->q[0] & 0x7fffffffffffffffUL; rd->q[1] = rs2->q[1]; break; case FNEGQ: rd->q[0] = rs2->q[0] ^ 0x8000000000000000UL; rd->q[1] = rs2->q[1]; break; /* float to int */ case FSTOI: FP_TO_INT_S (IR, SB, 32, 1); break; case FDTOI: FP_TO_INT_D (IR, DB, 32, 1); break; case FQTOI: FP_TO_INT_Q (IR, QB, 32, 1); break; case FSTOX: FP_TO_INT_S (XR, SB, 64, 1); break; case FDTOX: FP_TO_INT_D (XR, DB, 64, 1); break; case FQTOX: FP_TO_INT_Q (XR, QB, 64, 1); break; /* int to float */ case FITOQ: IR = rs2->s; FP_FROM_INT_Q (QR, IR, 32, int); break; case FXTOQ: XR = rs2->d; FP_FROM_INT_Q (QR, XR, 64, long); break; /* Only Ultra-III generates these */ case FXTOS: XR = rs2->d; FP_FROM_INT_S (SR, XR, 64, long); break; case FXTOD: XR = rs2->d; FP_FROM_INT_D (DR, XR, 64, long); break; #if 0 /* Optimized inline in sparc64/kernel/entry.S */ case FITOS: IR = rs2->s; FP_FROM_INT_S (SR, IR, 32, int); break; #endif case FITOD: IR = rs2->s; FP_FROM_INT_D (DR, IR, 32, int); break; /* float to float */ case FSTOD: FP_CONV (D, S, 1, 1, DR, SB); break; case FSTOQ: FP_CONV (Q, S, 2, 1, QR, SB); break; case FDTOQ: FP_CONV (Q, D, 2, 1, QR, DB); break; case FDTOS: FP_CONV (S, D, 1, 1, SR, DB); break; case FQTOS: FP_CONV (S, Q, 1, 2, SR, QB); break; case FQTOD: FP_CONV (D, Q, 1, 2, DR, QB); break; /* comparison */ case FCMPQ: case FCMPEQ: FP_CMP_Q(XR, QB, QA, 3); if (XR == 3 && (((insn >> 5) & 0x1ff) == FCMPEQ || FP_ISSIGNAN_Q(QA) || FP_ISSIGNAN_Q(QB))) FP_SET_EXCEPTION (FP_EX_INVALID); } if (!FP_INHIBIT_RESULTS) { switch ((type >> 6) & 0x7) { case 0: xfsr = current_thread_info()->xfsr[0]; if (XR == -1) XR = 2; switch (freg & 3) { /* fcc0, 1, 2, 3 */ case 0: xfsr &= ~0xc00; xfsr |= (XR << 10); break; case 1: xfsr &= ~0x300000000UL; xfsr |= (XR << 32); break; case 2: xfsr &= ~0xc00000000UL; xfsr |= (XR << 34); break; case 3: xfsr &= ~0x3000000000UL; xfsr |= (XR << 36); break; } current_thread_info()->xfsr[0] = xfsr; break; case 1: rd->s = IR; break; case 2: rd->d = XR; break; case 5: FP_PACK_SP (rd, SR); break; case 6: FP_PACK_DP (rd, DR); break; case 7: FP_PACK_QP (rd, QR); break; } } if(_fex != 0) return record_exception(regs, _fex); /* Success and no exceptions detected. */ current_thread_info()->xfsr[0] &= ~(FSR_CEXC_MASK); regs->tpc = regs->tnpc; regs->tnpc += 4; return 1; } err: return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
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: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; UNUSED(u1_is_idr_slice); if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag && (num_mb_skip & 1)) { num_mb_skip++; } ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = -1; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) { if(ps_dec->ps_pps[i].u1_is_valid == TRUE) { if(ps_dec->ps_pps[i].ps_sps->u1_is_valid == TRUE) { j = i; break; } } } if(j == -1) { return ERROR_INV_SLICE_HDR_T; } /* call ih264d_start_of_pic only if it was not called earlier*/ if(ps_dec->u4_pic_buf_got == 0) { ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; ps_dec->ps_cur_slice->u1_nal_unit_type = 1; ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } ps_dec->u4_first_slice_in_pic = 0; } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { if((u1_mbaff) && (ps_dec->u4_num_mbs_cur_nmb & 1)) { ps_dec->u4_num_mbs_cur_nmb = ps_dec->u4_num_mbs_cur_nmb - 1; ps_dec->u2_cur_mb_addr--; } u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; if(u1_num_mbs) { ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } /* Inserting new slice only if the current slice has atleast 1 MB*/ if(ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice < (UWORD32)(ps_dec->u2_total_mbs_coded >> ps_slice->u1_mbaff_frame_flag)) { ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->u2_cur_slice_num++; ps_dec->ps_parse_cur_slice++; } } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded >> u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; ps_dec->u2_mbx = (MOD(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby = (DIV(ps_dec->ps_cur_slice->u2_first_mb_in_slice - 1, ps_dec->u2_frm_wd_in_mbs)); ps_dec->u2_mby <<= u1_mbaff; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u2_total_mbs_coded += u1_num_mbs; if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) { ps_dec->ps_parse_cur_slice++; ps_dec->u2_cur_slice_num++; } ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; } Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba CWE ID: CWE-200 Target: 1 Example 2: Code: bool GLSurfaceEGLSurfaceControl::OnMakeCurrent(GLContext* context) { context_ = context; return true; } Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. [email protected] Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <[email protected]> Commit-Queue: Antoine Labour <[email protected]> Reviewed-by: Antoine Labour <[email protected]> Auto-Submit: Khushal <[email protected]> Cr-Commit-Position: refs/heads/master@{#629852} 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: UnacceleratedStaticBitmapImage::MakeAccelerated( base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) { if (!context_wrapper) return nullptr; // Can happen if the context is lost. GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext(); if (!grcontext) return nullptr; // Can happen if the context is lost. sk_sp<SkImage> sk_image = paint_image_.GetSkImage(); sk_sp<SkImage> gpu_skimage = sk_image->makeTextureImage(grcontext, sk_image->colorSpace()); if (!gpu_skimage) return nullptr; return AcceleratedStaticBitmapImage::CreateFromSkImage( std::move(gpu_skimage), std::move(context_wrapper)); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119 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 UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { UINT status; UINT32 Length; UINT32 ChannelId; ChannelId = drdynvc_read_variable_uint(s, cbChId); Length = drdynvc_read_variable_uint(s, Sp); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp, cbChId, ChannelId, Length); status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId, Length); if (status) return status; return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s); } Commit Message: Fix for #4866: Added additional length checks CWE ID: Target: 1 Example 2: Code: PHP_FUNCTION(openssl_get_cipher_methods) { zend_bool aliases = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &aliases) == FAILURE) { return; } array_init(return_value); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, aliases ? openssl_add_method_or_alias: openssl_add_method, return_value); } 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 Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, profile_data, profile_size, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); profile_data=0; profile_size=0; if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=(MagickOffsetType)ReadBlobLSBLong(image); profile_size=(MagickOffsetType)ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((MagickSizeType) (length/256) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Read embeded ICC profile */ if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) && (profile_size > 0)) { StringInfo *profile; unsigned char *datum; offset=start_position+14+profile_data; if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset) || (GetBlobSize(image) < (MagickSizeType) (offset+profile_size))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); profile=AcquireStringInfo((size_t) profile_size); if (profile == (StringInfo *) NULL) ThrowReaderException(CorruptImageError,"MemoryAllocationFailed"); datum=GetStringInfoDatum(profile); if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size) { MagickOffsetType profile_size_orig; /* Trimming padded bytes. */ profile_size_orig=(MagickOffsetType) datum[0] << 24; profile_size_orig|=(MagickOffsetType) datum[1] << 16; profile_size_orig|=(MagickOffsetType) datum[2] << 8; profile_size_orig|=(MagickOffsetType) datum[3]; if (profile_size_orig < profile_size) SetStringInfoLength(profile,(size_t) profile_size_orig); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %u bytes",(unsigned int) profile_size_orig); (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; offset=(MagickOffsetType) bmp_info.ba_offset; if (offset != 0) if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); *magick='\0'; count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1600 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: create_surface_from_thumbnail_data (guchar *data, gint width, gint height, gint rowstride) { guchar *cairo_pixels; cairo_surface_t *surface; static cairo_user_data_key_t key; int j; cairo_pixels = (guchar *)g_malloc (4 * width * height); surface = cairo_image_surface_create_for_data ((unsigned char *)cairo_pixels, CAIRO_FORMAT_RGB24, width, height, 4 * width); cairo_surface_set_user_data (surface, &key, cairo_pixels, (cairo_destroy_func_t)g_free); for (j = height; j; j--) { guchar *p = data; guchar *q = cairo_pixels; guchar *end = p + 3 * width; while (p < end) { #if G_BYTE_ORDER == G_LITTLE_ENDIAN q[0] = p[2]; q[1] = p[1]; q[2] = p[0]; #else q[1] = p[0]; q[2] = p[1]; q[3] = p[2]; #endif p += 3; q += 4; } data += rowstride; cairo_pixels += 4 * width; } return surface; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: TabContents* PrintPreviewHandler::preview_tab_contents() const { return TabContents::FromWebContents(preview_web_contents()); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct tm* localtime64_r_override(const time_t* timep, struct tm* result) { if (g_am_zygote_or_renderer) { ProxyLocaltimeCallToBrowser(*timep, result, NULL, 0); return result; } CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, InitLibcLocaltimeFunctions)); struct tm* res = g_libc_localtime64_r(timep, result); #if defined(MEMORY_SANITIZER) if (res) __msan_unpoison(res, sizeof(*res)); if (res->tm_zone) __msan_unpoison_string(res->tm_zone); #endif return res; } 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 Output:
0
Here are some example code snippets. Analyze the following code, 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::notifyNodeInsertedInternal(Node& root, NodeVector& postInsertionNotificationTargets) { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) { if (!inDocument() && !node.isContainerNode()) continue; if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this)) postInsertionNotificationTargets.append(&node); for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) notifyNodeInsertedInternal(*shadowRoot, postInsertionNotificationTargets); } } Commit Message: Fix an optimisation in ContainerNode::notifyNodeInsertedInternal [email protected] BUG=544020 Review URL: https://codereview.chromium.org/1420653003 Cr-Commit-Position: refs/heads/master@{#355240} CWE ID: Target: 1 Example 2: Code: static void free_func_state(struct bpf_func_state *state) { if (!state) return; kfree(state->stack); kfree(state); } Commit Message: bpf: 32-bit RSH verification must truncate input before the ALU op When I wrote commit 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification"), I assumed that, in order to emulate 64-bit arithmetic with 32-bit logic, it is sufficient to just truncate the output to 32 bits; and so I just moved the register size coercion that used to be at the start of the function to the end of the function. That assumption is true for almost every op, but not for 32-bit right shifts, because those can propagate information towards the least significant bit. Fix it by always truncating inputs for 32-bit ops to 32 bits. Also get rid of the coerce_reg_to_size() after the ALU op, since that has no effect. Fixes: 468f6eafa6c4 ("bpf: fix 32-bit ALU op verification") Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[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: bool DragController::IsCopyKeyDown(DragData* drag_data) { int modifiers = drag_data->GetModifiers(); #if defined(OS_MACOSX) return modifiers & WebInputEvent::kAltKey; #else return modifiers & WebInputEvent::kControlKey; #endif } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool tailmatch(const char *little, const char *bigone) { size_t littlelen = strlen(little); size_t biglen = strlen(bigone); if(littlelen > biglen) return FALSE; return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE; } Commit Message: cookie: fix tailmatching to prevent cross-domain leakage Cookies set for 'example.com' could accidentaly also be sent by libcurl to the 'bexample.com' (ie with a prefix to the first domain name). This is a security vulnerabilty, CVE-2013-1944. Bug: http://curl.haxx.se/docs/adv_20130412.html CWE ID: CWE-200 Target: 1 Example 2: Code: static inline void foldQuoteMarksAndSoftHyphens(String& s) { s.replace(hebrewPunctuationGeresh, '\''); s.replace(hebrewPunctuationGershayim, '"'); s.replace(leftDoubleQuotationMark, '"'); s.replace(leftSingleQuotationMark, '\''); s.replace(rightDoubleQuotationMark, '"'); s.replace(rightSingleQuotationMark, '\''); s.replace(softHyphen, 0); } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 [email protected] Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: add_options(opt) option_t *opt; { struct option_list *list; list = malloc(sizeof(*list)); if (list == 0) novm("option list entry"); list->options = opt; list->next = extra_options; extra_options = list; } Commit Message: pppd: Eliminate potential integer overflow in option parsing When we are reading in a word from an options file, we maintain a count of the length we have seen so far in 'len', which is an int. When len exceeds MAXWORDLEN - 1 (i.e. 1023) we cease storing characters in the buffer but we continue to increment len. Since len is an int, it will wrap around to -2147483648 after it reaches 2147483647. At that point our test of (len < MAXWORDLEN-1) will succeed and we will start writing characters to memory again. This may enable an attacker to overwrite the heap and thereby corrupt security-relevant variables. For this reason it has been assigned a CVE identifier, CVE-2014-3158. This fixes the bug by ceasing to increment len once it reaches MAXWORDLEN. Reported-by: Lee Campbell <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, 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 ReturnsValidPath(int dir_type) { base::FilePath path; bool result = PathService::Get(dir_type, &path); bool check_path_exists = true; #if defined(OS_POSIX) if (dir_type == base::DIR_CACHE) check_path_exists = false; #endif #if defined(OS_LINUX) if (dir_type == base::DIR_USER_DESKTOP) check_path_exists = false; #endif #if defined(OS_WIN) if (dir_type == base::DIR_DEFAULT_USER_QUICK_LAUNCH) { if (base::win::GetVersion() < base::win::VERSION_VISTA) { wchar_t default_profile_path[MAX_PATH]; DWORD size = arraysize(default_profile_path); return (result && ::GetDefaultUserProfileDirectory(default_profile_path, &size) && StartsWith(path.value(), default_profile_path, false)); } } else if (dir_type == base::DIR_TASKBAR_PINS) { if (base::win::GetVersion() < base::win::VERSION_WIN7) check_path_exists = false; } #endif #if defined(OS_MAC) if (dir_type != base::DIR_EXE && dir_type != base::DIR_MODULE && dir_type != base::FILE_EXE && dir_type != base::FILE_MODULE) { if (path.ReferencesParent()) return false; } #else if (path.ReferencesParent()) return false; #endif return result && !path.empty() && (!check_path_exists || file_util::PathExists(path)); } Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX. BUG=163208 TEST=none Review URL: https://codereview.chromium.org/12829005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: void CLASS nokia_load_raw() { uchar *data, *dp; ushort *pixel, *pix; int rev, dwide, row, c; rev = 3 * (order == 0x4949); dwide = raw_width * 5 / 4; data = (uchar *) malloc (dwide + raw_width*2); merror (data, "nokia_load_raw()"); pixel = (ushort *) (data + dwide); for (row=0; row < raw_height; row++) { if ((int) fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=5, pix+=4) FORC4 pix[c] = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); if (row < top_margin) FORC(width) black += pixel[c]; else FORC(width) BAYER(row-top_margin,c) = pixel[c]; } free (data); if (top_margin) black /= top_margin * width; maximum = 0x3ff; } Commit Message: Avoid overflow in ljpeg_start(). 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: AutomationInternalCustomBindings::AutomationInternalCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context), is_active_profile_(true), tree_change_observer_overall_filter_( api::automation::TREE_CHANGE_OBSERVER_FILTER_NOTREECHANGES) { #define ROUTE_FUNCTION(FN) \ RouteFunction(#FN, \ base::Bind(&AutomationInternalCustomBindings::FN, \ base::Unretained(this))) ROUTE_FUNCTION(IsInteractPermitted); ROUTE_FUNCTION(GetSchemaAdditions); ROUTE_FUNCTION(GetRoutingID); ROUTE_FUNCTION(StartCachingAccessibilityTrees); ROUTE_FUNCTION(DestroyAccessibilityTree); ROUTE_FUNCTION(AddTreeChangeObserver); ROUTE_FUNCTION(RemoveTreeChangeObserver); ROUTE_FUNCTION(GetChildIDAtIndex); ROUTE_FUNCTION(GetFocus); ROUTE_FUNCTION(GetState); #undef ROUTE_FUNCTION RouteTreeIDFunction( "GetRootID", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Integer::New(isolate, cache->tree.root()->id())); }); RouteTreeIDFunction( "GetDocURL", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set( v8::String::NewFromUtf8(isolate, cache->tree.data().url.c_str())); }); RouteTreeIDFunction( "GetDocTitle", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set( v8::String::NewFromUtf8(isolate, cache->tree.data().title.c_str())); }); RouteTreeIDFunction( "GetDocLoaded", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Boolean::New(isolate, cache->tree.data().loaded)); }); RouteTreeIDFunction("GetDocLoadingProgress", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Number::New( isolate, cache->tree.data().loading_progress)); }); RouteTreeIDFunction("GetAnchorObjectID", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Number::New( isolate, cache->tree.data().sel_anchor_object_id)); }); RouteTreeIDFunction("GetAnchorOffset", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Number::New(isolate, cache->tree.data().sel_anchor_offset)); }); RouteTreeIDFunction("GetFocusObjectID", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Number::New( isolate, cache->tree.data().sel_focus_object_id)); }); RouteTreeIDFunction("GetFocusOffset", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache) { result.Set(v8::Number::New(isolate, cache->tree.data().sel_focus_offset)); }); RouteNodeIDFunction( "GetParentID", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node) { if (node->parent()) result.Set(v8::Integer::New(isolate, node->parent()->id())); }); RouteNodeIDFunction("GetChildCount", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node) { result.Set(v8::Integer::New(isolate, node->child_count())); }); RouteNodeIDFunction( "GetIndexInParent", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node) { result.Set(v8::Integer::New(isolate, node->index_in_parent())); }); RouteNodeIDFunction( "GetRole", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node) { std::string role_name = ui::ToString(node->data().role); result.Set(v8::String::NewFromUtf8(isolate, role_name.c_str())); }); RouteNodeIDFunction( "GetLocation", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node) { gfx::Rect location = ComputeGlobalNodeBounds(cache, node); location.Offset(cache->location_offset); result.Set(RectToV8Object(isolate, location)); }); RouteNodeIDPlusRangeFunction( "GetBoundsForRange", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, TreeCache* cache, ui::AXNode* node, int start, int end) { gfx::Rect location = ComputeGlobalNodeBounds(cache, node); location.Offset(cache->location_offset); if (node->data().role == ui::AX_ROLE_INLINE_TEXT_BOX) { std::string name = node->data().GetStringAttribute(ui::AX_ATTR_NAME); std::vector<int> character_offsets = node->data().GetIntListAttribute(ui::AX_ATTR_CHARACTER_OFFSETS); int len = static_cast<int>(std::min(name.size(), character_offsets.size())); if (start >= 0 && start <= end && end <= len) { int start_offset = start > 0 ? character_offsets[start - 1] : 0; int end_offset = end > 0 ? character_offsets[end - 1] : 0; switch (node->data().GetIntAttribute(ui::AX_ATTR_TEXT_DIRECTION)) { case ui::AX_TEXT_DIRECTION_LTR: default: location.set_x(location.x() + start_offset); location.set_width(end_offset - start_offset); break; case ui::AX_TEXT_DIRECTION_RTL: location.set_x(location.x() + location.width() - end_offset); location.set_width(end_offset - start_offset); break; case ui::AX_TEXT_DIRECTION_TTB: location.set_y(location.y() + start_offset); location.set_height(end_offset - start_offset); break; case ui::AX_TEXT_DIRECTION_BTT: location.set_y(location.y() + location.height() - end_offset); location.set_height(end_offset - start_offset); break; } } } result.Set(RectToV8Object(isolate, location)); }); RouteNodeIDPlusAttributeFunction( "GetStringAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { ui::AXStringAttribute attribute = ui::ParseAXStringAttribute(attribute_name); std::string attr_value; if (!node->data().GetStringAttribute(attribute, &attr_value)) return; result.Set(v8::String::NewFromUtf8(isolate, attr_value.c_str())); }); RouteNodeIDPlusAttributeFunction( "GetBoolAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { ui::AXBoolAttribute attribute = ui::ParseAXBoolAttribute(attribute_name); bool attr_value; if (!node->data().GetBoolAttribute(attribute, &attr_value)) return; result.Set(v8::Boolean::New(isolate, attr_value)); }); RouteNodeIDPlusAttributeFunction( "GetIntAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { ui::AXIntAttribute attribute = ui::ParseAXIntAttribute(attribute_name); int attr_value; if (!node->data().GetIntAttribute(attribute, &attr_value)) return; result.Set(v8::Integer::New(isolate, attr_value)); }); RouteNodeIDPlusAttributeFunction( "GetFloatAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { ui::AXFloatAttribute attribute = ui::ParseAXFloatAttribute(attribute_name); float attr_value; if (!node->data().GetFloatAttribute(attribute, &attr_value)) return; result.Set(v8::Number::New(isolate, attr_value)); }); RouteNodeIDPlusAttributeFunction( "GetIntListAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { ui::AXIntListAttribute attribute = ui::ParseAXIntListAttribute(attribute_name); if (!node->data().HasIntListAttribute(attribute)) return; const std::vector<int32_t>& attr_value = node->data().GetIntListAttribute(attribute); v8::Local<v8::Array> array_result( v8::Array::New(isolate, attr_value.size())); for (size_t i = 0; i < attr_value.size(); ++i) array_result->Set(static_cast<uint32_t>(i), v8::Integer::New(isolate, attr_value[i])); result.Set(array_result); }); RouteNodeIDPlusAttributeFunction( "GetHtmlAttribute", [](v8::Isolate* isolate, v8::ReturnValue<v8::Value> result, ui::AXNode* node, const std::string& attribute_name) { std::string attr_value; if (!node->data().GetHtmlAttribute(attribute_name.c_str(), &attr_value)) return; result.Set(v8::String::NewFromUtf8(isolate, attr_value.c_str())); }); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID: Output:
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 RegisterOptimizationHintsComponent(ComponentUpdateService* cus, PrefService* profile_prefs) { if (!previews::params::IsOptimizationHintsEnabled()) { return; } bool data_saver_enabled = base::CommandLine::ForCurrentProcess()->HasSwitch( data_reduction_proxy::switches::kEnableDataReductionProxy) || (profile_prefs && profile_prefs->GetBoolean( data_reduction_proxy::prefs::kDataSaverEnabled)); if (!data_saver_enabled) return; auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<OptimizationHintsComponentInstallerPolicy>()); installer->Register(cus, base::OnceClosure()); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119 Target: 1 Example 2: Code: bool InputHandler::willOpenPopupForNode(Node* node) { if (!node) return false; ASSERT(!node->isInShadowTree()); if (node->hasTagName(HTMLNames::selectTag) || node->hasTagName(HTMLNames::optionTag)) { return true; } if (node->isElementNode()) { Element* element = static_cast<Element*>(node); if (DOMSupport::isPopupInputField(element)) return true; } return false; } 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: static int pvc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int error; lock_sock(sk); error = vcc_getsockopt(sock, level, optname, optval, optlen); release_sock(sk); return error; } Commit Message: atm: fix info leak via getsockname() The ATM code fails to initialize the two padding bytes of struct sockaddr_atmpvc inserted for alignment. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MediaControlVolumeSliderElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; if (event->type() == EventTypeNames::mousedown) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeBegin")); if (event->type() == EventTypeNames::mouseup) Platform::current()->recordAction( UserMetricsAction("Media.Controls.VolumeChangeEnd")); double volume = value().toDouble(); mediaElement().setVolume(volume); mediaElement().setMuted(false); } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119 Target: 1 Example 2: Code: tsqueryrecv(PG_FUNCTION_ARGS) { StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); TSQuery query; int i, len; QueryItem *item; int datalen; char *ptr; uint32 size; const char **operands; size = pq_getmsgint(buf, sizeof(uint32)); if (size > (MaxAllocSize / sizeof(QueryItem))) elog(ERROR, "invalid size of tsquery"); /* Allocate space to temporarily hold operand strings */ operands = palloc(size * sizeof(char *)); /* Allocate space for all the QueryItems. */ len = HDRSIZETQ + sizeof(QueryItem) * size; query = (TSQuery) palloc0(len); query->size = size; item = GETQUERY(query); datalen = 0; for (i = 0; i < size; i++) { item->type = (int8) pq_getmsgint(buf, sizeof(int8)); if (item->type == QI_VAL) { size_t val_len; /* length after recoding to server encoding */ uint8 weight; uint8 prefix; const char *val; pg_crc32 valcrc; weight = (uint8) pq_getmsgint(buf, sizeof(uint8)); prefix = (uint8) pq_getmsgint(buf, sizeof(uint8)); val = pq_getmsgstring(buf); val_len = strlen(val); /* Sanity checks */ if (weight > 0xF) elog(ERROR, "invalid tsquery: invalid weight bitmap"); if (val_len > MAXSTRLEN) elog(ERROR, "invalid tsquery: operand too long"); if (datalen > MAXSTRPOS) elog(ERROR, "invalid tsquery: total operand length exceeded"); /* Looks valid. */ INIT_CRC32(valcrc); COMP_CRC32(valcrc, val, val_len); FIN_CRC32(valcrc); item->qoperand.weight = weight; item->qoperand.prefix = (prefix) ? true : false; item->qoperand.valcrc = (int32) valcrc; item->qoperand.length = val_len; item->qoperand.distance = datalen; /* * Operand strings are copied to the final struct after this loop; * here we just collect them to an array */ operands[i] = val; datalen += val_len + 1; /* + 1 for the '\0' terminator */ } else if (item->type == QI_OPR) { int8 oper; oper = (int8) pq_getmsgint(buf, sizeof(int8)); if (oper != OP_NOT && oper != OP_OR && oper != OP_AND) elog(ERROR, "invalid tsquery: unrecognized operator type %d", (int) oper); if (i == size - 1) elog(ERROR, "invalid pointer to right operand"); item->qoperator.oper = oper; } else elog(ERROR, "unrecognized tsquery node type: %d", item->type); item++; } /* Enlarge buffer to make room for the operand values. */ query = (TSQuery) repalloc(query, len + datalen); item = GETQUERY(query); ptr = GETOPERAND(query); /* * Fill in the left-pointers. Checks that the tree is well-formed as a * side-effect. */ findoprnd(item, size); /* Copy operands to output struct */ for (i = 0; i < size; i++) { if (item->type == QI_VAL) { memcpy(ptr, operands[i], item->qoperand.length + 1); ptr += item->qoperand.length + 1; } item++; } pfree(operands); Assert(ptr - GETOPERAND(query) == datalen); SET_VARSIZE(query, len + datalen); PG_RETURN_TSVECTOR(query); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SegmentInfo::SegmentInfo( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_pMuxingAppAsUTF8(NULL), m_pWritingAppAsUTF8(NULL), m_pTitleAsUTF8(NULL) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; 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: void update_rq_clock(struct rq *rq) { s64 delta; lockdep_assert_held(&rq->lock); if (rq->clock_skip_update & RQCF_ACT_SKIP) return; delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; if (delta < 0) return; rq->clock += delta; update_rq_clock_task(rq, delta); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <[email protected]>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: CURLcode imap_perform(struct connectdata *conn, bool *connected, /* connect status after PASV / PORT */ bool *dophase_done) { /* this is IMAP and no proxy */ CURLcode result=CURLE_OK; DEBUGF(infof(conn->data, "DO phase starts\n")); if(conn->data->set.opt_no_body) { /* requested no body means no transfer... */ struct FTP *imap = conn->data->state.proto.imap; imap->transfer = FTPTRANSFER_INFO; } *dophase_done = FALSE; /* not done yet */ /* start the first command in the DO phase */ result = imap_select(conn); if(result) return result; /* run the state-machine */ if(conn->data->state.used_interface == Curl_if_multi) result = imap_multi_statemach(conn, dophase_done); else { result = imap_easy_statemach(conn); *dophase_done = TRUE; /* with the easy interface we are done here */ } *connected = conn->bits.tcpconnect[FIRSTSOCKET]; if(*dophase_done) DEBUGF(infof(conn->data, "DO phase is complete\n")); return result; } Commit Message: URL sanitize: reject URLs containing bad data Protocols (IMAP, POP3 and SMTP) that use the path part of a URL in a decoded manner now use the new Curl_urldecode() function to reject URLs with embedded control codes (anything that is or decodes to a byte value less than 32). URLs containing such codes could easily otherwise be used to do harm and allow users to do unintended actions with otherwise innocent tools and applications. Like for example using a URL like pop3://pop3.example.com/1%0d%0aDELE%201 when the app wants a URL to get a mail and instead this would delete one. This flaw is considered a security vulnerability: CVE-2012-0036 Security advisory at: http://curl.haxx.se/docs/adv_20120124.html Reported by: Dan Fandrich CWE ID: CWE-89 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltStylesheetPtr XSLStyleSheet::compileStyleSheet() { if (m_embedded) return xsltLoadStylesheetPI(document()); ASSERT(!m_stylesheetDocTaken); xsltStylesheetPtr result = xsltParseStylesheetDoc(m_stylesheetDoc); if (result) m_stylesheetDocTaken = true; return result; } Commit Message: Avoid reparsing an XSLT stylesheet after the first failure. Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing. (The test cannot be converted to text-only due to its invalid stylesheet). [email protected],[email protected],[email protected] BUG=271939 Review URL: https://chromiumcodereview.appspot.com/23103007 git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: static void decode_and_reconstruct_block_intra_uv (SAMPLE *rec_u, SAMPLE *rec_v, int stride, int size, int qp, SAMPLE *pblock_u, SAMPLE *pblock_v, int16_t *coeffq_u, int16_t *coeffq_v, int tb_split, int upright_available,int downleft_available, intra_mode_t intra_mode,int ypos,int xpos,int width,int comp, int bitdepth, qmtx_t ** iwmatrix, SAMPLE *pblock_y, SAMPLE *rec_y, int rec_stride, int sub){ int16_t *rcoeff = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32); int16_t *rblock = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32); int16_t *rblock2 = thor_alloc(2*MAX_TR_SIZE*MAX_TR_SIZE, 32); SAMPLE* left_data = (SAMPLE*)thor_alloc((2*MAX_TR_SIZE+2)*sizeof(SAMPLE),32)+1; SAMPLE* top_data = (SAMPLE*)thor_alloc((2*MAX_TR_SIZE+2)*sizeof(SAMPLE),32)+1; SAMPLE top_left; if (tb_split){ int size2 = size/2; int i,j,index; for (i=0;i<size;i+=size2){ for (j=0;j<size;j+=size2){ TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_u,stride,&rec_u[i*stride+j],stride,i,j,ypos,xpos,size2,upright_available,downleft_available,1,bitdepth); TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos+i,xpos+j,size2,&pblock_u[i*size+j],size,intra_mode,bitdepth); TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_v,stride,&rec_v[i*stride+j],stride,i,j,ypos,xpos,size2,upright_available,downleft_available,1,bitdepth); TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos+i,xpos+j,size2,&pblock_v[i*size+j],size,intra_mode,bitdepth); if (pblock_y) TEMPLATE(improve_uv_prediction)(&pblock_y[i*size+j], &pblock_u[i*size+j], &pblock_v[i*size+j], &rec_y[(i<<sub)*rec_stride+(j<<sub)], size2 << sub, size << sub, rec_stride, sub, bitdepth); index = 2*(i/size2) + (j/size2); TEMPLATE(dequantize)(coeffq_u+index*size2*size2, rcoeff, qp, size2, iwmatrix ? iwmatrix[log2i(size2/4)] : NULL); inverse_transform (rcoeff, rblock2, size2, bitdepth); TEMPLATE(reconstruct_block)(rblock2,&pblock_u[i*size+j],&rec_u[i*stride+j],size2,size,stride,bitdepth); TEMPLATE(dequantize)(coeffq_v+index*size2*size2, rcoeff, qp, size2, iwmatrix ? iwmatrix[log2i(size2/4)] : NULL); inverse_transform (rcoeff, rblock2, size2, bitdepth); TEMPLATE(reconstruct_block)(rblock2,&pblock_v[i*size+j],&rec_v[i*stride+j],size2,size,stride,bitdepth); } } } else{ TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_u,stride,NULL,0,0,0,ypos,xpos,size,upright_available,downleft_available,0,bitdepth); TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos,xpos,size,pblock_u,size,intra_mode,bitdepth); TEMPLATE(make_top_and_left)(left_data,top_data,&top_left,rec_v,stride,NULL,0,0,0,ypos,xpos,size,upright_available,downleft_available,0,bitdepth); TEMPLATE(get_intra_prediction)(left_data,top_data,top_left,ypos,xpos,size,pblock_v,size,intra_mode,bitdepth); if (pblock_y) TEMPLATE(improve_uv_prediction)(pblock_y, pblock_u, pblock_v, rec_y, size << sub, size << sub, rec_stride, sub, bitdepth); TEMPLATE(dequantize)(coeffq_u, rcoeff, qp, size, iwmatrix ? iwmatrix[log2i(size/4)] : NULL); inverse_transform (rcoeff, rblock, size, bitdepth); TEMPLATE(reconstruct_block)(rblock,pblock_u,rec_u,size,size,stride,bitdepth); TEMPLATE(dequantize)(coeffq_v, rcoeff, qp, size, iwmatrix ? iwmatrix[log2i(size/4)] : NULL); inverse_transform (rcoeff, rblock, size, bitdepth); TEMPLATE(reconstruct_block)(rblock,pblock_v,rec_v,size,size,stride,bitdepth); } thor_free(top_data - 1); thor_free(left_data - 1); thor_free(rcoeff); thor_free(rblock); thor_free(rblock2); } Commit Message: Fix possible stack overflows in decoder for illegal bit streams Fixes CVE-2018-0429 A vulnerability in the Thor decoder (available at: https://github.com/cisco/thor) could allow an authenticated, local attacker to cause segmentation faults and stack overflows when using a non-conformant Thor bitstream as input. The vulnerability is due to lack of input validation when parsing the bitstream. A successful exploit could allow the attacker to cause a stack overflow and potentially inject and execute arbitrary code. 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 ssdp_recv(int sd) { ssize_t len; struct sockaddr sa; socklen_t salen; char buf[MAX_PKT_SIZE]; memset(buf, 0, sizeof(buf)); len = recvfrom(sd, buf, sizeof(buf), MSG_DONTWAIT, &sa, &salen); if (len > 0) { buf[len] = 0; if (sa.sa_family != AF_INET) return; if (strstr(buf, "M-SEARCH *")) { size_t i; char *ptr, *type; struct ifsock *ifs; struct sockaddr_in *sin = (struct sockaddr_in *)&sa; ifs = find_outbound(&sa); if (!ifs) { logit(LOG_DEBUG, "No matching socket for client %s", inet_ntoa(sin->sin_addr)); return; } logit(LOG_DEBUG, "Matching socket for client %s", inet_ntoa(sin->sin_addr)); type = strcasestr(buf, "\r\nST:"); if (!type) { logit(LOG_DEBUG, "No Search Type (ST:) found in M-SEARCH *, assuming " SSDP_ST_ALL); type = SSDP_ST_ALL; send_message(ifs, type, &sa); return; } type = strchr(type, ':'); if (!type) return; type++; while (isspace(*type)) type++; ptr = strstr(type, "\r\n"); if (!ptr) return; *ptr = 0; for (i = 0; supported_types[i]; i++) { if (!strcmp(supported_types[i], type)) { logit(LOG_DEBUG, "M-SEARCH * ST: %s from %s port %d", type, inet_ntoa(sin->sin_addr), ntohs(sin->sin_port)); send_message(ifs, type, &sa); return; } } logit(LOG_DEBUG, "M-SEARCH * for unsupported ST: %s from %s", type, inet_ntoa(sin->sin_addr)); } } } Commit Message: Fix #1: Ensure recv buf is always NUL terminated Signed-off-by: Joachim Nilsson <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_eh_handle_sas_errors(struct Scsi_Host *shost, struct list_head *work_q) { struct scsi_cmnd *cmd, *n; enum task_disposition res = TASK_IS_DONE; int tmf_resp, need_reset; struct sas_internal *i = to_sas_internal(shost->transportt); unsigned long flags; struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); LIST_HEAD(done); /* clean out any commands that won the completion vs eh race */ list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_task *task; spin_lock_irqsave(&dev->done_lock, flags); /* by this point the lldd has either observed * SAS_HA_FROZEN and is leaving the task alone, or has * won the race with eh and decided to complete it */ task = TO_SAS_TASK(cmd); spin_unlock_irqrestore(&dev->done_lock, flags); if (!task) list_move_tail(&cmd->eh_entry, &done); } Again: list_for_each_entry_safe(cmd, n, work_q, eh_entry) { struct sas_task *task = TO_SAS_TASK(cmd); list_del_init(&cmd->eh_entry); spin_lock_irqsave(&task->task_state_lock, flags); need_reset = task->task_state_flags & SAS_TASK_NEED_DEV_RESET; spin_unlock_irqrestore(&task->task_state_lock, flags); if (need_reset) { SAS_DPRINTK("%s: task 0x%p requests reset\n", __func__, task); goto reset; } SAS_DPRINTK("trying to find task 0x%p\n", task); res = sas_scsi_find_task(task); switch (res) { case TASK_IS_DONE: SAS_DPRINTK("%s: task 0x%p is done\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_ABORTED: SAS_DPRINTK("%s: task 0x%p is aborted\n", __func__, task); sas_eh_defer_cmd(cmd); continue; case TASK_IS_AT_LU: SAS_DPRINTK("task 0x%p is at LU: lu recover\n", task); reset: tmf_resp = sas_recover_lu(task->dev, cmd); if (tmf_resp == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("dev %016llx LU %llx is " "recovered\n", SAS_ADDR(task->dev), cmd->device->lun); sas_eh_defer_cmd(cmd); sas_scsi_clear_queue_lu(work_q, cmd); goto Again; } /* fallthrough */ case TASK_IS_NOT_AT_LU: case TASK_ABORT_FAILED: SAS_DPRINTK("task 0x%p is not at LU: I_T recover\n", task); tmf_resp = sas_recover_I_T(task->dev); if (tmf_resp == TMF_RESP_FUNC_COMPLETE || tmf_resp == -ENODEV) { struct domain_device *dev = task->dev; SAS_DPRINTK("I_T %016llx recovered\n", SAS_ADDR(task->dev->sas_addr)); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_I_T(work_q, dev); goto Again; } /* Hammer time :-) */ try_to_reset_cmd_device(cmd); if (i->dft->lldd_clear_nexus_port) { struct asd_sas_port *port = task->dev->port; SAS_DPRINTK("clearing nexus for port:%d\n", port->id); res = i->dft->lldd_clear_nexus_port(port); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus port:%d " "succeeded\n", port->id); sas_eh_finish_cmd(cmd); sas_scsi_clear_queue_port(work_q, port); goto Again; } } if (i->dft->lldd_clear_nexus_ha) { SAS_DPRINTK("clear nexus ha\n"); res = i->dft->lldd_clear_nexus_ha(ha); if (res == TMF_RESP_FUNC_COMPLETE) { SAS_DPRINTK("clear nexus ha " "succeeded\n"); sas_eh_finish_cmd(cmd); goto clear_q; } } /* If we are here -- this means that no amount * of effort could recover from errors. Quite * possibly the HA just disappeared. */ SAS_DPRINTK("error from device %llx, LUN %llx " "couldn't be recovered in any way\n", SAS_ADDR(task->dev->sas_addr), cmd->device->lun); sas_eh_finish_cmd(cmd); goto clear_q; } } out: list_splice_tail(&done, work_q); list_splice_tail_init(&ha->eh_ata_q, work_q); return; clear_q: SAS_DPRINTK("--- Exit %s -- clear_q\n", __func__); list_for_each_entry_safe(cmd, n, work_q, eh_entry) sas_eh_finish_cmd(cmd); goto out; } Commit Message: scsi: libsas: defer ata device eh commands to libata When ata device doing EH, some commands still attached with tasks are not passed to libata when abort failed or recover failed, so libata did not handle these commands. After these commands done, sas task is freed, but ata qc is not freed. This will cause ata qc leak and trigger a warning like below: WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037 ata_eh_finish+0xb4/0xcc CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1 ...... Call trace: [<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc [<ffff0000088b8420>] ata_do_eh+0xc4/0xd8 [<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c [<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694 [<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80 [<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170 [<ffff0000080ebd70>] process_one_work+0x144/0x390 [<ffff0000080ec100>] worker_thread+0x144/0x418 [<ffff0000080f2c98>] kthread+0x10c/0x138 [<ffff0000080855dc>] ret_from_fork+0x10/0x18 If ata qc leaked too many, ata tag allocation will fail and io blocked for ever. As suggested by Dan Williams, defer ata device commands to libata and merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle ata qcs correctly after this. Signed-off-by: Jason Yan <[email protected]> CC: Xiaofei Tan <[email protected]> CC: John Garry <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Dan Williams <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 1 Example 2: Code: int ssl3_send_server_certificate(SSL *s) { CERT_PKEY *cpk; if (s->state == SSL3_ST_SW_CERT_A) { cpk = ssl_get_server_send_pkey(s); if (cpk == NULL) { /* VRS: allow null cert if auth == KRB5 */ if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR); s->state = SSL_ST_ERR; return (0); } } if (!ssl3_output_cert_chain(s, cpk)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR); s->state = SSL_ST_ERR; return (0); } s->state = SSL3_ST_SW_CERT_B; } /* SSL3_ST_SW_CERT_B */ return ssl_do_write(s); } Commit Message: 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: MediaPlayerService::Client::ServiceDeathNotifier::~ServiceDeathNotifier() { mService->unlinkToDeath(this); } Commit Message: MediaPlayerService: avoid invalid static cast Bug: 30204103 Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028 (cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d) 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 RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, bool presented, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, presented, sync_point)); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: acpi_os_read_pci_configuration(struct acpi_pci_id * pci_id, u32 reg, u64 *value, u32 width) { int result, size; u32 value32; if (!value) return AE_BAD_PARAMETER; switch (width) { case 8: size = 1; break; case 16: size = 2; break; case 32: size = 4; break; default: return AE_ERROR; } result = raw_pci_read(pci_id->segment, pci_id->bus, PCI_DEVFN(pci_id->device, pci_id->function), reg, size, &value32); *value = value32; return (result ? AE_ERROR : AE_OK); } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static v8::Handle<v8::ArrayBuffer> toV8Object(ArrayBuffer* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { if (!impl) return v8::Handle<v8::ArrayBuffer>(); v8::Handle<v8::Value> wrapper = toV8(impl, creationContext, isolate); ASSERT(wrapper->IsArrayBuffer()); return wrapper.As<v8::ArrayBuffer>(); } 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:
0
Here are some example code snippets. Analyze the following code, 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 Erase(const std::string& addr) { base::AutoLock lock(lock_); map_.erase(addr); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: epass2003_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left) { int r; u8 kid; u8 retries = 0; u8 pin_low = 3; unsigned char maxtries = 0; LOG_FUNC_CALLED(card->ctx); internal_sanitize_pin_info(&data->pin1, 0); internal_sanitize_pin_info(&data->pin2, 1); data->flags |= SC_PIN_CMD_NEED_PADDING; kid = data->pin_reference; /* get pin retries */ if (data->cmd == SC_PIN_CMD_GET_INFO) { r = get_external_key_retries(card, 0x80 | kid, &retries); if (r == SC_SUCCESS) { data->pin1.tries_left = retries; if (tries_left) *tries_left = retries; r = get_external_key_maxtries(card, &maxtries); LOG_TEST_RET(card->ctx, r, "get max counter failed"); data->pin1.max_tries = maxtries; } } else if (data->cmd == SC_PIN_CMD_UNBLOCK) { /* verify */ r = external_key_auth(card, (kid + 1), (unsigned char *)data->pin1.data, data->pin1.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else if (data->cmd == SC_PIN_CMD_CHANGE || data->cmd == SC_PIN_CMD_UNBLOCK) { /* change */ r = update_secret_key(card, 0x04, kid, data->pin2.data, (unsigned long)data->pin2.len); LOG_TEST_RET(card->ctx, r, "verify pin failed"); } else { r = external_key_auth(card, kid, (unsigned char *)data->pin1.data, data->pin1.len); get_external_key_retries(card, 0x80 | kid, &retries); if (retries < pin_low) sc_log(card->ctx, "Verification failed (remaining tries: %d)", retries); } LOG_TEST_RET(card->ctx, r, "verify pin failed"); if (r == SC_SUCCESS) { data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN; } return r; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ScriptPromise BluetoothRemoteGATTCharacteristic::getDescriptorsImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, const String& descriptor) { if (!getGatt()->connected()) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected)); } if (!getGatt()->device()->isValidCharacteristic( m_characteristic->instance_id)) { return ScriptPromise::rejectWithDOMException( scriptState, BluetoothRemoteGATTUtils::CreateDOMException( BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); getGatt()->AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); WTF::Optional<String> uuid = WTF::nullopt; if (!descriptor.isEmpty()) uuid = descriptor; service->RemoteCharacteristicGetDescriptors( m_characteristic->instance_id, quantity, uuid, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTCharacteristic::GetDescriptorsCallback, wrapPersistent(this), m_characteristic->instance_id, quantity, wrapPersistent(resolver)))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} 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 LauncherView::ButtonPressed(views::Button* sender, const views::Event& event) { if (dragging_) return; if (sender == overflow_button_) ShowOverflowMenu(); if (!delegate_) return; int view_index = view_model_->GetIndexOfView(sender); if (view_index == -1) return; switch (model_->items()[view_index].type) { case TYPE_TABBED: case TYPE_APP_PANEL: case TYPE_APP_SHORTCUT: case TYPE_PLATFORM_APP: delegate_->ItemClicked(model_->items()[view_index], event.flags()); break; case TYPE_APP_LIST: Shell::GetInstance()->ToggleAppList(); break; case TYPE_BROWSER_SHORTCUT: if (event.flags() & ui::EF_CONTROL_DOWN) delegate_->CreateNewWindow(); else delegate_->CreateNewTab(); break; } } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void GpuMessageFilter::CreateCommandBufferCallback( IPC::Message* reply, int32 route_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); GpuHostMsg_CreateViewCommandBuffer::WriteReplyParams(reply, route_id); Send(reply); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob) { m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin()); if (m_urlForReading.isEmpty()) { failed(FileError::SECURITY_ERR); return; } ThreadableBlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url()); ResourceRequest request(m_urlForReading); request.setHTTPMethod("GET"); if (m_hasRange) request.setHTTPHeaderField("Range", String::format("bytes=%d-%d", m_rangeStart, m_rangeEnd)); ThreadableLoaderOptions options; options.sendLoadCallbacks = SendCallbacks; options.sniffContent = DoNotSniffContent; options.preflightPolicy = ConsiderPreflight; options.allowCredentials = AllowStoredCredentials; options.crossOriginRequestPolicy = DenyCrossOriginRequests; options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy; if (m_client) m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options); else ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: 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: mainloop_destroy_trigger(crm_trigger_t * source) { source->trigger = FALSE; if (source->id > 0) { g_source_remove(source->id); } return TRUE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Target: 1 Example 2: Code: int tls1_mac(SSL *ssl, unsigned char *md, int send) { SSL3_RECORD *rec; unsigned char *seq; EVP_MD_CTX *hash; size_t md_size, orig_len; int i; EVP_MD_CTX hmac, *mac_ctx; unsigned char header[13]; int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM)); int t; if (send) { rec= &(ssl->s3->wrec); seq= &(ssl->s3->write_sequence[0]); hash=ssl->write_hash; } else { rec= &(ssl->s3->rrec); seq= &(ssl->s3->read_sequence[0]); hash=ssl->read_hash; } t=EVP_MD_CTX_size(hash); OPENSSL_assert(t >= 0); md_size=t; /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */ if (stream_mac) { mac_ctx = hash; } else { EVP_MD_CTX_copy(&hmac,hash); mac_ctx = &hmac; } if (ssl->version == DTLS1_VERSION || ssl->version == DTLS1_BAD_VER) { unsigned char dtlsseq[8],*p=dtlsseq; s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p); memcpy (p,&seq[2],6); memcpy(header, dtlsseq, 8); } else memcpy(header, seq, 8); /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */ orig_len = rec->length+md_size+((unsigned int)rec->type>>8); rec->type &= 0xff; header[8]=rec->type; header[9]=(unsigned char)(ssl->version>>8); header[10]=(unsigned char)(ssl->version); header[11]=(rec->length)>>8; header[12]=(rec->length)&0xff; if (!send && EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE && ssl3_cbc_record_digest_supported(mac_ctx)) { /* This is a CBC-encrypted record. We must avoid leaking any * timing-side channel information about how many blocks of * data we are hashing because that gives an attacker a * timing-oracle. */ ssl3_cbc_digest_record( mac_ctx, md, &md_size, header, rec->input, rec->length + md_size, orig_len, ssl->s3->read_mac_secret, ssl->s3->read_mac_secret_size, 0 /* not SSLv3 */); } else { EVP_DigestSignUpdate(mac_ctx,header,sizeof(header)); EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length); t=EVP_DigestSignFinal(mac_ctx,md,&md_size); OPENSSL_assert(t > 0); #ifdef OPENSSL_FIPS if (!send && FIPS_mode()) tls_fips_digest_extra( ssl->enc_read_ctx, mac_ctx, rec->input, rec->length, orig_len); #endif } if (!stream_mac) EVP_MD_CTX_cleanup(&hmac); #ifdef TLS_DEBUG printf("sec="); {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); } printf("seq="); {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); } printf("buf="); {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); } printf("rec="); {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); } #endif if (ssl->version != DTLS1_VERSION && ssl->version != DTLS1_BAD_VER) { for (i=7; i>=0; i--) { ++seq[i]; if (seq[i] != 0) break; } } #ifdef TLS_DEBUG {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); } #endif return(md_size); } 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: int pid_delete_dentry(const struct dentry *dentry) { /* Is the task we represent dead? * If so, then don't put the dentry on the lru list, * kill it immediately. */ return proc_inode_is_dead(d_inode(dentry)); } Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready If /proc/<PID>/environ gets read before the envp[] array is fully set up in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to read more bytes than are actually written, as env_start will already be set but env_end will still be zero, making the range calculation underflow, allowing to read beyond the end of what has been written. Fix this as it is done for /proc/<PID>/cmdline by testing env_end for zero. It is, apparently, intentionally set last in create_*_tables(). This bug was found by the PaX size_overflow plugin that detected the arithmetic underflow of 'this_len = env_end - (env_start + src)' when env_end is still zero. The expected consequence is that userland trying to access /proc/<PID>/environ of a not yet fully set up process may get inconsistent data as we're in the middle of copying in the environment variables. Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363 Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461 Signed-off-by: Mathias Krause <[email protected]> Cc: Emese Revfy <[email protected]> Cc: Pax Team <[email protected]> Cc: Al Viro <[email protected]> Cc: Mateusz Guzik <[email protected]> Cc: Alexey Dobriyan <[email protected]> Cc: Cyrill Gorcunov <[email protected]> Cc: Jarod Wilson <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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: void GraphicsContext::clipPath(const Path&, WindRule) { notImplemented(); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: struct timespec64 current_time(struct inode *inode) { struct timespec64 now = current_kernel_time64(); if (unlikely(!inode->i_sb)) { WARN(1, "current_time() called with uninitialized super_block in the inode"); return now; } return timespec64_trunc(now, inode->i_sb->s_time_gran); } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ps_files_valid_key(const char *key) { size_t len; const char *p; char c; int ret = 1; for (p = key; (c = *p); p++) { /* valid characters are a..z,A..Z,0..9 */ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ',' || c == '-')) { ret = 0; break; } } len = p - key; /* Somewhat arbitrary length limit here, but should be way more than anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */ if (len == 0 || len > 128) { ret = 0; } return ret; } 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 inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct rtmsg *rtm; struct nlattr *tb[RTA_MAX+1]; struct fib_result res = {}; struct rtable *rt = NULL; struct flowi4 fl4; __be32 dst = 0; __be32 src = 0; u32 iif; int err; int mark; struct sk_buff *skb; u32 table_id = RT_TABLE_MAIN; kuid_t uid; err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err < 0) goto errout; rtm = nlmsg_data(nlh); skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout; } /* Reserve room for dummy headers, this skb can pass through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); /* Bugfix: need to give ip_route_input enough of an IP header to * not gag. */ ip_hdr(skb)->protocol = IPPROTO_UDP; ip_hdr(skb)->saddr = src; ip_hdr(skb)->daddr = dst; skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr)); memset(&fl4, 0, sizeof(fl4)); fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_free; } skb->protocol = htons(ETH_P_IP); skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_free; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = rt->rt_table_id; if (rtm->rtm_flags & RTM_F_FIB_MATCH) err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); else err = rt_fill_info(net, dst, src, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); if (err < 0) goto errout_free; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout: return err; errout_free: rcu_read_unlock(); kfree_skb(skb); goto errout; } Commit Message: net: check and errout if res->fi is NULL when RTM_F_FIB_MATCH is set Syzkaller hit 'general protection fault in fib_dump_info' bug on commit 4.13-rc5.. Guilty file: net/ipv4/fib_semantics.c kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN Modules linked in: CPU: 0 PID: 2808 Comm: syz-executor0 Not tainted 4.13.0-rc5 #1 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014 task: ffff880078562700 task.stack: ffff880078110000 RIP: 0010:fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP: 0018:ffff880078117010 EFLAGS: 00010206 RAX: dffffc0000000000 RBX: 00000000000000fe RCX: 0000000000000002 RDX: 0000000000000006 RSI: ffff880078117084 RDI: 0000000000000030 RBP: ffff880078117268 R08: 000000000000000c R09: ffff8800780d80c8 R10: 0000000058d629b4 R11: 0000000067fce681 R12: 0000000000000000 R13: ffff8800784bd540 R14: ffff8800780d80b5 R15: ffff8800780d80a4 FS: 00000000022fa940(0000) GS:ffff88007fc00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00000000004387d0 CR3: 0000000079135000 CR4: 00000000000006f0 Call Trace: inet_rtm_getroute+0xc89/0x1f50 net/ipv4/route.c:2766 rtnetlink_rcv_msg+0x288/0x680 net/core/rtnetlink.c:4217 netlink_rcv_skb+0x340/0x470 net/netlink/af_netlink.c:2397 rtnetlink_rcv+0x28/0x30 net/core/rtnetlink.c:4223 netlink_unicast_kernel net/netlink/af_netlink.c:1265 [inline] netlink_unicast+0x4c4/0x6e0 net/netlink/af_netlink.c:1291 netlink_sendmsg+0x8c4/0xca0 net/netlink/af_netlink.c:1854 sock_sendmsg_nosec net/socket.c:633 [inline] sock_sendmsg+0xca/0x110 net/socket.c:643 ___sys_sendmsg+0x779/0x8d0 net/socket.c:2035 __sys_sendmsg+0xd1/0x170 net/socket.c:2069 SYSC_sendmsg net/socket.c:2080 [inline] SyS_sendmsg+0x2d/0x50 net/socket.c:2076 entry_SYSCALL_64_fastpath+0x1a/0xa5 RIP: 0033:0x4512e9 RSP: 002b:00007ffc75584cc8 EFLAGS: 00000216 ORIG_RAX: 000000000000002e RAX: ffffffffffffffda RBX: 0000000000000002 RCX: 00000000004512e9 RDX: 0000000000000000 RSI: 0000000020f2cfc8 RDI: 0000000000000003 RBP: 000000000000000e R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000216 R12: fffffffffffffffe R13: 0000000000718000 R14: 0000000020c44ff0 R15: 0000000000000000 Code: 00 0f b6 8d ec fd ff ff 48 8b 85 f0 fd ff ff 88 48 17 48 8b 45 28 48 8d 78 30 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <0f> b6 04 02 84 c0 74 08 3c 03 0f 8e cb 0c 00 00 48 8b 45 28 44 RIP: fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP: ffff880078117010 ---[ end trace 254a7af28348f88b ]--- This patch adds a res->fi NULL check. example run: $ip route get 0.0.0.0 iif virt1-0 broadcast 0.0.0.0 dev lo cache <local,brd> iif virt1-0 $ip route get 0.0.0.0 iif virt1-0 fibmatch RTNETLINK answers: No route to host Reported-by: idaifish <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Fixes: b61798130f1b ("net: ipv4: RTM_GETROUTE: return matched fib result when requested") Signed-off-by: Roopa Prabhu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: static inline void lockdep_softirq_end(bool in_hardirq) { lockdep_softirq_exit(); if (in_hardirq) trace_hardirq_enter(); } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode, int type, struct posix_acl *acl) { char *name; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = reiserfs_posix_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0); /* * Ensure that the inode gets dirtied if we're only using * the mode bits and an old ACL didn't exist. We don't need * to check if the inode is hashed here since we won't get * called by reiserfs_inherit_default_acl(). */ if (error == -ENODATA) { error = 0; if (type == ACL_TYPE_ACCESS) { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } } kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 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 FILE *open_log_file(void) { if(log_fp) /* keep it open unless we rotate */ return log_fp; log_fp = fopen(log_file, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) { printf("Warning: Cannot open log file '%s' for writing\n", log_file); } return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; } Commit Message: Merge branch 'maint' CWE ID: CWE-264 Target: 1 Example 2: Code: void V8TestObject::StringSequenceMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_stringSequenceMethod"); test_object_v8_internal::StringSequenceMethodMethod(info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int req_parsebody(lua_State *L) { apr_array_header_t *pairs; apr_off_t len; int res; apr_size_t size; apr_size_t max_post_size; char *multipart; const char *contentType; request_rec *r = ap_lua_check_request_rec(L, 1); max_post_size = (apr_size_t) luaL_optint(L, 2, MAX_STRING_LEN); multipart = apr_pcalloc(r->pool, 256); contentType = apr_table_get(r->headers_in, "Content-Type"); lua_newtable(L); lua_newtable(L); /* [table, table] */ if (contentType != NULL && (sscanf(contentType, "multipart/form-data; boundary=%250c", multipart) == 1)) { char *buffer, *key, *filename; char *start = 0, *end = 0, *crlf = 0; const char *data; int i; size_t vlen = 0; size_t len = 0; if (lua_read_body(r, &data, (apr_off_t*) &size, max_post_size) != OK) { return 2; } len = strlen(multipart); i = 0; for ( start = strstr((char *) data, multipart); start != NULL; start = end ) { i++; if (i == POST_MAX_VARS) break; crlf = strstr((char *) start, "\r\n\r\n"); if (!crlf) break; end = ap_lua_binstrstr(crlf, (size - (crlf - data)), multipart, len); if (end == NULL) break; key = (char *) apr_pcalloc(r->pool, 256); filename = (char *) apr_pcalloc(r->pool, 256); vlen = end - crlf - 8; buffer = (char *) apr_pcalloc(r->pool, vlen+1); memcpy(buffer, crlf + 4, vlen); sscanf(start + len + 2, "Content-Disposition: form-data; name=\"%255[^\"]\"; filename=\"%255[^\"]\"", key, filename); if (strlen(key)) { req_aprtable2luatable_cb_len(L, key, buffer, vlen); } } } else { char *buffer; res = ap_parse_form_data(r, NULL, &pairs, -1, max_post_size); if (res == OK) { while(pairs && !apr_is_empty_array(pairs)) { ap_form_pair_t *pair = (ap_form_pair_t *) apr_array_pop(pairs); apr_brigade_length(pair->value, 1, &len); size = (apr_size_t) len; buffer = apr_palloc(r->pool, size + 1); apr_brigade_flatten(pair->value, buffer, &size); buffer[len] = 0; req_aprtable2luatable_cb(L, pair->name, buffer); } } } return 2; /* [table<string, string>, table<string, array<string>>] */ } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, 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 ndp_sock_open(struct ndp *ndp) { int sock; int ret; int err; int val; sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6); if (sock == -1) { err(ndp, "Failed to create ICMP6 socket."); return -errno; } val = 1; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO."); err = -errno; goto close_sock; } val = 255; ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)); if (ret == -1) { err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS."); err = -errno; goto close_sock; } ndp->sock = sock; return 0; close_sock: close(sock); return err; } Commit Message: libndp: validate the IPv6 hop limit None of the NDP messages should ever come from a non-local network; as stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA), and 8.1. (redirect): - The IP Hop Limit field has a value of 255, i.e., the packet could not possibly have been forwarded by a router. This fixes CVE-2016-3698. Reported by: Julien BERNARD <[email protected]> Signed-off-by: Lubomir Rintel <[email protected]> Signed-off-by: Jiri Pirko <[email protected]> CWE ID: CWE-284 Target: 1 Example 2: Code: HRESULT CGaiaCredentialBase::CommandLinkClicked(DWORD dwFieldID) { return E_NOTIMPL; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#646278} 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: clear_all_old(mrb_state *mrb, mrb_gc *gc) { mrb_bool origin_mode = gc->generational; mrb_assert(is_generational(gc)); if (is_major_gc(gc)) { /* finish the half baked GC */ incremental_gc_until(mrb, gc, MRB_GC_STATE_ROOT); } /* Sweep the dead objects, then reset all the live objects * (including all the old objects, of course) to white. */ gc->generational = FALSE; prepare_incremental_sweep(mrb, gc); incremental_gc_until(mrb, gc, MRB_GC_STATE_ROOT); gc->generational = origin_mode; /* The gray objects have already been painted as white */ gc->atomic_gray_list = gc->gray_list = NULL; } Commit Message: Clear unused stack region that may refer freed objects; fix #3596 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: sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo) { Sg_request *srp; int val; unsigned int ms; val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if (val > SG_MAX_QUEUE) break; memset(&rinfo[val], 0, SZ_SG_REQ_INFO); rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; val++; } } Commit Message: scsi: sg: fixup infoleak when using SG_GET_REQUEST_TABLE When calling SG_GET_REQUEST_TABLE ioctl only a half-filled table is returned; the remaining part will then contain stale kernel memory information. This patch zeroes out the entire table to avoid this issue. Signed-off-by: Hannes Reinecke <[email protected]> Reviewed-by: Bart Van Assche <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Eric Dumazet <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void NavigationController::RestoreFromState( const std::vector<TabNavigation>& navigations, int selected_navigation, bool from_last_session) { DCHECK(entry_count() == 0 && !pending_entry()); DCHECK(selected_navigation >= 0 && selected_navigation < static_cast<int>(navigations.size())); needs_reload_ = true; CreateNavigationEntriesFromTabNavigations(navigations, &entries_); FinishRestore(selected_navigation, from_last_session); } Commit Message: Ensure URL is updated after a cross-site navigation is pre-empted by an "ignored" navigation. BUG=77507 TEST=NavigationControllerTest.LoadURL_IgnorePreemptsPending Review URL: http://codereview.chromium.org/6826015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@81307 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: xps_select_font_encoding(xps_font_t *font, int idx) { byte *cmapdata, *entry; int pid, eid; if (idx < 0 || idx >= font->cmapsubcount) return; cmapdata = font->data + font->cmaptable; entry = cmapdata + 4 + idx * 8; pid = u16(entry + 0); eid = u16(entry + 2); font->cmapsubtable = font->cmaptable + u32(entry + 4); font->usepua = (pid == 3 && eid == 0); } Commit Message: CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: authentic_set_current_files(struct sc_card *card, struct sc_path *path, unsigned char *resp, size_t resplen, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); if (resplen) { switch (resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (path) file->path = *path; rv = authentic_process_fci(card, file, resp, resplen); LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error"); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } if (file->type == SC_FILE_TYPE_DF) { struct sc_path cur_df_path; memset(&cur_df_path, 0, sizeof(cur_df_path)); if (card->cache.valid && card->cache.current_df) { cur_df_path = card->cache.current_df->path; sc_file_free(card->cache.current_df); } card->cache.current_df = NULL; sc_file_dup(&card->cache.current_df, file); if (cur_df_path.len) { memcpy(card->cache.current_df->path.value + cur_df_path.len, card->cache.current_df->path.value, card->cache.current_df->path.len); memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len); card->cache.current_df->path.len += cur_df_path.len; } sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } else { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) *file_out = file; else sc_file_free(file); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125 Target: 1 Example 2: Code: void Browser::AddNewContents(WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_pos, bool user_gesture, bool* was_blocked) { chrome::AddWebContents(this, source, new_contents, disposition, initial_pos, user_gesture, was_blocked); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { avpriv_request_sample(track->par, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } Commit Message: avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id Fixes: out of array access Fixes: ffmpeg_bof_1.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-129 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 SeekHead::ParseEntry( IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadUInt(pReader, pos, len); if (seekIdId != 0x13AB) //SeekID ID return false; if ((pos + len) > stop) return false; pos += len; //consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); //payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; //consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) //SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; //consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; //consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; //consume payload if (pos != stop) return false; return true; } 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: base::WeakPtr<FileSystemManagerImpl> FileSystemManagerImpl::GetWeakPtr() { DCHECK_CURRENTLY_ON(BrowserThread::IO); return weak_factory_.GetWeakPtr(); } Commit Message: Disable FileSystemManager::CreateWriter if WritableFiles isn't enabled. Bug: 922677 Change-Id: Ib16137cbabb2ec07f1ffc0484722f1d9cc533404 Reviewed-on: https://chromium-review.googlesource.com/c/1416570 Commit-Queue: Marijn Kruisselbrink <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#623552} CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } Commit Message: Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). CVE-2014-8275 Reviewed-by: Emilia Käsper <[email protected]> CWE ID: CWE-310 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: krb5_ldap_get_password_policy_from_dn(krb5_context context, char *pol_name, char *pol_dn, osa_policy_ent_t *policy) { krb5_error_code st=0, tempst=0; LDAP *ld=NULL; LDAPMessage *result=NULL,*ent=NULL; kdb5_dal_handle *dal_handle=NULL; krb5_ldap_context *ldap_context=NULL; krb5_ldap_server_handle *ldap_server_handle=NULL; /* Clear the global error string */ krb5_clear_error_message(context); /* validate the input parameters */ if (pol_dn == NULL) return EINVAL; *policy = NULL; SETUP_CONTEXT(); GET_HANDLE(); *(policy) = (osa_policy_ent_t) malloc(sizeof(osa_policy_ent_rec)); if (*policy == NULL) { st = ENOMEM; goto cleanup; } memset(*policy, 0, sizeof(osa_policy_ent_rec)); LDAP_SEARCH(pol_dn, LDAP_SCOPE_BASE, "(objectclass=krbPwdPolicy)", password_policy_attributes); ent=ldap_first_entry(ld, result); if (ent != NULL) { if ((st = populate_policy(context, ld, ent, pol_name, *policy)) != 0) goto cleanup; } cleanup: ldap_msgfree(result); if (st != 0) { if (*policy != NULL) { krb5_ldap_free_password_policy(context, *policy); *policy = NULL; } } krb5_ldap_put_handle_to_pool(ldap_context, ldap_server_handle); return st; } Commit Message: Fix LDAP misused policy name crash [CVE-2014-5353] In krb5_ldap_get_password_policy_from_dn, if LDAP_SEARCH returns successfully with no results, return KRB5_KDB_NOENTRY instead of returning success with a zeroed-out policy object. This fixes a null dereference when an admin attempts to use an LDAP ticket policy name as a password policy name. CVE-2014-5353: In MIT krb5, when kadmind is configured to use LDAP for the KDC database, an authenticated remote attacker can cause a NULL dereference by attempting to use a named ticket policy object as a password policy for a principal. The attacker needs to be authenticated as a user who has the elevated privilege for setting password policy by adding or modifying principals. Queries to LDAP scoped to the krbPwdPolicy object class will correctly not return entries of other classes, such as ticket policy objects, but may return success with no returned elements if an object with the requested DN exists in a different object class. In this case, the routine to retrieve a password policy returned success with a password policy object that consisted entirely of zeroed memory. In particular, accesses to the policy name will dereference a NULL pointer. KDC operation does not access the policy name field, but most kadmin operations involving the principal with incorrect password policy will trigger the crash. Thanks to Patrik Kis for reporting this problem. CVSSv2 Vector: AV:N/AC:M/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:C [[email protected]: CVE description and CVSS score] ticket: 8051 (new) target_version: 1.13.1 tags: pullup CWE ID: Target: 1 Example 2: Code: JSValue jsTestObjUnsignedIntSequenceAttr(ExecState* exec, JSValue slotBase, const Identifier&) { JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(slotBase)); UNUSED_PARAM(exec); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); JSValue result = jsArray(exec, castedThis->globalObject(), impl->unsignedIntSequenceAttr()); return result; } 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: OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (defParams->nPortIndex >= mPorts.size()) { return OMX_ErrorBadPortIndex; } if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUnsupportedSetting; } PortInfo *port = &mPorts.editItemAt(defParams->nPortIndex); if (defParams->nBufferSize > port->mDef.nBufferSize) { port->mDef.nBufferSize = defParams->nBufferSize; } if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) { ALOGW("component requires at least %u buffers (%u requested)", port->mDef.nBufferCountMin, defParams->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } port->mDef.nBufferCountActual = defParams->nBufferCountActual; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } 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: void HttpBridge::MakeAsynchronousPost() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::AutoLock lock(fetch_state_lock_); DCHECK(!fetch_state_.request_completed); if (fetch_state_.aborted) return; fetch_state_.url_poster = new URLFetcher(url_for_request_, URLFetcher::POST, this); fetch_state_.url_poster->set_request_context(context_getter_for_request_); fetch_state_.url_poster->set_upload_data(content_type_, request_content_); fetch_state_.url_poster->set_extra_request_headers(extra_headers_); fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES); fetch_state_.url_poster->Start(); } Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc. This change modified http_bridge so that it uses a factory to construct the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to use an URLFetcher factory which will prevent access to www.example.com during the test. BUG=none TEST=sync_backend_host_unittest.cc Review URL: http://codereview.chromium.org/7053011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: bool HasPreviousSessionData() { return provider()->HasPreviousSessionData(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 MediaRecorderHandler::OnEncodedVideo( const media::WebmMuxer::VideoParameters& params, std::unique_ptr<std::string> encoded_data, std::unique_ptr<std::string> encoded_alpha, TimeTicks timestamp, bool is_key_frame) { DCHECK(main_render_thread_checker_.CalledOnValidThread()); if (UpdateTracksAndCheckIfChanged()) { client_->OnError("Amount of tracks in MediaStream has changed."); return; } if (!webm_muxer_) return; if (!webm_muxer_->OnEncodedVideo(params, std::move(encoded_data), std::move(encoded_alpha), timestamp, is_key_frame)) { DLOG(ERROR) << "Error muxing video data"; client_->OnError("Error muxing video data"); } } Commit Message: Check context is attached before creating MediaRecorder Bug: 896736 Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34 Reviewed-on: https://chromium-review.googlesource.com/c/1324231 Commit-Queue: Emircan Uysaler <[email protected]> Reviewed-by: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#606242} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, 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 av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) chunk_size[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) chunk_offset[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) audio_size[i] = avio_rl32(pb) & 0xFFFF; /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; } Commit Message: avformat/rl2: Fix DoS due to lack of eof check Fixes: loop.rl2 Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 Target: 1 Example 2: Code: void GLES2DecoderImpl::DoRegisterSharedIdsCHROMIUM( GLuint namespace_id, GLsizei n, const GLuint* ids) { IdAllocatorInterface* id_allocator = group_->GetIdAllocator(namespace_id); for (GLsizei ii = 0; ii < n; ++ii) { if (!id_allocator->MarkAsUsed(ids[ii])) { for (GLsizei jj = 0; jj < ii; ++jj) { id_allocator->FreeID(ids[jj]); } LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, "RegisterSharedIdsCHROMIUM", "attempt to register id that already exists"); return; } } } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxInterface *decoder = NULL; const VpxVideoInfo *info = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { vpx_img_write(img, outfile); ++frame_cnt; } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec"); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 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 scsi_write_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode != SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_write_complete(r, -EINVAL); return; } n = r->iov.iov_len / 512; if (n) { if (s->tray_open) { scsi_write_complete(r, -ENOMEDIUM); } qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE); r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n, scsi_write_complete, r); if (r->req.aiocb == NULL) { scsi_write_complete(r, -ENOMEM); } } else { /* Invoke completion routine to fetch data from host. */ scsi_write_complete(r, 0); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: nfsd4_check_open_attributes(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open) { __be32 status = nfs_ok; if (open->op_create == NFS4_OPEN_CREATE) { if (open->op_createmode == NFS4_CREATE_UNCHECKED || open->op_createmode == NFS4_CREATE_GUARDED) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd_attrmask); else if (open->op_createmode == NFS4_CREATE_EXCLUSIVE4_1) status = check_attr_support(rqstp, cstate, open->op_bmval, nfsd41_ex_attrmask); } return status; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) { return do_sock_sendmsg(sock, msg, size, false); } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: [email protected] # v3.19 Signed-off-by: Al Viro <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void comps_objmrtree_unite(COMPS_ObjMRTree *rt1, COMPS_ObjMRTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; COMPS_ObjListIt *it2; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); pair->added = 0; for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_ObjMRTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_ObjMRTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key+strlen(parent_pair->key), ((COMPS_ObjMRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_ObjMRTreeData*)it->data)->key) + 1)); memcpy(pair->key, ((COMPS_ObjMRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_ObjMRTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_ObjMRTreeData*)it->data)->data->first != NULL) { for (it2 = ((COMPS_ObjMRTreeData*)it->data)->data->first; it2 != NULL; it2 = it2->next) { comps_objmrtree_set(rt1, pair->key, it2->comps_obj); } if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } /* current node hasn't data */ } else { if (((COMPS_ObjMRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. CWE ID: CWE-416 Target: 1 Example 2: Code: static int sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *transport) { struct sock *sk = skb->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &transport->fl.u.ip6; int res; pr_debug("%s: skb:%p, len:%d, src:%pI6 dst:%pI6\n", __func__, skb, skb->len, &fl6->saddr, &fl6->daddr); IP6_ECN_flow_xmit(sk, fl6->flowlabel); if (!(transport->param_flags & SPP_PMTUD_ENABLE)) skb->ignore_df = 1; SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS); rcu_read_lock(); res = ip6_xmit(sk, skb, fl6, sk->sk_mark, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); return res; } Commit Message: sctp: do not inherit ipv6_{mc|ac|fl}_list from parent SCTP needs fixes similar to 83eaddab4378 ("ipv6/dccp: do not inherit ipv6_mc_list from parent"), otherwise bad things can happen. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void watchdog_overflow_callback(struct perf_event *event, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { /* Ensure the watchdog never gets throttled */ event->hw.interrupts = 0; if (__this_cpu_read(watchdog_nmi_touch) == true) { __this_cpu_write(watchdog_nmi_touch, false); return; } /* check for a hardlockup * This is done by making sure our timer interrupt * is incrementing. The timer interrupt should have * fired multiple times before we overflow'd. If it hasn't * then this is a good indication the cpu is stuck */ if (is_hardlockup()) { int this_cpu = smp_processor_id(); /* only print hardlockups once */ if (__this_cpu_read(hard_watchdog_warn) == true) return; if (hardlockup_panic) panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu); else WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu); __this_cpu_write(hard_watchdog_warn, true); return; } __this_cpu_write(hard_watchdog_warn, false); return; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 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 init_ssl_connection(SSL *con) { int i; const char *str; X509 *peer; long verify_error; MS_STATIC char buf[BUFSIZ]; #ifndef OPENSSL_NO_KRB5 char *client_princ; #endif #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; i = SSL_accept(con); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) { fprintf(stderr, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); return (1); } BIO_printf(bio_err, "ERROR\n"); verify_error = SSL_get_verify_result(con); if (verify_error != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_error)); } /* Always print any error messages */ ERR_print_errors(bio_err); return (0); } if (s_brief) print_ssl_summary(bio_err, con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "subject=%s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf); BIO_printf(bio_s_out, "issuer=%s\n", buf); X509_free(peer); } if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_curves(bio_s_out, con, 0); #endif BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_cache_hit(con)) BIO_printf(bio_s_out, "Reused session-id\n"); if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) & TLS1_FLAGS_TLS_PADDING_BUG) BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n"); #ifndef OPENSSL_NO_KRB5 client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con)); if (client_princ != NULL) { BIO_printf(bio_s_out, "Kerberos peer principal is %s\n", client_princ); } #endif /* OPENSSL_NO_KRB5 */ BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(con) ? "" : " NOT"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = OPENSSL_malloc(keymatexportlen); if (exportedkeymat != NULL) { if (!SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0)) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } } return (1); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: std::unique_ptr<WebContents> WebContentsImpl::GetCreatedWindow( int process_id, int main_frame_widget_route_id) { auto key = GlobalRoutingID(process_id, main_frame_widget_route_id); auto iter = pending_contents_.find(key); if (iter == pending_contents_.end()) return nullptr; std::unique_ptr<WebContents> new_contents = std::move(iter->second); pending_contents_.erase(key); WebContentsImpl* raw_new_contents = static_cast<WebContentsImpl*>(new_contents.get()); RemoveDestructionObserver(raw_new_contents); if (BrowserPluginGuest::IsGuest(raw_new_contents)) return new_contents; if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() || !new_contents->GetMainFrame()->GetView()) { return nullptr; } return new_contents; } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CrosLibrary::TestApi::SetLoginLibrary( LoginLibrary* library, bool own) { library_->login_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionMethodWithCallbackArg(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); if (exec->argumentCount() <= 0 || !exec->argument(0).isFunction()) { setDOMException(exec, TYPE_MISMATCH_ERR); return JSValue::encode(jsUndefined()); } RefPtr<TestCallback> callback = JSTestCallback::create(asObject(exec->argument(0)), castedThis->globalObject()); impl->methodWithCallbackArg(callback); return JSValue::encode(jsUndefined()); } 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: Eina_Bool ewk_frame_navigate_possible(Evas_Object* ewkFrame, int steps) { EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, false); EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame, false); WebCore::Page* page = smartData->frame->page(); return page->canGoBackOrForward(steps); } Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing https://bugs.webkit.org/show_bug.cgi?id=85879 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17 Reviewed by Noam Rosenthal. Source/WebKit/efl: _ewk_frame_smart_del() is considering now that the frame can be present in cache. loader()->detachFromParent() is only applied for the main frame. loader()->cancelAndClear() is not used anymore. * ewk/ewk_frame.cpp: (_ewk_frame_smart_del): LayoutTests: * platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html. git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; #ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; #endif if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } #ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); #endif #ifdef TLSEXT_TYPE_encrypt_then_mac s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC; #endif if (data >= (d+n-2)) goto ri_check; n2s(data,length); if (data+length != d+n) { *al = SSL_AD_DECODE_ERROR; return 0; } while(data <= (d+n-4)) { n2s(data,type); n2s(data,size); if (data+size > (d+n)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } #ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); #if 0 fprintf(stderr,"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); sdata = s->session->tlsext_ecpointformatlist; #endif } #endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if (!tls_use_ticket(s) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } #ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); if (s->s3->server_opaque_prf_input_len == 0) s->s3->server_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ else s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } #endif else if (type == TLSEXT_TYPE_status_request) { /* MUST be empty and only sent if we've requested * a status request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } #ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } #endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (s->alpn_client_proto_list == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /* The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned) size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned) size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if(!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } #ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch(data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } #endif else if (type == TLSEXT_TYPE_use_srtp) { if(ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } /* If this extension type was not otherwise handled, but * matches a custom_cli_ext_record, then send it to the c * callback */ else if (s->ctx->custom_cli_ext_records_count) { size_t i; custom_cli_ext_record* record; for (i = 0; i < s->ctx->custom_cli_ext_records_count; i++) { record = &s->ctx->custom_cli_ext_records[i]; if (record->ext_type == type) { if (record->fn2 && !record->fn2(s, type, data, size, al, record->arg)) return 0; break; } } } #ifdef TLSEXT_TYPE_encrypt_then_mac else if (type == TLSEXT_TYPE_encrypt_then_mac) { /* Ignore if inappropriate ciphersuite */ if (s->s3->tmp.new_cipher->algorithm_mac != SSL_AEAD) s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC; } #endif data += size; } if (data != d+n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* Determine if we need to see RI. Strictly speaking if we want to * avoid an attack we should *always* see RI even on initial server * hello because the client doesn't see any renegotiation during an * attack. However this would mean we could not connect to any server * which doesn't support RI so for the immediate future tolerate RI * absence on initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; } Commit Message: CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HostCache::RecordSet(SetOutcome outcome, base::TimeTicks now, const Entry* old_entry, const Entry& new_entry) { CACHE_HISTOGRAM_ENUM("Set", outcome, MAX_SET_OUTCOME); switch (outcome) { case SET_INSERT: case SET_UPDATE_VALID: break; case SET_UPDATE_STALE: { EntryStaleness stale; old_entry->GetStaleness(now, network_changes_, &stale); CACHE_HISTOGRAM_TIME("UpdateStale.ExpiredBy", stale.expired_by); CACHE_HISTOGRAM_COUNT("UpdateStale.NetworkChanges", stale.network_changes); CACHE_HISTOGRAM_COUNT("UpdateStale.StaleHits", stale.stale_hits); if (old_entry->error() == OK && new_entry.error() == OK) { AddressListDeltaType delta = FindAddressListDeltaType( old_entry->addresses(), new_entry.addresses()); RecordUpdateStale(delta, stale); } break; } case MAX_SET_OUTCOME: NOTREACHED(); break; } } Commit Message: Add PersistenceDelegate to HostCache PersistenceDelegate is a new interface for persisting the contents of the HostCache. This commit includes the interface itself, the logic in HostCache for interacting with it, and a mock implementation of the interface for testing. It does not include support for immediate data removal since that won't be needed for the currently planned use case. BUG=605149 Review-Url: https://codereview.chromium.org/2943143002 Cr-Commit-Position: refs/heads/master@{#481015} CWE ID: Target: 1 Example 2: Code: void StorageHandler::NotifyCacheStorageContentChanged(const std::string& origin, const std::string& name) { DCHECK_CURRENTLY_ON(BrowserThread::UI); frontend_->CacheStorageContentUpdated(origin, name); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: enqueue_waiting_conn(conn c) { tube t; size_t i; global_stat.waiting_ct++; c->type |= CONN_TYPE_WAITING; for (i = 0; i < c->watch.used; i++) { t = c->watch.items[i]; t->stat.waiting_ct++; ms_append(&t->waiting, c); } } Commit Message: Discard job body bytes if the job is too big. Previously, a malicious user could craft a job payload and inject beanstalk commands without the client application knowing. (An extra-careful client library could check the size of the job body before sending the put command, but most libraries do not do this, nor should they have to.) Reported by Graham Barr. 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 LauncherView::ShowOverflowMenu() { #if !defined(OS_MACOSX) if (!delegate_) return; std::vector<LauncherItem> items; GetOverflowItems(&items); if (items.empty()) return; MenuDelegateImpl menu_delegate; ui::SimpleMenuModel menu_model(&menu_delegate); for (size_t i = 0; i < items.size(); ++i) menu_model.AddItem(static_cast<int>(i), delegate_->GetTitle(items[i])); views::MenuModelAdapter menu_adapter(&menu_model); overflow_menu_runner_.reset(new views::MenuRunner(menu_adapter.CreateMenu())); gfx::Rect bounds(overflow_button_->size()); gfx::Point origin; ConvertPointToScreen(overflow_button_, &origin); if (overflow_menu_runner_->RunMenuAt(GetWidget(), NULL, gfx::Rect(origin, size()), views::MenuItemView::TOPLEFT, 0) == views::MenuRunner::MENU_DELETED) return; Shell::GetInstance()->UpdateShelfVisibility(); if (menu_delegate.activated_command_id() == -1) return; LauncherID activated_id = items[menu_delegate.activated_command_id()].id; LauncherItems::const_iterator window_iter = model_->ItemByID(activated_id); if (window_iter == model_->items().end()) return; // Window was deleted while menu was up. delegate_->ItemClicked(*window_iter, ui::EF_NONE); #endif // !defined(OS_MACOSX) } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static uint32_t i6300esb_mem_readw(void *vp, hwaddr addr) { uint32_t data = 0; I6300State *d = vp; i6300esb_debug("addr = %x\n", (int) addr); if (addr == 0xc) { /* The previous reboot flag is really bit 9, but there is * a bug in the Linux driver where it thinks it's bit 12. * Set both. */ data = d->previous_reboot_flag ? 0x1200 : 0; } return data; } Commit Message: CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word) { Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self; const byte *data = z->data; uint32_t result; if (offset + 4 < z->size) result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; else if (offset > z->size) return -1; else { int i; result = 0; for (i = 0; i < z->size - offset; i++) result |= data[offset + i] << ((3 - i) << 3); } *word = result; return 0; } 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: mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t lhs; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, m) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%" SIZE_T_FORMAT "u, " "nbytes=%" SIZE_T_FORMAT "u)\n", m->type, m->flag, offset, o, nbytes); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[0] << 8) | p->hs[1]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; lhs = (p->hs[1] << 8) | p->hs[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[0] << 24) | (p->hl[1] << 16) | (p->hl[2] << 8) | p->hl[3]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[3] << 24) | (p->hl[2] << 16) | (p->hl[1] << 8) | p->hl[0]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; lhs = (p->hl[1] << 24) | (p->hl[0] << 16) | (p->hl[3] << 8) | p->hl[2]; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = lhs & off; break; case FILE_OPOR: offset = lhs | off; break; case FILE_OPXOR: offset = lhs ^ off; break; case FILE_OPADD: offset = lhs + off; break; case FILE_OPMINUS: offset = lhs - off; break; case FILE_OPMULTIPLY: offset = lhs * off; break; case FILE_OPDIVIDE: offset = lhs / off; break; case FILE_OPMODULO: offset = lhs % off; break; } } else offset = lhs; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (OFFSET_OOB(nbytes, offset, 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, m) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (OFFSET_OOB(nbytes, offset, 1)) return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (OFFSET_OOB(nbytes, offset, 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (OFFSET_OOB(nbytes, offset, 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (OFFSET_OOB(nbytes, offset, 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (OFFSET_OOB(nbytes, offset, m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (offset == 0) return 0; if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, recursion_level, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(ms, m, "%u"), offset) == -1) { free(rbuf); return -1; } if (file_printf(ms, "%s", rbuf) == -1) { free(rbuf); return -1; } } free(rbuf); return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0; return 1; } Commit Message: - reduce recursion level from 20 to 10 and make a symbolic constant for it. - pull out the guts of saving and restoring the output buffer into functions and take care not to overwrite the error message if an error happened. CWE ID: CWE-399 Target: 1 Example 2: Code: void RunOpenDeviceCallback(const DeviceManager::OpenDeviceCallback& callback, OpenDeviceError error) { callback.Run(error); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 UnloadController::RemoveFromSet(UnloadListenerSet* set, content::WebContents* web_contents) { DCHECK(is_attempting_to_close_browser_); UnloadListenerSet::iterator iter = std::find(set->begin(), set->end(), web_contents); if (iter != set->end()) { set->erase(iter); 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers)); spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check; #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions); return SUCCESS; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid, TSK_FS_ATTR * a_attr, unsigned char dataForkQ) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint16_t nodesize; /* size of nodes (all, regardless of the name) */ uint32_t cur_node; /* node id of the current node */ char *node = NULL; uint8_t is_done; uint8_t desiredType; tsk_error_reset(); if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record_attr: Looking for extents for file %" PRIu32 " %s\n", cnid, dataForkQ ? "data fork" : "resource fork"); if (!hfs->has_extents_file) { return 0; } desiredType = dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC; if (hfs->extents_file == NULL) { ssize_t cnt; if ((hfs->extents_file = tsk_fs_file_open_meta(fs, NULL, HFS_EXTENTS_FILE_ID)) == NULL) { return 1; } /* cache the data attribute */ hfs->extents_attr = tsk_fs_attrlist_get(hfs->extents_file->meta->attr, TSK_FS_ATTR_TYPE_DEFAULT); if (!hfs->extents_attr) { tsk_error_errstr2_concat (" - Default Attribute not found in Extents File"); return 1; } cnt = tsk_fs_attr_read(hfs->extents_attr, 14, (char *) &(hfs->extents_header), sizeof(hfs_btree_header_record), 0); if (cnt != sizeof(hfs_btree_header_record)) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_ext_find_extent_record_attr: Error reading header"); return 1; } } nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) { return 1; } /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: " "empty extents btree\n"); free(node); return 0; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; if (cur_node > tsk_getu32(fs->endian, hfs->extents_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: Node %d too large for file", cur_node); free(node); return 1; } cur_off = (TSK_OFF_T)cur_node * nodesize; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: reading node %" PRIu32 " at offset %" PRIuOFF "\n", cur_node, cur_off); cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_ext_find_extent_record_attr: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: Index node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); for (rec = 0; rec < num_rec; ++rec) { int cmp; size_t rec_off; hfs_btree_key_ext *key; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_ext *) & node[rec_off]; cmp = hfs_ext_compare_keys(hfs, cnid, key); if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: record %" PRIu16 " ; keylen %" PRIu16 " (FileId: %" PRIu32 ", ForkType: %" PRIu8 ", StartBlk: %" PRIu32 "); compare: %d\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->file_id), key->fork_type, tsk_getu32(fs->endian, key->start_block), cmp); /* save the info from this record unless it is bigger than cnid */ if ((cmp <= 0) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->extents_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (cmp > 0) { break; } } if (next_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d", cnid, cur_node); is_done = 1; break; } cur_node = next_node; } /* with a leaf, we process until we are past cnid. We move right too if we can */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: Leaf node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_ext *key; uint32_t rec_cnid; hfs_extents *extents; TSK_OFF_T ext_off = 0; int keylen; TSK_FS_ATTR_RUN *attr_run; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_ext *) & node[rec_off]; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ", %" PRIu8 ", %" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->file_id), key->fork_type, tsk_getu32(fs->endian, key->start_block)); rec_cnid = tsk_getu32(fs->endian, key->file_id); if (rec_cnid < cnid) { continue; } if (rec_cnid > cnid) { is_done = 1; break; } if (key->fork_type != desiredType) { if (dataForkQ) { is_done = 1; break; } else continue; } keylen = 2 + tsk_getu16(fs->endian, key->key_len); if (rec_off + keylen + sizeof(hfs_extents) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } ext_off = tsk_getu32(fs->endian, key->start_block); extents = (hfs_extents *) & node[rec_off + keylen]; attr_run = hfs_extents_to_attr(fs, extents->extents, ext_off); if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) { tsk_error_errstr2_concat (" - hfs_ext_find_extent_record_attr"); free(node); return 1; } if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) { tsk_error_errstr2_concat (" - hfs_ext_find_extent_record_attr"); free(node); return 1; } } cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; break; } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_ext_find_extent_record: btree node %" PRIu32 " (%" PRIuOFF ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; } Commit Message: Merge pull request #1374 from JordyZomer/develop Fix CVE-2018-19497. 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: IMPEG2D_ERROR_CODES_T impeg2d_vld_decode( dec_state_t *ps_dec, WORD16 *pi2_outAddr, /*!< Address where decoded symbols will be stored */ const UWORD8 *pu1_scan, /*!< Scan table to be used */ UWORD8 *pu1_pos, /*!< Scan table to be used */ UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */ UWORD16 u2_chroma_flag, /*!< Chroma Block or not */ UWORD16 u2_d_picture, /*!< D Picture or not */ UWORD16 u2_intra_vlc_format, /*!< Intra VLC format */ UWORD16 u2_mpeg2, /*!< MPEG-2 or not */ WORD32 *pi4_num_coeffs /*!< Returns the number of coeffs in block */ ) { UWORD32 u4_sym_len; UWORD32 u4_decoded_value; UWORD32 u4_level_first_byte; WORD32 u4_level; UWORD32 u4_run, u4_numCoeffs; UWORD32 u4_buf; UWORD32 u4_buf_nxt; UWORD32 u4_offset; UWORD32 *pu4_buf_aligned; UWORD32 u4_bits; stream_t *ps_stream = &ps_dec->s_bit_stream; WORD32 u4_pos; UWORD32 u4_nz_cols; UWORD32 u4_nz_rows; *pi4_num_coeffs = 0; ps_dec->u4_non_zero_cols = 0; ps_dec->u4_non_zero_rows = 0; u4_nz_cols = ps_dec->u4_non_zero_cols; u4_nz_rows = ps_dec->u4_non_zero_rows; GET_TEMP_STREAM_DATA(u4_buf,u4_buf_nxt,u4_offset,pu4_buf_aligned,ps_stream) /**************************************************************************/ /* Decode the DC coefficient in case of Intra block */ /**************************************************************************/ if(u2_intra_flag) { WORD32 dc_size; WORD32 dc_diff; WORD32 maxLen; WORD32 idx; maxLen = MPEG2_DCT_DC_SIZE_LEN; idx = 0; if(u2_chroma_flag != 0) { maxLen += 1; idx++; } { WORD16 end = 0; UWORD32 maxLen_tmp = maxLen; UWORD16 m_iBit; /* Get the maximum number of bits needed to decode a symbol */ IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,maxLen) do { maxLen_tmp--; /* Read one bit at a time from the variable to decode the huffman code */ m_iBit = (UWORD8)((u4_bits >> maxLen_tmp) & 0x1); /* Get the next node pointer or the symbol from the tree */ end = gai2_impeg2d_dct_dc_size[idx][end][m_iBit]; }while(end > 0); dc_size = end + MPEG2_DCT_DC_SIZE_OFFSET; /* Flush the appropriate number of bits from the stream */ FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,(maxLen - maxLen_tmp),pu4_buf_aligned) } if (dc_size != 0) { UWORD32 u4_bits; IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, dc_size) dc_diff = u4_bits; if ((dc_diff & (1 << (dc_size - 1))) == 0) //v Probably the prediction algo? dc_diff -= (1 << dc_size) - 1; } else { dc_diff = 0; } pi2_outAddr[*pi4_num_coeffs] = dc_diff; /* This indicates the position of the coefficient. Since this is the DC * coefficient, we put the position as 0. */ pu1_pos[*pi4_num_coeffs] = pu1_scan[0]; (*pi4_num_coeffs)++; if (0 != dc_diff) { u4_nz_cols |= 0x01; u4_nz_rows |= 0x01; } u4_numCoeffs = 1; } /**************************************************************************/ /* Decoding of first AC coefficient in case of non Intra block */ /**************************************************************************/ else { /* First symbol can be 1s */ UWORD32 u4_bits; IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,1) if(u4_bits == 1) { FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,1, pu4_buf_aligned) IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, 1) if(u4_bits == 1) { pi2_outAddr[*pi4_num_coeffs] = -1; } else { pi2_outAddr[*pi4_num_coeffs] = 1; } /* This indicates the position of the coefficient. Since this is the DC * coefficient, we put the position as 0. */ pu1_pos[*pi4_num_coeffs] = pu1_scan[0]; (*pi4_num_coeffs)++; u4_numCoeffs = 1; u4_nz_cols |= 0x01; u4_nz_rows |= 0x01; } else { u4_numCoeffs = 0; } } if (1 == u2_d_picture) { PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream) ps_dec->u4_non_zero_cols = u4_nz_cols; ps_dec->u4_non_zero_rows = u4_nz_rows; return ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE); } if (1 == u2_intra_vlc_format && u2_intra_flag) { while(1) { UWORD32 lead_zeros; WORD16 DecodedValue; u4_sym_len = 17; IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,u4_sym_len) DecodedValue = gau2_impeg2d_tab_one_1_9[u4_bits >> 8]; u4_sym_len = (DecodedValue & 0xf); u4_level = DecodedValue >> 9; /* One table lookup */ if(0 != u4_level) { u4_run = ((DecodedValue >> 4) & 0x1f); u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } else { if (DecodedValue == END_OF_BLOCK_ONE) { u4_sym_len = 4; break; } else { /*Second table lookup*/ lead_zeros = CLZ(u4_bits) - 20;/* -16 since we are dealing with WORD32 */ if (0 != lead_zeros) { u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F; /* Flush the number of bits */ if (1 == lead_zeros) { u4_sym_len = ((u4_bits & 0x18) >> 3) == 2 ? 11:10; } else { u4_sym_len = 11 + lead_zeros; } /* flushing */ FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) /* Calculate the address */ u4_bits = ((lead_zeros - 1) << 5) + u4_bits; DecodedValue = gau2_impeg2d_tab_one_10_16[u4_bits]; u4_run = BITS(DecodedValue, 8,4); u4_level = ((WORD16) DecodedValue) >> 9; u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } /*********************************************************************/ /* MPEG2 Escape Code */ /*********************************************************************/ else if(u2_mpeg2 == 1) { u4_sym_len = 6; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18) u4_decoded_value = u4_bits; u4_run = (u4_decoded_value >> 12); u4_level = (u4_decoded_value & 0x0FFF); if (u4_level) u4_level = (u4_level - ((u4_level & 0x0800) << 1)); u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } /*********************************************************************/ /* MPEG1 Escape Code */ /*********************************************************************/ else { /*----------------------------------------------------------- * MPEG-1 Stream * * <See D.9.3 of MPEG-2> Run-level escape syntax * Run-level values that cannot be coded with a VLC are coded * by the escape code '0000 01' followed by * either a 14-bit FLC (127 <= level <= 127), * or a 22-bit FLC (255 <= level <= 255). * This is described in Annex B,B.5f of MPEG-1.standard *-----------------------------------------------------------*/ /*----------------------------------------------------------- * First 6 bits are the value of the Run. Next is First 8 bits * of Level. These bits decide whether it is 14 bit FLC or * 22-bit FLC. * * If( first 8 bits of Level == '1000000' or '00000000') * then its is 22-bit FLC. * else * it is 14-bit FLC. *-----------------------------------------------------------*/ u4_sym_len = 6; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14) u4_decoded_value = u4_bits; u4_run = (u4_decoded_value >> 8); u4_level_first_byte = (u4_decoded_value & 0x0FF); if(u4_level_first_byte & 0x7F) { /*------------------------------------------------------- * First 8 bits of level are neither 1000000 nor 00000000 * Hence 14-bit FLC (Last 8 bits are used to get level) * * Level = (msb of Level_First_Byte is 1)? * Level_First_Byte - 256 : Level_First_Byte *-------------------------------------------------------*/ u4_level = (u4_level_first_byte - ((u4_level_first_byte & 0x80) << 1)); } else { /*------------------------------------------------------- * Next 8 bits are either 1000000 or 00000000 * Hence 22-bit FLC (Last 16 bits are used to get level) * * Level = (msb of Level_First_Byte is 1)? * Level_Second_Byte - 256 : Level_Second_Byte *-------------------------------------------------------*/ IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8) u4_level = u4_bits; u4_level = (u4_level - (u4_level_first_byte << 1)); } u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } } } u4_nz_cols |= 1 << (u4_pos & 0x7); u4_nz_rows |= 1 << (u4_pos >> 0x3); } IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len) if (u4_numCoeffs > 64) { return IMPEG2D_MB_TEX_DECODE_ERR; } } else { while(1) { UWORD32 lead_zeros; UWORD16 DecodedValue; u4_sym_len = 17; IBITS_NXT(u4_buf, u4_buf_nxt, u4_offset, u4_bits, u4_sym_len) DecodedValue = gau2_impeg2d_tab_zero_1_9[u4_bits >> 8]; u4_sym_len = BITS(DecodedValue, 3, 0); u4_level = ((WORD16) DecodedValue) >> 9; if (0 != u4_level) { u4_run = BITS(DecodedValue, 8,4); u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } else { if(DecodedValue == END_OF_BLOCK_ZERO) { u4_sym_len = 2; break; } else { lead_zeros = CLZ(u4_bits) - 20;/* -15 since we are dealing with WORD32 */ /*Second table lookup*/ if (0 != lead_zeros) { u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F; /* Flush the number of bits */ u4_sym_len = 11 + lead_zeros; /* Calculate the address */ u4_bits = ((lead_zeros - 1) << 5) + u4_bits; DecodedValue = gau2_impeg2d_tab_zero_10_16[u4_bits]; u4_run = BITS(DecodedValue, 8,4); u4_level = ((WORD16) DecodedValue) >> 9; u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; if (1 == lead_zeros) u4_sym_len--; /* flushing */ FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } /*Escape Sequence*/ else if(u2_mpeg2 == 1) { u4_sym_len = 6; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18) u4_decoded_value = u4_bits; u4_run = (u4_decoded_value >> 12); u4_level = (u4_decoded_value & 0x0FFF); if (u4_level) u4_level = (u4_level - ((u4_level & 0x0800) << 1)); u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } /*********************************************************************/ /* MPEG1 Escape Code */ /*********************************************************************/ else { /*----------------------------------------------------------- * MPEG-1 Stream * * <See D.9.3 of MPEG-2> Run-level escape syntax * Run-level values that cannot be coded with a VLC are coded * by the escape code '0000 01' followed by * either a 14-bit FLC (127 <= level <= 127), * or a 22-bit FLC (255 <= level <= 255). * This is described in Annex B,B.5f of MPEG-1.standard *-----------------------------------------------------------*/ /*----------------------------------------------------------- * First 6 bits are the value of the Run. Next is First 8 bits * of Level. These bits decide whether it is 14 bit FLC or * 22-bit FLC. * * If( first 8 bits of Level == '1000000' or '00000000') * then its is 22-bit FLC. * else * it is 14-bit FLC. *-----------------------------------------------------------*/ u4_sym_len = 6; FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned) IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14) u4_decoded_value = u4_bits; u4_run = (u4_decoded_value >> 8); u4_level_first_byte = (u4_decoded_value & 0x0FF); if(u4_level_first_byte & 0x7F) { /*------------------------------------------------------- * First 8 bits of level are neither 1000000 nor 00000000 * Hence 14-bit FLC (Last 8 bits are used to get level) * * Level = (msb of Level_First_Byte is 1)? * Level_First_Byte - 256 : Level_First_Byte *-------------------------------------------------------*/ u4_level = (u4_level_first_byte - ((u4_level_first_byte & 0x80) << 1)); } else { /*------------------------------------------------------- * Next 8 bits are either 1000000 or 00000000 * Hence 22-bit FLC (Last 16 bits are used to get level) * * Level = (msb of Level_First_Byte is 1)? * Level_Second_Byte - 256 : Level_Second_Byte *-------------------------------------------------------*/ IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8) u4_level = u4_bits; u4_level = (u4_level - (u4_level_first_byte << 1)); } u4_numCoeffs += u4_run; u4_pos = pu1_scan[u4_numCoeffs++ & 63]; pu1_pos[*pi4_num_coeffs] = u4_pos; pi2_outAddr[*pi4_num_coeffs] = u4_level; (*pi4_num_coeffs)++; } } } u4_nz_cols |= 1 << (u4_pos & 0x7); u4_nz_rows |= 1 << (u4_pos >> 0x3); } if (u4_numCoeffs > 64) { return IMPEG2D_MB_TEX_DECODE_ERR; } IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len) } PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream) ps_dec->u4_non_zero_cols = u4_nz_cols; ps_dec->u4_non_zero_rows = u4_nz_rows; return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Fixed stack buffer overflow Bugfix: 25812590 Moved check for numCoeffs > 64 inside the coeff decode loop Change-Id: I444b77ef2a3da9233ec14bb72ac70b7e2fa56bd1 (cherry picked from commit ff3496c45c571da7eb93d6f9f05758813468fc72) 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: ComponentControllerImpl::ComponentControllerImpl(WebContentRunner* runner) : runner_(runner), controller_binding_(this), frame_observer_binding_(this) { DCHECK(runner); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264 Target: 1 Example 2: Code: fz_keep_colorspace(fz_context *ctx, fz_colorspace *cs) { return fz_keep_key_storable(ctx, &cs->key_storable); } 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 fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fdct16x16_c(in, out, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Output:
1