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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Path validation and migration: RFC 9000 §8.2 and §9.//!//! A QUIC connection is not tied to an address. §9: "an endpoint can migrate//! a connection to a new local address by sending packets containing//! non-probing frames from that address" — which is the feature that lets a//! phone walk out of a building without dropping its downloads, and is also//! the feature that would let anyone with a forged source address point//! somebody else's connection at a victim.//!//! §8.2 is what tells those two apart. "Path validation tests that packets//! sent on a path to a peer are received by that peer... Path validation is//! used to ensure that packets received from a migrating peer do not carry a//! spoofed source address." An endpoint sends eight unpredictable octets and//! waits for them back: an attacker who can write a source address but not//! read the replies sent to it cannot produce the echo.//!//! ## What a path is here//!//! A small integer the caller chooses. This library has no sockets, so it has//! no opinion about addresses — the caller receives a datagram from somewhere,//! decides whether that somewhere is a path it has seen before, and hands in//! the number it uses for it. §8.2 says a path is "the 2-tuple of IP address//! and port"; which 2-tuples exist and how they are numbered is the caller's//! business, and keeping it there is what lets this be tested without a//! network.//!//! ## The two halves that look alike and are not//!//! §8.2.2 has one rule with a warning attached: "a PATH_RESPONSE frame MUST//! be sent on the network path where the PATH_CHALLENGE frame was received...//! This requirement MUST NOT be enforced by the endpoint that initiates path//! validation, as that would enable an attack on migration." So a responder//! is strict about where it replies and an initiator is lax about where the//! reply arrives — and §8.2.3 says why the laxity is safe: "a PATH_RESPONSE//! frame received on any network path validates the path on which the//! PATH_CHALLENGE was sent." The entropy is what validates, not the route it//! came back by.
const std = @import("std");
const recovery = @import("recovery.zig");const frame = @import("frame.zig");
/// §19.17: the payload of a PATH_CHALLENGE, and of the PATH_RESPONSE that/// echoes it.pub const challenge_len = 8;
/// How many paths one connection will track.////// Two is the number migration needs: the one in use and the one being/// probed. §8.2 permits probing several at once — "the number of simultaneous/// paths used for probes is limited by the number of extra connection IDs its/// peer has previously supplied" — and for migration alone more than two is a/// choice to spend memory on a case that does not arise for a client/// changing network.////// Four is what multipath needs: draft-ietf-quic-multipath-21 gives each of/// a connection's paths a 4-tuple of its own, and `Connection.max_paths` is/// four. Still a fixed number, for the reason `observe` gives.pub const capacity = 4;
/// The caller's own number for a path.pub const Id = u8;
pub const Error = error{ /// No room to track another path. NoRoom,};
/// One path, and how much is known about it.pub const Path = struct { id: Id = 0, in_use: bool = false, /// §8.2.3: whether the peer has proved it receives what is sent here. validated: bool = false, /// The challenge outstanding on this path, if one is. challenge: ?[challenge_len]u8 = null, /// When it was sent, so that a probe that goes unanswered can be retried /// or abandoned. challenged_at: recovery.Instant = 0, /// Whether the challenge has actually left. §8.2.1: "an endpoint SHOULD /// NOT send multiple PATH_CHALLENGE frames in a single packet", and there /// is no point repeating one that has not been answered yet either — the /// peer is expected to answer the one it got. sent_challenge: bool = false, /// §9.3: the highest packet number seen from this path, which is what /// decides whether a migration is news or a reordered straggler — "an /// endpoint only changes the address to which it sends packets in /// response to the highest-numbered non-probing packet." highest_seen: u64 = 0, /// §8.2 and §21.1.1.1: how much has arrived from here and how much has /// been sent to it, for the three-times limit that applies until the path /// is validated. received: u64 = 0, sent: u64 = 0, /// Whether this endpoint chose this path, rather than learning of it from /// a packet that arrived on it. /// /// §21.1.1.1's three-times limit exists so that a connection cannot be /// used as a reflector: "if responding to an unverified source address, /// the server MUST NOT send more than three times as many bytes as the /// number of bytes it has received". The words that matter are /// *responding* and *source address* -- the danger is answering an /// address an attacker put in a packet, which might be a victim's. /// /// An address this endpoint picked itself is not that. Nobody supplied /// it, so nobody can aim it, and the limit would only stop this endpoint /// from ever sending the PATH_CHALLENGE that would lift it -- nothing has /// arrived from a path nothing has been sent to, so three times nothing /// is nothing, for ever. /// /// Unvalidated all the same: §8.2 still requires the challenge to be /// answered before the path carries anything that matters. What this /// changes is only whether the challenge itself may go out. chosen: bool = false,
/// draft-ietf-quic-address-discovery-01: the address the peer's datagrams /// on this path come from, as the caller last said. /// /// The caller's to supply, since only the caller has seen a socket: this /// is the one place the library holds an address it did not read out of /// a frame, and it holds it only to report it back to the peer. peer_address: ?frame.Address = null, /// Whether an OBSERVED_ADDRESS is owed on this path: a new path, a /// changed address, or a report that was lost. observation_owed: bool = false, /// §4.1: the most recent report the peer made about this path, and its /// sequence number -- "a peer SHOULD ignore an incoming OBSERVED_ADDRESS /// frame if it previously received another OBSERVED_ADDRESS frame for the /// same path with a Sequence Number equal to or higher". observed: ?frame.Address = null, observed_sequence: u64 = 0,};
/// The paths a connection knows about.pub const Paths = struct { entries: [capacity]Path = @splat(.{}), /// The path packets are sent on. active: Id = 0, /// §8.2.2: responses owed, and the path each is owed on. "An endpoint /// MUST NOT delay transmission of a packet containing a PATH_RESPONSE /// frame unless constrained by congestion control", so these are sent at /// the first opportunity and not batched. owed: [capacity]?Owed = @splat(null),
/// A PATH_RESPONSE this endpoint owes, and the path §8.2.2 requires it to /// go out on. pub const Owed = struct { path: Id, data: [challenge_len]u8 };
/// §21.1.1.1's limit, and §8.1's: an endpoint may not send more than /// three times what it has received from an address it has not validated. pub const amplification_factor = 3;
/// Starts with one path, the one the handshake happened on, which is /// validated by the handshake itself — §8.1: "the successful completion /// of the handshake implicitly validates the client's address." pub fn init(id: Id) Paths { var paths: Paths = .{ .active = id }; paths.entries[0] = .{ .id = id, .in_use = true, .validated = true }; return paths; }
pub fn find(paths: *Paths, id: Id) ?*Path { for (&paths.entries) |*path| { if (path.in_use and path.id == id) return path; } return null; }
/// Finds a path, or starts tracking it. /// /// A new path is not validated and not in use: §9.3 has an endpoint /// validate before committing to it, and §9.3.1 explains what the /// commitment would cost if the address were forged — "connection /// migration might be used to amplify the volume of data that an attacker /// can generate toward a victim." pub fn observe(paths: *Paths, id: Id) Error!*Path { if (paths.find(id)) |path| return path; for (&paths.entries) |*path| { if (path.in_use) continue; path.* = .{ .id = id, .in_use = true }; return path; } // Every slot taken by a path that is either in use or being probed. // §9.3 does not require an endpoint to entertain every address that // sends it a packet, and a table that grew would be one an attacker // sized. return error.NoRoom; }
/// Stops tracking a path nothing uses any more, along with any response /// still owed on it, so that the slot is free for another. The path in /// use is never forgotten. pub fn forget(paths: *Paths, id: Id) void { if (id == paths.active) return; const path = paths.find(id) orelse return; path.* = .{}; for (&paths.owed) |*slot| { if (slot.*) |owed| if (owed.path == id) { slot.* = null; }; } }
/// §8.2.2: notes that a challenge arrived and must be echoed back the way /// it came. pub fn owe(paths: *Paths, id: Id, data: [challenge_len]u8) void { for (&paths.owed) |*slot| { if (slot.* == null) { slot.* = .{ .path = id, .data = data }; return; } } // §8.2.2: "an endpoint MUST NOT send more than one PATH_RESPONSE // frame in response to one PATH_CHALLENGE frame... The peer is // expected to send more PATH_CHALLENGE frames as necessary to evoke // additional PATH_RESPONSE frames." Dropping one is therefore within // the design rather than a failure of it. }
/// The next response owed, if any. pub fn nextOwed(paths: *const Paths) ?Owed { for (paths.owed) |maybe| { if (maybe) |owed| return owed; } return null; }
pub fn sentResponse(paths: *Paths, data: [challenge_len]u8) void { for (&paths.owed) |*slot| { if (slot.*) |owed| { if (std.mem.eql(u8, &owed.data, &data)) slot.* = null; } } }
/// §8.2.1: starts validating a path with eight unpredictable octets. /// /// Unpredictable is the whole mechanism: an attacker who can forge a /// source address but cannot see the packets sent to it must not be able /// to guess what to echo. §8.2.3 is blunt about the weaker alternative — /// "receipt of an acknowledgment for a packet containing a PATH_CHALLENGE /// frame is not adequate validation, since the acknowledgment can be /// spoofed by a malicious peer." pub fn challenge(paths: *Paths, id: Id, rng: std.Random, now: recovery.Instant) Error![challenge_len]u8 { const path = try paths.observe(id); var data: [challenge_len]u8 = undefined; rng.bytes(&data); path.challenge = data; path.challenged_at = now; path.sent_challenge = false; return data; }
/// §8.2.3: a response arrived. Returns the path it validates, if it /// validates one. /// /// "A PATH_RESPONSE frame received on any network path validates the path /// on which the PATH_CHALLENGE was sent" — so this does not care which /// path the response came in on, and §8.2.2 explains that the laxity is /// deliberate: enforcing it "would enable an attack on migration". pub fn onResponse(paths: *Paths, data: [challenge_len]u8) ?*Path { for (&paths.entries) |*path| { if (!path.in_use) continue; const outstanding = path.challenge orelse continue; if (!std.mem.eql(u8, &outstanding, &data)) continue; path.challenge = null; path.validated = true; return path; } return null; }
/// §9.3: whether a non-probing packet from `id` should move the /// connection there. /// /// "An endpoint only changes the address to which it sends packets in /// response to the highest-numbered non-probing packet. This ensures that /// an endpoint does not send packets to an old peer address in the case /// that it receives reordered packets." So a straggler from an address /// the peer has already left does not drag the connection back to it. pub fn isMigration(paths: *Paths, id: Id, number: u64) bool { if (id == paths.active) return false; const active = paths.find(paths.active) orelse return true; return number > active.highest_seen; }
/// Moves the connection to a path. pub fn migrate(paths: *Paths, id: Id) void { paths.active = id; }
/// Records that this endpoint chose a path rather than being told about /// it, which is what exempts it from §21.1.1.1's limit. See `Path.chosen`. pub fn choose(paths: *Paths, id: Id) void { const path = paths.find(id) orelse return; path.chosen = true; }
/// §8.1 and §21.1.1.1: how much more may be sent to a path before it has /// been validated. /// /// Unlimited once validated, and three times what arrived before that. /// The limit is what stops a connection being a reflector: an attacker /// who forges a victim's address gets three octets of attack per octet it /// sends itself, which is not an amplifier worth building. pub fn sendable(paths: *Paths, id: Id) usize { const path = paths.find(id) orelse return 0; if (path.validated or path.chosen) return std.math.maxInt(usize); const allowance = path.received *| amplification_factor; if (path.sent >= allowance) return 0; return @intCast(@min(allowance - path.sent, @as(u64, std.math.maxInt(usize)))); }};
const testing = std.testing;
test "RFC 9000 8.1: the handshake validates the path it happened on" { // "The successful completion of the handshake implicitly validates the // client's address" — a peer that completed a TLS handshake demonstrably // receives what is sent to it, which is exactly what path validation // sets out to prove. var paths: Paths = .init(0); try testing.expect(paths.find(0).?.validated); try testing.expectEqual(@as(usize, std.math.maxInt(usize)), paths.sendable(0));}
test "RFC 9000 8.2.3: the echo validates, whatever path it comes back on" { // "A PATH_RESPONSE frame received on any network path validates the path // on which the PATH_CHALLENGE was sent." The entropy is what validates, // not the route it returned by — and §8.2.2 warns that enforcing the // route "would enable an attack on migration". var rng_impl: std.Random.DefaultPrng = .init(1); var paths: Paths = .init(0);
const data = try paths.challenge(1, rng_impl.random(), 100); try testing.expect(!paths.find(1).?.validated);
// Wrong data validates nothing, which is the whole mechanism: an attacker // who can forge a source address but not read the replies has nothing to // echo. try testing.expectEqual(@as(?*Path, null), paths.onResponse(@splat(0xff))); try testing.expect(!paths.find(1).?.validated);
const validated = paths.onResponse(data).?; try testing.expectEqual(@as(Id, 1), validated.id); try testing.expect(paths.find(1).?.validated);
// And the same response again validates nothing further: the challenge is // spent. try testing.expectEqual(@as(?*Path, null), paths.onResponse(data));}
test "RFC 9000 8.2.2: a response goes back the way the challenge came" { var paths: Paths = .init(0); paths.owe(1, @splat(0xab)); paths.owe(0, @splat(0xcd));
const first = paths.nextOwed().?; try testing.expectEqual(@as(Id, 1), first.path); paths.sentResponse(first.data);
const second = paths.nextOwed().?; try testing.expectEqual(@as(Id, 0), second.path); paths.sentResponse(second.data); try testing.expectEqual(@as(?Paths.Owed, null), paths.nextOwed());}
test "RFC 9000 9.3: a reordered straggler does not drag the connection back" { // "An endpoint only changes the address to which it sends packets in // response to the highest-numbered non-probing packet. This ensures that // an endpoint does not send packets to an old peer address in the case // that it receives reordered packets." var paths: Paths = .init(0); paths.find(0).?.highest_seen = 10;
// A packet from elsewhere, newer than anything seen on the active path: // the peer has moved. try testing.expect(paths.isMigration(1, 11)); // And one that is older: a straggler from before the move, or an // attacker replaying one. try testing.expect(!paths.isMigration(1, 9)); // A packet from the path already in use is not a migration at all. try testing.expect(!paths.isMigration(0, 99));}
test "RFC 9000 9.3.1: an unvalidated path gets three times what it sent" { // "It is possible that a peer is spoofing its source address to cause an // endpoint to send excessive amounts of data to an unwilling host." // Three times is not much of an amplifier, which is the point. var paths: Paths = .init(0); const path = try paths.observe(1); try testing.expectEqual(@as(usize, 0), paths.sendable(1));
path.received = 1200; try testing.expectEqual(@as(usize, 3600), paths.sendable(1)); path.sent = 3600; try testing.expectEqual(@as(usize, 0), paths.sendable(1));
// Validation is what lifts it, and nothing else does. path.validated = true; try testing.expectEqual(@as(usize, std.math.maxInt(usize)), paths.sendable(1));}
test "the table is bounded, so a peer cannot choose how many paths to track" { var paths: Paths = .init(0); for (1..capacity) |id| _ = try paths.observe(@intCast(id)); try testing.expectError(error.NoRoom, paths.observe(capacity)); // The ones it does know are unaffected. try testing.expect(paths.find(0) != null); try testing.expect(paths.find(1) != null);}
test "a path forgotten frees its slot, and the path in use is never forgotten" { var paths: Paths = .init(0); for (1..capacity) |id| _ = try paths.observe(@intCast(id)); paths.owe(1, @splat(0xab)); paths.forget(1); try testing.expect(paths.find(1) == null); try testing.expect(paths.nextOwed() == null); _ = try paths.observe(capacity); paths.forget(0); try testing.expect(paths.find(0) != null);}