Skip to content

Commit 62ae278

Browse files
mcollinaaduh95
authored andcommitted
http2: charge inbound DATA retained by streams to maxSessionMemory
Inbound DATA frames delivered to JS while a stream is paused are retained in the stream's readable buffer until the application reads them. These were not counted against the session's maxSessionMemory, so a peer could send many tiny DATA frames on a stream the application is not draining and make the session retain an unbounded amount of memory, in proportion to the number of frames rather than the bytes sent. Charge each such DATA chunk (plus a per-chunk overhead comparable to the Buffer view bookkeeping) against maxSessionMemory, and release it when the stream resumes reading (ReadStart) or is destroyed (RemoveStream). Add connection-level backpressure so the session stops reading from the socket once it can no longer afford the inbound queued data, resuming when the application consumes it. Refs: https://hackerone.com/reports/4089663 Signed-off-by: Matteo Collina <hello@matteocollina.com> PR-URL: nodejs-private/node-private#1000 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> CVE-ID: CVE-2026-123868
1 parent 40d3d8d commit 62ae278

4 files changed

Lines changed: 204 additions & 12 deletions

File tree

‎doc/api/http2.md‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2884,9 +2884,12 @@ changes:
28842884
limit to be exceeded, but new `Http2Stream` instances will be rejected
28852885
while this limit is exceeded. The current number of `Http2Stream` sessions,
28862886
the current memory use of the header compression tables, header blocks
2887-
retained by open streams, current data queued to be sent, and
2888-
unacknowledged `PING` and `SETTINGS` frames are all counted towards the
2889-
current limit. **Default:** `10`.
2887+
retained by open streams, current data queued to be sent, inbound DATA
2888+
frames retained by undrained streams, and unacknowledged `PING` and
2889+
`SETTINGS` frames are all counted towards the current limit. When the limit
2890+
is exceeded the session stops reading from the socket (applying
2891+
backpressure) until the application consumes the queued data. **Default:**
2892+
`10`.
28902893
* `maxHeaderListPairs` {number} Sets the maximum number of header entries.
28912894
This is similar to [`server.maxHeadersCount`][] or
28922895
[`request.maxHeadersCount`][] in the `node:http` module. The minimum value
@@ -3112,9 +3115,12 @@ changes:
31123115
limit to be exceeded, but new `Http2Stream` instances will be rejected
31133116
while this limit is exceeded. The current number of `Http2Stream` sessions,
31143117
the current memory use of the header compression tables, header blocks
3115-
retained by open streams, current data queued to be sent, and
3116-
unacknowledged `PING` and `SETTINGS` frames are all counted towards the
3117-
current limit. **Default:** `10`.
3118+
retained by open streams, current data queued to be sent, inbound DATA
3119+
frames retained by undrained streams, and unacknowledged `PING`
3120+
and `SETTINGS` frames are all counted towards the current limit. When the
3121+
limit is exceeded the session stops reading from the socket (applying
3122+
backpressure) until the application consumes the queued data. **Default:**
3123+
`10`.
31183124
* `maxHeaderListPairs` {number} Sets the maximum number of header entries.
31193125
This is similar to [`server.maxHeadersCount`][] or
31203126
[`request.maxHeadersCount`][] in the `node:http` module. The minimum value
@@ -3304,9 +3310,12 @@ changes:
33043310
limit to be exceeded, but new `Http2Stream` instances will be rejected
33053311
while this limit is exceeded. The current number of `Http2Stream` sessions,
33063312
the current memory use of the header compression tables, header blocks
3307-
retained by open streams, current data queued to be sent, and
3308-
unacknowledged `PING` and `SETTINGS` frames are all counted towards the
3309-
current limit. **Default:** `10`.
3313+
retained by open streams, current data queued to be sent, inbound DATA
3314+
frames retained by undrained streams, and unacknowledged `PING` and
3315+
`SETTINGS` frames are all counted towards the current limit. When the limit
3316+
is exceeded the session stops reading from the socket (applying
3317+
backpressure) until the application consumes the queued data. **Default:**
3318+
`10`.
33103319
* `maxHeaderListPairs` {number} Sets the maximum number of header entries.
33113320
This is similar to [`server.maxHeadersCount`][] or
33123321
[`request.maxHeadersCount`][] in the `node:http` module. The minimum value

