// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Retry, and the tokens that make address validation stateless: RFC 9000 //! §8.1 and RFC 9001 §5.8. //! //! A server that answers an Initial packet is answering an address it has not //! checked. §8: "an endpoint MUST NOT send more than three times as many //! bytes as the number of bytes it has received" is the limit that makes that //! survivable, and Retry is how a server stops paying it: instead of //! completing a handshake with whoever sent the packet, it sends back a token //! and waits to see the token come back from the same address. Only then does //! it commit any state at all. //! //! ## Two things called a token, doing different jobs //! //! §8.1.2: a token in an Initial packet came either from a Retry packet in //! *this* connection attempt or from a NEW_TOKEN frame in an earlier one. The //! first proves the client is at the address it claims right now; the second //! lets a returning client skip the round trip altogether. §8.1.4 asks less //! of the first — tokens in Retry packets "SHOULD include information that //! allows the server to verify that the source IP address and port in client //! packets remain constant" — and more of the second, which "MUST include //! information that allows the server to verify that the client IP address //! has not changed". //! //! ## What the integrity tag is for, and what it is not //! //! §5.8 of RFC 9001 gives the Retry Integrity Tag "two properties: it allows //! the discarding of packets that have accidentally been corrupted by the //! network, and only an entity that observes an Initial packet can send a //! valid Retry packet." Both halves are worth reading precisely. The key is a //! published constant, so the tag is not a secret and authenticates nobody: //! what it proves is that whoever wrote the Retry knew the connection ID the //! client invented, which an off-path attacker does not. An on-path attacker //! knows it too, and §21.2 says so plainly. //! //! The token inside is the part with a real key, and that key is the server's //! alone — §8.1.4: "only the server requires access to the integrity //! protection key for tokens." const std = @import("std"); const Aes128Gcm = std.crypto.aead.aes_gcm.Aes128Gcm; const Hmac = std.crypto.auth.hmac.sha2.HmacSha256; const packet = @import("packet.zig"); /// §5.8: "the secret key, K, is 128 bits equal to /// 0xbe0c690b9f66575a1d766b54e368c84e." /// /// Published, and deliberately: the tag is a checksum with a fixed key, not a /// signature. The RFC gives the HKDF-Expand-Label derivation it came from so /// the constant can be checked rather than trusted. pub const integrity_key = [16]u8{ 0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e, }; /// §5.8: "the nonce, N, is 96 bits equal to 0x461599d35d632bf2239825bb." pub const integrity_nonce = [12]u8{ 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb, }; pub const tag_len = packet.retry_integrity_tag_len; pub const Error = error{ /// The buffer offered was too small. NoSpace, /// The tag did not match: a corrupted packet, or one written by somebody /// who had not seen the client's Initial. BadIntegrityTag, /// The token was not one this server issued, was issued for another /// address, or has expired. BadToken, }; /// §5.8's Retry Pseudo-Packet, which is what the tag covers. /// /// "The Retry Pseudo-Packet is not sent over the wire. It is computed by /// taking the transmitted Retry packet, removing the Retry Integrity Tag, and /// prepending the two following fields" — the length of the connection ID the /// client originally chose, and that connection ID. Which is the whole trick: /// the value the tag depends on is one that never appears in the packet, so /// only somebody who saw the client's Initial can produce it. fn pseudoPacket(out: []u8, original_destination: []const u8, retry_without_tag: []const u8) Error![]u8 { if (out.len < 1 + original_destination.len + retry_without_tag.len) return error.NoSpace; out[0] = @intCast(original_destination.len); @memcpy(out[1..][0..original_destination.len], original_destination); const at = 1 + original_destination.len; @memcpy(out[at..][0..retry_without_tag.len], retry_without_tag); return out[0 .. at + retry_without_tag.len]; } /// The largest Retry packet this will compute a tag over. /// /// A Retry arrives in a datagram, and §14 guarantees no path carries more /// than 1200 octets without path MTU discovery — so this is generous rather /// than tight. The bound exists because the pseudo-packet has to be /// assembled somewhere: `Aes128Gcm.encrypt` takes its associated data as one /// slice, so there is no feeding it in pieces. pub const max_retry_len = 2048; /// §5.8: the tag for a Retry packet, given the connection ID the client chose. /// /// `retry_without_tag` is the whole Retry packet up to where the tag goes, /// and `original_destination` is the Destination Connection ID of the /// client's first Initial. `NoSpace` means the pseudo-packet would not fit in /// the space set aside for it, which a connection ID within version 1's /// twenty octets and a packet within `max_retry_len` always do. pub fn integrityTag( original_destination: []const u8, retry_without_tag: []const u8, ) Error![tag_len]u8 { var buffer: [1 + packet.max_connection_id_len + max_retry_len]u8 = undefined; const pseudo = try pseudoPacket(&buffer, original_destination, retry_without_tag); var tag: [tag_len]u8 = undefined; // §5.8: "the plaintext, P, is empty" — the tag authenticates the // associated data and carries nothing. Aes128Gcm.encrypt(&.{}, &tag, &.{}, pseudo, integrity_nonce, integrity_key); return tag; } test integrityTag { // §A.4: the Retry answering §A.2's Initial, whose client chose // 0x8394c8f03e515708. The tag is the last sixteen octets of the packet, // and covers everything before them plus that connection ID. const original = [_]u8{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; const without_tag = [_]u8{ 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, }; const tag = try integrityTag(&original, &without_tag); try testing.expectEqualSlices(u8, &.{ 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba, }, &tag); } /// Builds a Retry packet: §17.2.5 of RFC 9000. /// /// `source` is the connection ID the server is choosing for itself, and /// §7.3 makes the client check it later against the /// `retry_source_connection_id` transport parameter — which is what stops an /// attacker injecting a Retry to steer the connection onto a connection ID of /// its choosing. /// /// `destination` is the client's Source Connection ID, `original_destination` /// the Destination Connection ID of the Initial being answered, which the tag /// covers and the packet does not carry, and `token` is what the client must /// return — normally from `Token.mint`. The packet is written into the front /// of `out` and returned, tag included. `NoSpace` means `out` is too small, /// or the packet too long for `integrityTag`. `destination` and `source` /// must each be at most 255 octets, the most a length octet can say. pub fn write( out: []u8, original_destination: []const u8, destination: []const u8, source: []const u8, token: []const u8, ) Error![]u8 { const needed = 1 + 4 + 1 + destination.len + 1 + source.len + token.len + tag_len; if (out.len < needed) return error.NoSpace; var at: usize = 0; // §17.2: long header, fixed bit, type 3, and then four bits §17.2.5 // calls "Unused" and requires a client to ignore. Setting them is // therefore free, and they are set the way RFC 9001's Appendix A.4 sets // them — all ones — because that is what makes the test below an // octet-for-octet comparison against a packet somebody else published // rather than a comparison of this code with itself. out[at] = 0xff; at += 1; std.mem.writeInt(u32, out[at..][0..4], packet.version_1, .big); at += 4; out[at] = @intCast(destination.len); at += 1; @memcpy(out[at..][0..destination.len], destination); at += destination.len; out[at] = @intCast(source.len); at += 1; @memcpy(out[at..][0..source.len], source); at += source.len; @memcpy(out[at..][0..token.len], token); at += token.len; const tag = try integrityTag(original_destination, out[0..at]); @memcpy(out[at..][0..tag_len], &tag); at += tag_len; return out[0..at]; } test write { // A server refusing to commit state until the client proves its address: // a token bound to that address, sent back in a Retry under a connection // ID of the server's own choosing. const client_chose = [_]u8{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; var token_buf: [Token.max_len]u8 = undefined; const token = try Token.mint(&token_buf, @splat(0x5a), "192.0.2.1:443", &client_chose, 1000); var out: [128]u8 = undefined; const retry = try write(&out, &client_chose, &.{ 1, 2, 3, 4 }, &.{ 5, 6, 7, 8 }, token); // It parses as a Retry carrying that token, and its tag checks out // against the connection ID the client chose. const header = try packet.parse(retry, 0); try testing.expectEqual(packet.Kind.retry, header.kind); try testing.expectEqualSlices(u8, token, header.token); try verify(retry, &client_chose); } /// Checks a Retry packet's integrity tag against the connection ID the client /// itself chose, which is the value an off-path attacker cannot know. /// /// `retry` is the whole Retry packet, tag included. §17.2.5.2: "a client MUST /// discard a Retry packet with a zero-length Retry Token field" as well as one /// whose tag does not verify, but only the tag is checked here: the token /// length, and every other field, is the caller's to look at. A packet too /// long for `integrityTag` to check is `NoSpace` rather than /// `BadIntegrityTag`; either way it is not one to act on. pub fn verify(retry: []const u8, original_destination: []const u8) Error!void { if (retry.len < tag_len) return error.BadIntegrityTag; const body = retry[0 .. retry.len - tag_len]; const expected = try integrityTag(original_destination, body); const actual = retry[retry.len - tag_len ..][0..tag_len]; // Constant time, because a comparison that stopped early would leak how // much of a forged tag was right. if (!std.crypto.timing_safe.eql([tag_len]u8, expected, actual.*)) { return error.BadIntegrityTag; } } test verify { // §A.4's Retry, as a client that sent §A.2's Initial receives it. const sent_to = [_]u8{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; const retry = [_]u8{ 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba, }; try verify(&retry, &sent_to); // Anyone who did not see that Initial could not have written it. try testing.expectError(error.BadIntegrityTag, verify(&retry, &.{ 1, 2, 3, 4 })); } /// A server's address validation token: §8.1.4. /// /// "There is no need for a single well-defined format for the token because /// the server that generates the token also consumes it." So this is one /// choice among many, and its shape is dictated by what §8.1.4 asks the token /// to prove: that the client is at the address the token was issued to, that /// it was issued recently, and that the server issued it at all. /// /// The address is opaque octets supplied by the caller. This library has /// never seen an address — a path is a number the caller chooses — so /// binding a token to one is something only the caller can do. What it hands /// in should be the client's IP and port; what this does is make it /// impossible to change them without the server noticing. pub const Token = struct { /// §8.1.4: "an address validation token MUST be difficult to guess... /// the token MUST be covered by integrity protection against /// modification or falsification by clients." /// /// A MAC over everything the server needs back, and the server keeps the /// key. The alternative §8.1.4 allows — remembering a random value per /// client — is the state Retry exists to avoid. pub const Key = [32]u8; /// The octets a Retry token occupies: the original connection ID, its /// length, when it was issued, and the MAC. pub const max_len = 1 + packet.max_connection_id_len + 8 + Hmac.mac_length; /// §8.1.4: "servers SHOULD ensure that tokens sent in Retry packets are /// only accepted for a short time, as they are returned immediately by /// clients." A window measured in seconds, because the client is /// expected to answer within a round trip and anything older is a replay. pub const lifetime_seconds: u64 = 10; /// Mints a token for `address`, remembering `original_destination` so the /// server can put it in its `original_destination_connection_id` /// transport parameter afterwards (§7.3). /// /// `now_seconds` is the time of issue, on whatever clock the server will /// later hand `open`. The token is written into the front of `out`, which /// `max_len` octets always suffices for, and returned. `NoSpace` means /// `out` is too small or `original_destination` is longer than twenty /// octets. pub fn mint( out: []u8, key: Key, address: []const u8, original_destination: []const u8, now_seconds: u64, ) Error![]u8 { if (original_destination.len > packet.max_connection_id_len) return error.NoSpace; const body_len = 1 + original_destination.len + 8; if (out.len < body_len + Hmac.mac_length) return error.NoSpace; out[0] = @intCast(original_destination.len); @memcpy(out[1..][0..original_destination.len], original_destination); std.mem.writeInt(u64, out[1 + original_destination.len ..][0..8], now_seconds, .big); // The address is covered by the MAC but not carried in the token: the // server sees it again on the packet that returns the token, so // sending it would be telling the client something it already knows // and giving an attacker one more thing to rewrite. var mac: [Hmac.mac_length]u8 = undefined; var hmac: Hmac = .init(&key); hmac.update(out[0..body_len]); hmac.update(address); hmac.final(&mac); @memcpy(out[body_len..][0..Hmac.mac_length], &mac); return out[0 .. body_len + Hmac.mac_length]; } test mint { const key: Key = @splat(0x5a); const client_chose = [_]u8{ 8, 7, 6, 5, 4, 3, 2, 1 }; var buf: [max_len]u8 = undefined; const token = try mint(&buf, key, "192.0.2.1:443", &client_chose, 1000); // What goes in the Retry; the address is in the MAC and not in here. try testing.expectEqual(@as(usize, 1 + client_chose.len + 8 + Hmac.mac_length), token.len); try testing.expectEqualSlices(u8, &client_chose, try open(token, key, "192.0.2.1:443", 1003)); } /// Checks a token and returns the connection ID the client originally /// chose, which §7.3 has the server echo back. /// /// The token must have been minted under `key` for the same `address`, at /// most `lifetime_seconds` before `now_seconds` and not after it; anything /// else is `BadToken`. The slice returned points into `token`. pub fn open( token: []const u8, key: Key, address: []const u8, now_seconds: u64, ) Error![]const u8 { if (token.len < 1 + 8 + Hmac.mac_length) return error.BadToken; const id_len = token[0]; if (id_len > packet.max_connection_id_len) return error.BadToken; const body_len = 1 + @as(usize, id_len) + 8; if (token.len != body_len + Hmac.mac_length) return error.BadToken; var mac: [Hmac.mac_length]u8 = undefined; var hmac: Hmac = .init(&key); hmac.update(token[0..body_len]); hmac.update(address); hmac.final(&mac); // Constant time: a client that could measure how much of a forged MAC // was correct could forge the rest of it. if (!std.crypto.timing_safe.eql([Hmac.mac_length]u8, mac, token[body_len..][0..Hmac.mac_length].*)) { return error.BadToken; } const issued = std.mem.readInt(u64, token[1 + @as(usize, id_len) ..][0..8], .big); // §8.1.4: "attackers could replay tokens to use servers as amplifiers // in DDoS attacks. To protect against such attacks, servers MUST // ensure that replay of tokens is prevented or limited." A short // window limits it; preventing it outright would need the server to // remember which tokens it has seen, which is the state this design // exists to avoid. if (now_seconds < issued) return error.BadToken; if (now_seconds - issued > lifetime_seconds) return error.BadToken; return token[1..][0..id_len]; } /// Whether `token` has the layout `mint` writes, whether or not it opens. /// /// §8.1.3 tells a server to tell its own Retry tokens from other tokens, /// because the answer to a bad one differs: a client that has had a Retry /// will not accept another, so a bad Retry token is closed with /// INVALID_TOKEN, while anything else is treated as no token at all. pub fn shaped(token: []const u8) bool { if (token.len < 1) return false; const id_len = token[0]; if (id_len > packet.max_connection_id_len) return false; return token.len == 1 + @as(usize, id_len) + 8 + Hmac.mac_length; } test shaped { const key: Key = @splat(0x5a); var buf: [max_len]u8 = undefined; const token = try mint(&buf, key, "192.0.2.1:443", &.{ 8, 7, 6, 5 }, 1000); try testing.expect(shaped(token)); // Under any key and at any age: the shape is all it looks at. try testing.expectError(error.BadToken, open(token, @splat(0x5b), "192.0.2.1:443", 1001)); try testing.expect(shaped(token)); try testing.expect(!shaped(token[0 .. token.len - 1])); try testing.expect(!shaped(&.{})); try testing.expect(!shaped("a token from somebody else")); } test open { const key: Key = @splat(0x5a); var buf: [max_len]u8 = undefined; const token = try mint(&buf, key, "192.0.2.1:443", &.{ 8, 7, 6, 5 }, 1000); // The Initial that comes back with it, from the same address and in // good time: the server proceeds, using the connection ID inside. try testing.expectEqualSlices(u8, &.{ 8, 7, 6, 5 }, try open(token, key, "192.0.2.1:443", 1001)); // From anywhere else, or too late, and it proves nothing. try testing.expectError(error.BadToken, open(token, key, "198.51.100.7:443", 1001)); try testing.expectError(error.BadToken, open(token, key, "192.0.2.1:443", 1000 + lifetime_seconds + 1)); } }; const testing = std.testing; test "RFC 9001 A.4: the Retry packet from the appendix, octet for octet" { // "This shows a Retry packet that might be sent in response to the // Initial packet in Appendix A.2. The integrity check includes the // client-chosen connection ID value of 0x8394c8f03e515708, but that value // is not included in the final Retry packet." // // Which is the property the whole mechanism rests on, and the reason this // vector is worth having: a tag computed over what is visible would be a // checksum anyone could produce. const original: [8]u8 = .{ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08 }; const expected = [_]u8{ 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba, }; var buffer: [64]u8 = undefined; const built = try write( &buffer, &original, &.{}, // a zero-length Destination Connection ID &.{ 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5 }, "token", ); try testing.expectEqualSlices(u8, &expected, built); // And it verifies against the connection ID the client chose, which is // nowhere in those octets. try verify(built, &original); try testing.expectError(error.BadIntegrityTag, verify(built, &.{ 1, 2, 3, 4 })); } test "RFC 9001 5.8: a corrupted Retry does not verify" { const original: [4]u8 = .{ 1, 2, 3, 4 }; var buffer: [64]u8 = undefined; const built = try write(&buffer, &original, &.{ 9, 9 }, &.{ 7, 7, 7 }, "opaque"); try verify(built, &original); // Every octet matters: §5.8 covers the whole packet less the tag. for (0..built.len) |i| { var copy: [64]u8 = undefined; @memcpy(copy[0..built.len], built); copy[i] ^= 0x01; try testing.expectError(error.BadIntegrityTag, verify(copy[0..built.len], &original)); } } test "RFC 9000 8.1.4: a token is bound to the address it was issued to" { // "Tokens sent in Retry packets SHOULD include information that allows // the server to verify that the source IP address and port in client // packets remain constant." Without that, a token is a bearer credential // for making a server talk to whoever holds it. const key: Token.Key = @splat(0x5a); const original: [8]u8 = .{ 8, 7, 6, 5, 4, 3, 2, 1 }; var buffer: [Token.max_len]u8 = undefined; const token = try Token.mint(&buffer, key, "192.0.2.1:443", &original, 1000); try testing.expectEqualSlices(u8, &original, try Token.open(token, key, "192.0.2.1:443", 1000)); // A different address, and the same token is worthless. try testing.expectError(error.BadToken, Token.open(token, key, "192.0.2.2:443", 1000)); // Including a different port, which §8.1.4 names specifically. try testing.expectError(error.BadToken, Token.open(token, key, "192.0.2.1:444", 1000)); // And a different server key, which is what stops a client minting its // own: "only the server requires access to the integrity protection key // for tokens." try testing.expectError(error.BadToken, Token.open(token, @splat(0x5b), "192.0.2.1:443", 1000)); } test "RFC 9000 8.1.4: a Retry token is accepted only for a short time" { // "Servers SHOULD ensure that tokens sent in Retry packets are only // accepted for a short time, as they are returned immediately by // clients." The window is what limits replay, which §8.1.4 requires be // "prevented or limited" — preventing it outright means remembering every // token, which is the state Retry exists to avoid. const key: Token.Key = @splat(1); var buffer: [Token.max_len]u8 = undefined; const token = try Token.mint(&buffer, key, "address", &.{ 1, 2 }, 1000); _ = try Token.open(token, key, "address", 1000); _ = try Token.open(token, key, "address", 1000 + Token.lifetime_seconds); try testing.expectError( error.BadToken, Token.open(token, key, "address", 1000 + Token.lifetime_seconds + 1), ); // And a clock that has gone backwards is not a reason to accept one: a // token from the future was not issued by this server at this time. try testing.expectError(error.BadToken, Token.open(token, key, "address", 999)); } test "a token that is not a token" { const key: Token.Key = @splat(2); try testing.expectError(error.BadToken, Token.open(&.{}, key, "a", 0)); try testing.expectError(error.BadToken, Token.open("short", key, "a", 0)); // A length field that disagrees with the token's own size, which is the // cheapest thing for a client to try. var buffer: [Token.max_len]u8 = undefined; const token = try Token.mint(&buffer, key, "a", &.{ 1, 2, 3 }, 5); var copy: [Token.max_len]u8 = undefined; @memcpy(copy[0..token.len], token); copy[0] = 20; try testing.expectError(error.BadToken, Token.open(copy[0..token.len], key, "a", 5)); }