instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_gray_1_2_4_to_8_set( PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_gray_1_2_4_to_8_set( const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_gray_1_2_4_to_8(pp); /* NOTE: don't expect this to expand tRNS */ this->next->set(this->next, that, pp, pi); }
173,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } 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
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, unsigned char*& buf, size_t& buflen) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || len <= 0 || len > 8 || (available - pos) > len) return false; unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return false; pos += len; // consume length of size of payload rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return false; if ((pos + size) > available) return false; if (size >= LONG_MAX) return false; const long buflen_ = static_cast<long>(size); buf = SafeArrayAlloc<unsigned char>(1, buflen_); if (!buf) return false; status = pReader->Read(pos, buflen_, buf); if (status != 0) return false; buflen = buflen_; pos += size; // consume size of payload return true; }
173,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); }
171,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
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
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. */ if (!pipe_buf_get(ipipe, ibuf)) { if (ret == 0) ret = -EFAULT; break; } 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; }
170,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id, int route_id, bool alive, bool did_swap) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id, route_id, alive, did_swap)); return; } GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) { if (alive) host->Send(new AcceleratedSurfaceMsg_BufferPresented( route_id, did_swap, 0)); else host->ForceShutdown(); } } 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:
void AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id, int route_id, bool alive, uint64 surface_handle) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU, host_id, route_id, alive, surface_handle)); return; } GpuProcessHost* host = GpuProcessHost::FromID(host_id); if (host) { if (alive) host->Send(new AcceleratedSurfaceMsg_BufferPresented( route_id, surface_handle, 0)); else host->ForceShutdown(); } }
171,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs > CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; } Commit Message: mtd: spi-nor: Off by one in cqspi_setup_flash() There are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the > should be >=. Fixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller') Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Marek Vasut <[email protected]> Signed-off-by: Cyrille Pitchen <[email protected]> CWE ID: CWE-119
static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs >= CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; }
169,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::Resize() { static const int kGcInfoZapValue = 0x33; const size_t kInitialSize = 512; size_t new_size = gc_info_table_size_ ? 2 * gc_info_table_size_ : kInitialSize; DCHECK(new_size < GCInfoTable::kMaxIndex); g_gc_info_table = reinterpret_cast<GCInfo const**>(WTF::Partitions::FastRealloc( g_gc_info_table, new_size * sizeof(GCInfo), "GCInfo")); DCHECK(g_gc_info_table); memset(reinterpret_cast<uint8_t*>(g_gc_info_table) + gc_info_table_size_ * sizeof(GCInfo), kGcInfoZapValue, (new_size - gc_info_table_size_) * sizeof(GCInfo)); gc_info_table_size_ = new_size; } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::Resize() { const size_t new_limit = (limit_) ? 2 * limit_ : ComputeInitialTableLimit(); const size_t old_committed_size = limit_ * kEntrySize; const size_t new_committed_size = new_limit * kEntrySize; CHECK(table_); CHECK_EQ(0u, new_committed_size % base::kPageAllocationGranularity); CHECK_GE(MaxTableSize(), limit_ * kEntrySize); // Recommitting and zapping assumes byte-addressable storage. uint8_t* const current_table_end = reinterpret_cast<uint8_t*>(table_) + old_committed_size; const size_t table_size_delta = new_committed_size - old_committed_size; // Commit the new size and allow read/write. // TODO(ajwong): SetSystemPagesAccess should be part of RecommitSystemPages to // avoid having two calls here. bool ok = base::SetSystemPagesAccess(current_table_end, table_size_delta, base::PageReadWrite); CHECK(ok); ok = base::RecommitSystemPages(current_table_end, table_size_delta, base::PageReadWrite); CHECK(ok); // Zap unused values., memset(current_table_end, kGcInfoZapValue, table_size_delta); limit_ = new_limit; }
173,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readargs *args) { unsigned int len; int v; p = decode_fh(p, &args->fh); if (!p) return 0; args->offset = ntohl(*p++); len = args->count = ntohl(*p++); p++; /* totalcount - unused */ len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2); /* set up somewhere to store response. * We take pages, put them on reslist and include in iovec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readargs *args) { unsigned int len; int v; p = decode_fh(p, &args->fh); if (!p) return 0; args->offset = ntohl(*p++); len = args->count = ntohl(*p++); p++; /* totalcount - unused */ if (!xdr_argsize_check(rqstp, p)) return 0; len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2); /* set up somewhere to store response. * We take pages, put them on reslist and include in iovec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return 1; }
168,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_packet(unsigned char *data, int data_len) { struct mt_mactelnet_hdr pkthdr; /* Minimal size checks (pings are not supported here) */ if (data_len < MT_HEADER_LEN){ return -1; } parse_packet(data, &pkthdr); /* We only care about packets with correct sessionkey */ if (pkthdr.seskey != sessionkey) { return -1; } /* Handle data packets */ if (pkthdr.ptype == MT_PTYPE_DATA) { struct mt_packet odata; struct mt_mactelnet_control_hdr cpkt; int success = 0; /* Always transmit ACKNOWLEDGE packets in response to DATA packets */ init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN)); send_udp(&odata, 0); /* Accept first packet, and all packets greater than incounter, and if counter has wrapped around. */ if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) { incounter = pkthdr.counter; } else { /* Ignore double or old packets */ return -1; } /* Parse controlpacket data */ success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt); while (success) { /* If we receive pass_salt, transmit auth data back */ if (cpkt.cptype == MT_CPTYPE_PASSSALT) { memcpy(pass_salt, cpkt.data, cpkt.length); send_auth(username, password); } /* If the (remaining) data did not have a control-packet magic byte sequence, the data is raw terminal data to be outputted to the terminal. */ else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) { fwrite((const void *)cpkt.data, 1, cpkt.length, stdout); } /* END_AUTH means that the user/password negotiation is done, and after this point terminal data may arrive, so we set up the terminal to raw mode. */ else if (cpkt.cptype == MT_CPTYPE_END_AUTH) { /* we have entered "terminal mode" */ terminal_mode = 1; if (is_a_tty) { /* stop input buffering at all levels. Give full control of terminal to RouterOS */ raw_term(); setvbuf(stdin, (char*)NULL, _IONBF, 0); /* Add resize signal handler */ signal(SIGWINCH, sig_winch); } } /* Parse next controlpacket */ success = parse_control_packet(NULL, 0, &cpkt); } } else if (pkthdr.ptype == MT_PTYPE_ACK) { /* Handled elsewhere */ } /* The server wants to terminate the connection, we have to oblige */ else if (pkthdr.ptype == MT_PTYPE_END) { struct mt_packet odata; /* Acknowledge the disconnection by sending a END packet in return */ init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0); send_udp(&odata, 0); if (!quiet_mode) { fprintf(stderr, _("Connection closed.\n")); } /* exit */ running = 0; } else { fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac)); return -1; } return pkthdr.ptype; } Commit Message: Merge pull request #20 from eyalitki/master 2nd round security fixes from eyalitki CWE ID: CWE-119
static int handle_packet(unsigned char *data, int data_len) { struct mt_mactelnet_hdr pkthdr; /* Minimal size checks (pings are not supported here) */ if (data_len < MT_HEADER_LEN){ return -1; } parse_packet(data, &pkthdr); /* We only care about packets with correct sessionkey */ if (pkthdr.seskey != sessionkey) { return -1; } /* Handle data packets */ if (pkthdr.ptype == MT_PTYPE_DATA) { struct mt_packet odata; struct mt_mactelnet_control_hdr cpkt; int success = 0; /* Always transmit ACKNOWLEDGE packets in response to DATA packets */ init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN)); send_udp(&odata, 0); /* Accept first packet, and all packets greater than incounter, and if counter has wrapped around. */ if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) { incounter = pkthdr.counter; } else { /* Ignore double or old packets */ return -1; } /* Parse controlpacket data */ success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt); while (success) { /* If we receive pass_salt, transmit auth data back */ if (cpkt.cptype == MT_CPTYPE_PASSSALT) { /* check validity, server sends exactly 16 bytes */ if (cpkt.length != 16) { fprintf(stderr, _("Invalid salt length: %d (instead of 16) received from server %s\n"), cpkt.length, ether_ntoa((struct ether_addr *)dstmac)); } memcpy(pass_salt, cpkt.data, 16); send_auth(username, password); } /* If the (remaining) data did not have a control-packet magic byte sequence, the data is raw terminal data to be outputted to the terminal. */ else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) { fwrite((const void *)cpkt.data, 1, cpkt.length, stdout); } /* END_AUTH means that the user/password negotiation is done, and after this point terminal data may arrive, so we set up the terminal to raw mode. */ else if (cpkt.cptype == MT_CPTYPE_END_AUTH) { /* we have entered "terminal mode" */ terminal_mode = 1; if (is_a_tty) { /* stop input buffering at all levels. Give full control of terminal to RouterOS */ raw_term(); setvbuf(stdin, (char*)NULL, _IONBF, 0); /* Add resize signal handler */ signal(SIGWINCH, sig_winch); } } /* Parse next controlpacket */ success = parse_control_packet(NULL, 0, &cpkt); } } else if (pkthdr.ptype == MT_PTYPE_ACK) { /* Handled elsewhere */ } /* The server wants to terminate the connection, we have to oblige */ else if (pkthdr.ptype == MT_PTYPE_END) { struct mt_packet odata; /* Acknowledge the disconnection by sending a END packet in return */ init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0); send_udp(&odata, 0); if (!quiet_mode) { fprintf(stderr, _("Connection closed.\n")); } /* exit */ running = 0; } else { fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac)); return -1; } return pkthdr.ptype; }
166,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int newseg(struct ipc_namespace *ns, struct ipc_params *params) { key_t key = params->key; int shmflg = params->flg; size_t size = params->u.size; int error; struct shmid_kernel *shp; size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; struct file *file; char name[13]; int id; vm_flags_t acctflag = 0; if (size < SHMMIN || size > ns->shm_ctlmax) return -EINVAL; if (numpages << PAGE_SHIFT < size) return -ENOSPC; if (ns->shm_tot + numpages < ns->shm_tot || ns->shm_tot + numpages > ns->shm_ctlall) return -ENOSPC; shp = ipc_rcu_alloc(sizeof(*shp)); if (!shp) return -ENOMEM; shp->shm_perm.key = key; shp->shm_perm.mode = (shmflg & S_IRWXUGO); shp->mlock_user = NULL; shp->shm_perm.security = NULL; error = security_shm_alloc(shp); if (error) { ipc_rcu_putref(shp, ipc_rcu_free); return error; } sprintf(name, "SYSV%08x", key); if (shmflg & SHM_HUGETLB) { struct hstate *hs; size_t hugesize; hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK); if (!hs) { error = -EINVAL; goto no_file; } hugesize = ALIGN(size, huge_page_size(hs)); /* hugetlb_file_setup applies strict accounting */ if (shmflg & SHM_NORESERVE) acctflag = VM_NORESERVE; file = hugetlb_file_setup(name, hugesize, acctflag, &shp->mlock_user, HUGETLB_SHMFS_INODE, (shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK); } else { /* * Do not allow no accounting for OVERCOMMIT_NEVER, even * if it's asked for. */ if ((shmflg & SHM_NORESERVE) && sysctl_overcommit_memory != OVERCOMMIT_NEVER) acctflag = VM_NORESERVE; file = shmem_kernel_file_setup(name, size, acctflag); } error = PTR_ERR(file); if (IS_ERR(file)) goto no_file; id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni); if (id < 0) { error = id; goto no_id; } shp->shm_cprid = task_tgid_vnr(current); shp->shm_lprid = 0; shp->shm_atim = shp->shm_dtim = 0; shp->shm_ctim = get_seconds(); shp->shm_segsz = size; shp->shm_nattch = 0; shp->shm_file = file; shp->shm_creator = current; list_add(&shp->shm_clist, &current->sysvshm.shm_clist); /* * shmid gets reported as "inode#" in /proc/pid/maps. * proc-ps tools use this. Changing this will break them. */ file_inode(file)->i_ino = shp->shm_perm.id; ns->shm_tot += numpages; error = shp->shm_perm.id; ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); return error; no_id: if (is_file_hugepages(file) && shp->mlock_user) user_shm_unlock(size, shp->mlock_user); fput(file); no_file: ipc_rcu_putref(shp, shm_rcu_free); return error; } Commit Message: Initialize msg/shm IPC objects before doing ipc_addid() As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before having initialized the IPC object state. Yes, we initialize the IPC object in a locked state, but with all the lockless RCU lookup work, that IPC object lock no longer means that the state cannot be seen. We already did this for the IPC semaphore code (see commit e8577d1f0329: "ipc/sem.c: fully initialize sem_array before making it visible") but we clearly forgot about msg and shm. Reported-by: Dmitry Vyukov <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362
static int newseg(struct ipc_namespace *ns, struct ipc_params *params) { key_t key = params->key; int shmflg = params->flg; size_t size = params->u.size; int error; struct shmid_kernel *shp; size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT; struct file *file; char name[13]; int id; vm_flags_t acctflag = 0; if (size < SHMMIN || size > ns->shm_ctlmax) return -EINVAL; if (numpages << PAGE_SHIFT < size) return -ENOSPC; if (ns->shm_tot + numpages < ns->shm_tot || ns->shm_tot + numpages > ns->shm_ctlall) return -ENOSPC; shp = ipc_rcu_alloc(sizeof(*shp)); if (!shp) return -ENOMEM; shp->shm_perm.key = key; shp->shm_perm.mode = (shmflg & S_IRWXUGO); shp->mlock_user = NULL; shp->shm_perm.security = NULL; error = security_shm_alloc(shp); if (error) { ipc_rcu_putref(shp, ipc_rcu_free); return error; } sprintf(name, "SYSV%08x", key); if (shmflg & SHM_HUGETLB) { struct hstate *hs; size_t hugesize; hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK); if (!hs) { error = -EINVAL; goto no_file; } hugesize = ALIGN(size, huge_page_size(hs)); /* hugetlb_file_setup applies strict accounting */ if (shmflg & SHM_NORESERVE) acctflag = VM_NORESERVE; file = hugetlb_file_setup(name, hugesize, acctflag, &shp->mlock_user, HUGETLB_SHMFS_INODE, (shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK); } else { /* * Do not allow no accounting for OVERCOMMIT_NEVER, even * if it's asked for. */ if ((shmflg & SHM_NORESERVE) && sysctl_overcommit_memory != OVERCOMMIT_NEVER) acctflag = VM_NORESERVE; file = shmem_kernel_file_setup(name, size, acctflag); } error = PTR_ERR(file); if (IS_ERR(file)) goto no_file; shp->shm_cprid = task_tgid_vnr(current); shp->shm_lprid = 0; shp->shm_atim = shp->shm_dtim = 0; shp->shm_ctim = get_seconds(); shp->shm_segsz = size; shp->shm_nattch = 0; shp->shm_file = file; shp->shm_creator = current; id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni); if (id < 0) { error = id; goto no_id; } list_add(&shp->shm_clist, &current->sysvshm.shm_clist); /* * shmid gets reported as "inode#" in /proc/pid/maps. * proc-ps tools use this. Changing this will break them. */ file_inode(file)->i_ino = shp->shm_perm.id; ns->shm_tot += numpages; error = shp->shm_perm.id; ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); return error; no_id: if (is_file_hugepages(file) && shp->mlock_user) user_shm_unlock(size, shp->mlock_user); fput(file); no_file: ipc_rcu_putref(shp, shm_rcu_free); return error; }
166,579
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); treeScope()->adoptIfNeeded(attrNode); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); }
171,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(radius_get_vendor_attr) { int res; const void *data; int len; u_int32_t vendor; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &len) == FAILURE) { return; } res = rad_get_vendor_attr(&vendor, &data, (size_t *) &len); if (res == -1) { RETURN_FALSE; } else { array_init(return_value); add_assoc_long(return_value, "attr", res); add_assoc_long(return_value, "vendor", vendor); add_assoc_stringl(return_value, "data", (char *) data, len, 1); return; } } Commit Message: Fix a security issue in radius_get_vendor_attr(). The underlying rad_get_vendor_attr() function assumed that it would always be given valid VSA data. Indeed, the buffer length wasn't even passed in; the assumption was that the length field within the VSA structure would be valid. This could result in denial of service by providing a length that would be beyond the memory limit, or potential arbitrary memory access by providing a length greater than the actual data given. rad_get_vendor_attr() has been changed to require the raw data length be provided, and this is then used to check that the VSA is valid. Conflicts: radlib_vs.h CWE ID: CWE-119
PHP_FUNCTION(radius_get_vendor_attr) { const void *data, *raw; int len; u_int32_t vendor; unsigned char type; size_t data_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &raw, &len) == FAILURE) { return; } if (rad_get_vendor_attr(&vendor, &type, &data, &data_len, raw, len) == -1) { RETURN_FALSE; } else { array_init(return_value); add_assoc_long(return_value, "attr", type); add_assoc_long(return_value, "vendor", vendor); add_assoc_stringl(return_value, "data", (char *) data, data_len, 1); return; } }
166,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index) { struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table; int i, err = 0; int free = -1; mutex_lock(&table->mutex); for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) { if (free < 0 && (table->refs[i] == 0)) { free = i; continue; } if (table->refs[i] && (vlan == (MLX4_VLAN_MASK & be32_to_cpu(table->entries[i])))) { /* Vlan already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (table->total == table->max) { /* No free vlan entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID); err = mlx4_set_port_vlan_table(dev, port, table->entries); if (unlikely(err)) { mlx4_warn(dev, "Failed adding vlan: %u\n", vlan); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; } Commit Message: mlx4_en: Fix out of bounds array access When searching for a free entry in either mlx4_register_vlan() or mlx4_register_mac(), and there is no free entry, the loop terminates without updating the local variable free thus causing out of array bounds access. Fix this by adding a proper check outside the loop. Signed-off-by: Eli Cohen <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
int mlx4_register_vlan(struct mlx4_dev *dev, u8 port, u16 vlan, int *index) { struct mlx4_vlan_table *table = &mlx4_priv(dev)->port[port].vlan_table; int i, err = 0; int free = -1; mutex_lock(&table->mutex); for (i = MLX4_VLAN_REGULAR; i < MLX4_MAX_VLAN_NUM; i++) { if (free < 0 && (table->refs[i] == 0)) { free = i; continue; } if (table->refs[i] && (vlan == (MLX4_VLAN_MASK & be32_to_cpu(table->entries[i])))) { /* Vlan already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (free < 0) { err = -ENOMEM; goto out; } if (table->total == table->max) { /* No free vlan entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be32(vlan | MLX4_VLAN_VALID); err = mlx4_set_port_vlan_table(dev, port, table->entries); if (unlikely(err)) { mlx4_warn(dev, "Failed adding vlan: %u\n", vlan); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; }
169,872
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DataReductionProxyConfig::IsFetchInFlight() const { DCHECK(thread_checker_.CalledOnValidThread()); return warmup_url_fetcher_->IsFetchInFlight(); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
bool DataReductionProxyConfig::IsFetchInFlight() const { DCHECK(thread_checker_.CalledOnValidThread()); if (!warmup_url_fetcher_) return false; return warmup_url_fetcher_->IsFetchInFlight(); }
172,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { return original_context_.get(); } Commit Message: CWE ID: CWE-20
BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { BrowserContext* OTRBrowserContextImpl::GetOriginalContext() { return original_context_; }
165,414
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CuePoint::~CuePoint() { delete[] m_track_positions; } 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
CuePoint::~CuePoint()
174,462
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int sad = 0; const uint8_t* const reference = GetReference(block_idx); for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { sad += abs(source_data_[h * source_stride_ + w] - reference[h * reference_stride_ + w]); } if (sad > max_sad) { break; } } return sad; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int ReferenceSAD(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { sad += abs(source8[h * source_stride_ + w] - reference8[h * reference_stride_ + w]); #if CONFIG_VP9_HIGHBITDEPTH } else { sad += abs(source16[h * source_stride_ + w] - reference16[h * reference_stride_ + w]); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; }
174,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_association *new_asoc; int error = 0; char action; struct sctp_chunk *err_chk_p; /* Make sure that the chunk has a valid length from the protocol * perspective. In this case check to make sure we have at least * enough for the chunk header. Cookie length verification is * done later. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* "Decode" the chunk. We have no optional parameters so we * are in good shape. */ chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data; if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t))) goto nomem; /* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie * of a duplicate COOKIE ECHO match the Verification Tags of the * current association, consider the State Cookie valid even if * the lifespan is exceeded. */ new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, &err_chk_p); /* FIXME: * If the re-build failed, what is the proper error path * from here? * * [We should abort the association. --piggy] */ if (!new_asoc) { /* FIXME: Several errors are possible. A bad cookie should * be silently discarded, but think about logging it too. */ switch (error) { case -SCTP_IERROR_NOMEM: goto nomem; case -SCTP_IERROR_STALE_COOKIE: sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, err_chk_p); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case -SCTP_IERROR_BAD_SIG: default: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } /* Compare the tie_tag in cookie with the verification tag of * current association. */ action = sctp_tietags_compare(new_asoc, asoc); switch (action) { case 'A': /* Association restart. */ retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands, new_asoc); break; case 'B': /* Collision case B. */ retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands, new_asoc); break; case 'C': /* Collision case C. */ retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands, new_asoc); break; case 'D': /* Collision case D. */ retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands, new_asoc); break; default: /* Discard packet for all others. */ retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); break; } /* Delete the tempory new association. */ sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); /* Restore association pointer to provide SCTP command interpeter * with a valid context in case it needs to manipulate * the queues */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC((struct sctp_association *)asoc)); return retval; nomem: return SCTP_DISPOSITION_NOMEM; } Commit Message: sctp: Use correct sideffect command in duplicate cookie handling When SCTP is done processing a duplicate cookie chunk, it tries to delete a newly created association. For that, it has to set the right association for the side-effect processing to work. However, when it uses the SCTP_CMD_NEW_ASOC command, that performs more work then really needed (like hashing the associationa and assigning it an id) and there is no point to do that only to delete the association as a next step. In fact, it also creates an impossible condition where an association may be found by the getsockopt() call, and that association is empty. This causes a crash in some sctp getsockopts. The solution is rather simple. We simply use SCTP_CMD_SET_ASOC command that doesn't have all the overhead and does exactly what we need. Reported-by: Karl Heiss <[email protected]> Tested-by: Karl Heiss <[email protected]> CC: Neil Horman <[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:
sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { sctp_disposition_t retval; struct sctp_chunk *chunk = arg; struct sctp_association *new_asoc; int error = 0; char action; struct sctp_chunk *err_chk_p; /* Make sure that the chunk has a valid length from the protocol * perspective. In this case check to make sure we have at least * enough for the chunk header. Cookie length verification is * done later. */ if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* "Decode" the chunk. We have no optional parameters so we * are in good shape. */ chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data; if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t))) goto nomem; /* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie * of a duplicate COOKIE ECHO match the Verification Tags of the * current association, consider the State Cookie valid even if * the lifespan is exceeded. */ new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, &err_chk_p); /* FIXME: * If the re-build failed, what is the proper error path * from here? * * [We should abort the association. --piggy] */ if (!new_asoc) { /* FIXME: Several errors are possible. A bad cookie should * be silently discarded, but think about logging it too. */ switch (error) { case -SCTP_IERROR_NOMEM: goto nomem; case -SCTP_IERROR_STALE_COOKIE: sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, err_chk_p); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); case -SCTP_IERROR_BAD_SIG: default: return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } } /* Compare the tie_tag in cookie with the verification tag of * current association. */ action = sctp_tietags_compare(new_asoc, asoc); switch (action) { case 'A': /* Association restart. */ retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands, new_asoc); break; case 'B': /* Collision case B. */ retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands, new_asoc); break; case 'C': /* Collision case C. */ retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands, new_asoc); break; case 'D': /* Collision case D. */ retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands, new_asoc); break; default: /* Discard packet for all others. */ retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); break; } /* Delete the tempory new association. */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc)); sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); /* Restore association pointer to provide SCTP command interpeter * with a valid context in case it needs to manipulate * the queues */ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC((struct sctp_association *)asoc)); return retval; nomem: return SCTP_DISPOSITION_NOMEM; }
166,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WorkerProcessLauncherTest::WorkerProcessLauncherTest() : message_loop_(MessageLoop::TYPE_IO) { } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
WorkerProcessLauncherTest::WorkerProcessLauncherTest() : message_loop_(MessageLoop::TYPE_IO), client_pid_(GetCurrentProcessId()), permanent_error_(false) { }
171,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!ext4_handle_valid(handle)) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; } Commit Message: ext4: make orphan functions be no-op in no-journal mode Instead of checking whether the handle is valid, we check if journal is enabled. This avoids taking the s_orphan_lock mutex in all cases when there is no journal in use, including the error paths where ext4_orphan_del() is called with a handle set to NULL. Signed-off-by: Anatol Pomozov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: CWE-20
int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!EXT4_SB(sb)->s_journal) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; }
166,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap *base = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) { char *name = path_name(path, last); bitmap_pos = ext_index_add_object(object, name); free(name); } bitmap_set(base, bitmap_pos); } 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
static void show_object(struct object *object, struct strbuf *path, static void show_object(struct object *object, const char *name, void *data) { struct bitmap *base = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) bitmap_pos = ext_index_add_object(object, name); bitmap_set(base, bitmap_pos); }
167,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void set_fat(DOS_FS * fs, uint32_t cluster, int32_t new) { unsigned char *data = NULL; int size; loff_t offs; if (new == -1) new = FAT_EOF(fs); else if ((long)new == -2) new = FAT_BAD(fs); switch (fs->fat_bits) { case 12: data = fs->fat + cluster * 3 / 2; offs = fs->fat_start + cluster * 3 / 2; if (cluster & 1) { FAT_ENTRY prevEntry; get_fat(&prevEntry, fs->fat, cluster - 1, fs); data[0] = ((new & 0xf) << 4) | (prevEntry.value >> 8); data[1] = new >> 4; } else { FAT_ENTRY subseqEntry; if (cluster != fs->clusters - 1) get_fat(&subseqEntry, fs->fat, cluster + 1, fs); else subseqEntry.value = 0; data[0] = new & 0xff; data[1] = (new >> 8) | ((0xff & subseqEntry.value) << 4); } size = 2; break; case 16: data = fs->fat + cluster * 2; offs = fs->fat_start + cluster * 2; *(unsigned short *)data = htole16(new); size = 2; break; case 32: { FAT_ENTRY curEntry; get_fat(&curEntry, fs->fat, cluster, fs); data = fs->fat + cluster * 4; offs = fs->fat_start + cluster * 4; /* According to M$, the high 4 bits of a FAT32 entry are reserved and * are not part of the cluster number. So we never touch them. */ *(uint32_t *)data = htole32((new & 0xfffffff) | (curEntry.reserved << 28)); size = 4; } break; default: die("Bad FAT entry size: %d bits.", fs->fat_bits); } fs_write(offs, size, data); if (fs->nfats > 1) { fs_write(offs + fs->fat_size, size, data); } } Commit Message: set_fat(): Fix off-by-2 error leading to corruption in FAT12 In FAT12 two 12 bit entries are combined to a 24 bit value (three bytes). Therefore, when an even numbered FAT entry is set in FAT12, it must be be combined with the following entry. To prevent accessing beyond the end of the FAT array, it must be checked that the cluster is not the last one. Previously, the check tested that the requested cluster was equal to fs->clusters - 1. However, fs->clusters is the number of data clusters not including the two reserved FAT entries at the start so the test triggered two clusters early. If the third to last entry was written on a FAT12 filesystem with an odd number of clusters, the second to last entry would be corrupted. This corruption may also lead to invalid memory accesses when the corrupted entry becomes out of bounds and is used later. Change the test to fs->clusters + 1 to fix. Reported-by: Hanno Böck Signed-off-by: Andreas Bombe <[email protected]> CWE ID: CWE-189
void set_fat(DOS_FS * fs, uint32_t cluster, int32_t new) { unsigned char *data = NULL; int size; loff_t offs; if (new == -1) new = FAT_EOF(fs); else if ((long)new == -2) new = FAT_BAD(fs); switch (fs->fat_bits) { case 12: data = fs->fat + cluster * 3 / 2; offs = fs->fat_start + cluster * 3 / 2; if (cluster & 1) { FAT_ENTRY prevEntry; get_fat(&prevEntry, fs->fat, cluster - 1, fs); data[0] = ((new & 0xf) << 4) | (prevEntry.value >> 8); data[1] = new >> 4; } else { FAT_ENTRY subseqEntry; if (cluster != fs->clusters + 1) get_fat(&subseqEntry, fs->fat, cluster + 1, fs); else subseqEntry.value = 0; data[0] = new & 0xff; data[1] = (new >> 8) | ((0xff & subseqEntry.value) << 4); } size = 2; break; case 16: data = fs->fat + cluster * 2; offs = fs->fat_start + cluster * 2; *(unsigned short *)data = htole16(new); size = 2; break; case 32: { FAT_ENTRY curEntry; get_fat(&curEntry, fs->fat, cluster, fs); data = fs->fat + cluster * 4; offs = fs->fat_start + cluster * 4; /* According to M$, the high 4 bits of a FAT32 entry are reserved and * are not part of the cluster number. So we never touch them. */ *(uint32_t *)data = htole32((new & 0xfffffff) | (curEntry.reserved << 28)); size = 4; } break; default: die("Bad FAT entry size: %d bits.", fs->fat_bits); } fs_write(offs, size, data); if (fs->nfats > 1) { fs_write(offs + fs->fat_size, size, data); } }
167,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; } Commit Message: HID: hid-cypress: validate length of report Make sure we have enough of a report structure to validate before looking at it. Reported-by: Benoit Camredon <[email protected]> Tested-by: Benoit Camredon <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID:
static __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; if (*rsize < 4) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; }
168,288
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { int atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize <= 0) break; // Indicates the last atom or length too big. offset += atomsize; } return true; } Commit Message: Add extra checks to avoid integer overflow. BUG=425980 TEST=no crash with ASAN Review URL: https://codereview.chromium.org/659743004 Cr-Commit-Position: refs/heads/master@{#301249} CWE ID: CWE-189
static bool CheckMov(const uint8* buffer, int buffer_size) { RCHECK(buffer_size > 8); int offset = 0; while (offset + 8 < buffer_size) { uint32 atomsize = Read32(buffer + offset); uint32 atomtype = Read32(buffer + offset + 4); switch (atomtype) { case TAG('f','t','y','p'): case TAG('p','d','i','n'): case TAG('m','o','o','v'): case TAG('m','o','o','f'): case TAG('m','f','r','a'): case TAG('m','d','a','t'): case TAG('f','r','e','e'): case TAG('s','k','i','p'): case TAG('m','e','t','a'): case TAG('m','e','c','o'): case TAG('s','t','y','p'): case TAG('s','i','d','x'): case TAG('s','s','i','x'): case TAG('p','r','f','t'): case TAG('b','l','o','c'): break; default: return false; } if (atomsize == 1) { if (offset + 16 > buffer_size) break; if (Read32(buffer + offset + 8) != 0) break; // Offset is way past buffer size. atomsize = Read32(buffer + offset + 12); } if (atomsize == 0 || atomsize > static_cast<size_t>(buffer_size)) break; // Indicates the last atom or length too big. offset += atomsize; } return true; }
171,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* Chapters::Display::GetCountry() const { return m_country; } 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
const char* Chapters::Display::GetCountry() const
174,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool MultibufferDataSource::DidPassCORSAccessCheck() const { if (url_data()->cors_mode() == UrlData::CORS_UNSPECIFIED) return false; if (init_cb_) return false; if (failed_) return false; return true; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732
bool MultibufferDataSource::DidPassCORSAccessCheck() const {
172,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsData::CanRunOnPage(const Extension* extension, const GURL& document_url, const GURL& top_frame_url, int tab_id, int process_id, const URLPatternSet& permitted_url_patterns, std::string* error) const { if (g_policy_delegate && !g_policy_delegate->CanExecuteScriptOnPage( extension, document_url, top_frame_url, tab_id, process_id, error)) { return false; } bool can_execute_everywhere = CanExecuteScriptEverywhere(extension); if (!can_execute_everywhere && !ExtensionsClient::Get()->IsScriptableURL(document_url, error)) { return false; } if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kExtensionsOnChromeURLs)) { if (document_url.SchemeIs(content::kChromeUIScheme) && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessChromeUrl; return false; } } if (top_frame_url.SchemeIs(kExtensionScheme) && top_frame_url.GetOrigin() != Extension::GetBaseURLFromExtensionId(extension->id()).GetOrigin() && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessExtensionUrl; return false; } if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url)) return true; bool can_access = permitted_url_patterns.MatchesURL(document_url); if (!can_access && error) { *error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage, document_url.spec()); } return can_access; } Commit Message: Have the Debugger extension api check that it has access to the tab Check PermissionsData::CanAccessTab() prior to attaching the debugger. BUG=367567 Review URL: https://codereview.chromium.org/352523003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsData::CanRunOnPage(const Extension* extension, const GURL& document_url, const GURL& top_frame_url, int tab_id, int process_id, const URLPatternSet& permitted_url_patterns, std::string* error) const { if (g_policy_delegate && !g_policy_delegate->CanExecuteScriptOnPage( extension, document_url, top_frame_url, tab_id, process_id, error)) { return false; } if (IsRestrictedUrl(document_url, top_frame_url, extension, error)) return false; if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url)) return true; bool can_access = permitted_url_patterns.MatchesURL(document_url); if (!can_access && error) { *error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage, document_url.spec()); } return can_access; }
171,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur) { exsltDateValPtr ret; long carry, tempdays, temp; exsltDateValDatePtr r, d; exsltDateValDurationPtr u; if ((dt == NULL) || (dur == NULL)) return NULL; ret = exsltDateCreateDate(dt->type); if (ret == NULL) return NULL; r = &(ret->value.date); d = &(dt->value.date); u = &(dur->value.dur); /* normalization */ if (d->mon == 0) d->mon = 1; /* normalize for time zone offset */ u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */ d->tzo = 0; /* normalization */ if (d->day == 0) d->day = 1; /* month */ carry = d->mon + u->mon; r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13); carry = (long)FQUOTIENT_RANGE(carry, 1, 13); /* year (may be modified later) */ r->year = d->year + carry; if (r->year == 0) { if (d->year > 0) r->year--; else r->year++; } /* time zone */ r->tzo = d->tzo; r->tz_flag = d->tz_flag; /* seconds */ r->sec = d->sec + u->sec; carry = (long)FQUOTIENT((long)r->sec, 60); if (r->sec != 0.0) { r->sec = MODULO(r->sec, 60.0); } /* minute */ carry += d->min; r->min = (unsigned int)MODULO(carry, 60); carry = (long)FQUOTIENT(carry, 60); /* hours */ carry += d->hour; r->hour = (unsigned int)MODULO(carry, 24); carry = (long)FQUOTIENT(carry, 24); /* * days * Note we use tempdays because the temporary values may need more * than 5 bits */ if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) && (d->day > MAX_DAYINMONTH(r->year, r->mon))) tempdays = MAX_DAYINMONTH(r->year, r->mon); else if (d->day < 1) tempdays = 1; else tempdays = d->day; tempdays += u->day + carry; while (1) { if (tempdays < 1) { long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13); long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13); if (tyr == 0) tyr--; /* * Coverity detected an overrun in daysInMonth * of size 12 at position 12 with index variable "((r)->mon - 1)" */ if (tmon < 0) tmon = 0; if (tmon > 12) tmon = 12; tempdays += MAX_DAYINMONTH(tyr, tmon); carry = -1; } else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) { tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon); carry = 1; } else break; temp = r->mon + carry; r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13); r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13); if (r->year == 0) { if (temp < 1) r->year--; else r->year++; } } r->day = tempdays; /* * adjust the date/time type to the date values */ if (ret->type != XS_DATETIME) { if ((r->hour) || (r->min) || (r->sec)) ret->type = XS_DATETIME; else if (ret->type != XS_DATE) { if (r->day != 1) ret->type = XS_DATE; else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1)) ret->type = XS_GYEARMONTH; } } return 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
_exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur) { exsltDateValPtr ret; long carry, tempdays, temp; exsltDateValDatePtr r, d; exsltDateValDurationPtr u; if ((dt == NULL) || (dur == NULL)) return NULL; ret = exsltDateCreateDate(dt->type); if (ret == NULL) return NULL; r = &(ret->value.date); d = &(dt->value.date); u = &(dur->value.dur); /* normalize for time zone offset */ u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */ d->tzo = 0; /* month */ carry = d->mon + u->mon; r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13); carry = (long)FQUOTIENT_RANGE(carry, 1, 13); /* year (may be modified later) */ r->year = d->year + carry; if (r->year == 0) { if (d->year > 0) r->year--; else r->year++; } /* time zone */ r->tzo = d->tzo; r->tz_flag = d->tz_flag; /* seconds */ r->sec = d->sec + u->sec; carry = (long)FQUOTIENT((long)r->sec, 60); if (r->sec != 0.0) { r->sec = MODULO(r->sec, 60.0); } /* minute */ carry += d->min; r->min = (unsigned int)MODULO(carry, 60); carry = (long)FQUOTIENT(carry, 60); /* hours */ carry += d->hour; r->hour = (unsigned int)MODULO(carry, 24); carry = (long)FQUOTIENT(carry, 24); /* * days * Note we use tempdays because the temporary values may need more * than 5 bits */ if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) && (d->day > MAX_DAYINMONTH(r->year, r->mon))) tempdays = MAX_DAYINMONTH(r->year, r->mon); else if (d->day < 1) tempdays = 1; else tempdays = d->day; tempdays += u->day + carry; while (1) { if (tempdays < 1) { long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13); long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13); if (tyr == 0) tyr--; /* * Coverity detected an overrun in daysInMonth * of size 12 at position 12 with index variable "((r)->mon - 1)" */ if (tmon < 0) tmon = 0; if (tmon > 12) tmon = 12; tempdays += MAX_DAYINMONTH(tyr, tmon); carry = -1; } else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) { tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon); carry = 1; } else break; temp = r->mon + carry; r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13); r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13); if (r->year == 0) { if (temp < 1) r->year--; else r->year++; } } r->day = tempdays; /* * adjust the date/time type to the date values */ if (ret->type != XS_DATETIME) { if ((r->hour) || (r->min) || (r->sec)) ret->type = XS_DATETIME; else if (ret->type != XS_DATE) { if (r->day != 1) ret->type = XS_DATE; else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1)) ret->type = XS_GYEARMONTH; } } return ret; }
173,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting) { const struct k_clock *kc = timr->kclock; ktime_t now, remaining, iv; struct timespec64 ts64; bool sig_none; sig_none = timr->it_sigev_notify == SIGEV_NONE; iv = timr->it_interval; /* interval timer ? */ if (iv) { cur_setting->it_interval = ktime_to_timespec64(iv); } else if (!timr->it_active) { /* * SIGEV_NONE oneshot timers are never queued. Check them * below. */ if (!sig_none) return; } /* * The timespec64 based conversion is suboptimal, but it's not * worth to implement yet another callback. */ kc->clock_get(timr->it_clock, &ts64); now = timespec64_to_ktime(ts64); /* * When a requeue is pending or this is a SIGEV_NONE timer move the * expiry time forward by intervals, so expiry is > now. */ if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none)) timr->it_overrun += (int)kc->timer_forward(timr, now); remaining = kc->timer_remaining(timr, now); /* Return 0 only, when the timer is expired and not pending */ if (remaining <= 0) { /* * A single shot SIGEV_NONE timer must return 0, when * it is expired ! */ if (!sig_none) cur_setting->it_value.tv_nsec = 1; } else { cur_setting->it_value = ktime_to_timespec64(remaining); } } Commit Message: posix-timers: Sanitize overrun handling The posix timer overrun handling is broken because the forwarding functions can return a huge number of overruns which does not fit in an int. As a consequence timer_getoverrun(2) and siginfo::si_overrun can turn into random number generators. The k_clock::timer_forward() callbacks return a 64 bit value now. Make k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal accounting is correct. 3Remove the temporary (int) casts. Add a helper function which clamps the overrun value returned to user space via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value between 0 and INT_MAX. INT_MAX is an indicator for user space that the overrun value has been clamped. Reported-by: Team OWL337 <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Acked-by: John Stultz <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Michael Kerrisk <[email protected]> Link: https://lkml.kernel.org/r/[email protected] CWE ID: CWE-190
void common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting) { const struct k_clock *kc = timr->kclock; ktime_t now, remaining, iv; struct timespec64 ts64; bool sig_none; sig_none = timr->it_sigev_notify == SIGEV_NONE; iv = timr->it_interval; /* interval timer ? */ if (iv) { cur_setting->it_interval = ktime_to_timespec64(iv); } else if (!timr->it_active) { /* * SIGEV_NONE oneshot timers are never queued. Check them * below. */ if (!sig_none) return; } /* * The timespec64 based conversion is suboptimal, but it's not * worth to implement yet another callback. */ kc->clock_get(timr->it_clock, &ts64); now = timespec64_to_ktime(ts64); /* * When a requeue is pending or this is a SIGEV_NONE timer move the * expiry time forward by intervals, so expiry is > now. */ if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none)) timr->it_overrun += kc->timer_forward(timr, now); remaining = kc->timer_remaining(timr, now); /* Return 0 only, when the timer is expired and not pending */ if (remaining <= 0) { /* * A single shot SIGEV_NONE timer must return 0, when * it is expired ! */ if (!sig_none) cur_setting->it_value.tv_nsec = 1; } else { cur_setting->it_value = ktime_to_timespec64(remaining); } }
169,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: extract_header_length(uint16_t fc) { int len = 0; switch ((fc >> 10) & 0x3) { case 0x00: if (fc & (1 << 6)) /* intra-PAN with none dest addr */ return -1; break; case 0x01: return -1; case 0x02: len += 4; break; case 0x03: len += 10; break; } switch ((fc >> 14) & 0x3) { case 0x00: break; case 0x01: return -1; case 0x02: len += 4; break; case 0x03: len += 10; break; } if (fc & (1 << 6)) { if (len < 2) return -1; len -= 2; } return len; } Commit Message: CVE-2017-13000/IEEE 802.15.4: Add more bounds checks. While we're at it, add a bunch of macros for the frame control field's subfields, have the reserved frame types show the frame type value, use the same code path for processing source and destination addresses regardless of whether -v was specified (just leave out the addresses in non-verbose mode), and return the header length in all cases. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
extract_header_length(uint16_t fc)
170,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) { int labelfd = -1; int ret = 0; const char* name; char* command = NULL; name = lsm_name(); if (strcmp(name, "nop") == 0) goto out; if (strcmp(name, "none") == 0) goto out; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (on_exec) { labelfd = openat(procfd, "self/attr/exec", O_RDWR); } else { labelfd = openat(procfd, "self/attr/current", O_RDWR); } if (labelfd < 0) { SYSERROR("Unable to open LSM label"); ret = -1; goto out; } if (strcmp(name, "AppArmor") == 0) { int size; command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1); if (!command) { SYSERROR("Failed to write apparmor profile"); ret = -1; goto out; } size = sprintf(command, "changeprofile %s", lsm_label); if (size < 0) { SYSERROR("Failed to write apparmor profile"); ret = -1; goto out; } if (write(labelfd, command, size + 1) < 0) { SYSERROR("Unable to set LSM label"); ret = -1; goto out; } } else if (strcmp(name, "SELinux") == 0) { if (write(labelfd, lsm_label, strlen(lsm_label) + 1) < 0) { SYSERROR("Unable to set LSM label"); ret = -1; goto out; } } else { ERROR("Unable to restore label for unknown LSM: %s", name); ret = -1; goto out; } out: free(command); if (labelfd != -1) close(labelfd); return ret; } Commit Message: attach: do not send procfd to attached process So far, we opened a file descriptor refering to proc on the host inside the host namespace and handed that fd to the attached process in attach_child_main(). This was done to ensure that LSM labels were correctly setup. However, by exploiting a potential kernel bug, ptrace could be used to prevent the file descriptor from being closed which in turn could be used by an unprivileged container to gain access to the host namespace. Aside from this needing an upstream kernel fix, we should make sure that we don't pass the fd for proc itself to the attached process. However, we cannot completely prevent this, as the attached process needs to be able to change its apparmor profile by writing to /proc/self/attr/exec or /proc/self/attr/current. To minimize the attack surface, we only send the fd for /proc/self/attr/exec or /proc/self/attr/current to the attached process. To do this we introduce a little more IPC between the child and parent: * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * [set LXC_ATTACH_NO_NEW_PRIVS] * X <------------------------------------ send 3 * [open LSM label fd] * send 4 ------------------------------------> X * [set LSM label] * close socket close socket * run program The attached child tells the parent when it is ready to have its LSM labels set up. The parent then opens an approriate fd for the child PID to /proc/<pid>/attr/exec or /proc/<pid>/attr/current and sends it via SCM_RIGHTS to the child. The child can then set its LSM laben. Both sides then close the socket fds and the child execs the requested process. Signed-off-by: Christian Brauner <[email protected]> CWE ID: CWE-264
int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) { static int lsm_openat(int procfd, pid_t pid, int on_exec) { int ret = -1; int labelfd = -1; const char* name; #define __LSMATTRLEN /* /proc */ (5 + /* /pid-to-str */ 21 + /* /current */ 7 + /* \0 */ 1) char path[__LSMATTRLEN]; name = lsm_name(); if (strcmp(name, "nop") == 0) return 0; if (strcmp(name, "none") == 0) return 0; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (on_exec) { ret = snprintf(path, __LSMATTRLEN, "%d/attr/exec", pid); if (ret < 0 || ret >= __LSMATTRLEN) return -1; labelfd = openat(procfd, path, O_RDWR); } else { ret = snprintf(path, __LSMATTRLEN, "%d/attr/current", pid); if (ret < 0 || ret >= __LSMATTRLEN) return -1; labelfd = openat(procfd, path, O_RDWR); } if (labelfd < 0) { SYSERROR("Unable to open LSM label"); return -1; } return labelfd; } static int lsm_set_label_at(int lsm_labelfd, int on_exec, char *lsm_label) { int fret = -1; const char* name; char *command = NULL; name = lsm_name(); if (strcmp(name, "nop") == 0) return 0; if (strcmp(name, "none") == 0) return 0; /* We don't support on-exec with AppArmor */ if (strcmp(name, "AppArmor") == 0) on_exec = 0; if (strcmp(name, "AppArmor") == 0) { int size; command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1); if (!command) { SYSERROR("Failed to write apparmor profile"); goto out; } size = sprintf(command, "changeprofile %s", lsm_label); if (size < 0) { SYSERROR("Failed to write apparmor profile"); goto out; } if (write(lsm_labelfd, command, size + 1) < 0) { SYSERROR("Unable to set LSM label: %s.", command); goto out; } INFO("Set LSM label to: %s.", command); } else if (strcmp(name, "SELinux") == 0) { if (write(lsm_labelfd, lsm_label, strlen(lsm_label) + 1) < 0) { SYSERROR("Unable to set LSM label"); goto out; } INFO("Set LSM label to: %s.", lsm_label); } else { ERROR("Unable to restore label for unknown LSM: %s", name); goto out; } fret = 0; out: free(command); if (lsm_labelfd != -1) close(lsm_labelfd); return fret; }
168,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ConnectionInfoPopupAndroid::ConnectionInfoPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
ConnectionInfoPopupAndroid::ConnectionInfoPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), web_contents, nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); }
171,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ParamTraits<AudioParameters>::Read(const Message* m, PickleIterator* iter, AudioParameters* r) { int format, channel_layout, sample_rate, bits_per_sample, frames_per_buffer, channels; if (!m->ReadInt(iter, &format) || !m->ReadInt(iter, &channel_layout) || !m->ReadInt(iter, &sample_rate) || !m->ReadInt(iter, &bits_per_sample) || !m->ReadInt(iter, &frames_per_buffer) || !m->ReadInt(iter, &channels)) return false; r->Reset(static_cast<AudioParameters::Format>(format), static_cast<ChannelLayout>(channel_layout), sample_rate, bits_per_sample, frames_per_buffer); return true; } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool ParamTraits<AudioParameters>::Read(const Message* m, PickleIterator* iter, AudioParameters* r) { int format, channel_layout, sample_rate, bits_per_sample, frames_per_buffer, channels; if (!m->ReadInt(iter, &format) || !m->ReadInt(iter, &channel_layout) || !m->ReadInt(iter, &sample_rate) || !m->ReadInt(iter, &bits_per_sample) || !m->ReadInt(iter, &frames_per_buffer) || !m->ReadInt(iter, &channels)) return false; r->Reset(static_cast<AudioParameters::Format>(format), static_cast<ChannelLayout>(channel_layout), sample_rate, bits_per_sample, frames_per_buffer); if (!r->IsValid()) return false; return true; }
171,526
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OPENSSL_fork_child(void) { rand_fork(); } Commit Message: CWE ID: CWE-330
void OPENSSL_fork_child(void) { }
165,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId __unused, int32_t ioId __unused, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); return 0; }
173,343
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_tRNS_to_alpha_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_tRNS_to_alpha_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* We don't know yet whether there will be a tRNS chunk, but we know that * this transformation should do nothing if there already is an alpha * channel. In addition, after the bug fix in 1.7.0, there is no longer * any action on a palette image. */ return # if PNG_LIBPNG_VER >= 10700 colour_type != PNG_COLOR_TYPE_PALETTE && # endif (colour_type & PNG_COLOR_MASK_ALPHA) == 0; }
173,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionTtsController::SpeakNow(Utterance* utterance) { std::string extension_id = GetMatchingExtensionId(utterance); if (!extension_id.empty()) { current_utterance_ = utterance; utterance->set_extension_id(extension_id); ListValue args; args.Set(0, Value::CreateStringValue(utterance->text())); DictionaryValue* options = static_cast<DictionaryValue*>( utterance->options()->DeepCopy()); if (options->HasKey(util::kEnqueueKey)) options->Remove(util::kEnqueueKey, NULL); args.Set(1, options); args.Set(2, Value::CreateIntegerValue(utterance->id())); std::string json_args; base::JSONWriter::Write(&args, false, &json_args); utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension( extension_id, events::kOnSpeak, json_args, utterance->profile(), GURL()); return; } GetPlatformImpl()->clear_error(); bool success = GetPlatformImpl()->Speak( utterance->text(), utterance->locale(), utterance->gender(), utterance->rate(), utterance->pitch(), utterance->volume()); if (!success) { utterance->set_error(GetPlatformImpl()->error()); utterance->FinishAndDestroy(); return; } current_utterance_ = utterance; CheckSpeechStatus(); } 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
void ExtensionTtsController::SpeakNow(Utterance* utterance) { } double pitch = 1.0; if (options->HasKey(constants::kPitchKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kPitchKey, &pitch)); if (pitch < 0.0 || pitch > 2.0) { error_ = constants::kErrorInvalidPitch; return false; } }
170,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <[email protected]> Commit-Queue: Victor Costan <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection->GetWeakPtr()), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); }
173,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void SetUp() { old_client_ = content::GetContentClient(); content::SetContentClient(&client_); old_browser_client_ = content::GetContentClient()->browser(); content::GetContentClient()->set_browser(&browser_client_); url_util::AddStandardScheme(kPrivilegedScheme); url_util::AddStandardScheme(chrome::kChromeUIScheme); }
171,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VerifyDailyContentLengthPrefLists( const int64* original_values, size_t original_count, const int64* received_values, size_t received_count, const int64* original_with_data_reduction_proxy_enabled_values, size_t original_with_data_reduction_proxy_enabled_count, const int64* received_with_data_reduction_proxy_enabled_values, size_t received_with_data_reduction_proxy_count, const int64* original_via_data_reduction_proxy_values, size_t original_via_data_reduction_proxy_count, const int64* received_via_data_reduction_proxy_values, size_t received_via_data_reduction_proxy_count) { VerifyPrefList(prefs::kDailyHttpOriginalContentLength, original_values, original_count); VerifyPrefList(prefs::kDailyHttpReceivedContentLength, received_values, received_count); VerifyPrefList( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count); VerifyPrefList( prefs::kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count); VerifyPrefList( prefs::kDailyOriginalContentLengthViaDataReductionProxy, original_via_data_reduction_proxy_values, original_via_data_reduction_proxy_count); VerifyPrefList( prefs::kDailyContentLengthViaDataReductionProxy, received_via_data_reduction_proxy_values, received_via_data_reduction_proxy_count); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void VerifyDailyContentLengthPrefLists( // Verify all daily data saving pref list values. void VerifyDailyDataSavingContentLengthPrefLists( const int64* original_values, size_t original_count, const int64* received_values, size_t received_count, const int64* original_with_data_reduction_proxy_enabled_values, size_t original_with_data_reduction_proxy_enabled_count, const int64* received_with_data_reduction_proxy_enabled_values, size_t received_with_data_reduction_proxy_count, const int64* original_via_data_reduction_proxy_values, size_t original_via_data_reduction_proxy_count, const int64* received_via_data_reduction_proxy_values, size_t received_via_data_reduction_proxy_count) { VerifyPrefList(prefs::kDailyHttpOriginalContentLength, original_values, original_count); VerifyPrefList(prefs::kDailyHttpReceivedContentLength, received_values, received_count); VerifyPrefList( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count); VerifyPrefList( prefs::kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count); VerifyPrefList( prefs::kDailyOriginalContentLengthViaDataReductionProxy, original_via_data_reduction_proxy_values, original_via_data_reduction_proxy_count); VerifyPrefList( prefs::kDailyContentLengthViaDataReductionProxy, received_via_data_reduction_proxy_values, received_via_data_reduction_proxy_count); }
171,330
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void die_codec(vpx_codec_ctx_t *ctx, const char *s) { const char *detail = vpx_codec_error_detail(ctx); printf("%s: %s\n", s, vpx_codec_error(ctx)); if(detail) printf(" %s\n",detail); exit(EXIT_FAILURE); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void die_codec(vpx_codec_ctx_t *ctx, const char *s) {
174,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) { if (!initialized_successfully_) return ""; return chromeos::GetKeyboardOverlayId(input_method_id); } 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
virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) { if (!initialized_successfully_) return ""; return input_method::GetKeyboardOverlayId(input_method_id); }
170,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << entry["mh_command"].toString(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } } Commit Message: CWE ID: CWE-20
ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { // // The action reply // ActionReply reply; // Get the mount executable // const QString mount = findMountExecutable(); // QMapIterator<QString, QVariant> it(args); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); #if defined(Q_OS_LINUX) proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true); #endif QVariantMap entry = it.value().toMap(); // Check the executable // if (mount != entry["mh_command"].toString()) { // Something weird is going on, bail out. reply.setType(ActionReply::HelperErrorType); return reply; } else { // Do nothing } // KProcess proc(this); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << entry["mh_command"].toString(); command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool userKill = false; QStringList command; #if defined(Q_OS_LINUX) command << mount; command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); command << entry["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << mount; command << entry["mh_options"].toStringList(); command << entry["mh_unc"].toString(); command << entry["mh_mountpoint"].toString(); else { } if (HelperSupport::isStopped()) { proc.kill(); userKill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!userKill) { reply.setType(ActionReply::HelperErrorType); reply.setErrorDescription(i18n("The mount process crashed.")); break; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed()); } }
164,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } R_FREE (bb); } Commit Message: Fix #10293 - Use-after-free in r_anal_bb_free() CWE ID: CWE-416
R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } if (bb->next) { // avoid double free bb->next->prev = NULL; } R_FREE (bb); // double free }
169,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Tracks::Tracks( 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_trackEntries(NULL), m_trackEntriesEnd(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
Tracks::Tracks(
174,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame( WebKit::WebFrame* frame, WebKit::WebNode* node, scoped_ptr<PrepareFrameAndViewForPrint>* prepare) { if (!InitPrintSettings(frame, node, false)) return false; DCHECK(!prepare->get()); prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params, frame, node)); UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(), &print_pages_params_->params); Send(new PrintHostMsg_DidGetDocumentCookie( routing_id(), print_pages_params_->params.document_cookie)); return true; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool PrintWebViewHelper::InitPrintSettingsAndPrepareFrame( WebKit::WebFrame* frame, WebKit::WebNode* node, scoped_ptr<PrepareFrameAndViewForPrint>* prepare) { if (!InitPrintSettings(frame)) return false; DCHECK(!prepare->get()); prepare->reset(new PrepareFrameAndViewForPrint(print_pages_params_->params, frame, node)); UpdatePrintableSizeInPrintParameters(frame, node, prepare->get(), &print_pages_params_->params); Send(new PrintHostMsg_DidGetDocumentCookie( routing_id(), print_pages_params_->params.document_cookie)); return true; }
170,260
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdateTargetInfoAvPairs(bool is_mic_enabled, bool is_epa_enabled, const std::string& channel_bindings, const std::string& spn, std::vector<AvPair>* av_pairs, uint64_t* server_timestamp, size_t* target_info_len) { *server_timestamp = UINT64_MAX; *target_info_len = 0; bool need_flags_added = is_mic_enabled; for (AvPair& pair : *av_pairs) { *target_info_len += pair.avlen + kAvPairHeaderLen; switch (pair.avid) { case TargetInfoAvId::kFlags: if (is_mic_enabled) { pair.flags = pair.flags | TargetInfoAvFlags::kMicPresent; } need_flags_added = false; break; case TargetInfoAvId::kTimestamp: *server_timestamp = pair.timestamp; break; case TargetInfoAvId::kEol: case TargetInfoAvId::kChannelBindings: case TargetInfoAvId::kTargetName: NOTREACHED(); break; default: break; } } if (need_flags_added) { DCHECK(is_mic_enabled); AvPair flags_pair(TargetInfoAvId::kFlags, sizeof(uint32_t)); flags_pair.flags = TargetInfoAvFlags::kMicPresent; av_pairs->push_back(flags_pair); *target_info_len += kAvPairHeaderLen + flags_pair.avlen; } if (is_epa_enabled) { std::vector<uint8_t> channel_bindings_hash(kChannelBindingsHashLen, 0); if (!channel_bindings.empty()) { GenerateChannelBindingHashV2(channel_bindings, channel_bindings_hash); } av_pairs->emplace_back(TargetInfoAvId::kChannelBindings, std::move(channel_bindings_hash)); base::string16 spn16 = base::UTF8ToUTF16(spn); NtlmBufferWriter spn_writer(spn16.length() * 2); bool spn_writer_result = spn_writer.WriteUtf16String(spn16) && spn_writer.IsEndOfBuffer(); DCHECK(spn_writer_result); av_pairs->emplace_back(TargetInfoAvId::kTargetName, spn_writer.Pass()); *target_info_len += (2 * kAvPairHeaderLen) + kChannelBindingsHashLen + (spn16.length() * 2); } *target_info_len += kAvPairHeaderLen; } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22
void UpdateTargetInfoAvPairs(bool is_mic_enabled, bool is_epa_enabled, const std::string& channel_bindings, const std::string& spn, std::vector<AvPair>* av_pairs, uint64_t* server_timestamp, size_t* target_info_len) { *server_timestamp = UINT64_MAX; *target_info_len = 0; bool need_flags_added = is_mic_enabled; for (AvPair& pair : *av_pairs) { *target_info_len += pair.avlen + kAvPairHeaderLen; switch (pair.avid) { case TargetInfoAvId::kFlags: if (is_mic_enabled) { pair.flags = pair.flags | TargetInfoAvFlags::kMicPresent; } need_flags_added = false; break; case TargetInfoAvId::kTimestamp: *server_timestamp = pair.timestamp; break; case TargetInfoAvId::kEol: case TargetInfoAvId::kChannelBindings: case TargetInfoAvId::kTargetName: NOTREACHED(); break; default: break; } } if (need_flags_added) { DCHECK(is_mic_enabled); AvPair flags_pair(TargetInfoAvId::kFlags, sizeof(uint32_t)); flags_pair.flags = TargetInfoAvFlags::kMicPresent; av_pairs->push_back(flags_pair); *target_info_len += kAvPairHeaderLen + flags_pair.avlen; } if (is_epa_enabled) { std::vector<uint8_t> channel_bindings_hash(kChannelBindingsHashLen, 0); if (!channel_bindings.empty()) { GenerateChannelBindingHashV2( channel_bindings, base::make_span<kChannelBindingsHashLen>(channel_bindings_hash)); } av_pairs->emplace_back(TargetInfoAvId::kChannelBindings, std::move(channel_bindings_hash)); base::string16 spn16 = base::UTF8ToUTF16(spn); NtlmBufferWriter spn_writer(spn16.length() * 2); bool spn_writer_result = spn_writer.WriteUtf16String(spn16) && spn_writer.IsEndOfBuffer(); DCHECK(spn_writer_result); av_pairs->emplace_back(TargetInfoAvId::kTargetName, spn_writer.Pass()); *target_info_len += (2 * kAvPairHeaderLen) + kChannelBindingsHashLen + (spn16.length() * 2); } *target_info_len += kAvPairHeaderLen; }
172,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_U32 port, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned int nPortIndex; (void) hComp; DEBUG_PRINT_LOW("In for decoder free_buffer"); if (m_state == OMX_StateIdle && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { DEBUG_PRINT_LOW(" free buffer while Component in Loading pending"); } else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)|| (m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) { DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port); } else if ((port == OMX_CORE_INPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) || (port == OMX_CORE_OUTPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) { DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port); } else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) { DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); return OMX_ErrorIncorrectStateOperation; } else if (m_state != OMX_StateInvalid) { DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); } if (port == OMX_CORE_INPUT_PORT_INDEX) { /*Check if arbitrary bytes*/ if (!arbitrary_bytes && !input_use_buffer) nPortIndex = buffer - m_inp_mem_ptr; else nPortIndex = buffer - m_inp_heap_ptr; DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex); if (nPortIndex < drv_ctx.ip_buf.actualcount) { BITMASK_CLEAR(&m_inp_bm_count,nPortIndex); BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex); if (input_use_buffer == true) { DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex); if (m_phdr_pmem_ptr) free_input_buffer(m_phdr_pmem_ptr[nPortIndex]); } else { if (arbitrary_bytes) { if (m_phdr_pmem_ptr) free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]); else free_input_buffer(nPortIndex,NULL); } else free_input_buffer(buffer); } m_inp_bPopulated = OMX_FALSE; if(release_input_done()) release_buffers(this, VDEC_BUFFER_TYPE_INPUT); /*Free the Buffer Header*/ if (release_input_done()) { DEBUG_PRINT_HIGH("ALL input buffers are freed/released"); free_input_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING) && release_input_done()) { DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING); post_event(OMX_CommandPortDisable, OMX_CORE_INPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else if (port == OMX_CORE_OUTPUT_PORT_INDEX) { nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (nPortIndex < drv_ctx.op_buf.actualcount) { DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex); BITMASK_CLEAR(&m_out_bm_count,nPortIndex); m_out_bPopulated = OMX_FALSE; client_buffers.free_output_buffer (buffer); if(release_output_done()) { release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT); } if (release_output_done()) { free_output_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING) && release_output_done()) { DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it"); DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING); #ifdef _ANDROID_ICS_ if (m_enable_android_native_buffers) { DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers"); memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); } #endif post_event(OMX_CommandPortDisable, OMX_CORE_OUTPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else { eRet = OMX_ErrorBadPortIndex; } if ((eRet == OMX_ErrorNone) && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { if (release_done()) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING); post_event(OMX_CommandStateSet, OMX_StateLoaded, OMX_COMPONENT_GENERATE_EVENT); } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Do not allow changing theactual buffer count while still holding allocation (Client can technically negotiate buffer count on a free/disabled port) Add safety checks to free only as many buffers were allocated. Fixes: Security Vulnerability - Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVdec problem #3) Bug: 27532282 27661749 Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523 CWE ID: CWE-119
OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_U32 port, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned int nPortIndex; (void) hComp; DEBUG_PRINT_LOW("In for decoder free_buffer"); if (m_state == OMX_StateIdle && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { DEBUG_PRINT_LOW(" free buffer while Component in Loading pending"); } else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)|| (m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) { DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port); } else if ((port == OMX_CORE_INPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) || (port == OMX_CORE_OUTPUT_PORT_INDEX && BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) { DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port); } else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) { DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); return OMX_ErrorIncorrectStateOperation; } else if (m_state != OMX_StateInvalid) { DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers"); post_event(OMX_EventError, OMX_ErrorPortUnpopulated, OMX_COMPONENT_GENERATE_EVENT); } if (port == OMX_CORE_INPUT_PORT_INDEX) { /*Check if arbitrary bytes*/ if (!arbitrary_bytes && !input_use_buffer) nPortIndex = buffer - m_inp_mem_ptr; else nPortIndex = buffer - m_inp_heap_ptr; DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex); if (nPortIndex < drv_ctx.ip_buf.actualcount && BITMASK_PRESENT(&m_inp_bm_count, nPortIndex)) { BITMASK_CLEAR(&m_inp_bm_count,nPortIndex); BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex); if (input_use_buffer == true) { DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex); if (m_phdr_pmem_ptr) free_input_buffer(m_phdr_pmem_ptr[nPortIndex]); } else { if (arbitrary_bytes) { if (m_phdr_pmem_ptr) free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]); else free_input_buffer(nPortIndex,NULL); } else free_input_buffer(buffer); } m_inp_bPopulated = OMX_FALSE; if(release_input_done()) release_buffers(this, VDEC_BUFFER_TYPE_INPUT); /*Free the Buffer Header*/ if (release_input_done()) { DEBUG_PRINT_HIGH("ALL input buffers are freed/released"); free_input_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING) && release_input_done()) { DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING); post_event(OMX_CommandPortDisable, OMX_CORE_INPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else if (port == OMX_CORE_OUTPUT_PORT_INDEX) { nPortIndex = buffer - client_buffers.get_il_buf_hdr(); if (nPortIndex < drv_ctx.op_buf.actualcount && BITMASK_PRESENT(&m_out_bm_count, nPortIndex)) { DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex); BITMASK_CLEAR(&m_out_bm_count,nPortIndex); m_out_bPopulated = OMX_FALSE; client_buffers.free_output_buffer (buffer); if(release_output_done()) { release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT); } if (release_output_done()) { free_output_buffer_header(); } } else { DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid"); eRet = OMX_ErrorBadPortIndex; } if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING) && release_output_done()) { DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it"); DEBUG_PRINT_LOW("MOVING TO DISABLED STATE"); BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING); #ifdef _ANDROID_ICS_ if (m_enable_android_native_buffers) { DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers"); memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); } #endif post_event(OMX_CommandPortDisable, OMX_CORE_OUTPUT_PORT_INDEX, OMX_COMPONENT_GENERATE_EVENT); } } else { eRet = OMX_ErrorBadPortIndex; } if ((eRet == OMX_ErrorNone) && (BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) { if (release_done()) { BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING); post_event(OMX_CommandStateSet, OMX_StateLoaded, OMX_COMPONENT_GENERATE_EVENT); } } return eRet; }
173,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; * Begin Time Functions * ***********************/ static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; int n; int i; char buf[18]; if (strchr (text, '-')) { char *p = (char *) text, *p2 = buf; } if (*p != '-') { *p2 = *p; p2++; } p++; } } Commit Message: CWE ID: CWE-119
static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; * Begin Time Functions * ***********************/ static time_t mkgmtime(struct tm *tm) { static const int mdays[12] = {0,31,59,90,120,151,181,212,243,273,304,334}; return ((((((tm->tm_year - 70) * 365) + mdays[tm->tm_mon] + tm->tm_mday-1 + (tm->tm_year-68-1+(tm->tm_mon>=2))/4) * 24) + tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec; } static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; int n; int i; char buf[30]; if (strchr (text, '-')) { char *p = (char *) text, *p2 = buf; } if (*p != '-') { *p2 = *p; p2++; if (p2-buf >= sizeof(buf)) { return -1; } } p++; } }
164,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_factory_(this) { RouteFunction("StartSession", base::Bind(&DisplaySourceCustomBindings::StartSession, weak_factory_.GetWeakPtr())); RouteFunction("TerminateSession", base::Bind(&DisplaySourceCustomBindings::TerminateSession, weak_factory_.GetWeakPtr())); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
DisplaySourceCustomBindings::DisplaySourceCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_factory_(this) { RouteFunction("StartSession", "displaySource", base::Bind(&DisplaySourceCustomBindings::StartSession, weak_factory_.GetWeakPtr())); RouteFunction("TerminateSession", "displaySource", base::Bind(&DisplaySourceCustomBindings::TerminateSession, weak_factory_.GetWeakPtr())); }
172,248
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GpuChannelHost::GpuChannelHost( GpuChannelHostFactory* factory, int gpu_process_id, int client_id) : factory_(factory), gpu_process_id_(gpu_process_id), client_id_(client_id), state_(kUnconnected) { } 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:
GpuChannelHost::GpuChannelHost( GpuChannelHostFactory* factory, int gpu_host_id, int client_id) : factory_(factory), client_id_(client_id), gpu_host_id_(gpu_host_id), state_(kUnconnected) { }
170,929
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringCase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringCase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringCase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringCase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringASCIICase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringASCIICase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringASCIICase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringASCIICase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; }
171,931
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void unset_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { vpx_active_map_t map = {0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = NULL; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); } 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
static void unset_active_map(const vpx_codec_enc_cfg_t *cfg, vpx_codec_ctx_t *codec) { vpx_active_map_t map = {0, 0, 0}; map.rows = (cfg->g_h + 15) / 16; map.cols = (cfg->g_w + 15) / 16; map.active_map = NULL; if (vpx_codec_control(codec, VP8E_SET_ACTIVEMAP, &map)) die_codec(codec, "Failed to set active map"); }
174,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error) { *ret = x +1; return TRUE; } Commit Message: CWE ID: CWE-264
my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error)
165,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SessionService::CreateTabsAndWindows( const std::vector<SessionCommand*>& data, std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { for (std::vector<SessionCommand*>::const_iterator i = data.begin(); i != data.end(); ++i) { const SessionCommand::id_type kCommandSetWindowBounds2 = 10; const SessionCommand* command = *i; switch (command->id()) { case kCommandSetTabWindow: { SessionID::id_type payload[2]; if (!command->GetPayload(payload, sizeof(payload))) return true; GetTab(payload[1], tabs)->window_id.set_id(payload[0]); break; } case kCommandSetWindowBounds2: { WindowBoundsPayload2 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); GetWindow(payload.window_id, windows)->show_state = payload.is_maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL; break; } case kCommandSetWindowBounds3: { WindowBoundsPayload3 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (payload.show_state > ui::SHOW_STATE_DEFAULT && payload.show_state < ui::SHOW_STATE_END && payload.show_state != ui::SHOW_STATE_INACTIVE) { show_state = static_cast<ui::WindowShowState>(payload.show_state); } else { NOTREACHED(); } GetWindow(payload.window_id, windows)->show_state = show_state; break; } case kCommandSetTabIndexInWindow: { TabIndexInWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->tab_visual_index = payload.index; break; } case kCommandTabClosed: case kCommandWindowClosed: { ClosedPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; if (command->id() == kCommandTabClosed) { delete GetTab(payload.id, tabs); tabs->erase(payload.id); } else { delete GetWindow(payload.id, windows); windows->erase(payload.id); } break; } case kCommandTabNavigationPathPrunedFromBack: { TabNavigationPathPrunedFromBackPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; SessionTab* tab = GetTab(payload.id, tabs); tab->navigations.erase( FindClosestNavigationWithIndex(&(tab->navigations), payload.index), tab->navigations.end()); break; } case kCommandTabNavigationPathPrunedFromFront: { TabNavigationPathPrunedFromFrontPayload payload; if (!command->GetPayload(&payload, sizeof(payload)) || payload.index <= 0) { return true; } SessionTab* tab = GetTab(payload.id, tabs); tab->current_navigation_index = std::max(-1, tab->current_navigation_index - payload.index); for (std::vector<TabNavigation>::iterator i = tab->navigations.begin(); i != tab->navigations.end();) { i->set_index(i->index() - payload.index); if (i->index() < 0) i = tab->navigations.erase(i); else ++i; } break; } case kCommandUpdateTabNavigation: { TabNavigation navigation; SessionID::id_type tab_id; if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id)) return true; SessionTab* tab = GetTab(tab_id, tabs); std::vector<TabNavigation>::iterator i = FindClosestNavigationWithIndex(&(tab->navigations), navigation.index()); if (i != tab->navigations.end() && i->index() == navigation.index()) *i = navigation; else tab->navigations.insert(i, navigation); break; } case kCommandSetSelectedNavigationIndex: { SelectedNavigationIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->current_navigation_index = payload.index; break; } case kCommandSetSelectedTabInIndex: { SelectedTabInIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->selected_tab_index = payload.index; break; } case kCommandSetWindowType: { WindowTypePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->is_constrained = false; GetWindow(payload.id, windows)->type = BrowserTypeForWindowType( static_cast<WindowType>(payload.index)); break; } case kCommandSetPinnedState: { PinnedStatePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state; break; } case kCommandSetExtensionAppID: { SessionID::id_type tab_id; std::string extension_app_id; if (!RestoreSetTabExtensionAppIDCommand( *command, &tab_id, &extension_app_id)) { return true; } GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id); break; } default: return true; } } return true; } Commit Message: Metrics for measuring how much overhead reading compressed content states adds. BUG=104293 TEST=NONE Review URL: https://chromiumcodereview.appspot.com/9426039 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool SessionService::CreateTabsAndWindows( const std::vector<SessionCommand*>& data, std::map<int, SessionTab*>* tabs, std::map<int, SessionWindow*>* windows) { ResetContentStateReadingMetrics(); for (std::vector<SessionCommand*>::const_iterator i = data.begin(); i != data.end(); ++i) { const SessionCommand::id_type kCommandSetWindowBounds2 = 10; const SessionCommand* command = *i; switch (command->id()) { case kCommandSetTabWindow: { SessionID::id_type payload[2]; if (!command->GetPayload(payload, sizeof(payload))) return true; GetTab(payload[1], tabs)->window_id.set_id(payload[0]); break; } case kCommandSetWindowBounds2: { WindowBoundsPayload2 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); GetWindow(payload.window_id, windows)->show_state = payload.is_maximized ? ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL; break; } case kCommandSetWindowBounds3: { WindowBoundsPayload3 payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x, payload.y, payload.w, payload.h); ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; if (payload.show_state > ui::SHOW_STATE_DEFAULT && payload.show_state < ui::SHOW_STATE_END && payload.show_state != ui::SHOW_STATE_INACTIVE) { show_state = static_cast<ui::WindowShowState>(payload.show_state); } else { NOTREACHED(); } GetWindow(payload.window_id, windows)->show_state = show_state; break; } case kCommandSetTabIndexInWindow: { TabIndexInWindowPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->tab_visual_index = payload.index; break; } case kCommandTabClosed: case kCommandWindowClosed: { ClosedPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; if (command->id() == kCommandTabClosed) { delete GetTab(payload.id, tabs); tabs->erase(payload.id); } else { delete GetWindow(payload.id, windows); windows->erase(payload.id); } break; } case kCommandTabNavigationPathPrunedFromBack: { TabNavigationPathPrunedFromBackPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; SessionTab* tab = GetTab(payload.id, tabs); tab->navigations.erase( FindClosestNavigationWithIndex(&(tab->navigations), payload.index), tab->navigations.end()); break; } case kCommandTabNavigationPathPrunedFromFront: { TabNavigationPathPrunedFromFrontPayload payload; if (!command->GetPayload(&payload, sizeof(payload)) || payload.index <= 0) { return true; } SessionTab* tab = GetTab(payload.id, tabs); tab->current_navigation_index = std::max(-1, tab->current_navigation_index - payload.index); for (std::vector<TabNavigation>::iterator i = tab->navigations.begin(); i != tab->navigations.end();) { i->set_index(i->index() - payload.index); if (i->index() < 0) i = tab->navigations.erase(i); else ++i; } break; } case kCommandUpdateTabNavigation: { TabNavigation navigation; SessionID::id_type tab_id; if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id)) return true; SessionTab* tab = GetTab(tab_id, tabs); std::vector<TabNavigation>::iterator i = FindClosestNavigationWithIndex(&(tab->navigations), navigation.index()); if (i != tab->navigations.end() && i->index() == navigation.index()) *i = navigation; else tab->navigations.insert(i, navigation); break; } case kCommandSetSelectedNavigationIndex: { SelectedNavigationIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.id, tabs)->current_navigation_index = payload.index; break; } case kCommandSetSelectedTabInIndex: { SelectedTabInIndexPayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->selected_tab_index = payload.index; break; } case kCommandSetWindowType: { WindowTypePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetWindow(payload.id, windows)->is_constrained = false; GetWindow(payload.id, windows)->type = BrowserTypeForWindowType( static_cast<WindowType>(payload.index)); break; } case kCommandSetPinnedState: { PinnedStatePayload payload; if (!command->GetPayload(&payload, sizeof(payload))) return true; GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state; break; } case kCommandSetExtensionAppID: { SessionID::id_type tab_id; std::string extension_app_id; if (!RestoreSetTabExtensionAppIDCommand( *command, &tab_id, &extension_app_id)) { return true; } GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id); break; } default: return true; } } WriteContentStateReadingMetrics(); return true; }
171,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++ << 8); *quantum|=(unsigned short) (*p++ << 0); return(p); }static inline void WriteResourceLong(unsigned char *p, Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p);
169,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote( base::PlatformFile handle, const IPC::SyncChannel& channel, bool should_close_source) { return content::BrokerGetFileHandleForProcess(handle, channel.peer_pid(), should_close_source); } 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
IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote(
170,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; ctxt->_eip = ctxt->src.val; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ ctxt->_eip = ctxt->src.val; break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; rc = assign_eip_near(ctxt, ctxt->src.val); if (rc != X86EMUL_CONTINUE) break; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ rc = assign_eip_near(ctxt, ctxt->src.val); break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; }
169,910
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); } 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:
PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", "pageCapture", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", "pageCapture", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); }
173,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } Commit Message: CWE ID: CWE-20
PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); }
165,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; } Commit Message: CWE ID: CWE-22
user_change_icon_file_authorized_cb (Daemon *daemon, User *user, GDBusMethodInvocation *context, gpointer data) { g_autofree gchar *filename = NULL; g_autoptr(GFile) file = NULL; g_autoptr(GFileInfo) info = NULL; guint32 mode; GFileType type; guint64 size; filename = g_strdup (data); if (filename == NULL || *filename == '\0') { g_autofree gchar *dest_path = NULL; g_autoptr(GFile) dest = NULL; g_autoptr(GError) error = NULL; g_clear_pointer (&filename, g_free); dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL); dest = g_file_new_for_path (dest_path); if (!g_file_delete (dest, NULL, &error) && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) { throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message); return; } goto icon_saved; } file = g_file_new_for_path (filename); g_clear_pointer (&filename, g_free); /* Canonicalize path so we can call g_str_has_prefix on it * below without concern for ../ path components moving outside * the prefix */ filename = g_file_get_path (file); info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "," G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, return; }
164,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); { printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; goto err0; } globalParams = new GlobalParams(); ok = extractPages (argv[1], argv[2]); if (ok) { exitCode = 0; } delete globalParams; err0: return exitCode; } Commit Message: CWE ID: CWE-20
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%d' if more than one page should be extracted", destFileName); return false; } // destFileName can have multiple %% and one %d // We use auxDestFileName to replace all the valid % appearances // by 'A' (random char that is not %), if at the end of replacing // any of the valid appearances there is still any % around, the // pattern is wrong char *auxDestFileName = strdup(destFileName); // %% can appear as many times as you want char *p = strstr(auxDestFileName, "%%"); while (p != NULL) { *p = 'A'; *(p + 1) = 'A'; p = strstr(p, "%%"); } // %d can appear only one time p = strstr(auxDestFileName, "%d"); if (p != NULL) { *p = 'A'; } // at this point any other % is wrong p = strstr(auxDestFileName, "%"); if (p != NULL) { error(errSyntaxError, -1, "'{0:s}' can only contain one '%d' pattern", destFileName); free(auxDestFileName); return false; } free(auxDestFileName); for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); { printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; goto err0; } globalParams = new GlobalParams(); ok = extractPages (argv[1], argv[2]); if (ok) { exitCode = 0; } delete globalParams; err0: return exitCode; }
164,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(int argc, const char **argv) { const char * prog = *argv; const char * outfile = NULL; const char * suffix = NULL; const char * prefix = NULL; int done = 0; /* if at least one file is processed */ struct global global; global_init(&global); while (--argc > 0) { ++argv; if (strcmp(*argv, "--debug") == 0) { /* To help debugging problems: */ global.errors = global.warnings = 1; global.quiet = 0; global.verbose = 7; } else if (strncmp(*argv, "--max=", 6) == 0) { global.idat_max = (png_uint_32)atol(6+*argv); if (global.skip < SKIP_UNSAFE) global.skip = SKIP_UNSAFE; } else if (strcmp(*argv, "--max") == 0) { global.idat_max = 0x7fffffff; if (global.skip < SKIP_UNSAFE) global.skip = SKIP_UNSAFE; } else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0) global.optimize_zlib = 1; else if (strncmp(*argv, "--out=", 6) == 0) outfile = 6+*argv; else if (strncmp(*argv, "--suffix=", 9) == 0) suffix = 9+*argv; else if (strncmp(*argv, "--prefix=", 9) == 0) prefix = 9+*argv; else if (strcmp(*argv, "--strip=none") == 0) global.skip = SKIP_NONE; else if (strcmp(*argv, "--strip=crc") == 0) global.skip = SKIP_BAD_CRC; else if (strcmp(*argv, "--strip=unsafe") == 0) global.skip = SKIP_UNSAFE; else if (strcmp(*argv, "--strip=unused") == 0) global.skip = SKIP_UNUSED; else if (strcmp(*argv, "--strip=transform") == 0) global.skip = SKIP_TRANSFORM; else if (strcmp(*argv, "--strip=color") == 0) global.skip = SKIP_COLOR; else if (strcmp(*argv, "--strip=all") == 0) global.skip = SKIP_ALL; else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0) global.errors = 1; else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0) global.warnings = 1; else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0) { if (global.quiet) global.quiet = 2; else global.quiet = 1; } else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0) ++global.verbose; #if 0 /* NYI */ # ifdef PNG_MAXIMUM_INFLATE_WINDOW else if (strcmp(*argv, "--test") == 0) ++set_option; # endif #endif else if ((*argv)[0] == '-') usage(prog); else { size_t outlen = strlen(*argv); char temp_name[FILENAME_MAX+1]; if (outfile == NULL) /* else this takes precedence */ { /* Consider the prefix/suffix options */ if (prefix != NULL) { size_t prefixlen = strlen(prefix); if (prefixlen+outlen > FILENAME_MAX) { fprintf(stderr, "%s: output file name too long: %s%s%s\n", prog, prefix, *argv, suffix ? suffix : ""); global.status_code |= WRITE_ERROR; continue; } memcpy(temp_name, prefix, prefixlen); memcpy(temp_name+prefixlen, *argv, outlen); outlen += prefixlen; outfile = temp_name; } else if (suffix != NULL) memcpy(temp_name, *argv, outlen); temp_name[outlen] = 0; if (suffix != NULL) { size_t suffixlen = strlen(suffix); if (outlen+suffixlen > FILENAME_MAX) { fprintf(stderr, "%s: output file name too long: %s%s\n", prog, *argv, suffix); global.status_code |= WRITE_ERROR; continue; } memcpy(temp_name+outlen, suffix, suffixlen); outlen += suffixlen; temp_name[outlen] = 0; outfile = temp_name; } } (void)one_file(&global, *argv, outfile); ++done; outfile = NULL; } } if (!done) usage(prog); return global_end(&global); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(int argc, const char **argv) { char temp_name[FILENAME_MAX+1]; const char * prog = *argv; const char * outfile = NULL; const char * suffix = NULL; const char * prefix = NULL; int done = 0; /* if at least one file is processed */ struct global global; global_init(&global); while (--argc > 0) { ++argv; if (strcmp(*argv, "--debug") == 0) { /* To help debugging problems: */ global.errors = global.warnings = 1; global.quiet = 0; global.verbose = 7; } else if (strncmp(*argv, "--max=", 6) == 0) { global.idat_max = (png_uint_32)atol(6+*argv); if (global.skip < SKIP_UNSAFE) global.skip = SKIP_UNSAFE; } else if (strcmp(*argv, "--max") == 0) { global.idat_max = 0x7fffffff; if (global.skip < SKIP_UNSAFE) global.skip = SKIP_UNSAFE; } else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0) global.optimize_zlib = 1; else if (strncmp(*argv, "--out=", 6) == 0) outfile = 6+*argv; else if (strncmp(*argv, "--suffix=", 9) == 0) suffix = 9+*argv; else if (strncmp(*argv, "--prefix=", 9) == 0) prefix = 9+*argv; else if (strcmp(*argv, "--strip=none") == 0) global.skip = SKIP_NONE; else if (strcmp(*argv, "--strip=crc") == 0) global.skip = SKIP_BAD_CRC; else if (strcmp(*argv, "--strip=unsafe") == 0) global.skip = SKIP_UNSAFE; else if (strcmp(*argv, "--strip=unused") == 0) global.skip = SKIP_UNUSED; else if (strcmp(*argv, "--strip=transform") == 0) global.skip = SKIP_TRANSFORM; else if (strcmp(*argv, "--strip=color") == 0) global.skip = SKIP_COLOR; else if (strcmp(*argv, "--strip=all") == 0) global.skip = SKIP_ALL; else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0) global.errors = 1; else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0) global.warnings = 1; else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0) { if (global.quiet) global.quiet = 2; else global.quiet = 1; } else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0) ++global.verbose; #if 0 /* NYI */ # ifdef PNG_MAXIMUM_INFLATE_WINDOW else if (strcmp(*argv, "--test") == 0) ++set_option; # endif #endif else if ((*argv)[0] == '-') usage(prog); else { size_t outlen = strlen(*argv); if (outfile == NULL) /* else this takes precedence */ { /* Consider the prefix/suffix options */ if (prefix != NULL) { size_t prefixlen = strlen(prefix); if (prefixlen+outlen > FILENAME_MAX) { fprintf(stderr, "%s: output file name too long: %s%s%s\n", prog, prefix, *argv, suffix ? suffix : ""); global.status_code |= WRITE_ERROR; continue; } memcpy(temp_name, prefix, prefixlen); memcpy(temp_name+prefixlen, *argv, outlen); outlen += prefixlen; outfile = temp_name; } else if (suffix != NULL) memcpy(temp_name, *argv, outlen); temp_name[outlen] = 0; if (suffix != NULL) { size_t suffixlen = strlen(suffix); if (outlen+suffixlen > FILENAME_MAX) { fprintf(stderr, "%s: output file name too long: %s%s\n", prog, *argv, suffix); global.status_code |= WRITE_ERROR; continue; } memcpy(temp_name+outlen, suffix, suffixlen); outlen += suffixlen; temp_name[outlen] = 0; outfile = temp_name; } } (void)one_file(&global, *argv, outfile); ++done; outfile = NULL; } } if (!done) usage(prog); return global_end(&global); }
173,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void install_local_socket(asocket* s) { adb_mutex_lock(&socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { local_socket_next_id = 1; } insert_local_socket(s, &local_socket_list); adb_mutex_unlock(&socket_list_lock); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
void install_local_socket(asocket* s) { std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { fatal("local socket id overflow"); } insert_local_socket(s, &local_socket_list); }
174,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool OutOfProcessInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this); std::string document_url = document_url_var.is_string() ? document_url_var.AsString() : std::string(); std::string extension_url = std::string(kChromeExtension); bool in_extension = !document_url.compare(0, extension_url.size(), extension_url); if (in_extension) { for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "full-frame") == 0) { full_ = true; break; } } } if (full_) SetPluginToHandleFindRequests(); pp::VarDictionary translated_strings; translated_strings.Set(kType, kJSSetTranslatedStringsType); translated_strings.Set(kJSGetPasswordString, GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD)); translated_strings.Set(kJSLoadingString, GetLocalizedString(PP_RESOURCESTRING_PDFLOADING)); translated_strings.Set(kJSLoadFailedString, GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED)); PostMessage(translated_strings); text_input_.reset(new pp::TextInput_Dev(this)); const char* stream_url = nullptr; const char* original_url = nullptr; const char* headers = nullptr; bool is_material = false; for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "src") == 0) original_url = argv[i]; else if (strcmp(argn[i], "stream-url") == 0) stream_url = argv[i]; else if (strcmp(argn[i], "headers") == 0) headers = argv[i]; else if (strcmp(argn[i], "is-material") == 0) is_material = true; else if (strcmp(argn[i], "top-toolbar-height") == 0) base::StringToInt(argv[i], &top_toolbar_height_); } if (is_material) background_color_ = kBackgroundColorMaterial; else background_color_ = kBackgroundColor; if (!original_url) return false; if (!stream_url) stream_url = original_url; if (IsPrintPreviewUrl(original_url)) return true; LoadUrl(stream_url); url_ = original_url; return engine_->New(original_url, headers); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20
bool OutOfProcessInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { // the plugin to be loaded in the extension and print preview to avoid // exposing sensitive APIs directly to external websites. pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this); if (!document_url_var.is_string()) return false; std::string document_url = document_url_var.AsString(); std::string extension_url = std::string(kChromeExtension); std::string print_preview_url = std::string(kChromePrint); if (!base::StringPiece(document_url).starts_with(kChromeExtension) && !base::StringPiece(document_url).starts_with(kChromePrint)) { return false; } // Check if the plugin is full frame. This is passed in from JS. for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "full-frame") == 0) { full_ = true; break; } } if (full_) SetPluginToHandleFindRequests(); pp::VarDictionary translated_strings; translated_strings.Set(kType, kJSSetTranslatedStringsType); translated_strings.Set(kJSGetPasswordString, GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD)); translated_strings.Set(kJSLoadingString, GetLocalizedString(PP_RESOURCESTRING_PDFLOADING)); translated_strings.Set(kJSLoadFailedString, GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED)); PostMessage(translated_strings); text_input_.reset(new pp::TextInput_Dev(this)); const char* stream_url = nullptr; const char* original_url = nullptr; const char* headers = nullptr; bool is_material = false; for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "src") == 0) original_url = argv[i]; else if (strcmp(argn[i], "stream-url") == 0) stream_url = argv[i]; else if (strcmp(argn[i], "headers") == 0) headers = argv[i]; else if (strcmp(argn[i], "is-material") == 0) is_material = true; else if (strcmp(argn[i], "top-toolbar-height") == 0) base::StringToInt(argv[i], &top_toolbar_height_); } if (is_material) background_color_ = kBackgroundColorMaterial; else background_color_ = kBackgroundColor; if (!original_url) return false; if (!stream_url) stream_url = original_url; if (IsPrintPreviewUrl(original_url)) return true; LoadUrl(stream_url); url_ = original_url; return engine_->New(original_url, headers); }
172,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WriteFromUrlOperation::Download(const base::Closure& continuation) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { return; } download_continuation_ = continuation; SetStage(image_writer_api::STAGE_DOWNLOAD); url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); url_fetcher_->Start(); } Commit Message: Network traffic annotation added to extensions::image_writer::WriteFromUrlOperation. Network traffic annotation is added to network request of extensions::image_writer::WriteFromUrlOperation. BUG=656607 Review-Url: https://codereview.chromium.org/2691963002 Cr-Commit-Position: refs/heads/master@{#451456} CWE ID:
void WriteFromUrlOperation::Download(const base::Closure& continuation) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { return; } download_continuation_ = continuation; SetStage(image_writer_api::STAGE_DOWNLOAD); // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("cros_recovery_image_download", R"( semantics { sender: "Chrome OS Recovery Utility" description: "The Google Chrome OS recovery utility downloads the recovery " "image from Google Download Server." trigger: "User uses the Chrome OS Recovery Utility app/extension, selects " "a Chrome OS recovery image, and clicks the Create button to write " "the image to a USB or SD card." data: "URL of the image file to be downloaded. No other data or user " "identifier is sent." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: true cookies_store: "user" setting: "This feature cannot be disabled by settings, it can only be used " "by whitelisted apps/extension." policy_exception_justification: "Not implemented, considered not useful." })"); url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this, traffic_annotation); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); url_fetcher_->Start(); }
171,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void BooleanOrNullAttributeAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); TestObject* impl = V8TestObject::ToImpl(holder); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute"); bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state); if (exception_state.HadException()) return; bool is_null = IsUndefinedOrNull(v8_value); impl->setBooleanOrNullAttribute(cpp_value, is_null); } 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:
static void BooleanOrNullAttributeAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); TestObject* impl = V8TestObject::ToImpl(holder); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "booleanOrNullAttribute"); bool is_null = IsUndefinedOrNull(v8_value); bool cpp_value = is_null ? bool() : NativeValueTraits<IDLBoolean>::NativeValue(info.GetIsolate(), v8_value, exception_state); if (exception_state.HadException()) return; impl->setBooleanOrNullAttribute(cpp_value, is_null); }
172,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( const gpu::Mailbox& mailbox, const gpu::SyncToken& sync_token, unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, IntSize mailbox_size) : paint_image_content_id_(cc::PaintImage::GetNextContentId()) { texture_holder_ = std::make_unique<MailboxTextureHolder>( mailbox, sync_token, texture_id, std::move(context_provider_wrapper), mailbox_size); thread_checker_.DetachFromThread(); } 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
AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage( const gpu::Mailbox& mailbox, const gpu::SyncToken& sync_token, unsigned texture_id, base::WeakPtr<WebGraphicsContext3DProviderWrapper>&& context_provider_wrapper, IntSize mailbox_size) : paint_image_content_id_(cc::PaintImage::GetNextContentId()) { texture_holder_ = std::make_unique<MailboxTextureHolder>( mailbox, sync_token, texture_id, std::move(context_provider_wrapper), mailbox_size); }
172,589
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection( const IPC::Message& msg, int listen_socket_id, net::IPEndPoint remote_address, int connected_socket_id) { P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id); if (!socket) { LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection " "for invalid socket_id."; return; } P2PSocketHost* accepted_connection = socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id); if (accepted_connection) { sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>( ExtendedSocketId(msg.routing_id(), connected_socket_id), accepted_connection)); } } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection( const IPC::Message& msg, int listen_socket_id, const net::IPEndPoint& remote_address, int connected_socket_id) { P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id); if (!socket) { LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection " "for invalid socket_id."; return; } P2PSocketHost* accepted_connection = socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id); if (accepted_connection) { sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>( ExtendedSocketId(msg.routing_id(), connected_socket_id), accepted_connection)); } }
170,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { efree(source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; } Commit Message: CWE ID: CWE-416
void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); zend_shared_alloc_register_xlat_entry(source, retval); if (free_source) { efree(source); } return retval; }
164,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t height, length, width; 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); } /* Read AAI Dune image. */ width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Convert AAI raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); if (*p == 254) *p=255; SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* 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 ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadAAIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; size_t height, length, width; 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); } /* Read AAI Dune image. */ width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((width == 0UL) || (height == 0UL)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Convert AAI raster image to pixel packets. */ image->columns=width; image->rows=height; image->depth=8; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } pixels=(unsigned char *) AcquireQuantumMemory(image->columns, 4*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) 4*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); if (*p == 254) *p=255; SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (q->opacity != OpaqueOpacity) image->matte=MagickTrue; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobLSBLong(image); height=ReadBlobLSBLong(image); if ((width != 0UL) && (height != 0UL)) { /* 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 ((width != 0UL) && (height != 0UL)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int netbk_count_requests(struct xenvif *vif, struct xen_netif_tx_request *first, struct xen_netif_tx_request *txp, int work_to_do) { RING_IDX cons = vif->tx.req_cons; int frags = 0; if (!(first->flags & XEN_NETTXF_more_data)) return 0; do { if (frags >= work_to_do) { netdev_dbg(vif->dev, "Need more frags\n"); return -frags; } if (unlikely(frags >= MAX_SKB_FRAGS)) { netdev_dbg(vif->dev, "Too many frags\n"); return -frags; } memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + frags), sizeof(*txp)); if (txp->size > first->size) { netdev_dbg(vif->dev, "Frags galore\n"); return -frags; } first->size -= txp->size; frags++; if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) { netdev_dbg(vif->dev, "txp->offset: %x, size: %u\n", txp->offset, txp->size); return -frags; } } while ((txp++)->flags & XEN_NETTXF_more_data); return frags; } Commit Message: xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int netbk_count_requests(struct xenvif *vif, struct xen_netif_tx_request *first, struct xen_netif_tx_request *txp, int work_to_do) { RING_IDX cons = vif->tx.req_cons; int frags = 0; if (!(first->flags & XEN_NETTXF_more_data)) return 0; do { if (frags >= work_to_do) { netdev_err(vif->dev, "Need more frags\n"); netbk_fatal_tx_err(vif); return -frags; } if (unlikely(frags >= MAX_SKB_FRAGS)) { netdev_err(vif->dev, "Too many frags\n"); netbk_fatal_tx_err(vif); return -frags; } memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + frags), sizeof(*txp)); if (txp->size > first->size) { netdev_err(vif->dev, "Frag is bigger than frame.\n"); netbk_fatal_tx_err(vif); return -frags; } first->size -= txp->size; frags++; if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) { netdev_err(vif->dev, "txp->offset: %x, size: %u\n", txp->offset, txp->size); netbk_fatal_tx_err(vif); return -frags; } } while ((txp++)->flags & XEN_NETTXF_more_data); return frags; }
166,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int su3000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); d->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info("Attached DS3000/TS2020!"); return 0; } info("Failed to attach DS3000/TS2020!"); return -EIO; } 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
static int su3000_frontend_attach(struct dvb_usb_adapter *d) static int su3000_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0xe; state->data[1] = 0x80; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x02; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 0; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0xe; state->data[1] = 0x83; state->data[2] = 1; if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) err("command 0x0e transfer failed."); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err("command 0x51 transfer failed."); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, &d->i2c_adap); if (adap->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, &dw2104_ts2020_config, &d->i2c_adap)) { info("Attached DS3000/TS2020!"); return 0; } info("Failed to attach DS3000/TS2020!"); return -EIO; }
168,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size > 512) return 0; net::ProxyBypassRules rules; std::string input(data, data + size); rules.ParseFromString(input); rules.ParseFromStringUsingSuffixMatching(input); return 0; } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size > 512) return 0; net::ProxyBypassRules rules; std::string input(data, data + size); const net::ProxyBypassRules::ParseFormat kFormats[] = { net::ProxyBypassRules::ParseFormat::kDefault, net::ProxyBypassRules::ParseFormat::kHostnameSuffixMatching, }; for (auto format : kFormats) rules.ParseFromString(input, format); return 0; }
172,645
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot)); ASSERT(isolatedInline); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } }
171,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderFrameHostManager::RenderFrameHostManager( FrameTreeNode* frame_tree_node, RenderFrameHostDelegate* render_frame_delegate, RenderWidgetHostDelegate* render_widget_delegate, Delegate* delegate) : frame_tree_node_(frame_tree_node), delegate_(delegate), render_frame_delegate_(render_frame_delegate), render_widget_delegate_(render_widget_delegate), interstitial_page_(nullptr), weak_factory_(this) { DCHECK(frame_tree_node_); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
RenderFrameHostManager::RenderFrameHostManager( FrameTreeNode* frame_tree_node, RenderFrameHostDelegate* render_frame_delegate, RenderWidgetHostDelegate* render_widget_delegate, Delegate* delegate) : frame_tree_node_(frame_tree_node), delegate_(delegate), render_frame_delegate_(render_frame_delegate), render_widget_delegate_(render_widget_delegate), weak_factory_(this) { DCHECK(frame_tree_node_); }
172,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(up, &kts); return err; } Commit Message: Fix order of arguments to compat_put_time[spec|val] Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in net/socket.c") introduced a bug where the helper functions to take either a 64-bit or compat time[spec|val] got the arguments in the wrong order, passing the kernel stack pointer off as a user pointer (and vice versa). Because of the user address range check, that in turn then causes an EFAULT due to the user pointer range checking failing for the kernel address. Incorrectly resuling in a failed system call for 32-bit processes with a 64-bit kernel. On odder architectures like HP-PA (with separate user/kernel address spaces), it can be used read kernel memory. Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; }
165,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GaiaOAuthClient::Core::OnUserInfoFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { std::string email; if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kEmailValue, &email); } } if (email.empty()) { delegate_->OnNetworkError(response_code); } else { delegate_->OnRefreshTokenResponse( email, access_token_, expires_in_seconds_); } } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::OnUserInfoFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); url_fetcher_type_ = URL_FETCHER_NONE; std::string email; if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kEmailValue, &email); } } if (email.empty()) { delegate_->OnNetworkError(response_code); } else { delegate_->OnRefreshTokenResponse( email, access_token_, expires_in_seconds_); } }
170,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int base64decode_block(unsigned char *target, const char *data, size_t data_size) { int w1,w2,w3,w4; int i; size_t n; if (!data || (data_size <= 0)) { return 0; } n = 0; i = 0; while (n < data_size-3) { w1 = base64_table[(int)data[n]]; w2 = base64_table[(int)data[n+1]]; w3 = base64_table[(int)data[n+2]]; w4 = base64_table[(int)data[n+3]]; if (w2 >= 0) { target[i++] = (char)((w1*4 + (w2 >> 4)) & 255); } if (w3 >= 0) { target[i++] = (char)((w2*16 + (w3 >> 2)) & 255); } if (w4 >= 0) { target[i++] = (char)((w3*64 + w4) & 255); } n+=4; } return i; } Commit Message: base64: Rework base64decode to handle split encoded data correctly CWE ID: CWE-125
static int base64decode_block(unsigned char *target, const char *data, size_t data_size)
168,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, bigint *modulus, bigint *pub_exp) { int i, size; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; i = 10; /* start at the first possible non-padded byte */ while (block[i++] && i < sig_len); size = sig_len - i; /* get only the bit we want */ if (size > 0) { int len; const uint8_t *sig_ptr = get_signature(&block[i], &len); if (sig_ptr) { bir = bi_import(ctx, sig_ptr, len); } } free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; } Commit Message: Apply CVE fixes for X509 parsing Apply patches developed by Sze Yiu which correct a vulnerability in X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info. CWE ID: CWE-347
static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, static bigint *sig_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len, uint8_t sig_type, bigint *modulus, bigint *pub_exp) { int i; bigint *decrypted_bi, *dat_bi; bigint *bir = NULL; uint8_t *block = (uint8_t *)malloc(sig_len); const uint8_t *sig_prefix = NULL; uint8_t sig_prefix_size = 0, hash_len = 0; /* adjust our expections */ switch (sig_type) { case SIG_TYPE_MD5: sig_prefix = sig_prefix_md5; sig_prefix_size = sizeof(sig_prefix_md5); break; case SIG_TYPE_SHA1: sig_prefix = sig_prefix_sha1; sig_prefix_size = sizeof(sig_prefix_sha1); break; case SIG_TYPE_SHA256: sig_prefix = sig_prefix_sha256; sig_prefix_size = sizeof(sig_prefix_sha256); break; case SIG_TYPE_SHA384: sig_prefix = sig_prefix_sha384; sig_prefix_size = sizeof(sig_prefix_sha384); break; case SIG_TYPE_SHA512: sig_prefix = sig_prefix_sha512; sig_prefix_size = sizeof(sig_prefix_sha512); break; } if (sig_prefix) hash_len = sig_prefix[sig_prefix_size - 1]; /* check length (#A) */ if (sig_len < 2 + 8 + 1 + sig_prefix_size + hash_len) goto err; /* decrypt */ dat_bi = bi_import(ctx, sig, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* convert to a normal block */ decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp); bi_export(ctx, decrypted_bi, block, sig_len); ctx->mod_offset = BIGINT_M_OFFSET; /* check the first 2 bytes */ if (block[0] != 0 || block[1] != 1) goto err; /* check the padding */ i = 2; /* start at the first padding byte */ while (i < sig_len - 1 - sig_prefix_size - hash_len) { /* together with (#A), we require at least 8 bytes of padding */ if (block[i++] != 0xFF) goto err; } /* check end of padding */ if (block[i++] != 0) goto err; /* check the ASN.1 metadata */ if (memcmp_P(block+i, sig_prefix, sig_prefix_size)) goto err; /* now we can get the hash we need */ bir = bi_import(ctx, block + i + sig_prefix_size, hash_len); err: free(block); /* save a few bytes of memory */ bi_clear_cache(ctx); return bir; }
169,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX hctx; EVP_CIPHER_CTX ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ HMAC_CTX_init(&hctx); EVP_CIPHER_CTX_init(&ctx); if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, &ctx, &hctx, 0); if (rv < 0) return -1; if (rv == 0) return 2; if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, 16)) return 2; HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(), NULL); EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + 16); } /* Attempt to process session ticket, first conduct sanity and * integrity checks on ticket. */ mlen = HMAC_size(&hctx); if (mlen < 0) { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ HMAC_Update(&hctx, etick, eticklen); HMAC_Final(&hctx, tick_hmac, NULL); HMAC_CTX_cleanup(&hctx); if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) return 2; /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx); { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen); if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_cleanup(&ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_cleanup(&ctx); p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* The session ID, if non-empty, is used by some clients to * detect that the ticket has been accepted. So we copy it to * the session structure. If it is empty set length to zero * as required by standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* For session parse failure, indicate that we need to send a new * ticket. */ return 2; } Commit Message: CWE ID: CWE-20
static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX hctx; EVP_CIPHER_CTX ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ HMAC_CTX_init(&hctx); EVP_CIPHER_CTX_init(&ctx); if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, &ctx, &hctx, 0); if (rv < 0) return -1; if (rv == 0) return 2; if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, 16)) return 2; HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(), NULL); EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + 16); } /* Attempt to process session ticket, first conduct sanity and * integrity checks on ticket. */ mlen = HMAC_size(&hctx); if (mlen < 0) { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ HMAC_Update(&hctx, etick, eticklen); HMAC_Final(&hctx, tick_hmac, NULL); HMAC_CTX_cleanup(&hctx); if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_cleanup(&ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx); { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen); if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_cleanup(&ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_cleanup(&ctx); p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* The session ID, if non-empty, is used by some clients to * detect that the ticket has been accepted. So we copy it to * the session structure. If it is empty set length to zero * as required by standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* For session parse failure, indicate that we need to send a new * ticket. */ return 2; }
165,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LoadingStatsCollector::CleanupAbandonedStats() { base::TimeTicks time_now = base::TimeTicks::Now(); for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) { if (time_now - it->second->start_time > max_stats_age_) { ReportPreconnectAccuracy(*it->second, std::map<GURL, OriginRequestSummary>()); it = preconnect_stats_.erase(it); } else { ++it; } } } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void LoadingStatsCollector::CleanupAbandonedStats() { base::TimeTicks time_now = base::TimeTicks::Now(); for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) { if (time_now - it->second->start_time > max_stats_age_) { ReportPreconnectAccuracy(*it->second, {}); it = preconnect_stats_.erase(it); } else { ++it; } } }
172,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dns_stricmp(const char* str1, const char* str2) { char c1, c2; *----------------------------------------------------------------------------*/ /* DNS variables */ static struct udp_pcb *dns_pcb; static u8_t dns_seqno; static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS]; if (c1_upc != c2_upc) { /* still not equal */ /* don't care for < or > */ return 1; } } else { /* characters are not equal but none is in the alphabet range */ return 1; } Commit Message: CWE ID: CWE-345
dns_stricmp(const char* str1, const char* str2) { char c1, c2; *----------------------------------------------------------------------------*/ /* DNS variables */ static struct udp_pcb *dns_pcbs[DNS_MAX_SOURCE_PORTS]; #if ((LWIP_DNS_SECURE & LWIP_DNS_SECURE_RAND_SRC_PORT) != 0) static u8_t dns_last_pcb_idx; #endif static u8_t dns_seqno; static struct dns_table_entry dns_table[DNS_TABLE_SIZE]; static struct dns_req_entry dns_requests[DNS_MAX_REQUESTS]; if (c1_upc != c2_upc) { /* still not equal */ /* don't care for < or > */ return 1; } } else { /* characters are not equal but none is in the alphabet range */ return 1; }
165,048
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); } else { v9fs_path_sprintf(target, "%s", name); } return 0; } Commit Message: CWE ID: CWE-732
static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); } else if (strcmp(name, "/")) { v9fs_path_sprintf(target, "%s", name); } else { /* We want the path of the export root to be relative, otherwise * "*at()" syscalls would treat it as "/" in the host. */ v9fs_path_sprintf(target, "%s", "."); } return 0; }
165,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { xmlXPathObjectPtr tmp; /* pop the result if any */ tmp = valuePop(ctxt); if (tmp != contextObj) /* * Free up the result * then pop off contextObj, which will be freed later */ xmlXPathReleaseObject(xpctxt, tmp); valuePop(ctxt); goto evaluation_error; } if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); } return(contextSize); } Commit Message: Fix libxml XPath bug. BUG=89402 Review URL: http://codereview.chromium.org/7508039 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95382 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { xmlXPathObjectPtr tmp; /* pop the result if any */ tmp = valuePop(ctxt); while (tmp != contextObj) { /* * Free up the result * then pop off contextObj, which will be freed later */ xmlXPathReleaseObject(xpctxt, tmp); tmp = valuePop(ctxt); } goto evaluation_error; } if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); } return(contextSize); }
170,365
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DWORD WtsSessionProcessDelegate::Core::GetExitCode() { DCHECK(main_task_runner_->BelongsToCurrentThread()); DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } return exit_code; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
DWORD WtsSessionProcessDelegate::Core::GetExitCode() { DWORD WtsSessionProcessDelegate::Core::GetProcessId() const { DWORD pid = 0; if (pipe_.IsValid() && get_named_pipe_client_pid_(pipe_, &pid)) { return pid; } else { return 0; } } bool WtsSessionProcessDelegate::Core::IsPermanentError( int failure_count) const { // Get exit code of the worker process if it is available. DWORD exit_code = CONTROL_C_EXIT; if (worker_process_.IsValid()) { if (!::GetExitCodeProcess(worker_process_, &exit_code)) { LOG_GETLASTERROR(INFO) << "Failed to query the exit code of the worker process"; exit_code = CONTROL_C_EXIT; } } // Stop trying to restart the worker process if it exited due to // misconfiguration. return (kMinPermanentErrorExitCode <= exit_code && exit_code <= kMaxPermanentErrorExitCode); }
171,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_number( cJSON *item, const char *num ) { int64_t i = 0; double f = 0; int isint = 1; int sign = 1, scale = 0, subscale = 0, signsubscale = 1; /* Could use sscanf for this? */ if ( *num == '-' ) { /* Has sign. */ sign = -1; ++num; } if ( *num == '0' ) /* Is zero. */ ++num; if ( *num >= '1' && *num<='9' ) { /* Number. */ do { i = ( i * 10 ) + ( *num - '0' ); f = ( f * 10.0 ) + ( *num - '0' ); ++num; } while ( *num >= '0' && *num <= '9' ); } if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) { /* Fractional part. */ isint = 0; ++num; do { f = ( f * 10.0 ) + ( *num++ - '0' ); scale--; } while ( *num >= '0' && *num <= '9' ); } if ( *num == 'e' || *num == 'E' ) { /* Exponent. */ isint = 0; ++num; if ( *num == '+' ) ++num; else if ( *num == '-' ) { /* With sign. */ signsubscale = -1; ++num; } while ( *num >= '0' && *num <= '9' ) subscale = ( subscale * 10 ) + ( *num++ - '0' ); } /* Put it together. */ if ( isint ) { /* Int: number = +/- number */ i = sign * i; item->valueint = i; item->valuefloat = i; } else { /* Float: number = +/- number.fraction * 10^+/- exponent */ f = sign * f * ipow( 10.0, scale + subscale * signsubscale ); item->valueint = f; item->valuefloat = f; } item->type = cJSON_Number; return num; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static const char *parse_number( cJSON *item, const char *num ) static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } typedef struct {char *buffer; int length; int offset; } printbuffer; static char* ensure(printbuffer *p,int needed) { char *newbuffer;int newsize; if (!p || !p->buffer) return 0; needed+=p->offset; if (needed<=p->length) return p->buffer+p->offset; newsize=pow2gt(needed); newbuffer=(char*)cJSON_malloc(newsize); if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} if (newbuffer) memcpy(newbuffer,p->buffer,p->length); cJSON_free(p->buffer); p->length=newsize; p->buffer=newbuffer; return newbuffer+p->offset; }
167,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: size_t jsvGetString(const JsVar *v, char *str, size_t len) { assert(len>0); const char *s = jsvGetConstString(v); if (s) { /* don't use strncpy here because we don't * want to pad the entire buffer with zeros */ len--; int l = 0; while (*s && l<len) { str[l] = s[l]; l++; } str[l] = 0; return l; } else if (jsvIsInt(v)) { itostr(v->varData.integer, str, 10); return strlen(str); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, str, len); return strlen(str); } else if (jsvHasCharacterData(v)) { assert(!jsvIsStringExt(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (l--<=1) { *str = 0; jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } else { JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here if (stringVar) { size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var jsvUnLock(stringVar); return l; } else { str[0] = 0; jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); return 0; } } } Commit Message: fix jsvGetString regression CWE ID: CWE-119
size_t jsvGetString(const JsVar *v, char *str, size_t len) { assert(len>0); const char *s = jsvGetConstString(v); if (s) { /* don't use strncpy here because we don't * want to pad the entire buffer with zeros */ len--; int l = 0; while (s[l] && l<len) { str[l] = s[l]; l++; } str[l] = 0; return l; } else if (jsvIsInt(v)) { itostr(v->varData.integer, str, 10); return strlen(str); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, str, len); return strlen(str); } else if (jsvHasCharacterData(v)) { assert(!jsvIsStringExt(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (l--<=1) { *str = 0; jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } else { JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here if (stringVar) { size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var jsvUnLock(stringVar); return l; } else { str[0] = 0; jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); return 0; } } }
169,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; utee_param_to_param(param, callee_params); } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, &param->u[n].mem.mobj, &param->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; } Commit Message: core: svc: always check ta parameters Always check TA parameters from a user TA. This prevents a user TA from passing invalid pointers to a pseudo TA. Fixes: OP-TEE-2018-0007: "Buffer checks missing when calling pseudo TAs". Signed-off-by: Jens Wiklander <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Joakim Bech <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-119
static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; res = utee_param_to_param(utc, param, callee_params); if (res != TEE_SUCCESS) return res; } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, &param->u[n].mem.mobj, &param->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; }
169,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; } Commit Message: ipsec: Fix aborted xfrm policy dump crash An independent security researcher, Mohamed Ghannam, has reported this vulnerability to Beyond Security's SecuriTeam Secure Disclosure program. The xfrm_dump_policy_done function expects xfrm_dump_policy to have been called at least once or it will crash. This can be triggered if a dump fails because the target socket's receive buffer is full. This patch fixes it by using the cb->start mechanism to ensure that the initialisation is always done regardless of the buffer situation. Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list") Signed-off-by: Herbert Xu <[email protected]> Signed-off-by: Steffen Klassert <[email protected]> CWE ID: CWE-416
static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args; struct net *net = sock_net(cb->skb->sk); xfrm_policy_walk_done(walk, net); return 0; }
167,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Extension::HasAPIPermission(const std::string& function_name) const { base::AutoLock auto_lock(runtime_data_lock_); return runtime_data_.GetActivePermissions()-> HasAccessToFunction(function_name); } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool Extension::HasAPIPermission(const std::string& function_name) const { base::AutoLock auto_lock(runtime_data_lock_); return runtime_data_.GetActivePermissions()-> HasAccessToFunction(function_name, true); }
171,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: idna_strerror (Idna_rc rc) { const char *p; bindtextdomain (PACKAGE, LOCALEDIR); switch (rc) { case IDNA_SUCCESS: p = _("Success"); break; case IDNA_STRINGPREP_ERROR: p = _("String preparation failed"); break; case IDNA_PUNYCODE_ERROR: p = _("Punycode failed"); break; case IDNA_CONTAINS_NON_LDH: p = _("Non-digit/letter/hyphen in input"); break; case IDNA_CONTAINS_MINUS: p = _("Forbidden leading or trailing minus sign (`-')"); break; case IDNA_INVALID_LENGTH: p = _("Output would be too large or too small"); break; case IDNA_NO_ACE_PREFIX: p = _("Input does not start with ACE prefix (`xn--')"); break; case IDNA_ROUNDTRIP_VERIFY_ERROR: p = _("String not idempotent under ToASCII"); break; case IDNA_CONTAINS_ACE_PREFIX: p = _("Input already contain ACE prefix (`xn--')"); break; case IDNA_ICONV_ERROR: p = _("System iconv failed"); break; case IDNA_MALLOC_ERROR: p = _("Cannot allocate memory"); break; case IDNA_DLOPEN_ERROR: p = _("System dlopen failed"); break; default: p = _("Unknown error"); break; } return p; } Commit Message: CWE ID: CWE-119
idna_strerror (Idna_rc rc) { const char *p; bindtextdomain (PACKAGE, LOCALEDIR); switch (rc) { case IDNA_SUCCESS: p = _("Success"); break; case IDNA_STRINGPREP_ERROR: p = _("String preparation failed"); break; case IDNA_PUNYCODE_ERROR: p = _("Punycode failed"); break; case IDNA_CONTAINS_NON_LDH: p = _("Non-digit/letter/hyphen in input"); break; case IDNA_CONTAINS_MINUS: p = _("Forbidden leading or trailing minus sign (`-')"); break; case IDNA_INVALID_LENGTH: p = _("Output would be too large or too small"); break; case IDNA_NO_ACE_PREFIX: p = _("Input does not start with ACE prefix (`xn--')"); break; case IDNA_ROUNDTRIP_VERIFY_ERROR: p = _("String not idempotent under ToASCII"); break; case IDNA_CONTAINS_ACE_PREFIX: p = _("Input already contain ACE prefix (`xn--')"); break; case IDNA_ICONV_ERROR: p = _("Could not convert string in locale encoding"); break; case IDNA_MALLOC_ERROR: p = _("Cannot allocate memory"); break; case IDNA_DLOPEN_ERROR: p = _("System dlopen failed"); break; default: p = _("Unknown error"); break; } return p; }
164,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GestureProviderAura::OnTouchEventAck(bool event_consumed) { DCHECK(pending_gestures_.empty()); DCHECK(!handling_event_); base::AutoReset<bool> handling_event(&handling_event_, true); filtered_gesture_provider_.OnTouchEventAck(event_consumed); } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GestureProviderAura::OnTouchEventAck(bool event_consumed) { DCHECK(pending_gestures_.empty()); DCHECK(!handling_event_); base::AutoReset<bool> handling_event(&handling_event_, true); filtered_gesture_provider_.OnTouchEventAck(event_consumed); last_touch_event_latency_info_.Clear(); }
171,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct user_element *ue = kcontrol->private_data; memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size); return 0; } Commit Message: ALSA: control: Protect user controls against concurrent access The user-control put and get handlers as well as the tlv do not protect against concurrent access from multiple threads. Since the state of the control is not updated atomically it is possible that either two write operations or a write and a read operation race against each other. Both can lead to arbitrary memory disclosure. This patch introduces a new lock that protects user-controls from concurrent access. Since applications typically access controls sequentially than in parallel a single lock per card should be fine. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct user_element *ue = kcontrol->private_data; mutex_lock(&ue->card->user_ctl_lock); memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size); mutex_unlock(&ue->card->user_ctl_lock); return 0; }
166,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void http_end_txn_clean_session(struct session *s) { int prev_status = s->txn.status; /* FIXME: We need a more portable way of releasing a backend's and a * server's connections. We need a safer way to reinitialize buffer * flags. We also need a more accurate method for computing per-request * data. */ /* unless we're doing keep-alive, we want to quickly close the connection * to the server. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { s->req->cons->flags |= SI_FL_NOLINGER | SI_FL_NOHALF; si_shutr(s->req->cons); si_shutw(s->req->cons); } if (s->flags & SN_BE_ASSIGNED) { s->be->beconn--; if (unlikely(s->srv_conn)) sess_change_server(s, NULL); } s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now); session_process_counters(s); if (s->txn.status) { int n; n = s->txn.status / 100; if (n < 1 || n > 5) n = 0; if (s->fe->mode == PR_MODE_HTTP) { s->fe->fe_counters.p.http.rsp[n]++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->fe->fe_counters.p.http.comp_rsp++; } if ((s->flags & SN_BE_ASSIGNED) && (s->be->mode == PR_MODE_HTTP)) { s->be->be_counters.p.http.rsp[n]++; s->be->be_counters.p.http.cum_req++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->be->be_counters.p.http.comp_rsp++; } } /* don't count other requests' data */ s->logs.bytes_in -= s->req->buf->i; s->logs.bytes_out -= s->rep->buf->i; /* let's do a final log if we need it */ if (!LIST_ISEMPTY(&s->fe->logformat) && s->logs.logwait && !(s->flags & SN_MONITOR) && (!(s->fe->options & PR_O_NULLNOLOG) || s->req->total)) { s->do_log(s); } /* stop tracking content-based counters */ session_stop_content_counters(s); session_update_time_stats(s); s->logs.accept_date = date; /* user-visible date for logging */ s->logs.tv_accept = now; /* corrected date for internal use */ tv_zero(&s->logs.tv_request); s->logs.t_queue = -1; s->logs.t_connect = -1; s->logs.t_data = -1; s->logs.t_close = 0; s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */ s->logs.srv_queue_size = 0; /* we will get this number soon */ s->logs.bytes_in = s->req->total = s->req->buf->i; s->logs.bytes_out = s->rep->total = s->rep->buf->i; if (s->pend_pos) pendconn_free(s->pend_pos); if (objt_server(s->target)) { if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; objt_server(s->target)->cur_sess--; } if (may_dequeue_tasks(objt_server(s->target), s->be)) process_srv_queue(objt_server(s->target)); } s->target = NULL; /* only release our endpoint if we don't intend to reuse the * connection. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { si_release_endpoint(s->req->cons); } s->req->cons->state = s->req->cons->prev_state = SI_ST_INI; s->req->cons->err_type = SI_ET_NONE; s->req->cons->conn_retries = 0; /* used for logging too */ s->req->cons->exp = TICK_ETERNITY; s->req->cons->flags &= SI_FL_DONT_WAKE; /* we're in the context of process_session */ s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT); s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT); s->flags &= ~(SN_DIRECT|SN_ASSIGNED|SN_ADDR_SET|SN_BE_ASSIGNED|SN_FORCE_PRST|SN_IGNORE_PRST); s->flags &= ~(SN_CURR_SESS|SN_REDIRECTABLE|SN_SRV_REUSED); s->txn.meth = 0; http_reset_txn(s); s->txn.flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ; if (prev_status == 401 || prev_status == 407) { /* In HTTP keep-alive mode, if we receive a 401, we still have * a chance of being able to send the visitor again to the same * server over the same connection. This is required by some * broken protocols such as NTLM, and anyway whenever there is * an opportunity for sending the challenge to the proper place, * it's better to do it (at least it helps with debugging). */ s->txn.flags |= TX_PREFER_LAST; } if (s->fe->options2 & PR_O2_INDEPSTR) s->req->cons->flags |= SI_FL_INDEP_STR; if (s->fe->options2 & PR_O2_NODELAY) { s->req->flags |= CF_NEVER_WAIT; s->rep->flags |= CF_NEVER_WAIT; } /* if the request buffer is not empty, it means we're * about to process another request, so send pending * data with MSG_MORE to merge TCP packets when possible. * Just don't do this if the buffer is close to be full, * because the request will wait for it to flush a little * bit before proceeding. */ if (s->req->buf->i) { if (s->rep->buf->o && !buffer_full(s->rep->buf, global.tune.maxrewrite) && bi_end(s->rep->buf) <= s->rep->buf->data + s->rep->buf->size - global.tune.maxrewrite) s->rep->flags |= CF_EXPECT_MORE; } /* we're removing the analysers, we MUST re-enable events detection */ channel_auto_read(s->req); channel_auto_close(s->req); channel_auto_read(s->rep); channel_auto_close(s->rep); /* we're in keep-alive with an idle connection, monitor it */ si_idle_conn(s->req->cons); s->req->analysers = s->listener->analysers; s->rep->analysers = 0; } Commit Message: CWE ID: CWE-189
void http_end_txn_clean_session(struct session *s) { int prev_status = s->txn.status; /* FIXME: We need a more portable way of releasing a backend's and a * server's connections. We need a safer way to reinitialize buffer * flags. We also need a more accurate method for computing per-request * data. */ /* unless we're doing keep-alive, we want to quickly close the connection * to the server. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { s->req->cons->flags |= SI_FL_NOLINGER | SI_FL_NOHALF; si_shutr(s->req->cons); si_shutw(s->req->cons); } if (s->flags & SN_BE_ASSIGNED) { s->be->beconn--; if (unlikely(s->srv_conn)) sess_change_server(s, NULL); } s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now); session_process_counters(s); if (s->txn.status) { int n; n = s->txn.status / 100; if (n < 1 || n > 5) n = 0; if (s->fe->mode == PR_MODE_HTTP) { s->fe->fe_counters.p.http.rsp[n]++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->fe->fe_counters.p.http.comp_rsp++; } if ((s->flags & SN_BE_ASSIGNED) && (s->be->mode == PR_MODE_HTTP)) { s->be->be_counters.p.http.rsp[n]++; s->be->be_counters.p.http.cum_req++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->be->be_counters.p.http.comp_rsp++; } } /* don't count other requests' data */ s->logs.bytes_in -= s->req->buf->i; s->logs.bytes_out -= s->rep->buf->i; /* let's do a final log if we need it */ if (!LIST_ISEMPTY(&s->fe->logformat) && s->logs.logwait && !(s->flags & SN_MONITOR) && (!(s->fe->options & PR_O_NULLNOLOG) || s->req->total)) { s->do_log(s); } /* stop tracking content-based counters */ session_stop_content_counters(s); session_update_time_stats(s); s->logs.accept_date = date; /* user-visible date for logging */ s->logs.tv_accept = now; /* corrected date for internal use */ tv_zero(&s->logs.tv_request); s->logs.t_queue = -1; s->logs.t_connect = -1; s->logs.t_data = -1; s->logs.t_close = 0; s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */ s->logs.srv_queue_size = 0; /* we will get this number soon */ s->logs.bytes_in = s->req->total = s->req->buf->i; s->logs.bytes_out = s->rep->total = s->rep->buf->i; if (s->pend_pos) pendconn_free(s->pend_pos); if (objt_server(s->target)) { if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; objt_server(s->target)->cur_sess--; } if (may_dequeue_tasks(objt_server(s->target), s->be)) process_srv_queue(objt_server(s->target)); } s->target = NULL; /* only release our endpoint if we don't intend to reuse the * connection. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { si_release_endpoint(s->req->cons); } s->req->cons->state = s->req->cons->prev_state = SI_ST_INI; s->req->cons->err_type = SI_ET_NONE; s->req->cons->conn_retries = 0; /* used for logging too */ s->req->cons->exp = TICK_ETERNITY; s->req->cons->flags &= SI_FL_DONT_WAKE; /* we're in the context of process_session */ s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT|CF_WROTE_DATA); s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT|CF_WROTE_DATA); s->flags &= ~(SN_DIRECT|SN_ASSIGNED|SN_ADDR_SET|SN_BE_ASSIGNED|SN_FORCE_PRST|SN_IGNORE_PRST); s->flags &= ~(SN_CURR_SESS|SN_REDIRECTABLE|SN_SRV_REUSED); s->txn.meth = 0; http_reset_txn(s); s->txn.flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ; if (prev_status == 401 || prev_status == 407) { /* In HTTP keep-alive mode, if we receive a 401, we still have * a chance of being able to send the visitor again to the same * server over the same connection. This is required by some * broken protocols such as NTLM, and anyway whenever there is * an opportunity for sending the challenge to the proper place, * it's better to do it (at least it helps with debugging). */ s->txn.flags |= TX_PREFER_LAST; } if (s->fe->options2 & PR_O2_INDEPSTR) s->req->cons->flags |= SI_FL_INDEP_STR; if (s->fe->options2 & PR_O2_NODELAY) { s->req->flags |= CF_NEVER_WAIT; s->rep->flags |= CF_NEVER_WAIT; } /* if the request buffer is not empty, it means we're * about to process another request, so send pending * data with MSG_MORE to merge TCP packets when possible. * Just don't do this if the buffer is close to be full, * because the request will wait for it to flush a little * bit before proceeding. */ if (s->req->buf->i) { if (s->rep->buf->o && !buffer_full(s->rep->buf, global.tune.maxrewrite) && bi_end(s->rep->buf) <= s->rep->buf->data + s->rep->buf->size - global.tune.maxrewrite) s->rep->flags |= CF_EXPECT_MORE; } /* we're removing the analysers, we MUST re-enable events detection */ channel_auto_read(s->req); channel_auto_close(s->req); channel_auto_read(s->rep); channel_auto_close(s->rep); /* we're in keep-alive with an idle connection, monitor it */ si_idle_conn(s->req->cons); s->req->analysers = s->listener->analysers; s->rep->analysers = 0; }
164,989
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8>& data, double timestamp) { DCHECK_LT(port_index, output_streams_.size()); output_streams_[port_index]->Send(data); client->AccumulateMidiBytesSent(data.size()); } Commit Message: MidiManagerUsb should not trust indices provided by renderer. MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is provided by a renderer possibly under the control of an attacker, we must validate the given index before using it. BUG=456516 Review URL: https://codereview.chromium.org/907793002 Cr-Commit-Position: refs/heads/master@{#315303} CWE ID: CWE-119
void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8>& data, double timestamp) { if (port_index >= output_streams_.size()) { // |port_index| is provided by a renderer so we can't believe that it is // in the valid range. // TODO(toyoshim): Move this check to MidiHost and kill the renderer when // it fails. return; } output_streams_[port_index]->Send(data); client->AccumulateMidiBytesSent(data.size()); }
172,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); umount_mnt(p); } change_mnt_propagation(p, MS_PRIVATE); } } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-284
static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } }
167,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserEventRouter::ExtensionActionExecuted( Profile* profile, const ExtensionAction& extension_action, WebContents* web_contents) { const char* event_name = NULL; switch (extension_action.action_type()) { case Extension::ActionInfo::TYPE_BROWSER: event_name = "browserAction.onClicked"; break; case Extension::ActionInfo::TYPE_PAGE: event_name = "pageAction.onClicked"; break; case Extension::ActionInfo::TYPE_SCRIPT_BADGE: event_name = "scriptBadge.onClicked"; break; case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR: break; } if (event_name) { scoped_ptr<ListValue> args(new ListValue()); DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( web_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS); args->Append(tab_value); DispatchEventToExtension(profile, extension_action.extension_id(), event_name, args.Pass(), EventRouter::USER_GESTURE_ENABLED); } } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::ExtensionActionExecuted( Profile* profile, const ExtensionAction& extension_action, WebContents* web_contents) { const char* event_name = NULL; switch (extension_action.action_type()) { case Extension::ActionInfo::TYPE_BROWSER: event_name = "browserAction.onClicked"; break; case Extension::ActionInfo::TYPE_PAGE: event_name = "pageAction.onClicked"; break; case Extension::ActionInfo::TYPE_SCRIPT_BADGE: event_name = "scriptBadge.onClicked"; break; case Extension::ActionInfo::TYPE_SYSTEM_INDICATOR: break; } if (event_name) { scoped_ptr<ListValue> args(new ListValue()); DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( web_contents); args->Append(tab_value); DispatchEventToExtension(profile, extension_action.extension_id(), event_name, args.Pass(), EventRouter::USER_GESTURE_ENABLED); } }
171,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *provider_name; lua_authz_provider_spec *spec; apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE, cmd->temp_pool); ap_assert(provider_name != NULL); spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING); ap_assert(spec != NULL); if (require_line && *require_line) { const char *arg; spec->args = apr_array_make(cmd->pool, 2, sizeof(const char *)); while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) { APR_ARRAY_PUSH(spec->args, const char *) = arg; } } *parsed_require_line = spec; return NULL; } Commit Message: Merge r1642499 from trunk: *) SECURITY: CVE-2014-8109 (cve.mitre.org) mod_lua: Fix handling of the Require line when a LuaAuthzProvider is used in multiple Require directives with different arguments. PR57204 [Edward Lu <Chaosed0 gmail.com>] Submitted By: Edward Lu Committed By: covener Submitted by: covener Reviewed/backported by: jim git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-264
static const char *lua_authz_parse(cmd_parms *cmd, const char *require_line, const void **parsed_require_line) { const char *provider_name; lua_authz_provider_spec *spec; lua_authz_provider_func *func = apr_pcalloc(cmd->pool, sizeof(lua_authz_provider_func)); apr_pool_userdata_get((void**)&provider_name, AUTHZ_PROVIDER_NAME_NOTE, cmd->temp_pool); ap_assert(provider_name != NULL); spec = apr_hash_get(lua_authz_providers, provider_name, APR_HASH_KEY_STRING); ap_assert(spec != NULL); func->spec = spec; if (require_line && *require_line) { const char *arg; func->args = apr_array_make(cmd->pool, 2, sizeof(const char *)); while ((arg = ap_getword_conf(cmd->pool, &require_line)) && *arg) { APR_ARRAY_PUSH(func->args, const char *) = arg; } } *parsed_require_line = func; return NULL; }
166,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY); key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310
int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY); key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST || ret == -EOVERFLOW) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; }
166,193