‎src/node_http2.cc‎

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,10 @@ Http2Options::Http2Options(Http2State* http2_state, SessionType type) {
205205
// this is a credit based system. Existing streams may cause the limit
206206
// to be temporarily exceeded but once over the limit, new streams cannot
207207
// created.
208+
// Inbound DATA that is queued in the readable buffer of an undrained stream
209+
// also counts against this limit, and when the limit is reached the session
210+
// stops reading from the socket (applying backpressure) until the
211+
// application consumes the data.
208212
// Important: The maxSessionMemory option in javascript is expressed in
209213
// terms of MB increments (i.e. the value 1 == 1 MB)
210214
if (flags & (1 << IDX_OPTIONS_MAX_SESSION_MEMORY))
@@ -962,8 +966,18 @@ BaseObjectPtr<Http2Stream> Http2Session::RemoveStream(int32_t id) {
962966
DecrementCurrentSessionMemory(stream->retained_headers_length_);
963967
stream->retained_headers_length_ = 0;
964968
}
969+
if (stream->inbound_consumed_data_while_paused_memory_ > 0) {
970+
DecrementCurrentSessionMemory(
971+
stream->inbound_consumed_data_while_paused_memory_);
972+
inbound_queued_data_memory_ -=
973+
stream->inbound_consumed_data_while_paused_memory_;
974+
stream->inbound_consumed_data_while_paused_memory_ = 0;
975+
}
965976
DecrementCurrentSessionMemory(sizeof(*stream));
966977
}
978+
// Removing the stream may have freed inbound data memory that was keeping
979+
// the session from reading; resume if it now can make progress.
980+
MaybeStartReading();
967981
return stream;
968982
}
969983

