quic: refine rate limiting

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode:Opus 4.6
PR-URL: https://github.com/nodejs/node/pull/63483
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-05-27 11:35:47 +02:00
1 parent 75a4176b32
commit 98808baed1
12 files changed
+434 -184

No files matched your search

+84 -16
View File
@@ -744,7 +744,13 @@ added: v23.8.0
added: v23.8.0
-->
* Type: {bigint} The total number of QUIC retry attempts on this endpoint. Read only.
* Type: {bigint} The total number of retry packets sent by this endpoint. Read only.
### `endpointStats.retryRateLimited`
* Type: {bigint} The total number of retry packets dropped by the global rate
limiter. Read only. A non-zero value indicates the endpoint is under retry
flood pressure.
### `endpointStats.versionNegotiationCount`
@@ -752,7 +758,13 @@ added: v23.8.0
added: v23.8.0
-->
* Type: {bigint} The total number of sessions rejected due to QUIC version mismatch. Read only.
* Type: {bigint} The total number of version negotiation packets sent by this
endpoint. Read only.
### `endpointStats.versionNegotiationRateLimited`
* Type: {bigint} The total number of version negotiation packets dropped by
the global rate limiter. Read only.
### `endpointStats.statelessResetCount`
@@ -760,7 +772,13 @@ added: v23.8.0
added: v23.8.0
-->
* Type: {bigint} The total number of stateless resets handled by this endpoint. Read only.
* Type: {bigint} The total number of stateless reset packets sent by this
endpoint. Read only.
### `endpointStats.statelessResetRateLimited`
* Type: {bigint} The total number of stateless reset packets dropped by the
global rate limiter. Read only.
### `endpointStats.immediateCloseCount`
@@ -768,7 +786,13 @@ added: v23.8.0
added: v23.8.0
-->
* Type: {bigint} The total number of sessions that were closed before handshake completed. Read only.
* Type: {bigint} The total number of immediate connection close packets sent
by this endpoint. Read only.
### `endpointStats.immediateCloseRateLimited`
* Type: {bigint} The total number of immediate connection close packets
dropped by the global rate limiter. Read only.
## Class: `QuicSession`
@@ -2473,25 +2497,69 @@ addresses. When the limit is reached, new connections are refused with
This limit can also be changed dynamically after construction via
[`endpoint.maxConnectionsTotal`][].
#### `endpointOptions.maxRetries`
#### `endpointOptions.retryRate`
<!-- YAML
added: v23.8.0
-->
* Type: {number}
* **Default:** `100`
* Type: {bigint|number}
The maximum number of QUIC retry packets the endpoint will send per second.
This is a global rate limit (not per-host) that caps the total server-wide
retry response rate, preventing spoofed-source floods from consuming unbounded
resources.
Specifies the maximum number of QUIC retry attempts allowed per remote peer address.
#### `endpointOptions.retryBurst`
#### `endpointOptions.maxStatelessResetsPerHost`
* Type: {number}
* **Default:** `200`
<!-- YAML
added: v23.8.0
-->
The maximum burst of retry packets allowed before rate limiting takes effect.
* Type: {bigint|number}
#### `endpointOptions.statelessResetRate`
Specifies the maximum number of stateless resets that are allowed per remote peer address.
* Type: {number}
* **Default:** `100`
The maximum number of stateless reset packets the endpoint will send per second.
#### `endpointOptions.statelessResetBurst`
* Type: {number}
* **Default:** `200`
The maximum burst of stateless reset packets allowed before rate limiting
takes effect.
#### `endpointOptions.versionNegotiationRate`
* Type: {number}
* **Default:** `100`
The maximum number of version negotiation packets the endpoint will send per
second.
#### `endpointOptions.versionNegotiationBurst`
* Type: {number}
* **Default:** `200`
The maximum burst of version negotiation packets allowed before rate limiting
takes effect.
#### `endpointOptions.immediateCloseRate`
* Type: {number}
* **Default:** `100`
The maximum number of immediate connection close packets the endpoint will
send per second.
#### `endpointOptions.immediateCloseBurst`
* Type: {number}
* **Default:** `200`
The maximum burst of immediate connection close packets allowed before rate
limiting takes effect.
#### `endpointOptions.retryTokenExpiration`
+24 -6
View File
@@ -307,8 +307,14 @@ const endpointRegistry = new SafeSet();
* @property {boolean} [reusePort] Enable SO_REUSEPORT for multi-process load balancing
* @property {bigint|number} [maxConnectionsPerHost] The maximum number of connections per host
* @property {bigint|number} [maxConnectionsTotal] The maximum number of total connections
* @property {bigint|number} [maxRetries] The maximum number of retries
* @property {bigint|number} [maxStatelessResetsPerHost] The maximum number of stateless resets per host
* @property {number} [retryRate] Global rate limit for retry packets (per second)
* @property {number} [retryBurst] Burst capacity for retry rate limiter
* @property {number} [statelessResetRate] Global rate limit for stateless reset packets (per second)
* @property {number} [statelessResetBurst] Burst capacity for stateless reset rate limiter
* @property {number} [versionNegotiationRate] Global rate limit for version negotiation packets (per second)
* @property {number} [versionNegotiationBurst] Burst capacity for version negotiation rate limiter
* @property {number} [immediateCloseRate] Global rate limit for immediate close packets (per second)
* @property {number} [immediateCloseBurst] Burst capacity for immediate close rate limiter
* @property {ArrayBufferView} [resetTokenSecret] The reset token secret
* @property {bigint|number} [retryTokenExpiration] The retry token expiration
* @property {number} [rxDiagnosticLoss] The receive diagnostic loss probability (range 0.0-1.0)
@@ -3997,10 +4003,16 @@ class QuicEndpoint {
tokenExpiration,
maxConnectionsPerHost = 100,
maxConnectionsTotal = 10_000,
maxStatelessResetsPerHost,
disableStatelessReset,
addressLRUSize,
maxRetries,
retryRate,
retryBurst,
statelessResetRate,
statelessResetBurst,
versionNegotiationRate,
versionNegotiationBurst,
immediateCloseRate,
immediateCloseBurst,
rxDiagnosticLoss,
txDiagnosticLoss,
udpReceiveBufferSize,
@@ -4034,10 +4046,16 @@ class QuicEndpoint {
// Connection limits are set on the state buffer, not passed to C++.
maxConnectionsPerHost,
maxConnectionsTotal,
maxStatelessResetsPerHost,
disableStatelessReset,
addressLRUSize,
maxRetries,
retryRate,
retryBurst,
statelessResetRate,
statelessResetBurst,
versionNegotiationRate,
versionNegotiationBurst,
immediateCloseRate,
immediateCloseBurst,
rxDiagnosticLoss,
txDiagnosticLoss,
udpReceiveBufferSize,
+48
View File
@@ -60,9 +60,13 @@ const {
IDX_STATS_ENDPOINT_CLIENT_SESSIONS,
IDX_STATS_ENDPOINT_SERVER_BUSY_COUNT,
IDX_STATS_ENDPOINT_RETRY_COUNT,
IDX_STATS_ENDPOINT_RETRY_RATE_LIMITED,
IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_COUNT,
IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_RATE_LIMITED,
IDX_STATS_ENDPOINT_STATELESS_RESET_COUNT,
IDX_STATS_ENDPOINT_STATELESS_RESET_RATE_LIMITED,
IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_COUNT,
IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_RATE_LIMITED,
IDX_STATS_SESSION_CREATED_AT,
IDX_STATS_SESSION_DESTROYED_AT,
@@ -123,9 +127,13 @@ assert(IDX_STATS_ENDPOINT_SERVER_SESSIONS !== undefined);
assert(IDX_STATS_ENDPOINT_CLIENT_SESSIONS !== undefined);
assert(IDX_STATS_ENDPOINT_SERVER_BUSY_COUNT !== undefined);
assert(IDX_STATS_ENDPOINT_RETRY_COUNT !== undefined);
assert(IDX_STATS_ENDPOINT_RETRY_RATE_LIMITED !== undefined);
assert(IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_COUNT !== undefined);
assert(IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_RATE_LIMITED !== undefined);
assert(IDX_STATS_ENDPOINT_STATELESS_RESET_COUNT !== undefined);
assert(IDX_STATS_ENDPOINT_STATELESS_RESET_RATE_LIMITED !== undefined);
assert(IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_COUNT !== undefined);
assert(IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_RATE_LIMITED !== undefined);
assert(IDX_STATS_SESSION_CREATED_AT !== undefined);
assert(IDX_STATS_SESSION_DESTROYED_AT !== undefined);
assert(IDX_STATS_SESSION_CLOSING_AT !== undefined);
@@ -280,24 +288,48 @@ class QuicEndpointStats {
return this.#handle[IDX_STATS_ENDPOINT_RETRY_COUNT];
}
/** @type {bigint} */
get retryRateLimited() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_RETRY_RATE_LIMITED];
}
/** @type {bigint} */
get versionNegotiationCount() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_COUNT];
}
/** @type {bigint} */
get versionNegotiationRateLimited() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_VERSION_NEGOTIATION_RATE_LIMITED];
}
/** @type {bigint} */
get statelessResetCount() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_STATELESS_RESET_COUNT];
}
/** @type {bigint} */
get statelessResetRateLimited() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_STATELESS_RESET_RATE_LIMITED];
}
/** @type {bigint} */
get immediateCloseCount() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_COUNT];
}
/** @type {bigint} */
get immediateCloseRateLimited() {
assertIsQuicEndpointStats(this);
return this.#handle[IDX_STATS_ENDPOINT_IMMEDIATE_CLOSE_RATE_LIMITED];
}
toString() {
return JSONStringify(this.toJSON());
}
@@ -315,9 +347,13 @@ class QuicEndpointStats {
clientSessions,
serverBusyCount,
retryCount,
retryRateLimited,
versionNegotiationCount,
versionNegotiationRateLimited,
statelessResetCount,
statelessResetRateLimited,
immediateCloseCount,
immediateCloseRateLimited,
} = this;
return {
__proto__: null,
@@ -334,9 +370,13 @@ class QuicEndpointStats {
clientSessions: `${clientSessions}`,
serverBusyCount: `${serverBusyCount}`,
retryCount: `${retryCount}`,
retryRateLimited: `${retryRateLimited}`,
versionNegotiationCount: `${versionNegotiationCount}`,
versionNegotiationRateLimited: `${versionNegotiationRateLimited}`,
statelessResetCount: `${statelessResetCount}`,
statelessResetRateLimited: `${statelessResetRateLimited}`,
immediateCloseCount: `${immediateCloseCount}`,
immediateCloseRateLimited: `${immediateCloseRateLimited}`,
};
}
@@ -363,9 +403,13 @@ class QuicEndpointStats {
clientSessions,
serverBusyCount,
retryCount,
retryRateLimited,
versionNegotiationCount,
versionNegotiationRateLimited,
statelessResetCount,
statelessResetRateLimited,
immediateCloseCount,
immediateCloseRateLimited,
} = this;
return `QuicEndpointStats ${inspect({
@@ -380,9 +424,13 @@ class QuicEndpointStats {
clientSessions,
serverBusyCount,
retryCount,
retryRateLimited,
versionNegotiationCount,
versionNegotiationRateLimited,
statelessResetCount,
statelessResetRateLimited,
immediateCloseCount,
immediateCloseRateLimited,
}, opts)}`;
}
+1
View File
@@ -452,6 +452,7 @@
'test/cctest/test_quic_cid.cc',
'test/cctest/test_quic_error.cc',
'test/cctest/test_quic_preferredaddress.cc',
'test/cctest/test_quic_tokenbucket.cc',
'test/cctest/test_quic_tokens.cc',
],
'node_cctest_inspector_sources': [
+8 -2
View File
@@ -117,8 +117,14 @@ class SessionManager;
V(idle_timeout, "idleTimeout") \
V(max_idle_timeout, "maxIdleTimeout") \
V(max_payload_size, "maxPayloadSize") \
V(max_retries, "maxRetries") \
V(max_stateless_resets, "maxStatelessResetsPerHost") \
V(retry_rate, "retryRate") \
V(retry_burst, "retryBurst") \
V(stateless_reset_rate, "statelessResetRate") \
V(stateless_reset_burst, "statelessResetBurst") \
V(version_negotiation_rate, "versionNegotiationRate") \
V(version_negotiation_burst, "versionNegotiationBurst") \
V(immediate_close_rate, "immediateCloseRate") \
V(immediate_close_burst, "immediateCloseBurst") \
V(max_stream_window, "maxStreamWindow") \
V(max_window, "maxWindow") \
V(min_version, "minVersion") \
+18
View File
@@ -360,6 +360,24 @@ constexpr auto kSocketAddressInfoTimeout = 60 * NGTCP2_SECONDS;
constexpr size_t kMaxVectorCount = 16;
constexpr stream_id kMaxStreamId = std::numeric_limits<stream_id>::max();
// A token bucket rate limiter using lazy refill. No timer needed — tokens
// are computed on demand from the elapsed time since the last check.
// Used to cap the total rate of stateless responses (retry, reset,
// version negotiation, immediate close) regardless of source address,
// preventing spoofed-source floods from bypassing per-host limits.
struct TokenBucket final {
double rate; // tokens per second (refill rate)
double burst; // maximum tokens (bucket capacity)
double tokens; // current token count
uint64_t last_ts; // last refill timestamp (nanoseconds, uv_hrtime)
TokenBucket(double rate, double burst);
// Try to consume one token. Refills based on elapsed time, then
// attempts to consume. Returns true if the request is allowed.
bool consume();
};
class DebugIndentScope final {
public:
inline DebugIndentScope() { ++indent_; }
+83 -82
View File
@@ -73,9 +73,13 @@ namespace quic {
V(CLIENT_SESSIONS, client_sessions) \
V(SERVER_BUSY_COUNT, server_busy_count) \
V(RETRY_COUNT, retry_count) \
V(RETRY_RATE_LIMITED, retry_rate_limited) \
V(VERSION_NEGOTIATION_COUNT, version_negotiation_count) \
V(VERSION_NEGOTIATION_RATE_LIMITED, version_negotiation_rate_limited) \
V(STATELESS_RESET_COUNT, stateless_reset_count) \
V(IMMEDIATE_CLOSE_COUNT, immediate_close_count)
V(STATELESS_RESET_RATE_LIMITED, stateless_reset_rate_limited) \
V(IMMEDIATE_CLOSE_COUNT, immediate_close_count) \
V(IMMEDIATE_CLOSE_RATE_LIMITED, immediate_close_rate_limited)
struct Endpoint::State {
#define V(_, name, type) type name;
@@ -85,6 +89,23 @@ struct Endpoint::State {
STAT_STRUCT(Endpoint, ENDPOINT)
TokenBucket::TokenBucket(double rate, double burst)
: rate(rate), burst(burst), tokens(burst), last_ts(uv_hrtime()) {}
// Try to consume one token. Refills based on elapsed time, then
// attempts to consume. Returns true if the request is allowed.
bool TokenBucket::consume() {
uint64_t now = uv_hrtime();
double elapsed = static_cast<double>(now - last_ts) / 1e9; // seconds
last_ts = now;
tokens = std::min(burst, tokens + elapsed * rate);
if (tokens >= 1.0) {
tokens -= 1.0;
return true;
}
return false;
}
// ============================================================================
// Endpoint::Options
namespace {
@@ -97,6 +118,7 @@ bool is_diagnostic_packet_loss(double probability) {
CHECK(ncrypto::CSPRNG(&c, 1));
return (static_cast<double>(c) / 255) < probability;
}
#endif // DEBUG
template <typename Opt, double Opt::*member>
bool SetOption(Environment* env,
@@ -106,18 +128,24 @@ bool SetOption(Environment* env,
Local<Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
Local<Number> num;
if (!value->ToNumber(env->context()).ToLocal(&num)) {
if (!value->IsNumber()) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be a number", nameStr);
return false;
}
options->*member = num->Value();
Local<Number> num = value.As<Number>();
double dbl = num->Value();
if (dbl < 0) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be a non-negative number", nameStr);
return false;
}
options->*member = dbl;
}
return true;
}
#endif // DEBUG
template <typename Opt, uint8_t Opt::*member>
bool SetOption(Environment* env,
@@ -133,15 +161,15 @@ bool SetOption(Environment* env,
env, "The %s option must be an uint8", nameStr);
return false;
}
Local<Uint32> num;
if (!value->ToUint32(env->context()).ToLocal(&num) ||
num->Value() > std::numeric_limits<uint8_t>::max()) {
Local<Uint32> num = value.As<Uint32>();
uint32_t val = num->Value();
if (val > std::numeric_limits<uint8_t>::max()) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be an uint8", nameStr);
return false;
}
options->*member = num->Value();
options->*member = val;
}
return true;
}
@@ -195,9 +223,12 @@ Maybe<Endpoint::Options> Endpoint::Options::From(Environment* env,
env, &options, params, state.name##_string())
if (!SET(retry_token_expiration) || !SET(token_expiration) ||
!SET(max_stateless_resets) || !SET(address_lru_size) ||
!SET(max_retries) || !SET(validate_address) ||
!SET(address_lru_size) || !SET(validate_address) ||
!SET(disable_stateless_reset) || !SET(ipv6_only) || !SET(reuse_port) ||
!SET(retry_rate) || !SET(retry_burst) || !SET(stateless_reset_rate) ||
!SET(stateless_reset_burst) || !SET(version_negotiation_rate) ||
!SET(version_negotiation_burst) || !SET(immediate_close_rate) ||
!SET(immediate_close_burst) ||
#ifdef DEBUG
!SET(rx_loss) || !SET(tx_loss) ||
#endif
@@ -251,10 +282,21 @@ std::string Endpoint::Options::ToString() const {
" seconds";
res += prefix + "token expiration: " + std::to_string(token_expiration) +
" seconds";
res +=
prefix + "max stateless resets: " + std::to_string(max_stateless_resets);
res += prefix + "address lru size: " + std::to_string(address_lru_size);
res += prefix + "max retries: " + std::to_string(max_retries);
res += prefix + "retry rate: " + std::to_string(retry_rate) + "/s";
res += prefix + "retry burst: " + std::to_string(retry_burst);
res += prefix +
"stateless reset rate: " + std::to_string(stateless_reset_rate) + "/s";
res += prefix +
"stateless reset burst: " + std::to_string(stateless_reset_burst);
res += prefix + "version negotiation rate: " +
std::to_string(version_negotiation_rate) + "/s";
res += prefix + "version negotiation burst: " +
std::to_string(version_negotiation_burst);
res += prefix +
"immediate close rate: " + std::to_string(immediate_close_rate) + "/s";
res += prefix +
"immediate close burst: " + std::to_string(immediate_close_burst);
res += prefix + "validate address: " + boolToString(validate_address);
res += prefix +
"disable stateless reset: " + boolToString(disable_stateless_reset);
@@ -580,8 +622,6 @@ void Endpoint::InitPerContext(Realm* realm, Local<Object> target) {
#undef V
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_SOCKETADDRESS_LRU_SIZE);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_STATELESS_RESETS);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_RETRY_LIMIT);
static constexpr auto DEFAULT_RETRYTOKEN_EXPIRATION =
RetryToken::QUIC_DEFAULT_RETRYTOKEN_EXPIRATION / NGTCP2_SECONDS;
@@ -643,7 +683,14 @@ Endpoint::Endpoint(Environment* env,
HandleScope scope(this->env()->isolate());
Destroy();
}),
addr_validation_lru_(options_.address_lru_size) {
addr_validation_lru_(options_.address_lru_size),
retry_bucket_(options_.retry_rate, options_.retry_burst),
stateless_reset_bucket_(options_.stateless_reset_rate,
options_.stateless_reset_burst),
version_negotiation_bucket_(options_.version_negotiation_rate,
options_.version_negotiation_burst),
immediate_close_bucket_(options_.immediate_close_rate,
options_.immediate_close_burst) {
MakeWeak();
udp_.Unref();
idle_timer_.Unref();
@@ -964,55 +1011,31 @@ void Endpoint::SendBatch(Packet::Ptr* packets, size_t count) {
}
void Endpoint::SendRetry(const PathDescriptor& options) {
// Generating and sending retry packets does consume some system resources,
// and it is possible for a malicious peer to trigger sending a large number
// of retry packets, resulting in a potential DOS vector. To help ward that
// off, we track how many retry packets we send to a particular host and
// enforce limits. Note that since we are using an LRU cache these limits
// aren't strict. If a retry is sent, we increment the retry_count statistic
// to give application code a means of detecting and responding to abuse on
// its own. What this count does not give is the rate of retry, so it is still
// somewhat limited.
Debug(this, "Sending retry on path %s", options);
auto info = addr_validation_lru_.Upsert(options.remote_address);
if (++(info->retry_count) <= options_.max_retries) {
auto packet =
Packet::CreateRetryPacket(*this, options, options_.token_secret);
if (packet) {
STAT_INCREMENT(Stats, retry_count);
Send(std::move(packet));
}
if (!retry_bucket_.consume()) {
Debug(this, "Retry rate limit exceeded (global)");
STAT_INCREMENT(Stats, retry_rate_limited);
return;
}
// If creating the retry is unsuccessful, we just drop things on the floor.
// It's not worth committing any further resources to this one packet. We
// might want to log the failure at some point tho.
auto packet =
Packet::CreateRetryPacket(*this, options, options_.token_secret);
if (packet) {
STAT_INCREMENT(Stats, retry_count);
Send(std::move(packet));
}
}
void Endpoint::SendVersionNegotiation(const PathDescriptor& options) {
Debug(this, "Sending version negotiation on path %s", options);
// A malicious peer can trivially force version negotiation packets by
// sending packets with unsupported QUIC versions, potentially from
// spoofed source addresses. Rate-limit per remote host to prevent
// amplification attacks.
const auto exceeds_limits = [&] {
SocketAddressInfoTraits::Type* counts =
addr_validation_lru_.Peek(options.remote_address);
auto count = counts != nullptr ? counts->version_negotiation_count : 0;
return count >= kMaxVersionNegotiations;
};
if (exceeds_limits()) {
Debug(this,
"Version negotiation rate limit exceeded for %s",
options.remote_address);
if (!version_negotiation_bucket_.consume()) {
Debug(this, "Version negotiation rate limit exceeded (global)");
STAT_INCREMENT(Stats, version_negotiation_rate_limited);
return;
}
auto packet = Packet::CreateVersionNegotiationPacket(*this, options);
if (packet) {
addr_validation_lru_.Upsert(options.remote_address)
->version_negotiation_count++;
STAT_INCREMENT(Stats, version_negotiation_count);
Send(std::move(packet));
}
@@ -1028,17 +1051,9 @@ bool Endpoint::SendStatelessReset(const PathDescriptor& options,
options,
source_len);
const auto exceeds_limits = [&] {
SocketAddressInfoTraits::Type* counts =
addr_validation_lru_.Peek(options.remote_address);
auto count = counts != nullptr ? counts->reset_count : 0;
return count >= options_.max_stateless_resets;
};
// Per the QUIC spec, we need to protect against sending too many stateless
// reset tokens to an endpoint to prevent endless looping.
if (exceeds_limits()) {
Debug(this, "Stateless reset rate limit exceeded");
if (!stateless_reset_bucket_.consume()) {
Debug(this, "Stateless reset rate limit exceeded (global)");
STAT_INCREMENT(Stats, stateless_reset_rate_limited);
return false;
}
@@ -1047,7 +1062,6 @@ bool Endpoint::SendStatelessReset(const PathDescriptor& options,
if (packet) {
Debug(this, "Sending stateless reset packet (%zu bytes)", packet->length());
addr_validation_lru_.Upsert(options.remote_address)->reset_count++;
STAT_INCREMENT(Stats, stateless_reset_count);
Send(std::move(packet));
return true;
@@ -1062,28 +1076,15 @@ void Endpoint::SendImmediateConnectionClose(const PathDescriptor& options,
"Sending immediate connection close on path %s with reason %s",
options,
reason);
// A malicious peer can trigger immediate connection close packets by
// sending Initial packets with invalid tokens or when the server is
// busy. Rate-limit per remote host to prevent amplification attacks.
const auto exceeds_limits = [&] {
SocketAddressInfoTraits::Type* counts =
addr_validation_lru_.Peek(options.remote_address);
auto count = counts != nullptr ? counts->immediate_close_count : 0;
return count >= kMaxImmediateCloses;
};
if (exceeds_limits()) {
Debug(this,
"Immediate connection close rate limit exceeded for %s",
options.remote_address);
if (!immediate_close_bucket_.consume()) {
Debug(this, "Immediate connection close rate limit exceeded (global)");
STAT_INCREMENT(Stats, immediate_close_rate_limited);
return;
}
auto packet =
Packet::CreateImmediateConnectionClosePacket(*this, options, reason);
if (packet) {
addr_validation_lru_.Upsert(options.remote_address)
->immediate_close_count++;
STAT_INCREMENT(Stats, immediate_close_count);
Send(std::move(packet));
}
+36 -57
View File
@@ -29,37 +29,20 @@ class Endpoint final : public AsyncWrap, public Packet::Listener {
// The socket address LRU is used for tracking validated remote addresses.
static constexpr uint64_t DEFAULT_MAX_SOCKETADDRESS_LRU_SIZE = 1024;
// The max stateless resets is the maximum number of stateless reset packets
// that the Endpoint will generate for a given remote host within a window of
// time (while tracking that host in the socket address LRU). This is not
// mandated by QUIC, and the limit is arbitrary. We can set it to whatever
// we'd like. The purpose is to prevent a malicious peer from intentionally
// triggering generation of a large number of stateless resets. Once the
// limit is reached, packets that would have otherwise triggered generation
// of a stateless reset will simply be dropped instead.
static constexpr uint64_t DEFAULT_MAX_STATELESS_RESETS = 10;
// Similar to stateless resets, the max retry limit is the maximum number of
// retry packets that the Endpoint will generate for a given remote host
// within a window of time (while tracking that host in the socket address
// LRU). This is not mandated by QUIC, and the limit is arbitrary. We can set
// it to whatever we'd like. The purpose is to prevent a malicious peer from
// intentionally triggering generation of a large number of retries.
static constexpr uint64_t DEFAULT_MAX_RETRY_LIMIT = 10;
// Maximum number of version negotiation packets that will be sent to a
// given remote host within the LRU tracking window. Version negotiation
// packets are cheap to generate but can be used as an amplification
// vector with spoofed source addresses.
// TODO(@jasnell): Consider making this configurable via Endpoint::Options.
static constexpr uint64_t kMaxVersionNegotiations = 10;
// Maximum number of immediate connection close packets that will be sent
// to a given remote host within the LRU tracking window. These are sent
// when the server is busy or a token is invalid — a malicious peer could
// trigger a large number of them.
// TODO(@jasnell): Consider making this configurable via Endpoint::Options.
static constexpr uint64_t kMaxImmediateCloses = 10;
// Default rate limits for stateless responses. These are global token
// bucket limits that cap the total rate of each response type regardless
// of source address. This prevents spoofed-source floods from bypassing
// per-host limits (which are keyed by source IP and trivially defeated
// by rotating spoofed addresses). The rate is in responses per second
// and the burst is the maximum tokens the bucket can hold.
static constexpr double DEFAULT_RETRY_RATE = 100;
static constexpr double DEFAULT_RETRY_BURST = 200;
static constexpr double DEFAULT_STATELESS_RESET_RATE = 100;
static constexpr double DEFAULT_STATELESS_RESET_BURST = 200;
static constexpr double DEFAULT_VERSION_NEGOTIATION_RATE = 100;
static constexpr double DEFAULT_VERSION_NEGOTIATION_BURST = 200;
static constexpr double DEFAULT_IMMEDIATE_CLOSE_RATE = 100;
static constexpr double DEFAULT_IMMEDIATE_CLOSE_BURST = 200;
// Endpoint configuration options
struct Options final : public MemoryRetainer {
@@ -83,30 +66,22 @@ class Endpoint final : public AsyncWrap, public Packet::Listener {
uint64_t token_expiration =
RegularToken::QUIC_DEFAULT_REGULARTOKEN_EXPIRATION / NGTCP2_SECONDS;
// A stateless reset in QUIC is a discrete mechanism that one endpoint can
// use to communicate to a peer that it has lost whatever state it
// previously held about a session. Because generating a stateless reset
// consumes resources (even very modestly), they can be a DOS vector in
// which a malicious peer intentionally sends a large number of stateless
// reset eliciting packets. To protect against that risk, we limit the
// number of stateless resets that may be generated for a given remote host
// within a window of time. This is not mandated by QUIC, and the limit is
// arbitrary. We can set it to whatever we'd like.
uint64_t max_stateless_resets = DEFAULT_MAX_STATELESS_RESETS;
// For tracking the number of connections per host, the number of stateless
// resets that have been sent, and tracking the path verification status of
// a remote host, we maintain an LRU cache of the most recently seen hosts.
// The address_lru_size parameter determines the size of that cache. The
// default is set modestly at 10 times the default max connections per host.
// For tracking the path verification status of remote hosts, we maintain
// an LRU cache of the most recently seen hosts.
uint64_t address_lru_size = DEFAULT_MAX_SOCKETADDRESS_LRU_SIZE;
// Similar to stateless resets, we enforce a limit on the number of retry
// packets that can be generated and sent for a remote host. Generating
// retry packets consumes a modest amount of resources and it's fairly
// trivial for a malicious peer to trigger generation of a large number of
// retries, so limiting them helps prevent a DOS vector.
uint64_t max_retries = DEFAULT_MAX_RETRY_LIMIT;
// Global token bucket rate limits for stateless responses. These cap
// the total rate of each response type regardless of source address,
// preventing spoofed-source floods. Rate is in responses per second,
// burst is the maximum number of responses that can be sent in a burst.
double retry_rate = DEFAULT_RETRY_RATE;
double retry_burst = DEFAULT_RETRY_BURST;
double stateless_reset_rate = DEFAULT_STATELESS_RESET_RATE;
double stateless_reset_burst = DEFAULT_STATELESS_RESET_BURST;
double version_negotiation_rate = DEFAULT_VERSION_NEGOTIATION_RATE;
double version_negotiation_burst = DEFAULT_VERSION_NEGOTIATION_BURST;
double immediate_close_rate = DEFAULT_IMMEDIATE_CLOSE_RATE;
double immediate_close_burst = DEFAULT_IMMEDIATE_CLOSE_BURST;
// The validate_address parameter instructs the Endpoint to perform explicit
// address validation using retry tokens. This is strongly recommended and
@@ -475,10 +450,6 @@ class Endpoint final : public AsyncWrap, public Packet::Listener {
struct SocketAddressInfoTraits final {
struct Type final {
size_t reset_count;
size_t retry_count;
size_t version_negotiation_count;
size_t immediate_close_count;
uint64_t timestamp;
bool validated;
};
@@ -489,6 +460,14 @@ class Endpoint final : public AsyncWrap, public Packet::Listener {
SocketAddressLRU<SocketAddressInfoTraits> addr_validation_lru_;
// Global token buckets for stateless response rate limiting.
// These cap the total server-wide rate of each response type,
// regardless of source address.
TokenBucket retry_bucket_;
TokenBucket stateless_reset_bucket_;
TokenBucket version_negotiation_bucket_;
TokenBucket immediate_close_bucket_;
// Per-IP connection counts for maxConnectionsPerHost enforcement.
// Only populated when max_connections_per_host > 0. Entries are
// added in AddSession and removed when the count reaches 0 in
+77
View File
@@ -0,0 +1,77 @@
#if HAVE_OPENSSL && HAVE_QUIC
#include "quic/guard.h"
#ifndef OPENSSL_NO_QUIC
#include <env-inl.h>
#include <gtest/gtest.h>
#include <quic/defs.h>
#include <uv.h>
namespace node::quic {
namespace {
TEST(QuicTokenBucket, AllowsBurst) {
TokenBucket bucket(10, 5); // 10/sec rate, burst of 5
// Should allow up to burst count immediately
for (int i = 0; i < 5; i++) {
EXPECT_TRUE(bucket.consume()) << "consume " << i << " should succeed";
}
// Bucket should be empty now
EXPECT_FALSE(bucket.consume());
}
TEST(QuicTokenBucket, RefillsOverTime) {
TokenBucket bucket(1000, 1); // 1000/sec rate, burst of 1
// Drain the bucket
EXPECT_TRUE(bucket.consume());
EXPECT_FALSE(bucket.consume());
// Sleep 2ms — at 1000/sec that's ~2 tokens, but burst is 1
uv_sleep(2);
// Should have refilled to at least 1 (capped by burst)
EXPECT_TRUE(bucket.consume());
}
TEST(QuicTokenBucket, BurstCapacity) {
TokenBucket bucket(10000, 3); // high rate, burst of 3
// Drain
EXPECT_TRUE(bucket.consume());
EXPECT_TRUE(bucket.consume());
EXPECT_TRUE(bucket.consume());
EXPECT_FALSE(bucket.consume());
// Sleep enough to fully refill
uv_sleep(10);
// Should be capped at burst (3), not more
int count = 0;
while (bucket.consume()) count++;
EXPECT_EQ(count, 3);
}
TEST(QuicTokenBucket, ZeroRateAlwaysDenies) {
TokenBucket bucket(0, 0);
EXPECT_FALSE(bucket.consume());
EXPECT_FALSE(bucket.consume());
}
TEST(QuicTokenBucket, HighRateAllowsRapidConsume) {
TokenBucket bucket(1000000, 1000); // 1M/sec, burst 1000
// Should be able to consume many quickly
int count = 0;
for (int i = 0; i < 1000; i++) {
if (bucket.consume()) count++;
}
EXPECT_EQ(count, 1000);
}
} // namespace
} // namespace node::quic
#endif // OPENSSL_NO_QUIC
#endif // HAVE_OPENSSL && HAVE_QUIC
@@ -52,13 +52,6 @@ const cases = [
],
invalid: [-1, 65536, 1.5, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'maxStatelessResetsPerHost',
valid: [
1, 10, 100, 1000, 10000, 10000n,
],
invalid: [-1, -1n, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'addressLRUSize',
valid: [
@@ -67,11 +60,44 @@ const cases = [
invalid: [-1, -1n, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'maxRetries',
valid: [
1, 10, 100, 1000, 10000, 10000n,
],
invalid: [-1, -1n, 'a', null, false, true, {}, [], () => {}]
key: 'retryRate',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'retryBurst',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'statelessResetRate',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'statelessResetBurst',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'versionNegotiationRate',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'versionNegotiationBurst',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'immediateCloseRate',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'immediateCloseBurst',
valid: [0, 1, 10, 100.5, 1000],
invalid: [-1, 'a', null, false, true, {}, [], () => {}]
},
{
key: 'validateAddress',
@@ -88,9 +88,13 @@ const {
strictEqual(typeof endpoint.stats.clientSessions, 'bigint');
strictEqual(typeof endpoint.stats.serverBusyCount, 'bigint');
strictEqual(typeof endpoint.stats.retryCount, 'bigint');
strictEqual(typeof endpoint.stats.retryRateLimited, 'bigint');
strictEqual(typeof endpoint.stats.versionNegotiationCount, 'bigint');
strictEqual(typeof endpoint.stats.versionNegotiationRateLimited, 'bigint');
strictEqual(typeof endpoint.stats.statelessResetCount, 'bigint');
strictEqual(typeof endpoint.stats.statelessResetRateLimited, 'bigint');
strictEqual(typeof endpoint.stats.immediateCloseCount, 'bigint');
strictEqual(typeof endpoint.stats.immediateCloseRateLimited, 'bigint');
deepStrictEqual(Object.keys(endpoint.stats.toJSON()), [
'connected',
@@ -104,9 +108,13 @@ const {
'clientSessions',
'serverBusyCount',
'retryCount',
'retryRateLimited',
'versionNegotiationCount',
'versionNegotiationRateLimited',
'statelessResetCount',
'statelessResetRateLimited',
'immediateCloseCount',
'immediateCloseRateLimited',
]);
strictEqual(typeof inspect(endpoint.stats), 'string');
}
+9 -9
View File
@@ -6,8 +6,7 @@
// session closes.
// When disableStatelessReset is true, the server does NOT
// send a stateless reset.
// maxStatelessResetsPerHost rate limits the number of resets
// sent to a single remote address.
// Global token bucket rate limits the total number of resets.
import { hasQuic, skip, mustCall } from '../common/index.mjs';
import assert from 'node:assert';
@@ -138,9 +137,8 @@ const encoder = new TextEncoder();
await serverEndpoint.close();
}
// maxStatelessResetsPerHost rate limits resets per remote address.
// The LRU tracks resets per IP+port, so both sessions must share a
// client endpoint to have the same source address.
// Global token bucket rate limits stateless resets.
// With burst=1 and rate=0, only one reset can be sent.
{
let sessionCount = 0;
const serverDestroyed1 = Promise.withResolvers();
@@ -161,12 +159,12 @@ const encoder = new TextEncoder();
deferred.resolve();
});
}, 2), {
endpoint: { maxStatelessResetsPerHost: 1 },
endpoint: { statelessResetBurst: 1, statelessResetRate: 0 },
onerror(err) { ok(err); },
});
// Both clients share an endpoint so the server sees the same
// remote IP+port for both, making the rate limiter apply.
// The global token bucket rate limiter applies regardless of
// client source address.
const { QuicEndpoint } = await import('node:quic');
const clientEndpoint = new QuicEndpoint();
@@ -215,7 +213,7 @@ const encoder = new TextEncoder();
await serverDestroyed2.promise;
// Send a packet — the server would normally send a stateless reset,
// but the rate limit (1 per host) is already exhausted.
// but the global rate limit (burst of 1) is already exhausted.
// eslint-disable-next-line no-unused-vars
const s2b = await client2.createBidirectionalStream({
body: encoder.encode('after destroy 2'),
@@ -226,6 +224,8 @@ const encoder = new TextEncoder();
strictEqual(serverEndpoint.stats.statelessResetCount, 1n,
'Second reset should have been rate-limited');
ok(serverEndpoint.stats.statelessResetRateLimited > 0n,
'Rate-limited counter should be non-zero');
await clientEndpoint.close();
await serverEndpoint.close();