Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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].*;}
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 into `out`, at most `received` octets long.////// §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];}
/// §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;}
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}));}