Skip to content

Commit 6cd7e80

Browse files
mcollinaaduh95
authored andcommitted
http2: retain buffers until socket writes finish
Partial writes can leave slices of a stream's queued buffers in the session's outgoing write. Destroying the stream completes the original write request and allows those buffers to be collected while the socket still references them. Retain a non-completing reference to the write request for each queued buffer and propagate it to partial slices. Refs: https://hackerone.com/reports/4110110 Backport-PR-URL: nodejs-private/node-private#1047 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> PR-URL: nodejs-private/node-private#1017 CVE-ID: CVE-2026-123866
1 parent af6fbb6 commit 6cd7e80

3 files changed

Lines changed: 225 additions & 11 deletions

File tree

‎src/node_http2.cc‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2151,10 +2151,10 @@ int Http2Session::OnSendData(
21512151
continue;
21522152
}
21532153

2154-
// Slice off `length` bytes of the first write in the queue.
2155-
session->PushOutgoingBuffer(NgHttp2StreamWrite {
2156-
uv_buf_init(write.buf.base, length)
2157-
});
2154+
// Slice off `length` bytes of the first write in the queue. Retain the
2155+
// originating request until the slice is no longer used by the socket.
2156+
session->PushOutgoingBuffer(NgHttp2StreamWrite{
2157+
nullptr, write.buffer_owner, uv_buf_init(write.buf.base, length)});
21582158
write.buf.base += length;
21592159
write.buf.len -= length;
21602160
break;
@@ -2758,14 +2758,16 @@ int Http2Stream::DoWrite(WriteWrap* req_wrap,
27582758
return UV_EOF;
27592759
}
27602760
Debug(this, "queuing %d buffers to send", nbufs);
2761+
BaseObjectPtr<AsyncWrap> buffer_owner(req_wrap->GetAsyncWrap());
27612762
for (size_t i = 0; i < nbufs; ++i) {
27622763
// Store the req_wrap on the last write info in the queue, so that it is
27632764
// only marked as finished once all buffers associated with it are finished.
2764-
queue_.emplace(NgHttp2StreamWrite {
2765-
BaseObjectPtr<AsyncWrap>(
2766-
i == nbufs - 1 ? req_wrap->GetAsyncWrap() : nullptr),
2767-
bufs[i]
2768-
});
2765+
// Every entry retains the request separately so partial slices remain valid
2766+
// until the underlying socket write completes.
2767+
queue_.emplace(NgHttp2StreamWrite{
2768+
BaseObjectPtr<AsyncWrap>(i == nbufs - 1 ? buffer_owner : nullptr),
2769+
buffer_owner,
2770+
bufs[i]});
27692771
IncrementAvailableOutboundLength(bufs[i].len);
27702772
}
27712773
CHECK_NE(nghttp2_session_resume_data(
@@ -3542,6 +3544,7 @@ void Http2Ping::DetachFromSession() {
35423544
void NgHttp2StreamWrite::MemoryInfo(MemoryTracker* tracker) const {
35433545
if (req_wrap)
35443546
tracker->TrackField("req_wrap", req_wrap);
3547+
if (buffer_owner) tracker->TrackField("buffer_owner", buffer_owner);
35453548
tracker->TrackField("buf", buf);
35463549
}
35473550

‎src/node_http2.h‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,19 @@ using Http2Headers = NgHeaders<Http2HeadersTraits>;
147147
using Http2RcBufferPointer = NgRcBufPointer<Http2RcBufferPointerTraits>;
148148

149149
struct NgHttp2StreamWrite : public MemoryRetainer {
150+
// Completed once all buffers from the request have been consumed.
150151
BaseObjectPtr<AsyncWrap> req_wrap;
152+
// Retains the request's buffers without completing it.
153+
BaseObjectPtr<AsyncWrap> buffer_owner;
151154
uv_buf_t buf;
152155

153156
inline explicit NgHttp2StreamWrite(uv_buf_t buf_) : buf(buf_) {}
154-
inline NgHttp2StreamWrite(BaseObjectPtr<AsyncWrap> req_wrap, uv_buf_t buf_) :
155-
req_wrap(std::move(req_wrap)), buf(buf_) {}
157+
inline NgHttp2StreamWrite(BaseObjectPtr<AsyncWrap> req_wrap,
158+
BaseObjectPtr<AsyncWrap> buffer_owner,
159+
uv_buf_t buf_)
160+
: req_wrap(std::move(req_wrap)),
161+
buffer_owner(std::move(buffer_owner)),
162+
buf(buf_) {}
156163

157164
void MemoryInfo(MemoryTracker* tracker) const override;
158165
SET_MEMORY_INFO_NAME(NgHttp2StreamWrite)
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Flags: --expose-gc
2+
'use strict';
3+
4+
const common = require('../common');
5+
if (!common.hasCrypto)
6+
common.skip('missing crypto');
7+
const assert = require('assert');
8+
const http2 = require('http2');
9+
const net = require('net');
10+
11+
const FRAME_DATA = 0;
12+
const FRAME_HEADERS = 1;
13+
const FRAME_SETTINGS = 4;
14+
const FRAME_WINDOW_UPDATE = 8;
15+
const FLAG_END_STREAM = 1;
16+
const FLAG_END_HEADERS = 4;
17+
const FLAG_PRIORITY = 0x20;
18+
const INITIAL_WINDOW_SIZE = 65_535;
19+
const FIRST_WINDOW_SIZE = 3_000_000;
20+
const SECOND_WINDOW_INCREMENT = 20_000_000;
21+
const LARGE_RESPONSE_SIZE = 30_000_000;
22+
const SMALL_FIRST_BUFFER_SIZE = 80 * 1024;
23+
const SMALL_SECOND_BUFFER_SIZE = 20 * 1024;
24+
const SMALL_RESPONSE_SIZE =
25+
SMALL_FIRST_BUFFER_SIZE + SMALL_SECOND_BUFFER_SIZE;
26+
const EXPECTED_SMALL_PAYLOAD_SIZE = INITIAL_WINDOW_SIZE;
27+
// On v22.x a peer RST_STREAM is not processed while the server's socket write
28+
// is backpressured (the read-stop guard), so teardown must be app-initiated.
29+
// The server destroys the stream with its own idle timeout, which drains the
30+
// same queue on every release line.
31+
const STREAM_TIMEOUT = 1500;
32+
33+
const preface = Buffer.from('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n');
34+
35+
function frame(type, flags, streamID, payload = Buffer.alloc(0)) {
36+
const header = Buffer.alloc(9);
37+
header.writeUIntBE(payload.length, 0, 3);
38+
header[3] = type;
39+
header[4] = flags;
40+
header.writeUInt32BE(streamID, 5);
41+
return Buffer.concat([header, payload]);
42+
}
43+
44+
function windowUpdate(streamID, increment) {
45+
const payload = Buffer.alloc(4);
46+
payload.writeUInt32BE(increment);
47+
return frame(FRAME_WINDOW_UPDATE, 0, streamID, payload);
48+
}
49+
50+
function request(path, streamID, priority = false) {
51+
const authority = Buffer.from('127.0.0.1');
52+
let payload = Buffer.concat([
53+
Buffer.from([
54+
0x82, // :method: GET
55+
0x86, // :scheme: http
56+
0x01, authority.length, // Literal :authority
57+
]),
58+
authority,
59+
Buffer.from([0x04, path.length]), // Literal :path
60+
Buffer.from(path),
61+
]);
62+
let flags = FLAG_END_STREAM | FLAG_END_HEADERS;
63+
64+
if (priority) {
65+
const priorityPayload = Buffer.alloc(5);
66+
// Make this stream exclusively dependent on stream 1 so its DATA is
67+
// serialized after stream 1's DATA in the pending socket write.
68+
priorityPayload.writeUInt32BE(0x80000001);
69+
priorityPayload[4] = 15;
70+
payload = Buffer.concat([priorityPayload, payload]);
71+
flags |= FLAG_PRIORITY;
72+
}
73+
74+
return frame(FRAME_HEADERS, flags, streamID, payload);
75+
}
76+
77+
const replacementBuffers = [];
78+
let resumeClient;
79+
80+
const server = http2.createServer({ maxSessionMemory: 64 });
81+
server.on('stream', common.mustCall((stream, headers) => {
82+
const path = headers[':path'];
83+
stream.on('error', () => {});
84+
stream.respond();
85+
86+
if (path === '/A') {
87+
stream.end(Buffer.alloc(LARGE_RESPONSE_SIZE, 0x41));
88+
return;
89+
}
90+
91+
stream.on('close', common.mustCall(() => {
92+
setImmediate(() => {
93+
// Collect the canceled write and reuse allocations of the same size.
94+
// The pending socket slices must continue to refer to the original data.
95+
globalThis.gc();
96+
replacementBuffers.push(...Array.from(
97+
{ length: 32 },
98+
() => Buffer.alloc(SMALL_FIRST_BUFFER_SIZE, 0x56)));
99+
// Only now let the backpressured socket write drain.
100+
resumeClient();
101+
});
102+
}));
103+
// Use _writev() so the sliced first buffer does not carry the request's
104+
// completion reference. Every buffer must retain a separate owner. The
105+
// stream is torn down app-initiated: once the client stops reading, the
106+
// socket write stays pending and this idle timeout destroys the stream.
107+
stream.setTimeout(STREAM_TIMEOUT, () => stream.destroy());
108+
stream.cork();
109+
stream.write(Buffer.alloc(SMALL_FIRST_BUFFER_SIZE, 0x53));
110+
stream.end(Buffer.alloc(SMALL_SECOND_BUFFER_SIZE, 0x53));
111+
}, 2));
112+
113+
server.listen(0, common.mustCall(() => {
114+
const socket = net.connect(server.address().port, common.localhostIPv4);
115+
let received = Buffer.alloc(0);
116+
let stream1Received = 0;
117+
let secondWindowSent = false;
118+
let resetSent = false;
119+
const stream3Chunks = [];
120+
121+
resumeClient = () => socket.resume();
122+
123+
const finish = common.mustCall((payload) => {
124+
assert.strictEqual(payload.length, EXPECTED_SMALL_PAYLOAD_SIZE);
125+
assert.ok(
126+
payload.equals(Buffer.alloc(EXPECTED_SMALL_PAYLOAD_SIZE, 0x53)),
127+
'pending DATA used memory from a canceled write');
128+
129+
socket.destroy();
130+
server.close(common.mustCall());
131+
});
132+
133+
function onStream1Data() {
134+
if (!secondWindowSent) {
135+
if (stream1Received < FIRST_WINDOW_SIZE)
136+
return;
137+
// Stream 1 has consumed its whole first window, so the server has no
138+
// DATA left to send. Open stream 3 and the windows together: the server
139+
// packs the remaining stream 1 DATA and stream 3 DATA (serialized after
140+
// stream 1) into a single large socket write.
141+
secondWindowSent = true;
142+
socket.write(Buffer.concat([
143+
request('/S', 3, true),
144+
windowUpdate(0, SECOND_WINDOW_INCREMENT + SMALL_RESPONSE_SIZE),
145+
windowUpdate(1, SECOND_WINDOW_INCREMENT),
146+
]));
147+
return;
148+
}
149+
150+
if (resetSent || stream1Received <= FIRST_WINDOW_SIZE)
151+
return;
152+
153+
// Receiving DATA beyond the first window proves the large write has been
154+
// issued, and stream 3 DATA was packed into it. Stop reading so that write
155+
// stays pending. The server's per-stream timeout then destroys stream 3
156+
// while its slices are still queued; the server resumes us once the stream
157+
// is closed and the freed memory has been reused.
158+
resetSent = true;
159+
socket.pause();
160+
}
161+
162+
function parseFrames() {
163+
let offset = 0;
164+
while (offset + 9 <= received.length) {
165+
const length = received.readUIntBE(offset, 3);
166+
if (offset + 9 + length > received.length)
167+
break;
168+
169+
const type = received[offset + 3];
170+
const streamID = received.readUInt32BE(offset + 5) & 0x7fffffff;
171+
if (type === FRAME_DATA && streamID === 3) {
172+
stream3Chunks.push(received.subarray(
173+
offset + 9,
174+
offset + 9 + length));
175+
} else if (type === FRAME_DATA && streamID === 1) {
176+
stream1Received += length;
177+
onStream1Data();
178+
}
179+
offset += 9 + length;
180+
}
181+
received = received.subarray(offset);
182+
183+
const payload = Buffer.concat(stream3Chunks);
184+
if (payload.length < EXPECTED_SMALL_PAYLOAD_SIZE)
185+
return;
186+
187+
finish(payload);
188+
}
189+
190+
socket.on('connect', () => {
191+
socket.write(Buffer.concat([
192+
preface,
193+
frame(FRAME_SETTINGS, 0, 0),
194+
request('/A', 1),
195+
windowUpdate(0, FIRST_WINDOW_SIZE - INITIAL_WINDOW_SIZE),
196+
windowUpdate(1, FIRST_WINDOW_SIZE - INITIAL_WINDOW_SIZE),
197+
]));
198+
});
199+
200+
socket.on('data', (chunk) => {
201+
received = Buffer.concat([received, chunk]);
202+
parseFrames();
203+
});
204+
}));

0 commit comments

Comments
 (0)