// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Stateless reset: RFC 9000 §10.3. //! //! "A stateless reset is provided as an option of last resort for an endpoint //! that does not have access to the state of a connection. A crash or outage //! might result in peers continuing to send data to an endpoint that is //! unable to properly continue the connection." //! //! It is the one message in QUIC an endpoint can send about a connection it //! has entirely forgotten, and everything strange about it follows from that. //! There is no packet number, no encryption and no frame: a server that has //! lost its state has no keys to encrypt with and no numbers to count from. //! What it has is a static key and the connection ID off the packet that just //! arrived, and from those two it can recompute a sixteen-octet value that //! the peer will recognise and nobody else can guess. //! //! ## Why it looks like nothing in particular //! //! §10.3: "this design ensures that a Stateless Reset is — to the extent //! possible — indistinguishable from a regular packet with a short header." //! Two fixed bits, then random octets, then the token. An observer cannot //! tell a reset from ordinary traffic, which matters because the alternative //! is a signal anyone on the path can use to tell that a connection has just //! been torn down, and by whom. //! //! The same reasoning runs the other way and is easy to miss: §10.3 asks an //! endpoint to make its *own* packets at least 22 octets longer than the //! connection ID length it requires, "so that any Stateless Reset sent by the //! peer is indistinguishable from a valid packet sent to the endpoint". The //! disguise only works if there is something to hide among. //! //! ## Why the token is derived rather than remembered //! //! §10.3.2: "stateless reset specifically exists to handle the case where //! state is lost, so [storing a random token per connection] is suboptimal." //! A static key and `HMAC(key, connection_id)` gives an endpoint the same //! answer after a crash as before it — and the same answer on every machine //! in a cluster, which is the other half of the problem. const std = @import("std"); const Hmac = std.crypto.auth.hmac.sha2.HmacSha256; /// §19.15: the token is a 128-bit value. pub const token_len = 16; /// §10.3: "for the Stateless Reset to appear as a valid QUIC packet, the /// Unpredictable Bits field needs to include at least 38 bits of data (or 5 /// bytes, less the two fixed bits)." Five octets plus the token. pub const min_len = 5 + token_len; /// §10.3: "the endpoint SHOULD ensure that all packets it sends are at least /// 22 bytes longer than the minimum connection ID length that it requests the /// peer to include in its packets." /// /// Which is a rule about ordinary packets, not about resets: a reset is only /// hidden if the traffic it hides among is at least as long. pub const cover_len = 22; /// The static key an endpoint derives all of its tokens from. pub const Key = [32]u8; /// §10.3.2: `HMAC(static_key, connection_id)`, truncated to sixteen octets. /// /// "An endpoint that loses state can use the same method to generate a valid /// stateless reset token. The connection ID comes from the packet that the /// endpoint receives." Which is the whole design: the only inputs are a key /// that survives a restart and a value the peer helpfully puts in every /// packet it sends. pub fn token(key: Key, connection_id: []const u8) [token_len]u8 { var mac: [Hmac.mac_length]u8 = undefined; var hmac: Hmac = .init(&key); hmac.update(connection_id); hmac.final(&mac); return mac[0..token_len].*; } test token { // The value an endpoint puts in the NEW_CONNECTION_ID frame for `id`... const key: Key = @splat(0x42); const id = [_]u8{ 0xde, 0xad, 0xbe, 0xef }; const issued = token(key, &id); // ...is the same value it can work out again after a restart, from nothing // but its key and the connection ID on an incoming packet. try testing.expectEqualSlices(u8, &issued, &token(key, &id)); } pub const Error = error{ /// The buffer offered was too small to hold a reset that could pass for a /// packet. NoSpace, }; /// Writes a stateless reset carrying `value` into `out`, in answer to a /// packet `received` octets long, and returns it. /// /// The reset is one octet shorter than `received`, or as long as `out` if /// that is shorter still: random octets with the two fixed bits of a short /// header, then the token. If that leaves fewer than `min_len` octets — too /// few to pass for a packet — nothing is written and the answer is `NoSpace`, /// and the caller sends nothing at all. /// /// §10.3: "an endpoint that sends a Stateless Reset in response to a packet /// that is 43 bytes or shorter SHOULD send a Stateless Reset that is one byte /// shorter than the packet it responds to." The reason is not politeness but /// §10.3.3's loop: two endpoints that each answered the other's reset with a /// reset would trade them forever, and a reset that must be strictly shorter /// than what provoked it cannot go round more than a few times. pub fn write(out: []u8, rng: std.Random, value: [token_len]u8, received: usize) Error![]u8 { // One octet shorter than what arrived, and never longer than what a // caller offered. A reset longer than the packet it answers is the thing // §10.3.3 forbids. const room = @min(out.len, received -| 1); if (room < min_len) return error.NoSpace; // §10.3: as long as there is room for, so that a reset is // indistinguishable from the ordinary traffic it hides among — capped at // what the caller can hold and at what the incoming packet allows. const len = room; rng.bytes(out[0 .. len - token_len]); // "Fixed Bits (2) = 1": the high bit clear marks a short header and the // next bit is QUIC's fixed bit, which every packet has set. Everything // else in the first octet is deliberately random. out[0] = (out[0] & 0x3f) | 0x40; @memcpy(out[len - token_len ..][0..token_len], &value); return out[0..len]; } test write { var prng: std.Random.DefaultPrng = .init(1); const value = token(@splat(0x42), &.{ 0xde, 0xad, 0xbe, 0xef }); // A 50-octet packet arrived for a connection this endpoint has forgotten. var out: [128]u8 = undefined; const reset = try write(&out, prng.random(), value, 50); // One octet shorter than what provoked it, with the token at the end. try testing.expectEqual(@as(usize, 49), reset.len); try testing.expectEqualSlices(u8, &value, reset[reset.len - token_len ..]); } /// §10.3.1: whether a datagram is a stateless reset for one of the tokens /// this endpoint is holding. /// /// "An endpoint detects a potential Stateless Reset using the trailing 16 /// bytes of the UDP datagram... The comparison MUST be performed when the /// first packet in an incoming datagram either cannot be associated with a /// connection or cannot be decrypted." /// /// Constant time, because §10.3.1 asks for it in as many words: "endpoints /// MUST perform the comparison without leaking information about the value of /// the token. For example, performing this comparison in constant time /// protects the value of individual stateless reset tokens from information /// leakage through timing side channels." A token that can be extracted a /// byte at a time by measurement is a way to tear down somebody else's /// connection. pub fn matches(datagram: []const u8, tokens: []const [token_len]u8) bool { if (datagram.len < min_len) return false; const trailing = datagram[datagram.len - token_len ..][0..token_len]; var found = false; for (tokens) |candidate| { // No early exit: every candidate is compared, so the time taken says // how many tokens are held and nothing about which one matched. // §10.3.1 explicitly permits that much leakage — "an endpoint is not // expected to protect information about... the number of valid // stateless reset tokens". found = std.crypto.timing_safe.eql([token_len]u8, candidate, trailing.*) or found; } return found; } test matches { // The peer handed over this token with the connection ID it issued... const value = token(@splat(0x42), &.{ 0xde, 0xad, 0xbe, 0xef }); var prng: std.Random.DefaultPrng = .init(1); var out: [64]u8 = undefined; const datagram = try write(&out, prng.random(), value, 50); // ...so a datagram that cannot be decrypted is checked against it. try testing.expect(matches(datagram, &.{value})); try testing.expect(!matches(datagram, &.{@as([token_len]u8, @splat(0))})); } const testing = std.testing; test "RFC 9000 10.3.2: the token is recomputed, not remembered" { // "An endpoint that loses state can use the same method to generate a // valid stateless reset token. The connection ID comes from the packet // that the endpoint receives." Which is the property that makes a // stateless reset possible at all: the endpoint answering has forgotten // everything except its own static key. const key: Key = @splat(0x42); const id = [_]u8{ 1, 2, 3, 4 }; const first = token(key, &id); const after_a_crash = token(key, &id); try testing.expectEqualSlices(u8, &first, &after_a_crash); // A different connection ID gives a different token, which is what makes // a token useless against any connection but its own — §10.3: "a // stateless reset token is specific to a connection ID." try testing.expect(!std.mem.eql(u8, &first, &token(key, &.{ 1, 2, 3, 5 }))); // And a different key gives a different token, which is what stops // anyone else minting one. try testing.expect(!std.mem.eql(u8, &first, &token(@splat(0x43), &id))); } test "RFC 9000 10.3: a reset is shorter than the packet that provoked it" { // "An endpoint that sends a Stateless Reset in response to a packet that // is 43 bytes or shorter SHOULD send a Stateless Reset that is one byte // shorter than the packet it responds to." §10.3.3 is the reason: two // endpoints that each answered a reset with a reset would trade them // forever, and strictly shrinking cannot. var rng_impl: std.Random.DefaultPrng = .init(7); const rng = rng_impl.random(); const value: [token_len]u8 = @splat(0xaa); var out: [1200]u8 = undefined; const reset = try write(&out, rng, value, 40); try testing.expectEqual(@as(usize, 39), reset.len); // §10.3's "Fixed Bits (2) = 1": a short header, with QUIC's fixed bit // set, so that it passes for ordinary traffic. try testing.expectEqual(@as(u8, 0), reset[0] & 0x80); try testing.expectEqual(@as(u8, 0x40), reset[0] & 0x40); // And the token is the last sixteen octets, which is the only part the // peer reads. try testing.expectEqualSlices(u8, &value, reset[reset.len - token_len ..]); // A packet too short to answer at all: a reset needs 21 octets to pass // for a packet, and one shorter than that would announce itself. try testing.expectError(error.NoSpace, write(&out, rng, value, min_len)); try testing.expectError(error.NoSpace, write(&out, rng, value, 4)); } test "RFC 9000 10.3: two resets running are not identical" { // "The remainder of the first byte and an arbitrary number of bytes // following it are set to values that SHOULD be indistinguishable from // random." Two resets that matched would be a signature, which is // exactly what the design is avoiding. var rng_impl: std.Random.DefaultPrng = .init(11); const rng = rng_impl.random(); const value: [token_len]u8 = @splat(0xbb); var first: [64]u8 = undefined; var second: [64]u8 = undefined; const a = try write(&first, rng, value, 60); const b = try write(&second, rng, value, 60); try testing.expectEqual(a.len, b.len); try testing.expect(!std.mem.eql(u8, a, b)); // The token is the part that is the same, because it is the part that // means something. try testing.expectEqualSlices(u8, a[a.len - token_len ..], b[b.len - token_len ..]); } test "RFC 9000 10.3.1: a reset is recognised by its last sixteen octets" { var rng_impl: std.Random.DefaultPrng = .init(13); const rng = rng_impl.random(); const mine: [token_len]u8 = @splat(0x11); const theirs: [token_len]u8 = @splat(0x22); var out: [64]u8 = undefined; const reset = try write(&out, rng, theirs, 60); try testing.expect(matches(reset, &.{theirs})); try testing.expect(matches(reset, &.{ mine, theirs })); try testing.expect(!matches(reset, &.{mine})); // §10.3.1: "an endpoint MUST NOT check for any stateless reset tokens // associated with connection IDs it has not used or for connection IDs // that have been retired" — which is the caller's business, and is why // this takes the list rather than owning one. try testing.expect(!matches(reset, &.{})); // Anything too short to be a reset is not one, whatever it ends with. try testing.expect(!matches(reset[0..10], &.{theirs})); } test "an ordinary packet is not mistaken for a reset" { // The comparison is over the trailing octets of the *datagram*, so a // packet that merely contains the token somewhere is not a reset. That is // not a formality: the token travels in a NEW_CONNECTION_ID frame, so a // packet carrying one contains it in the clear as far as this comparison // is concerned. const value: [token_len]u8 = @splat(0x33); var datagram: [64]u8 = @splat(0); @memcpy(datagram[10..][0..token_len], &value); try testing.expect(!matches(&datagram, &.{value})); }