@@ -1471,11 +1485,23 @@ int Http2Session::OnDataChunkReceived(nghttp2_session* handle,
14711485
// If the stream owner (e.g. the JS Http2Stream) wants more data, just
14721486
// tell nghttp2 that all data has been consumed. Otherwise, defer until
14731487
// more data is being requested.
1474-
if (stream->is_reading())
1488+
if (stream->is_reading()) {
14751489
nghttp2_session_consume_stream(handle, id, avail);
1476-
else
1490+
} else {
14771491
stream->inbound_consumed_data_while_paused_ += avail;
14781492

1493+
// The Buffer handed to JS may stay alive in the readable queue for as
1494+
// long as the stream remains paused. Charge it (including a per-chunk
1495+
// overhead for the Buffer view) against maxSessionMemory so that a peer
1496+
// cannot make the session retain an unbounded amount of memory by
1497+
// sending many tiny DATA frames.
1498+
uint64_t memory =
1499+
static_cast<uint64_t>(avail) + kHttp2SessionDataChunkOverhead;
1500+
stream->inbound_consumed_data_while_paused_memory_ += memory;
1501+
session->inbound_queued_data_memory_ += memory;
1502+
session->IncrementCurrentSessionMemory(memory);
1503+
}
1504+
14791505
// If we have a gathered a lot of data for output, try sending it now.
14801506
if (session->outgoing_length_ > 4096 ||
14811507
stream->available_outbound_length_ > 4096) {
@@ -1925,12 +1951,30 @@ void Http2Session::MaybeStopReading() {
19251951
if (is_reading_stopped() || is_closing()) return;
19261952
int want_read = nghttp2_session_want_read(session_.get());
19271953
Debug(this, "wants read? %d", want_read);
1928-
if (want_read == 0) {
1954+
// Stop reading if nghttp2 does not want more data, a write is in progress,
1955+
// or the session is already holding more inbound DATA than its memory budget
1956+
// allows. The last condition bounds the amount of memory a peer can make the
1957+
// session retain by sending many small DATA frames on undrained streams.
1958+
if (want_read == 0 || inbound_queued_data_memory_ >= max_session_memory_) {
19291959
set_reading_stopped();
19301960
stream_->ReadStop();
19311961
}
19321962
}
19331963

1964+
void Http2Session::MaybeStartReading() {
1965+
// Restart reading once the session can make progress: nghttp2 wants more
1966+
// data, no write is in flight, and the inbound DATA queued while streams
1967+
// were paused no longer exceeds the session memory budget.
1968+
if (!is_reading_stopped() || is_closing() || is_destroyed()) return;
1969+
int want_read = nghttp2_session_want_read(session_.get());
1970+
Debug(this, "want read? %d", want_read);
1971+
if (want_read != 0 && !is_write_in_progress() &&
1972+
inbound_queued_data_memory_ < max_session_memory_) {
1973+
set_reading_stopped(false);
1974+
stream_->ReadStart();
1975+
}
1976+
}
1977+
19341978
// Unset the sending state, finish up all current writes, and reset
19351979
// storage for data and metadata that was associated with these writes.
19361980
void Http2Session::ClearOutgoing(int status) {
@@ -2688,6 +2732,21 @@ int Http2Stream::ReadStart() {
26882732
inbound_consumed_data_while_paused_);
26892733
inbound_consumed_data_while_paused_ = 0;
26902734

2735+
// The data that was queued while paused is now being consumed by the
2736+
// application, so release the memory charged against maxSessionMemory.
2737+
if (inbound_consumed_data_while_paused_memory_ > 0) {
2738+
session_->DecrementCurrentSessionMemory(
2739+
inbound_consumed_data_while_paused_memory_);
2740+
session_->DecrementInboundQueuedDataMemory(
2741+
inbound_consumed_data_while_paused_memory_);
2742+
inbound_consumed_data_while_paused_memory_ = 0;
2743+
}
2744+
2745+
// The session may have stopped reading because the memory limit was
2746+
// reached; now that the application is consuming data, it may be able to
2747+
// make progress again.
2748+
session_->MaybeStartReading();
2749+
26912750
return 0;
26922751
}
26932752

‎src/node_http2.h‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,14 @@ constexpr size_t kDefaultMaxSettings = 10;
3939
// Default maximum total memory cap for Http2Session.
4040
constexpr uint64_t kDefaultMaxSessionMemory = 10000000;
4141

42+
// Per-DATA-chunk bookkeeping overhead charged against maxSessionMemory. DATA
43+
// frames delivered to JS are turned into Buffer views that stay alive in the
44+
// readable queue while a stream is paused. The overhead accounts for the
45+
// per-chunk view (and related) bookkeeping that is not captured by the payload
46+
// length alone, so that a peer sending many tiny DATA frames cannot make a
47+
// session retain an unbounded amount of memory.
48+
constexpr size_t kHttp2SessionDataChunkOverhead = 128;
49+
4250
constexpr int32_t kDefaultConnectionWindowSize = 65535;
4351

4452
// These are the standard HTTP/2 defaults as specified by the RFC
@@ -529,6 +537,12 @@ class Http2Stream : public AsyncWrap,
529537
// backpressure handling.
530538
size_t inbound_consumed_data_while_paused_ = 0;
531539

540+
// The amount of memory charged against maxSessionMemory_ for DATA frames
541+
// that were handed to JS while the stream was paused and therefore may still
542+
// be retained in the readable queue. Released when the stream resumes
543+
// reading (ReadStart) or is destroyed.
544+
uint64_t inbound_consumed_data_while_paused_memory_ = 0;
545+
532546
// Outbound Data... This is the data written by the JS layer that is
533547
// waiting to be written out to the socket.
534548
std::queue<NgHttp2StreamWrite> queue_;
@@ -695,6 +709,10 @@ class Http2Session : public AsyncWrap,
695709
// Stop reading if nghttp2 doesn't want to anymore.
696710
void MaybeStopReading();
697711

712+
// Restart reading if the session was stopped because of the memory limit and
713+
// can now make progress.
714+
void MaybeStartReading();
715+
698716
// Returns pointer to the stream, or nullptr if stream does not exist
699717
BaseObjectPtr<Http2Stream> FindStream(int32_t id);
700718

@@ -788,6 +806,14 @@ class Http2Session : public AsyncWrap,
788806
current_session_memory_ -= amount;
789807
}
790808

809+
// Called by a stream when it stops holding inbound DATA while paused, to
810+
// keep inbound_queued_data_memory_ (which drives connection-level
811+
// backpressure) in sync. The caller is responsible for also calling
812+
// DecrementCurrentSessionMemory for the same amount.
813+
void DecrementInboundQueuedDataMemory(uint64_t amount) {
814+
inbound_queued_data_memory_ -= amount;
815+
}
816+
791817
void UpdateLocalCustomSettings(size_t count_,
792818
nghttp2_settings_entry* entries_);
793819

@@ -946,6 +972,11 @@ class Http2Session : public AsyncWrap,
946972
// The maximum amount of memory allocated for this session
947973
uint64_t max_session_memory_ = kDefaultMaxSessionMemory;
948974
uint64_t current_session_memory_ = 0;
975+
// The portion of current_session_memory_ that is held by inbound DATA frames
976+
// queued in stream readable buffers while the streams are paused. Used to
977+
// apply connection-level backpressure (stop reading) once the session cannot
978+
// afford to buffer more.
979+
uint64_t inbound_queued_data_memory_ = 0;
949980
// The amount of memory allocated by nghttp2 internals
950981
uint64_t current_nghttp2_memory_ = 0;
951982

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
if (!common.hasCrypto)
5+
common.skip('missing crypto');
6+
7+
const assert = require('assert');
8+
const http2 = require('http2');
9+
const net = require('net');
10+
11+
// Regression test: inbound DATA frames handed to JS on an undrained stream must
12+
// count against maxSessionMemory. Before the fix a peer could send many tiny
13+
// DATA frames on a stream the application never reads, and the session would
14+
// keep reading (and buffering) them. Because each frame becomes a Buffer view in
15+
// the readable queue, memory grew in proportion to the *number* of frames rather
16+
// than the bytes sent, so a single stream could make the process retain hundreds
17+
// of MB. With the fix the session charges the queued data against
18+
// maxSessionMemory and stops reading once it can no longer afford to buffer
19+
// more, keeping the readable buffer bounded.
20+
const maxSessionMemory = 1;
21+
const chunkSize = 1;
22+
const totalFrames = 200000;
23+
24+
let peakReadableLength = 0;
25+
26+
function frame(type, flags, id, payload) {
27+
const header = Buffer.alloc(9);
28+
header.writeUIntBE(payload.length, 0, 3);
29+
header[3] = type;
30+
header[4] = flags;
31+
header.writeUInt32BE(id, 5);
32+
return Buffer.concat([header, payload]);
33+
}
34+
35+
let session = null;
36+
let probe = null;
37+
38+
const server = http2.createServer({ maxSessionMemory });
39+
server.on('session', (s) => {
40+
session = s;
41+
s.on('error', () => {});
42+
});
43+
server.on('stream', (stream) => {
44+
stream.on('error', () => {});
45+
// The application never reads the request body, so the stream stays
46+
// undrained. Record the largest amount of data the readable buffer ever holds;
47+
// with the fix that stays bounded by maxSessionMemory instead of growing to
48+
// match the number of frames the peer sends.
49+
probe = setInterval(() => {
50+
peakReadableLength = Math.max(peakReadableLength, stream.readableLength);
51+
}, 10);
52+
});
53+
54+
server.listen(0, common.mustCall(() => {
55+
const sock = net.connect(server.address().port, '127.0.0.1');
56+
sock.on('error', () => {});
57+
58+
sock.on('connect', () => {
59+
sock.write(Buffer.from('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'));
60+
// Client SETTINGS.
61+
sock.write(frame(4, 0, 0, Buffer.alloc(0)));
62+
});
63+
64+
let settingsAcked = false;
65+
sock.on('data', (chunk) => {
66+
if (!settingsAcked && chunk.length >= 9 && chunk[3] === 4) {
67+
settingsAcked = true;
68+
// ACK the server's SETTINGS.
69+
sock.write(Buffer.from([0, 0, 0, 4, 1, 0, 0, 0, 0]));
70+
// Open one stream (END_HEADERS) and spray 1-byte DATA frames at it.
71+
const hpack = Buffer.from([0x83, 0x86, 0x84, 0x01, 0x01, 0x61]);
72+
sock.write(frame(1, 4, 1, hpack));
73+
const payload = Buffer.alloc(chunkSize, 0x61);
74+
const parts = [];
75+
for (let i = 0; i < totalFrames; i++) {
76+
parts.push(frame(0, 0, 1, payload));
77+
}
78+
sock.write(Buffer.concat(parts));
79+
}
80+
});
81+
82+
setTimeout(common.mustCall(() => {
83+
if (probe) clearInterval(probe);
84+
sock.destroy();
85+
if (session) session.destroy();
86+
server.close();
87+
// The session must not let one undrained stream buffer every frame it was
88+
// sent. Before the fix the readable buffer grew to totalFrames; with the fix
89+
// the backpressure keeps it bounded well below half of that.
90+
assert.ok(peakReadableLength < totalFrames / 2,
91+
`expected backpressure to bound readableLength, got ${peakReadableLength}`);
92+
}), 4000);
93+
}));

0 commit comments

Comments
 (0)