// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! RFC 9000 §17: the shape of a packet, and how to get one off a datagram. //! //! ## Reading a packet is two passes, and the protocol forces it //! //! The packet number is protected, and so are the two bits that say how long //! it is. So a reader cannot know where the packet number ends until it has //! removed header protection, and it cannot remove header protection until it //! knows where the packet number *begins* — which is why §5.4.2 of RFC 9001 //! fixes the sample offset at four octets past the start of the number and //! pretends the number is always four octets long. //! //! `Header.parse` is therefore the first pass: everything readable before any //! key is applied, plus `number_offset`, which is exactly what the second pass //! needs. `open` is both passes and the decryption, and is what a receiver //! actually calls. //! //! ## What a short header does not carry //! //! Its Destination Connection ID has no length field. A 1-RTT packet is read //! by an endpoint that chose that connection ID itself, so it knows how long //! it is; anything else looking at the packet cannot tell where the header //! ends. That is deliberate — it is what stops a middlebox from following a //! connection — and it means `parse` has to be told the length. There is no //! way to work it out from the octets. //! //! ## Everything here runs before authentication //! //! A datagram arrives from whoever can reach the port. Every bound in this //! file is checked against the buffer that actually arrived rather than //! against a length the packet claims for itself, and a packet that fails any //! check is dropped rather than answered: §5.2 of RFC 9000 is explicit that //! an endpoint MUST NOT send anything in response to a packet it could not //! process, because doing so is an amplification vector. const std = @import("std"); const assert = std.debug.assert; const protection = @import("protection.zig"); const tls = @import("tls.zig"); const varint = @import("varint.zig"); /// §17.2: "In QUIC version 1, this value MUST NOT exceed 20 bytes." pub const max_connection_id_len = 20; /// §17.2.5: the Retry Integrity Tag is 128 bits. pub const retry_integrity_tag_len = 16; /// §15: the version number of QUIC version 1, which is the only version this /// implements. Version 0 means Version Negotiation (§17.2.1) and is not a /// version an endpoint ever selects. pub const version_1: u32 = 1; /// §15: the versions this endpoint will speak, most preferred first. /// /// One, and the list exists rather than the constant because §17.2.1 puts a /// *list* in a Version Negotiation packet and a server with one version still /// has to write it as one. pub const supported_versions = [_]u32{version_1}; /// Whether this endpoint can speak a version a peer has asked for. /// /// Version 0 is not a version: §17.2.1 identifies a Version Negotiation /// packet "based on the Version field having a value of 0", so it is the one /// value no endpoint ever selects and no endpoint may answer as though it /// had been selected. pub fn supportsVersion(version: u32) bool { if (version == 0) return false; for (supported_versions) |known| { if (known == version) return true; } return false; } pub const Form = enum { long, short }; pub const Kind = enum { /// §17.2.2. Carries the first CRYPTO frames and the token, if any. initial, /// §17.2.3. zero_rtt, /// §17.2.4. handshake, /// §17.2.5. No packet number and no length: the rest of the datagram is /// the token and a 16-octet integrity tag. retry, /// §17.2.1. A version of zero, and the payload is a list of versions the /// server does support. It is not protected at all and has no packet /// number. version_negotiation, /// §17.3.1, the short header. one_rtt, /// Which encryption level protects a packet of this kind. pub fn level(k: Kind) ?tls.Level { return switch (k) { .initial => .initial, .zero_rtt => .early_data, .handshake => .handshake, .one_rtt => .application, // Neither is protected by a key schedule: a Retry carries a fixed // integrity tag (§5.8 of RFC 9001) and a Version Negotiation // carries nothing at all. .retry, .version_negotiation => null, }; } /// Whether a packet of this kind has a Packet Number field. pub fn hasNumber(k: Kind) bool { return switch (k) { .initial, .zero_rtt, .handshake, .one_rtt => true, .retry, .version_negotiation => false, }; } }; pub const Error = error{ /// The Fixed Bit is clear. §17.2 and §17.3 both say such a packet "MUST /// be discarded"; the bit exists so that QUIC can be told apart from the /// other things that share a UDP port with it (RFC 7983). NotQuic, /// The datagram ended inside the header. Truncated, /// A connection ID longer than the twenty octets §17.2 allows in version /// 1. "Endpoints that receive a version 1 long header with a value larger /// than 20 MUST drop the packet." ConnectionIdTooLong, /// The Length field reaches past the end of the datagram. A packet cannot /// be longer than what arrived, and believing it could is how a parser is /// made to read someone else's memory. LengthPastEnd, }; /// What can be read from a packet before any key is applied. pub const Header = struct { form: Form, kind: Kind, /// The first octet, with its protected bits still protected. For a packet /// with a number, the low bits are not yet meaningful. first: u8, /// Zero for a short header, which carries no version. version: u32, destination: []const u8, /// Empty for a short header, which carries no source connection ID. source: []const u8, /// An Initial packet's token, and empty for everything else. token: []const u8, /// Where the Packet Number field begins, which is what header protection /// is sampled relative to. Meaningless when `kind.hasNumber()` is false. number_offset: usize, /// One past the last octet of this packet within the datagram. /// /// Not necessarily the end of the datagram: §12.2 allows several packets /// to be coalesced into one, and a long header's Length field is how the /// next one is found. end: usize, /// The part of the packet that is the AEAD's associated data, once the /// packet number length is known: §5.3 of RFC 9001, "the contents of the /// QUIC header, starting from the first byte... up to and including the /// unprotected packet number". pub fn associatedData(h: Header, datagram: []const u8, number_len: usize) []const u8 { return datagram[0 .. h.number_offset + number_len]; } /// The protected payload: everything after the packet number, up to the /// end of this packet. pub fn ciphertext(h: Header, datagram: []const u8, number_len: usize) []const u8 { return datagram[h.number_offset + number_len .. h.end]; } }; /// Reads the header at the front of `datagram`. /// /// `local_connection_id_len` is how long this endpoint's own connection IDs /// are, and is used only for a short header — see the note at the top about /// why it cannot be discovered from the octets. pub fn parse(datagram: []const u8, local_connection_id_len: usize) Error!Header { return parseWith(datagram, local_connection_id_len, false); } /// `parse`, for an endpoint that may have agreed to see the Fixed Bit clear. /// /// RFC 9287 §3: "an endpoint that advertises the grease_quic_bit transport /// parameter MUST accept packets with the QUIC Bit set to a value of 0" -- /// Initial and Handshake packets included, since a peer may clear it on /// "all packets that are sent after receiving and processing transport /// parameters". So whether 0x40 is required is a property of the connection /// and not of the packet, and the caller is the one that knows. A datagram /// nobody has claimed yet is parsed with `parse`, strictly: until transport /// parameters have been exchanged a peer has no licence to clear the bit. pub fn parseWith(datagram: []const u8, local_connection_id_len: usize, fixed_bit_optional: bool) Error!Header { assert(local_connection_id_len <= max_connection_id_len); if (datagram.len < 1) return error.Truncated; const first = datagram[0]; if (first & 0x80 == 0) return parseShort(datagram, local_connection_id_len, fixed_bit_optional); // A long header. Version comes before the fixed-bit check, because a // Version Negotiation packet is the one packet allowed to clear it: // §17.2.1 says its first octet is "unused... and MUST be ignored". if (datagram.len < 5) return error.Truncated; const version = std.mem.readInt(u32, datagram[1..5], .big); var at: usize = 5; const destination = try readConnectionId(datagram, &at); const source = try readConnectionId(datagram, &at); if (version == 0) { return .{ .form = .long, .kind = .version_negotiation, .first = first, .version = 0, .destination = destination, .source = source, .token = &.{}, .number_offset = at, .end = datagram.len, }; } if (first & 0x40 == 0 and !fixed_bit_optional) return error.NotQuic; const kind: Kind = switch ((first & 0x30) >> 4) { 0 => .initial, 1 => .zero_rtt, 2 => .handshake, 3 => .retry, else => unreachable, }; if (kind == .retry) { // §17.2.5: no Length and no Packet Number. What remains is the Retry // Token and a 16-octet integrity tag, and the token is however much // is left over -- which is why a Retry shorter than the tag is not a // Retry. if (datagram.len - at < retry_integrity_tag_len) return error.Truncated; return .{ .form = .long, .kind = .retry, .first = first, .version = version, .destination = destination, .source = source, .token = datagram[at .. datagram.len - retry_integrity_tag_len], .number_offset = at, .end = datagram.len, }; } var token: []const u8 = &.{}; if (kind == .initial) { // §17.2.2: a Token Length and then that many octets. const token_len = try varint.parse(datagram[at..]); at += token_len.len; if (datagram.len - at < token_len.value) return error.Truncated; const n: usize = @intCast(token_len.value); token = datagram[at..][0..n]; at += n; } // §17.2: "the length of the remainder of the packet (that is, the Packet // Number and Payload fields)". const length = try varint.parse(datagram[at..]); at += length.len; if (datagram.len - at < length.value) return error.LengthPastEnd; return .{ .form = .long, .kind = kind, .first = first, .version = version, .destination = destination, .source = source, .token = token, .number_offset = at, .end = at + @as(usize, @intCast(length.value)), }; } fn parseShort(datagram: []const u8, connection_id_len: usize, fixed_bit_optional: bool) Error!Header { const first = datagram[0]; if (first & 0x40 == 0 and !fixed_bit_optional) return error.NotQuic; if (datagram.len < 1 + connection_id_len) return error.Truncated; return .{ .form = .short, .kind = .one_rtt, .first = first, .version = 0, .destination = datagram[1..][0..connection_id_len], .source = &.{}, .token = &.{}, .number_offset = 1 + connection_id_len, // §12.2: "a packet with a short header does not include a length, so // it can only be the last packet included in a UDP datagram". .end = datagram.len, }; } fn readConnectionId(datagram: []const u8, at: *usize) Error![]const u8 { if (datagram.len < at.* + 1) return error.Truncated; const len = datagram[at.*]; if (len > max_connection_id_len) return error.ConnectionIdTooLong; at.* += 1; if (datagram.len - at.* < len) return error.Truncated; const id = datagram[at.*..][0..len]; at.* += len; return id; } /// RFC 9000 Appendix A.3, transcribed. /// /// The packet number on the wire is truncated to one to four octets, and the /// full value is reconstructed from the largest number already authenticated /// in this packet number space. It matters because the *reconstructed* number /// goes into the AEAD nonce (§5.3 of RFC 9001): get it wrong and the packet /// does not decrypt, which is the good failure. The bad failure would be two /// different packets reconstructing to the same number, which is why the /// window is centred on what is expected rather than simply masked in. pub fn decodeNumber(largest: u64, truncated: u64, number_len: usize) u64 { assert(number_len >= 1 and number_len <= 4); const bits: u6 = @intCast(number_len * 8); const expected = largest +% 1; const window: u64 = @as(u64, 1) << bits; const half = window / 2; const mask = window - 1; const candidate = (expected & ~mask) | truncated; if (candidate + half <= expected and candidate < (@as(u64, 1) << 62) - window) { return candidate + window; } if (candidate > expected + half and candidate >= window) { return candidate - window; } return candidate; } /// How many octets a packet number must be written in, given the largest one /// the peer has acknowledged. /// /// Two rules, and §17.1 states them separately because they are different /// sums. /// /// Before anything has been acknowledged: "the full packet number MUST be /// included; it is not to be truncated". So the size is whatever holds the /// value — 255 goes out in one octet, because one octet holds 255 entire. /// /// Afterwards: "the sender MUST use a packet number size able to represent /// more than twice as large a range as the difference between the largest /// acknowledged packet number and the packet number being sent". *More than*, /// so a range of exactly 256 does not fit in the 256 values an octet has. The /// doubling is what leaves room for reordering: the receiver decodes to the /// candidate nearest what it expects, and half a window either side is the /// most it can be wrong by. pub fn encodedNumberLen(number: u64, largest_acked: ?u64) usize { const acked = largest_acked orelse { if (number < (1 << 8)) return 1; if (number < (1 << 16)) return 2; if (number < (1 << 24)) return 3; return 4; }; assert(number >= acked); const range = (number - acked) * 2; if (range < (1 << 8)) return 1; if (range < (1 << 16)) return 2; if (range < (1 << 24)) return 3; return 4; } pub const OpenError = Error || protection.Error || error{ /// The packet is too short to hold a header protection sample, which /// §5.4.2 of RFC 9001 says must be discarded. TooShortToSample, /// §17.2 and §17.3: the reserved bits "MUST be set to 0", and receiving /// them set after removing both protections is a connection error of type /// PROTOCOL_VIOLATION. Checked after decryption on purpose — §9.5 of RFC /// 9001 warns that discarding on the header alone leaks whether a guessed /// key was right. ReservedBitsSet, /// A packet kind that carries no packet number and so cannot be opened /// this way. NotProtected, /// What is left after the packet number is not even as long as an /// authentication tag, so there is nothing here to authenticate. TooShort, /// `out` is not long enough for the plaintext this packet would produce. /// /// Worth its own error rather than an assertion, because the length that /// decides it is **attacker-influenced**: the packet number length comes /// out of the header protection mask, so a packet protected with keys /// this endpoint does not have — or simply a datagram of noise — yields /// whatever length the mask happens to produce. A caller that had sized /// `out` for the length it expected would otherwise be overrun by a /// packet that guessed differently. BufferTooSmall, }; pub const Opened = struct { header: Header, number: u64, /// The decrypted frames. payload: []u8, }; /// Both passes and the decryption: everything a receiver does between a /// datagram arriving and having frames to read. /// /// `datagram` is modified in place — header protection is removed from it — /// and `out` receives the plaintext, which is sixteen octets shorter than the /// ciphertext. /// A packet whose header protection has been removed, before its payload has /// been decrypted. /// /// The split exists for key update. §6 of RFC 9001 puts the Key Phase bit in /// the short header, which is header-protected — so a receiver cannot know /// which packet protection keys a packet used until it has already removed /// header protection with a key that, §6.1 is explicit, "is not updated". The /// two halves therefore use different keys and have to happen in that order, /// and the removal is in place, so trying again with different keys is not an /// option: the octets have already been changed. pub const Revealed = struct { header: Header, /// The unmasked first octet, which carries the key phase for a short /// header. first: u8, number: u64, number_len: usize, /// §17.3.1's Key Phase bit, meaningful only for a short header. pub fn keyPhase(r: Revealed) bool { return r.first & 0x04 != 0; } }; /// Removes header protection and reconstructs the packet number, in place. /// /// `keys` is used only for its header protection key, which every key phase /// shares. pub fn reveal( keys: *const protection.Keys, largest: u64, datagram: []u8, local_connection_id_len: usize, /// See `parseWith`. fixed_bit_optional: bool, ) OpenError!Revealed { const header = try parseWith(datagram, local_connection_id_len, fixed_bit_optional); if (!header.kind.hasNumber()) return error.NotProtected; const sample = protection.sampleOf(datagram[0..header.end], header.number_offset) orelse return error.TooShortToSample; var number_bytes: [4]u8 = datagram[header.number_offset..][0..4].*; const number_len = protection.removeHeader(keys, sample, &datagram[0], &number_bytes); @memcpy(datagram[header.number_offset..][0..number_len], number_bytes[0..number_len]); var truncated: u64 = 0; for (number_bytes[0..number_len]) |b| truncated = (truncated << 8) | b; return .{ .header = header, .first = datagram[0], .number = decodeNumber(largest, truncated, number_len), .number_len = number_len, }; } /// Decrypts the payload of a packet whose header protection has been removed. pub fn decrypt( keys: *const protection.Keys, revealed: Revealed, datagram: []u8, out: []u8, ) OpenError!Opened { return decryptOn(keys, 0, revealed, datagram, out); } /// `decrypt` for a packet on multipath path `path`. pub fn decryptOn( keys: *const protection.Keys, path: u32, revealed: Revealed, datagram: []u8, out: []u8, ) OpenError!Opened { const header = revealed.header; // Both bounds before either slice: `number_len` was read out of a mask // and is not to be trusted until it has been checked against the packet // that actually arrived. const body_len = header.end - (header.number_offset + revealed.number_len); if (body_len < tls.tag_len) return error.TooShort; const plaintext_len = body_len - tls.tag_len; if (out.len < plaintext_len) return error.BufferTooSmall; const associated = header.associatedData(datagram[0..header.end], revealed.number_len); const ciphertext = header.ciphertext(datagram[0..header.end], revealed.number_len); try protection.decryptOn(keys, path, revealed.number, associated, ciphertext, out[0..plaintext_len]); // Now, and not before: §9.5 of RFC 9001 on why the reserved bits are // checked once the packet has been authenticated rather than as soon as // they are readable. const reserved: u8 = if (header.form == .long) 0x0c else 0x18; if (revealed.first & reserved != 0) return error.ReservedBitsSet; return .{ .header = .{ .form = header.form, .kind = header.kind, .first = revealed.first, .version = header.version, .destination = header.destination, .source = header.source, .token = header.token, .number_offset = header.number_offset, .end = header.end, }, .number = revealed.number, .payload = out[0..plaintext_len], }; } /// Both halves at once, for a packet whose keys are not in question — which /// is every packet that is not a 1-RTT packet, since §6 only ever updates /// those. pub fn open( keys: *const protection.Keys, largest: u64, datagram: []u8, local_connection_id_len: usize, out: []u8, ) OpenError!Opened { const revealed = try reveal(keys, largest, datagram, local_connection_id_len, false); return decrypt(keys, revealed, datagram, out); } const testing = std.testing; test "RFC 9000 A.3: the worked example of packet number decoding" { // "if the highest successfully authenticated packet had a packet number // of 0xa82f30ea, then a packet containing a 16-bit value of 0x9b32 will // be decoded as 0xa82f9b32." try testing.expectEqual( @as(u64, 0xa82f9b32), decodeNumber(0xa82f30ea, 0x9b32, 2), ); } test "a truncated packet number decodes to the value nearest what is expected" { // Straightforward: the next packet after 10, said in one octet. try testing.expectEqual(@as(u64, 11), decodeNumber(10, 11, 1)); // Across a wrap of the low octet: expecting 256, told 0. try testing.expectEqual(@as(u64, 256), decodeNumber(255, 0, 1)); // And backwards, for a packet that was reordered: expecting 256, told 254. try testing.expectEqual(@as(u64, 254), decodeNumber(255, 254, 1)); // Nothing received yet, so the first packet is whatever it says. try testing.expectEqual(@as(u64, 0), decodeNumber(0, 0, 1)); } test "a packet number is written in enough octets to be decoded again" { // Before anything is acknowledged: enough to hold the value entire. try testing.expectEqual(@as(usize, 1), encodedNumberLen(0, null)); try testing.expectEqual(@as(usize, 1), encodedNumberLen(255, null)); try testing.expectEqual(@as(usize, 2), encodedNumberLen(256, null)); try testing.expectEqual(@as(usize, 4), encodedNumberLen(1 << 24, null)); // Afterwards: more than twice the distance from the largest acknowledged, // so the boundary is a distance of 128 rather than 256. try testing.expectEqual(@as(usize, 1), encodedNumberLen(100, 99)); try testing.expectEqual(@as(usize, 1), encodedNumberLen(927, 800)); try testing.expectEqual(@as(usize, 2), encodedNumberLen(928, 800)); try testing.expectEqual(@as(usize, 4), encodedNumberLen(1 << 30, 0)); } test "whatever is encoded can be decoded, from any starting point" { // The property the two functions exist to have between them: a sender // that sizes a packet number by §17.1's rule and a receiver that decodes // it by Appendix A.3 always agree. Checked across a window either side of // what the receiver expects, which is where reordering puts real packets. const largest_acked: u64 = 1000; var number: u64 = largest_acked; while (number < largest_acked + 300) : (number += 1) { const len = encodedNumberLen(number, largest_acked); const mask = (@as(u64, 1) << @intCast(len * 8)) - 1; const truncated = number & mask; // The receiver's own idea of the largest it has authenticated moves // around independently of what the sender has been told. var largest_seen: u64 = number -| 3; while (largest_seen < number + 3) : (largest_seen += 1) { try testing.expectEqual(number, decodeNumber(largest_seen, truncated, len)); } } } test "a first octet with the fixed bit clear is not a QUIC packet" { // §17.2 and §17.3: "MUST be discarded". The bit is what lets QUIC share a // port with STUN, DTLS and the rest (RFC 7983). try testing.expectError(error.NotQuic, parse(&.{ 0x80, 0, 0, 0, 1, 0, 0 }, 0)); try testing.expectError(error.NotQuic, parse(&.{ 0x00, 0, 0, 0 }, 0)); } test "RFC 9287 3: a connection that agreed to it reads a clear Fixed Bit" { // The same two packets `parse` refuses above, read by an endpoint that // advertised grease_quic_bit: a long header whose type bits still say // Initial, and a short header that is still a 1-RTT packet. var initial: [16]u8 = @splat(0); initial[0] = 0x80; // long form, Fixed Bit clear, Initial std.mem.writeInt(u32, initial[1..5], 1, .big); initial[7] = 0; // no token initial[8] = 7; // Length const long = try parseWith(&initial, 0, true); try testing.expectEqual(Kind.initial, long.kind); const short = try parseWith(&.{ 0x00, 1, 2, 3, 4, 0xaa }, 4, true); try testing.expectEqual(Kind.one_rtt, short.kind); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, short.destination); // And `parse` is still strict, which is what a datagram no connection // has claimed is read with. try testing.expectError(error.NotQuic, parse(&initial, 0)); } test "a connection ID longer than version 1 allows is dropped" { var datagram: [64]u8 = @splat(0); datagram[0] = 0xc0; std.mem.writeInt(u32, datagram[1..5], 1, .big); datagram[5] = 21; try testing.expectError(error.ConnectionIdTooLong, parse(&datagram, 0)); } test "a Length that reaches past the datagram is refused" { // The check that stops a parser being told to read someone else's memory. var datagram: [32]u8 = @splat(0); datagram[0] = 0xc0; // long header, Initial std.mem.writeInt(u32, datagram[1..5], 1, .big); datagram[5] = 0; // no destination datagram[6] = 0; // no source datagram[7] = 0; // no token // A two-octet length of 16383, which is far past this buffer. datagram[8] = 0x7f; datagram[9] = 0xff; try testing.expectError(error.LengthPastEnd, parse(&datagram, 0)); } test "a header that has not all arrived is truncated, not wrong" { try testing.expectError(error.Truncated, parse(&.{}, 0)); try testing.expectError(error.Truncated, parse(&.{0xc0}, 0)); try testing.expectError(error.Truncated, parse(&.{ 0xc0, 0, 0, 0 }, 0)); // A short header whose connection ID is longer than what arrived. try testing.expectError(error.Truncated, parse(&.{ 0x40, 1, 2 }, 8)); } test "a short header's connection ID length comes from the caller" { // There is no field for it: an endpoint knows how long its own connection // IDs are, and nothing else can tell where the header ends. const datagram = [_]u8{ 0x40, 1, 2, 3, 4, 5, 6, 7, 8, 0xaa, 0xbb }; const h = try parse(&datagram, 8); try testing.expectEqual(Form.short, h.form); try testing.expectEqual(Kind.one_rtt, h.kind); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, h.destination); try testing.expectEqual(@as(usize, 9), h.number_offset); try testing.expectEqual(datagram.len, h.end); // The same octets read as a two-octet connection ID are a different // packet entirely, which is the point. const other = try parse(&datagram, 2); try testing.expectEqual(@as(usize, 3), other.number_offset); } test "a version of zero is a Version Negotiation packet whatever its first octet says" { // §17.2.1: the first octet is "unused... and MUST be ignored", so the // fixed bit being clear is not an error here and is an error everywhere // else. const datagram = [_]u8{ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; const h = try parse(&datagram, 0); try testing.expectEqual(Kind.version_negotiation, h.kind); try testing.expectEqual(@as(u32, 0), h.version); try testing.expectEqual(@as(?tls.Level, null), h.kind.level()); try testing.expect(!h.kind.hasNumber()); } test "each kind knows which encryption level protects it" { try testing.expectEqual(@as(?tls.Level, .initial), Kind.initial.level()); try testing.expectEqual(@as(?tls.Level, .early_data), Kind.zero_rtt.level()); try testing.expectEqual(@as(?tls.Level, .handshake), Kind.handshake.level()); try testing.expectEqual(@as(?tls.Level, .application), Kind.one_rtt.level()); try testing.expectEqual(@as(?tls.Level, null), Kind.retry.level()); } /// §17.2.1: the answer to a packet whose version this endpoint does not /// speak. /// /// It is the one packet that is "inherently not version specific", carries no /// packet number, is never acknowledged, and "consumes an entire UDP /// datagram" -- so it is written whole here rather than through `Builder`, /// which exists to coalesce numbered packets that share one. /// /// **The connection IDs are swapped, and that is the point of the packet.** /// "The server MUST include the value from the Source Connection ID field of /// the packet it receives in the Destination Connection ID field. The value /// for Source Connection ID MUST be copied from the Destination Connection ID /// of the received packet". Echoing both is what tells the client that /// whoever sent this saw its Initial, rather than being an off-path attacker /// guessing that a connection attempt was underway. The swap happens in here, /// against the header that was received, because a caller passing the two /// fields itself is a caller that can pass them the right way round and be /// wrong. /// /// `unused` fills the seven bits after the header form. §17.2.1 makes them /// "an arbitrary value" that clients MUST ignore, with one recommendation /// that is not arbitrary: "servers SHOULD set the most significant bit of /// this field (0x40) to 1 so that Version Negotiation packets appear to have /// the Fixed Bit field", which is what keeps a demultiplexer that shares this /// port with the protocols of RFC 7983 from mistaking it for something else. /// The version and both connection IDs of a long header, read without /// applying any version's rules to them. /// /// The counterpart to `writeVersionNegotiation` and necessary for the same /// reason: deciding whether to answer a packet cannot depend on rules that /// belong to the version being rejected. `parse` enforces version 1's /// twenty-octet connection ID limit, which is right for a packet this /// endpoint is going to process and wrong for one it is going to refuse. pub fn peekLongHeader(datagram: []const u8) Error!struct { version: u32, destination: []const u8, source: []const u8, } { if (datagram.len < 5) return error.Truncated; if (datagram[0] & 0x80 == 0) return error.NotQuic; const version = std.mem.readInt(u32, datagram[1..5], .big); var at: usize = 5; if (at >= datagram.len) return error.Truncated; const destination_len = datagram[at]; at += 1; if (datagram.len < at + destination_len) return error.Truncated; const destination = datagram[at..][0..destination_len]; at += destination_len; if (at >= datagram.len) return error.Truncated; const source_len = datagram[at]; at += 1; if (datagram.len < at + source_len) return error.Truncated; const source = datagram[at..][0..source_len]; return .{ .version = version, .destination = destination, .source = source }; } pub fn writeVersionNegotiation( out: []u8, received: Header, versions: []const u32, unused: u8, ) BuildError![]u8 { const destination = received.source; const source = received.destination; // Not `max_connection_id_len`, deliberately. §17.2.1: "Future versions of // QUIC could have different requirements for the lengths of connection // IDs... Version-specific rules for the connection ID therefore MUST NOT // influence a decision about whether to send a Version Negotiation // packet." Version 1's twenty-octet limit is exactly such a rule, and a // packet this endpoint refuses to answer because a *future* version's // connection ID is too long for *this* version is the failure the // sentence exists to prevent. The real limit is the one-octet length // field. if (destination.len > 255 or source.len > 255) return error.ConnectionIdTooLong; const len = 1 + 4 + 1 + destination.len + 1 + source.len + 4 * versions.len; if (out.len < len) return error.NoSpace; var at: usize = 0; out[at] = 0x80 | (unused & 0x7f); at += 1; // "The Version field of a Version Negotiation packet MUST be set to // 0x00000000", which is also how the client will recognise it. std.mem.writeInt(u32, out[at..][0..4], 0, .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; for (versions) |version| { std.mem.writeInt(u32, out[at..][0..4], version, .big); at += 4; } return out[0..at]; } pub const BuildError = error{ /// The buffer is not long enough for what was asked of it. NoSpace, /// A connection ID longer than the twenty octets version 1 allows. ConnectionIdTooLong, /// A packet number length outside 1..4. InvalidNumberLength, /// The finished packet is too short for header protection to sample. /// /// §5.4.2 of RFC 9001: "packets are padded so that the combined lengths /// of the encoded packet number and protected payload is at least 4 bytes /// longer than the sample required for header protection... This results /// in needing at least 3 bytes of frames in the unprotected payload if /// the packet number is encoded on a single byte". /// /// A distinct error rather than `NoSpace`, because the answer is /// different: the buffer is fine and the *packet* is too small, so the /// fix is `padTo` rather than a bigger buffer. TooShortToSample, } || frame.WriteError; /// Builds one packet into a caller's buffer. /// /// The order is forced by the protocol and the builder exists to get it right /// once. A long header carries a Length field covering the packet number and /// the payload, and neither is known when the header is written — so the /// field is *reserved* at a fixed width and filled in at the end, which §16 /// makes legal by permitting non-minimal varints. Then the payload is /// encrypted with the header as associated data, and only then is header /// protection applied, because §5.4.1 of RFC 9001 samples the mask out of the /// ciphertext. /// /// Get that order wrong in either direction and the packet is well-formed and /// unreadable. pub const Builder = struct { buffer: []u8, form: Form, number: u64, number_offset: usize, number_len: usize, /// Where the reserved Length field sits, and how wide it was reserved. /// Zero width for a short header, which has no such field. length_offset: usize, length_width: usize, /// Where the payload begins, and how much of it has been written. payload_start: usize, at: usize, pub const Long = struct { kind: Kind, version: u32 = 1, destination: []const u8, source: []const u8, /// Initial packets only; §17.2.2 requires a server to send none. token: []const u8 = &.{}, }; /// Starts a long header packet. /// /// `number_len` is the caller's, not this function's, because §17.1 makes /// it a policy question rather than an arithmetic one: `encodedNumberLen` /// gives the smallest legal choice, and a sender is free to use a longer /// one — RFC 9001's Appendix A sends packet number 2 in four octets, /// which is how this is checked against it. pub fn initLong(buffer: []u8, spec: Long, number: u64, number_len: usize) BuildError!Builder { if (number_len < 1 or number_len > 4) return error.InvalidNumberLength; if (spec.destination.len > max_connection_id_len) return error.ConnectionIdTooLong; if (spec.source.len > max_connection_id_len) return error.ConnectionIdTooLong; var at: usize = 0; const type_bits: u8 = switch (spec.kind) { .initial => 0x00, .zero_rtt => 0x10, .handshake => 0x20, .retry => return error.InvalidNumberLength, // no packet number .version_negotiation, .one_rtt => return error.InvalidNumberLength, }; // Header form, fixed bit, type, and the packet number length in the // low two bits. The reserved bits stay zero, as §17.2 requires before // protection is applied. try need(buffer, at, 1); buffer[at] = 0xc0 | type_bits | @as(u8, @intCast(number_len - 1)); at += 1; try need(buffer, at, 4); std.mem.writeInt(u32, buffer[at..][0..4], spec.version, .big); at += 4; at = try putId(buffer, at, spec.destination); at = try putId(buffer, at, spec.source); if (spec.kind == .initial) { at = try putVarint(buffer, at, spec.token.len); try need(buffer, at, spec.token.len); @memcpy(buffer[at..][0..spec.token.len], spec.token); at += spec.token.len; } // The Length field, reserved rather than written. Two octets unless // the buffer could hold a packet too big for them, which no datagram // on a real path ever is. const width: usize = if (buffer.len <= 16383) 2 else 4; const length_offset = at; try need(buffer, at, width); at += width; const number_offset = at; try need(buffer, at, number_len); writeNumber(buffer[at..][0..number_len], number); at += number_len; return .{ .buffer = buffer, .form = .long, .number = number, .number_offset = number_offset, .number_len = number_len, .length_offset = length_offset, .length_width = width, .payload_start = at, .at = at, }; } /// Starts a 1-RTT packet. pub fn initShort( buffer: []u8, destination: []const u8, number: u64, number_len: usize, key_phase: bool, ) BuildError!Builder { if (number_len < 1 or number_len > 4) return error.InvalidNumberLength; if (destination.len > max_connection_id_len) return error.ConnectionIdTooLong; try need(buffer, 0, 1 + destination.len + number_len); // Fixed bit set, spin bit clear, reserved bits zero, key phase, and // the packet number length. No length field: §12.2 makes a short // header packet the last one in its datagram for exactly that reason. buffer[0] = 0x40 | (@as(u8, @intFromBool(key_phase)) << 2) | @as(u8, @intCast(number_len - 1)); @memcpy(buffer[1..][0..destination.len], destination); const number_offset = 1 + destination.len; writeNumber(buffer[number_offset..][0..number_len], number); const start = number_offset + number_len; return .{ .buffer = buffer, .form = .short, .number = number, .number_offset = number_offset, .number_len = number_len, .length_offset = 0, .length_width = 0, .payload_start = start, .at = start, }; } /// Appends a frame to the payload. pub fn add(b: *Builder, f: frame.Frame) BuildError!void { // The authentication tag has to fit as well, and it is not written // until `finish` -- so the space for it is reserved here, where // running out is still recoverable. const room = b.buffer.len - b.at; if (room < tls.tag_len) return error.NoSpace; b.at += try frame.write(b.buffer[b.at .. b.buffer.len - tls.tag_len], f); } /// How many more octets of frames will fit, leaving room for the tag. pub fn remaining(b: *const Builder) usize { const used = b.at + tls.tag_len; return if (used >= b.buffer.len) 0 else b.buffer.len - used; } pub fn payloadLen(b: *const Builder) usize { return b.at - b.payload_start; } /// Pads the packet with PADDING frames until it is `total` octets long /// once the tag is added. /// /// §14.1 requires a client's Initial packets to be padded to at least /// 1200 octets, which is how QUIC stops an unverified address being used /// for amplification: a server may not send more than three times what it /// has received. pub fn padTo(b: *Builder, total: usize) BuildError!void { const would_be = b.at + tls.tag_len; if (would_be >= total) return; const n = total - would_be; if (b.remaining() < n) return error.NoSpace; @memset(b.buffer[b.at..][0..n], 0); b.at += n; } /// Encrypts the payload, fills in the Length, applies header protection, /// and returns the finished packet. pub fn finish(b: *Builder, keys: *const protection.Keys) BuildError![]u8 { return b.finishOn(keys, 0); } /// `finish` for a packet on multipath path `path`, whose nonce carries /// the path ID (draft-ietf-quic-multipath-21 §2.4). Path 0 is `finish`. pub fn finishOn(b: *Builder, keys: *const protection.Keys, path: u32) BuildError![]u8 { const payload_len = b.payloadLen(); const end = b.at + tls.tag_len; if (end > b.buffer.len) return error.NoSpace; // The Length covers the packet number and everything after it, // including the tag that does not exist yet. if (b.length_width != 0) { const value = b.number_len + payload_len + tls.tag_len; _ = varint.writeFixed( b.buffer[b.length_offset..][0..b.length_width], value, b.length_width, ); } // §5.3 of RFC 9001: the associated data is the header up to and // including the packet number, and the header protection has not been // applied to it yet. const header = b.buffer[0 .. b.number_offset + b.number_len]; var sealed: [2048]u8 = undefined; if (payload_len + tls.tag_len > sealed.len) return error.NoSpace; protection.encryptOn( keys, path, b.number, header, b.buffer[b.payload_start..b.at], sealed[0 .. payload_len + tls.tag_len], ); @memcpy(b.buffer[b.payload_start..end], sealed[0 .. payload_len + tls.tag_len]); // And only now the header, because the mask is sampled out of what // was just written. const sample = protection.sampleOf(b.buffer[0..end], b.number_offset) orelse return error.TooShortToSample; protection.protectHeader( keys, sample, &b.buffer[0], b.buffer[b.number_offset..][0..b.number_len], ); return b.buffer[0..end]; } }; fn need(buffer: []const u8, at: usize, n: usize) BuildError!void { if (buffer.len - at < n) return error.NoSpace; } fn putId(buffer: []u8, at: usize, id: []const u8) BuildError!usize { try need(buffer, at, 1 + id.len); buffer[at] = @intCast(id.len); @memcpy(buffer[at + 1 ..][0..id.len], id); return at + 1 + id.len; } fn putVarint(buffer: []u8, at: usize, value: u64) BuildError!usize { try need(buffer, at, varint.encodedLen(value)); return at + varint.write(buffer[at..], value).len; } /// §17.1: the packet number goes out in `out.len` octets, most significant /// first, truncated to that width. fn writeNumber(out: []u8, number: u64) void { for (out, 0..) |*b, i| { const shift: u6 = @intCast((out.len - 1 - i) * 8); b.* = @truncate(number >> shift); } } const frame = @import("frame.zig"); test "a packet built and then opened is the packet that went in" { const keys: protection.Keys = .initialKeys(&.{ 1, 2, 3, 4 }, .client); var buffer: [1200]u8 = undefined; var b = try Builder.initLong(&buffer, .{ .kind = .initial, .destination = &.{ 1, 2, 3, 4 }, .source = &.{ 9, 9 }, }, 7, 2); try b.add(.ping); try b.add(.{ .crypto = .{ .offset = 0, .data = "hello" } }); try b.padTo(1200); const wire = try b.finish(&keys); try testing.expectEqual(@as(usize, 1200), wire.len); var payload: [1200]u8 = undefined; const opened = try open(&keys, 0, wire, 0, &payload); try testing.expectEqual(Kind.initial, opened.header.kind); try testing.expectEqual(@as(u64, 7), opened.number); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, opened.header.destination); try testing.expectEqualSlices(u8, &.{ 9, 9 }, opened.header.source); var it: frame.Iterator = .init(opened.payload); try testing.expectEqual(frame.Kind.ping, (try it.next()).?); try testing.expectEqualStrings("hello", (try it.next()).?.crypto.data); // The rest is padding, which padTo added to reach the §14.1 minimum. try testing.expect((try it.next()).?.padding > 1000); try testing.expectEqual(@as(?frame.Frame, null), try it.next()); } test "a short header packet round-trips too" { const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [256]u8 = undefined; const cid = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 }; var b = try Builder.initShort(&buffer, &cid, 1000, 4, true); try b.add(.handshake_done); const wire = try b.finish(&keys); var payload: [256]u8 = undefined; const opened = try open(&keys, 999, wire, cid.len, &payload); try testing.expectEqual(Kind.one_rtt, opened.header.kind); try testing.expectEqual(Form.short, opened.header.form); try testing.expectEqual(@as(u64, 1000), opened.number); // The key phase bit survived protection and came back set. try testing.expect(opened.header.first & 0x04 != 0); var it: frame.Iterator = .init(opened.payload); try testing.expectEqual(frame.Kind.handshake_done, (try it.next()).?); } test "the reserved bits are zero on the way out" { // §17.2: "The value included prior to protection MUST be set to 0", and // a peer that finds them set after removing both protections treats it as // PROTOCOL_VIOLATION. Since `open` checks that, a builder that set them // would fail its own round trip -- but the check is worth making directly // rather than relying on that. const keys: protection.Keys = .initialKeys(&.{1}, .client); var buffer: [256]u8 = undefined; var b = try Builder.initLong(&buffer, .{ .kind = .handshake, .destination = &.{1}, .source = &.{}, }, 0, 1); try b.add(.ping); // Before protection is applied, the first octet is readable. try testing.expectEqual(@as(u8, 0), buffer[0] & 0x0c); // §5.4.2 again: one PING is not enough to sample from. try b.padTo(32); _ = try b.finish(&keys); } test "RFC 9001 5.4.2: a packet too short to sample is refused rather than sent" { // "at least 3 bytes of frames in the unprotected payload if the packet // number is encoded on a single byte". A lone PING is one, so a sender // that did not pad would produce a packet no receiver could unprotect. const keys: protection.Keys = .initialKeys(&.{1}, .client); var buffer: [256]u8 = undefined; var short = try Builder.initLong(&buffer, .{ .kind = .handshake, .destination = &.{1}, .source = &.{}, }, 0, 1); try short.add(.ping); try testing.expectError(error.TooShortToSample, short.finish(&keys)); // Two more octets of frames and it is sendable, which is exactly the // three the section names. var enough = try Builder.initLong(&buffer, .{ .kind = .handshake, .destination = &.{1}, .source = &.{}, }, 0, 1); try enough.add(.ping); try enough.add(.ping); try enough.add(.ping); _ = try enough.finish(&keys); } test "a builder refuses to overrun its buffer" { var buffer: [40]u8 = undefined; var b = try Builder.initLong(&buffer, .{ .kind = .initial, .destination = &.{1}, .source = &.{}, }, 0, 1); // Room is left for the authentication tag, so filling the payload stops // short of the buffer rather than at it. try testing.expect(b.remaining() < buffer.len - b.payload_start); try testing.expectError( error.NoSpace, b.add(.{ .crypto = .{ .offset = 0, .data = &[_]u8{0} ** 64 } }), ); try testing.expectError(error.NoSpace, b.padTo(1200)); } test "RFC 9000 17.2.1: a Version Negotiation packet echoes both connection IDs, swapped" { // "The server MUST include the value from the Source Connection ID field // of the packet it receives in the Destination Connection ID field. The // value for Source Connection ID MUST be copied from the Destination // Connection ID of the received packet." const received: Header = .{ .form = .long, .kind = .initial, .first = 0xc0, .version = 0xdeadbeef, .destination = &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, .source = &.{ 9, 10, 11 }, .token = &.{}, .number_offset = 0, .end = 0, }; var out: [128]u8 = undefined; const wire = try writeVersionNegotiation(&out, received, &supported_versions, 0x40); // §17.2.1: the form bit set, and the 0x40 recommendation honored so that // a demultiplexer sharing this port sees what looks like the Fixed Bit. try testing.expect(wire[0] & 0x80 != 0); try testing.expect(wire[0] & 0x40 != 0); try testing.expectEqual(@as(u32, 0), std.mem.readInt(u32, wire[1..5], .big)); // The swap, read straight off the wire rather than through the parser, so // that a parser with the same mistake in it could not agree. try testing.expectEqual(@as(u8, 3), wire[5]); try testing.expectEqualSlices(u8, received.source, wire[6..9]); try testing.expectEqual(@as(u8, 8), wire[9]); try testing.expectEqualSlices(u8, received.destination, wire[10..18]); try testing.expectEqual(@as(u32, version_1), std.mem.readInt(u32, wire[18..22], .big)); try testing.expectEqual(@as(usize, 22), wire.len); // And it parses back as what it is. const parsed = try parse(wire, 8); try testing.expectEqual(Kind.version_negotiation, parsed.kind); try testing.expectEqual(@as(u32, 0), parsed.version); try testing.expectEqualSlices(u8, received.source, parsed.destination); try testing.expectEqualSlices(u8, received.destination, parsed.source); } test "RFC 9000 17.2.1: version 0 is not a version any endpoint selects" { // "Upon receipt by a client, it will be identified as a Version // Negotiation packet based on the Version field having a value of 0", so // answering a zero version as though it had been chosen would be // answering a Version Negotiation packet with another one -- which §6.1 // forbids outright. try testing.expect(!supportsVersion(0)); try testing.expect(supportsVersion(version_1)); try testing.expect(!supportsVersion(0xdeadbeef)); // §6.3's reserved pattern, which a peer is entitled to send to check that // an unknown version is ignored rather than accepted. try testing.expect(!supportsVersion(0x1a2a3a4a)); } test "a Version Negotiation packet that will not fit is refused rather than truncated" { const received: Header = .{ .form = .long, .kind = .initial, .first = 0xc0, .version = 0xdeadbeef, .destination = &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, .source = &.{ 9, 10, 11 }, .token = &.{}, .number_offset = 0, .end = 0, }; var small: [21]u8 = undefined; try testing.expectError(error.NoSpace, writeVersionNegotiation(&small, received, &supported_versions, 0x40)); }