Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions src/quic/session.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1802,7 +1802,7 @@ Session::SendPendingDataScope::SendPendingDataScope(Session* session)

Session::SendPendingDataScope::SendPendingDataScope(
const BaseObjectPtr<Session>& session)
: session(session.get()) {
: session(session) {
CHECK_NOT_NULL(session);
CHECK(!session->is_destroyed());
++session->impl_->send_scope_depth_;
Expand All @@ -1811,7 +1811,8 @@ Session::SendPendingDataScope::SendPendingDataScope(
Session::SendPendingDataScope::~SendPendingDataScope() {
if (session->is_destroyed()) return;
DCHECK_GE(session->impl_->send_scope_depth_, 1);
Debug(session, "Send Scope Depth %zu", session->impl_->send_scope_depth_);
Debug(
session.get(), "Send Scope Depth %zu", session->impl_->send_scope_depth_);
if (--session->impl_->send_scope_depth_ == 0 &&
session->impl_->application_ && !session->impl_->handshake_deferred_) {
session->SendPendingData();
Expand Down Expand Up @@ -1868,7 +1869,11 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
"Datagram %" PRIu64 " abandoned after %u attempts",
front.id,
front.send_attempts);
// DatagramStatus -> EmitDatagramStatus can call into JS and destroy the
// session. Bail out before touching impl_ again.
DatagramStatus(front.id, DatagramStatus::ABANDONED);
if (is_destroyed()) [[unlikely]]
return 0;
PopPendingDatagram();
}

Expand Down Expand Up @@ -1929,7 +1934,11 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
// Non-fatal error cases. Peer either does not support datagrams
// or the datagram is too large for the peer's max.
// Abandon the datagram and signal skip by returning std::nullopt.
// DatagramStatus -> EmitDatagramStatus can call into JS and destroy the
// session. Bail out before touching impl_ again.
DatagramStatus(dg.id, DatagramStatus::ABANDONED);
if (is_destroyed()) [[unlikely]]
return 0;
PopPendingDatagram();
return 0;
}
Expand All @@ -1953,6 +1962,13 @@ ssize_t Session::TryWritePendingDatagram(PathStorage* path,
// and make sure to test thoroughly. When in doubt... don't change it.
void Session::SendPendingData() {
DCHECK(!is_destroyed());
// Pin the session for the duration of this method. The session is detached
// from JS ownership (SessionManager holds the sole BaseObjectPtr<Session>)
// and the synchronous JS callbacks below (StreamCommit, StreamDataBlocked,
// DatagramStatus, ...) can destroy and free it. Pinning keeps the Session
// object alive so the is_destroyed() guards and the update_stats scope-exit
// lambda never touch freed heap memory.
BaseObjectPtr<Session> self(this);
if (!can_send_packets()) [[unlikely]] {
return;
}
Expand Down Expand Up @@ -2143,7 +2159,14 @@ void Session::SendPendingData() {
// We should only have received this error if there was an actual
// stream identified in the stream data, but let's double check.
DCHECK_GE(stream_data.id, 0);
// StreamDataBlocked -> BlockStream -> EmitBlocked can call into JS
// and destroy the session. Bail out before continuing the loop; the
// next iteration would dereference the (now null) impl_.
StreamDataBlocked(stream_data.id);
if (is_destroyed()) [[unlikely]] {
closed = true;
return;
}
continue;
}
case NGTCP2_ERR_STREAM_SHUT_WR: {
Expand Down Expand Up @@ -2173,6 +2196,12 @@ void Session::SendPendingData() {
if (HasPendingDatagrams()) {
auto result = TryWritePendingDatagram(
&path, packet->data(), packet->length(), ts);
// TryWritePendingDatagram -> DatagramStatus can call into JS and
// destroy the session.
if (is_destroyed()) [[unlikely]] {
closed = true;
return;
}
// When result is 0, either the datagram was congestion controlled,
// didn't fit in the packet, or was abandoned. Skip and continue.

Expand Down Expand Up @@ -2234,6 +2263,12 @@ void Session::SendPendingData() {
}
auto result =
TryWritePendingDatagram(&path, packet->data(), packet->length(), ts);
// TryWritePendingDatagram -> DatagramStatus can call into JS and destroy
// the session.
if (is_destroyed()) [[unlikely]] {
closed = true;
return;
}
if (result > 0) {
Debug(this, "Sending datagram packet with %zd bytes", result);
enqueue_packet(packet, static_cast<size_t>(result), PacketInfo());
Expand Down Expand Up @@ -3140,6 +3175,10 @@ void Session::Send(Packet::Ptr packet, const PathStorage& path) {

datagram_id Session::SendDatagram(Store&& data) {
DCHECK(!is_destroyed());
// Pin the session. DatagramStatus below can call into JS and destroy the
// session; the pin keeps the Session object alive so is_destroyed() guards
// and trailing impl_ accesses are safe.
BaseObjectPtr<Session> self(this);

// Sending a datagram is best effort. If we cannot send it for any reason,
// we just return 0 to indicate that the datagram was not sent an the
Expand Down Expand Up @@ -3186,12 +3225,16 @@ datagram_id Session::SendDatagram(Store&& data) {
"Datagram queue full, dropping oldest datagram %" PRIu64,
oldest.id);
DatagramStatus(oldest.id, DatagramStatus::ABANDONED);
if (is_destroyed()) [[unlikely]]
return 0;
impl_->pending_datagrams_.pop_front();
} else {
// DROP_NEWEST: reject the incoming datagram.
Debug(
this, "Datagram queue full, dropping newest datagram %" PRIu64, did);
DatagramStatus(did, DatagramStatus::ABANDONED);
if (is_destroyed()) [[unlikely]]
return 0;
return did;
}
}
Expand Down
9 changes: 8 additions & 1 deletion src/quic/session.h
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,14 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source {
// exits. Scopes can be nested. When nested, pending data will be sent
// only when the outermost scope is exited.
struct SendPendingDataScope final {
Session* session;
// Sessions are detached from JS ownership: SessionManager::sessions_ holds
// the sole BaseObjectPtr<Session>. Synchronous JS callbacks made while the
// scope is active (BeginShutdown, EmitClose, DatagramStatus, EmitBlocked,
// EmitWantTrailers) can destroy the session and free it. Pinning the
// session with a strong BaseObjectPtr keeps the Session object alive for
// the lifetime of the scope so the destructor never dereferences freed
// heap memory.
BaseObjectPtr<Session> session;
explicit SendPendingDataScope(Session* session);
explicit SendPendingDataScope(const BaseObjectPtr<Session>& session);
~SendPendingDataScope();
Expand Down
9 changes: 9 additions & 0 deletions src/quic/streams.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1558,6 +1558,15 @@ void Stream::CapReadable(std::optional<uint64_t> maybe_final_size) {
void Stream::Destroy(QuicError error) {
if (is_destroyed()) return;

// Pin the stream for the duration of Destroy(). Stream objects are detached
// from JS ownership (the session's streams_ map holds the sole
// BaseObjectPtr<Stream>). ReturnFlowControlCredit and EmitClose below can
// call into JS, and a JS callback may destroy the session — which releases
// the last BaseObjectPtr<Stream> and frees `this` before the remaining
// teardown (id(), ReleaseArenaSlots(), RemoveStream()) runs. The pin keeps
// the Stream object alive through the whole function.
BaseObjectPtr<Stream> self(this);

// Record the destroyed at timestamp before notifying the JavaScript side
// that the stream is being destroyed.
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);
Expand Down
101 changes: 101 additions & 0 deletions test/parallel/test-quic-session-close-after-drain.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Flags: --experimental-quic --experimental-stream-iter --no-warnings

// Regression test for a heap-use-after-free in the QUIC session close path.
//
// When a server responds to an HTTP/3 request and then calls session.close()
// after the stream has fully drained (and been removed from the session's
// streams map), Session::Close(GRACEFUL) takes the "no open streams" branch
// and calls FinishClose(). FinishClose() emits the close event to JavaScript,
// and that synchronous JS callback can destroy the session — releasing the
// sole BaseObjectPtr<Session> held by SessionManager and freeing the Session
// object — while the SendPendingDataScope created at the top of Close() is
// still active. The scope's destructor then dereferences the freed session
// (SendPendingDataScope::~SendPendingDataScope() use-after-free).
//
// The fix pins the Session with a strong BaseObjectPtr<Session> for the
// lifetime of SendPendingDataScope (and of SendPendingData itself) so the
// destructor and trailing member accesses never operate on freed heap memory.

import { hasQuic, skip, mustCall } from '../common/index.mjs';
import assert from 'node:assert';
import * as fixtures from '../common/fixtures.mjs';

if (!hasQuic) {
skip('QUIC is not enabled');
}

const { listen, connect } = await import('node:quic');
const { createPrivateKey } = await import('node:crypto');
const { bytes } = await import('stream/iter');

const key = createPrivateKey(fixtures.readKey('agent1-key.pem'));
const cert = fixtures.readKey('agent1-cert.pem');
const decoder = new TextDecoder();
const encoder = new TextEncoder();

{
let serverSession;
let requestCount = 0;
const serverDone = Promise.withResolvers();

const serverEndpoint = await listen(mustCall((ss) => {
serverSession = ss;
ss.closed.catch(() => {});
ss.onstream = mustCall((stream) => {
stream.closed.catch(() => {});
stream.onheaders = mustCall((headers) => {
const reqPath = headers[':path'] || '/';
stream.sendHeaders({ ':status': '200' });
stream.writer.writeSync(encoder.encode('ok'));
stream.writer.endSync();

// Once the request stream has fully drained, close the session.
// Deferring via setTimeout ensures the
// stream has been removed from the session's streams map before
// close() is called, so Close(GRACEFUL) immediately finishes the
// close and emits the close event to JS synchronously while a
// SendPendingDataScope is alive — the path that previously used a
// freed Session.
if (++requestCount === 1) {
assert.strictEqual(reqPath, '/poc');
stream.closed.then(mustCall(() => {
setTimeout(mustCall(() => {
if (!serverSession.destroyed) {
serverSession.close();
}
serverDone.resolve();
}), 50);
})).catch(() => {});
}
});
});
}), {
sni: { '*': { keys: [key], certs: [cert] } },
});

const clientSession = await connect(serverEndpoint.address, {
servername: 'localhost',
verifyPeer: 'manual',
});
await clientSession.opened;
clientSession.closed.catch(() => {});

const stream = await clientSession.createBidirectionalStream({
headers: {
':method': 'GET',
':path': '/poc',
':scheme': 'https',
':authority': 'localhost',
},
});

const body = await bytes(stream);
assert.strictEqual(decoder.decode(body), 'ok');
await stream.closed;

await serverDone.promise;
await clientSession.closed.catch(() => {});

await clientSession.close().catch(() => {});
await serverEndpoint.close();
}
Loading