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.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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.//!//! `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;}
test supportsVersion { // A server deciding whether to answer an Initial or to offer Version // Negotiation instead. try testing.expect(supportsVersion(version_1)); try testing.expect(!supportsVersion(0x6b3343cf)); // QUIC version 2, not spoken here try testing.expect(!supportsVersion(0));}
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, and so which /// keys open it; null for the two kinds no key schedule protects. 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, }; }
test level { // A 0-RTT packet is opened with the early data keys, and a Retry with // none at all. try testing.expectEqual(@as(?tls.Level, .early_data), Kind.zero_rtt.level()); try testing.expectEqual(@as(?tls.Level, null), Kind.retry.level()); }
/// Whether a packet of this kind has a Packet Number field — and so /// whether it is header-protected and can go through `open`. pub fn hasNumber(k: Kind) bool { return switch (k) { .initial, .zero_rtt, .handshake, .one_rtt => true, .retry, .version_negotiation => false, }; }
test hasNumber { try testing.expect(Kind.handshake.hasNumber()); try testing.expect(!Kind.version_negotiation.hasNumber()); }};
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". /// /// `datagram` is the one `h` was parsed from, and `number_len` the length /// header protection revealed. The slice points into `datagram`, and is /// only the right associated data once header protection has been /// removed from those octets. pub fn associatedData(h: Header, datagram: []const u8, number_len: usize) []const u8 { return datagram[0 .. h.number_offset + number_len]; }
test associatedData { // §A.2's header, protection already removed: 22 octets ending in a // four-octet packet number. var datagram = rfc9001.client_protected_packet; @memcpy(datagram[0..rfc9001.client_header.len], &rfc9001.client_header); const h = try parse(&datagram, 0); try testing.expectEqualSlices(u8, &rfc9001.client_header, h.associatedData(&datagram, 4)); }
/// The protected payload: everything after the packet number, up to the /// end of this packet, tag included. Like `associatedData`, it takes the /// datagram `h` was parsed from and the revealed packet number length, /// and points into `datagram`. pub fn ciphertext(h: Header, datagram: []const u8, number_len: usize) []const u8 { return datagram[h.number_offset + number_len .. h.end]; }
test ciphertext { // §A.3's packet, with its two-octet packet number: what follows is the // payload and the tag, and nothing past the end of the packet. const datagram = rfc9001.server_protected_packet; const h = try parse(&datagram, 0); const sealed = h.ciphertext(&datagram, 2); try testing.expectEqual(rfc9001.server_payload.len + tls.tag_len, sealed.len); }};
/// 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. It must be at most twenty,/// which is asserted.////// Every kind of packet comes back, Retry and Version Negotiation included;/// `Header.kind` says which. The Fixed Bit must be set, except on a Version/// Negotiation packet, whose first octet is not interpreted at all. The/// connection IDs and the token in the result point into `datagram`, and/// `Header.end` is where the next coalesced packet, if any, begins.pub fn parse(datagram: []const u8, local_connection_id_len: usize) Error!Header { return parseWith(datagram, local_connection_id_len, false);}
test parse { // §A.2's Initial, as the server receives it: nothing about it needs a key // except the packet number and what follows. const h = try parse(&rfc9001.client_protected_packet, 0); try testing.expectEqual(Kind.initial, h.kind); try testing.expectEqualSlices(u8, &rfc9001.destination_connection_id, h.destination); try testing.expectEqual(@as(usize, 18), h.number_offset); try testing.expectEqual(rfc9001.client_protected_packet.len, h.end);
// A short header, read by the endpoint whose connection IDs are four // octets long. const short = try parse(&.{ 0x41, 0xaa, 0xbb, 0xcc, 0xdd, 0x00, 0x00 }, 4); try testing.expectEqual(Kind.one_rtt, short.kind); try testing.expectEqual(@as(usize, 5), short.number_offset);}
/// `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)), };}
test parseWith { // A peer that saw this endpoint's grease_quic_bit may send a 1-RTT packet // with the Fixed Bit clear. const datagram = [_]u8{ 0x01, 0xaa, 0xbb, 0xcc, 0xdd, 0x00, 0x00 }; try testing.expectError(error.NotQuic, parseWith(&datagram, 4, false)); const h = try parseWith(&datagram, 4, true); try testing.expectEqual(Kind.one_rtt, h.kind);}
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 centered on what is expected rather than simply masked in.////// `largest` is the largest packet number authenticated so far in this/// packet number space, `truncated` the value read off the wire after header/// protection was removed, and `number_len` how many octets it took, one to/// four (asserted). Before any packet has been authenticated, `largest` of/// zero is what the callers here pass.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;}
test decodeNumber { // Appendix A.3's example: 0xa82f30ea authenticated, then a packet whose // two octets of packet number read 0x9b32. try testing.expectEqual(@as(u64, 0xa82f9b32), decodeNumber(0xa82f30ea, 0x9b32, 2));}
/// 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.////// `largest_acked` is null before anything in this packet number space has/// been acknowledged, and must not be greater than `number` (asserted). The/// result is the fewest octets that will do; a sender may use more, and/// `Builder` takes whatever it is given.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;}
test encodedNumberLen { // §A.2 of RFC 9000's example: with 0xabe8b3 acknowledged, sending // 0xac5c02 needs sixteen bits. try testing.expectEqual(@as(usize, 2), encodedNumberLen(0xac5c02, 0xabe8b3)); // Nothing acknowledged yet, so the whole number goes out. try testing.expectEqual(@as(usize, 3), encodedNumberLen(0xac5c02, null));}
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,};
/// 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 { /// As `parse` read it, so `header.first` is still the protected octet. 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, which says whether the packet was protected /// with the current keys or the next ones. Meaningful only for a short /// header; a long header has no such bit and the value is noise. pub fn keyPhase(r: Revealed) bool { return r.first & 0x04 != 0; }
test keyPhase { // A 1-RTT packet sent after one key update, read by an endpoint that // must pick the keys to decrypt it with. const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [64]u8 = undefined; const datagram = try testShortPacket(&buffer, &keys, 1000, true);
const revealed = try reveal(&keys, 999, datagram, test_cid.len, false); try testing.expect(revealed.keyPhase()); }};
/// Removes header protection and reconstructs the packet number, in place.////// `keys` is used only for its header protection key, which every key phase/// shares. `largest` is the largest packet number authenticated so far in the/// packet's number space (see `decodeNumber`), and `local_connection_id_len`/// is as for `parse`.////// The first octet and the packet number in `datagram` are unmasked before/// anything has been authenticated, so a packet that then fails to decrypt/// has been changed and cannot be revealed again with another key. A Retry/// or Version Negotiation packet is `NotProtected`, and one too short to/// sample is `TooShortToSample`.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, };}
test reveal { // §A.3's server Initial, as the client receives it. Header protection // comes off, and the two-octet packet number it hid reads as 1. var datagram = rfc9001.server_protected_packet; const keys: protection.Keys = .initialKeys(&rfc9001.destination_connection_id, .server); const revealed = try reveal(&keys, 0, &datagram, 0, false);
try testing.expectEqual(@as(u64, 1), revealed.number); try testing.expectEqual(@as(usize, 2), revealed.number_len); // In place: the header in the datagram is now the unprotected one. try testing.expectEqualSlices(u8, &rfc9001.server_header, datagram[0..rfc9001.server_header.len]);}
/// Decrypts the payload of a packet whose header protection has been removed.////// `revealed` and `datagram` are what `reveal` returned and worked on, and/// `keys` are the packet protection keys for `revealed`'s key phase — which/// need not be the ones it was revealed with. `out` receives the plaintext and/// must hold the ciphertext less its sixteen-octet tag, or the answer is/// `BufferTooSmall`. The reserved bits are checked only after the packet has/// authenticated, and are `ReservedBitsSet` if they are not zero.////// The result's `payload` points into `out`, and its `header` into/// `datagram`, with `header.first` the unmasked octet.pub fn decrypt( keys: *const protection.Keys, revealed: Revealed, datagram: []u8, out: []u8,) OpenError!Opened { return decryptOn(keys, 0, revealed, datagram, out);}
test decrypt { // A 1-RTT packet, revealed with the header protection key every phase // shares and then decrypted with the keys its Key Phase bit picked. const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [64]u8 = undefined; const datagram = try testShortPacket(&buffer, &keys, 1000, false);
const revealed = try reveal(&keys, 999, datagram, test_cid.len, false); var payload: [64]u8 = undefined; const opened = try decrypt(&keys, revealed, datagram, &payload); try testing.expectEqual(@as(u64, 1000), opened.number); var it: frame.Iterator = .init(opened.payload); try testing.expectEqual(frame.Kind.handshake_done, (try it.next()).?);}
/// `decrypt` for a packet on multipath path `path`, whose nonce carries the/// path ID (draft-ietf-quic-multipath-21 §2.4). Path 0 is `decrypt`.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], };}
test decryptOn { // A 1-RTT packet sent on multipath path 2 opens only as a path 2 packet. const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [64]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 1000, 2, false); try b.add(.handshake_done); try b.padTo(32); const datagram = try b.finishOn(&keys, 2);
const revealed = try reveal(&keys, 999, datagram, test_cid.len, false); var payload: [64]u8 = undefined; try testing.expectError(error.AuthenticationFailed, decryptOn(&keys, 0, revealed, datagram, &payload)); const opened = try decryptOn(&keys, 2, revealed, datagram, &payload); try testing.expectEqual(@as(u64, 1000), opened.number);}
/// Both passes and the decryption: everything a receiver does between a/// datagram arriving and having frames to read.////// `reveal` and `decrypt` 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. The Fixed Bit is required, as by `parse`; a connection that agreed/// to grease it calls `reveal` and `decrypt` itself.////// `datagram` is modified in place — header protection is removed from it —/// and `out` receives the plaintext, which is sixteen octets shorter than the/// ciphertext. `largest` and `local_connection_id_len` are as for `reveal`.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);}
test open { // §A.2's Initial, as the server receives it: nothing authenticated yet, // so `largest` is zero. var datagram = rfc9001.client_protected_packet; const keys: protection.Keys = .initialKeys(&rfc9001.destination_connection_id, .client); var payload: [rfc9001.client_payload_len]u8 = undefined; const opened = try open(&keys, 0, &datagram, 0, &payload);
try testing.expectEqual(Kind.initial, opened.header.kind); try testing.expectEqual(@as(u64, 2), opened.number); try testing.expectEqualSlices(u8, &rfc9001.clientInitialPayload(), opened.payload);}
/// The connection ID `testShortPacket` addresses its packets to.const test_cid = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 };
/// A 1-RTT packet carrying HANDSHAKE_DONE, padded to be long enough to/// sample, for the doctests that need a short header to work on.fn testShortPacket(buffer: []u8, keys: *const protection.Keys, number: u64, key_phase: bool) BuildError![]u8 { var b = try Builder.initShort(buffer, &test_cid, number, 2, key_phase); try b.add(.handshake_done); try b.padTo(32); return b.finish(keys);}
const testing = std.testing;const rfc9001 = @import("rfc9001.zig");
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());}
/// 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.////// Only the header form bit is checked: a short header is `NotQuic`, and the/// Fixed Bit is not looked at. The connection IDs point into `datagram`.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 };}
test peekLongHeader { // An Initial for a version this endpoint has never heard of, with a // 32-octet connection ID that `parse` would refuse as too long for // version 1. var datagram: [64]u8 = @splat(0); datagram[0] = 0xc0; std.mem.writeInt(u32, datagram[1..5], 0x1a2a3a4a, .big); datagram[5] = 32; datagram[38] = 4;
try testing.expectError(error.ConnectionIdTooLong, parse(&datagram, 0)); const peeked = try peekLongHeader(&datagram); try testing.expect(!supportsVersion(peeked.version)); try testing.expectEqual(@as(usize, 32), peeked.destination.len); try testing.expectEqual(@as(usize, 4), peeked.source.len);}
/// §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.////// `received` needs only its two connection IDs filled in correctly; a/// caller with `peekLongHeader`'s result builds one from that. `versions` is/// written as given, most preferred first, and the packet goes into the front/// of `out`, `NoSpace` if it will not fit.////// `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.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];}
test writeVersionNegotiation { // A client tried version 0x1a2a3a4a, from connection ID 0x0102 to 0xaabb. var datagram: [16]u8 = @splat(0); datagram[0] = 0xc0; std.mem.writeInt(u32, datagram[1..5], 0x1a2a3a4a, .big); @memcpy(datagram[5..11], &[_]u8{ 2, 0xaa, 0xbb, 2, 0x01, 0x02 }); const peeked = try peekLongHeader(&datagram);
var out: [64]u8 = undefined; const wire = try writeVersionNegotiation(&out, .{ .form = .long, .kind = .version_negotiation, .first = datagram[0], .version = peeked.version, .destination = peeked.destination, .source = peeked.source, .token = &.{}, .number_offset = 0, .end = datagram.len, }, &supported_versions, 0x40);
// Back to where it came from, offering version 1 instead. const answer = try parse(wire, 0); try testing.expectEqual(Kind.version_negotiation, answer.kind); try testing.expectEqualSlices(u8, &.{ 0x01, 0x02 }, answer.destination); try testing.expectEqualSlices(u8, &.{ 0xaa, 0xbb }, answer.source); try testing.expectEqual(version_1, std.mem.readInt(u32, wire[wire.len - 4 ..][0..4], .big));}
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. /// /// Only Initial, 0-RTT and Handshake packets are built this way; any other /// `spec.kind` has no packet number and is `InvalidNumberLength`, as is a /// `number_len` outside one to four. A connection ID longer than twenty /// octets is `ConnectionIdTooLong`, and a header that does not fit in /// `buffer` is `NoSpace`. The builder writes into `buffer` and keeps it, /// so `buffer` must outlive it and the packet `finish` returns. 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, }; }
test initLong { // A client's first Handshake packet, numbered 0 in that space and // so written in a single octet. const keys: protection.Keys = .initialKeys(&.{ 1, 2, 3, 4 }, .client); var buffer: [128]u8 = undefined; var b = try Builder.initLong(&buffer, .{ .kind = .handshake, .destination = &.{ 1, 2, 3, 4 }, .source = &.{ 5, 6 }, }, 0, encodedNumberLen(0, null)); try b.add(.{ .crypto = .{ .offset = 0, .data = "finished" } }); const wire = try b.finish(&keys);
try testing.expectEqual(Kind.handshake, (try parse(wire, 0)).kind); }
/// Starts a 1-RTT packet, addressed to `destination`, with `key_phase` as /// its Key Phase bit and the spin bit clear. /// /// The errors are `initLong`'s, and `buffer` is held the same way. 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, }; }
test initShort { // A 1-RTT packet to the peer's eight-octet connection ID, with a // two-octet packet number. const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [64]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 1000, 2, false); try b.add(.handshake_done); try b.padTo(32); const wire = try b.finish(&keys);
try testing.expectEqual(Form.short, (try parse(wire, test_cid.len)).form); }
/// Appends a frame to the payload. /// /// A frame that would not fit, leaving room for the tag, is `NoSpace` /// and leaves the packet as it was, so the caller can send what it has /// and put the frame in the next one. 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); }
test add { var buffer: [64]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 0, 1, false); try b.add(.ping); try b.add(.{ .crypto = .{ .offset = 0, .data = "hi" } }); // A frame bigger than what is left does not go in. try testing.expectError(error.NoSpace, b.add(.{ .crypto = .{ .offset = 0, .data = &@as([64]u8, @splat(0)) } })); // PING is one octet; the CRYPTO frame is a type, an offset, a length // and its two octets of data. try testing.expectEqual(@as(usize, 1 + (1 + 1 + 1 + 2)), b.payloadLen()); }
/// 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; }
test remaining { // A 1200-octet datagram: header, then frames, then a sixteen-octet tag. var buffer: [1200]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 0, 1, false); try testing.expectEqual(@as(usize, 1200 - (1 + test_cid.len + 1) - 16), b.remaining()); try b.add(.ping); try testing.expectEqual(@as(usize, 1200 - (1 + test_cid.len + 1) - 16 - 1), b.remaining()); }
/// How many octets of frames, padding included, have been added so far: /// the plaintext `finish` will encrypt, without its tag. pub fn payloadLen(b: *const Builder) usize { return b.at - b.payload_start; }
test payloadLen { var buffer: [64]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 0, 1, false); try testing.expectEqual(@as(usize, 0), b.payloadLen()); try b.add(.ping); try b.add(.handshake_done); try testing.expectEqual(@as(usize, 2), b.payloadLen()); }
/// 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. /// /// `total` counts from the start of this packet's header, not of the /// datagram it will be coalesced into. A packet already that long is left /// alone, and one that cannot reach it in `buffer` is `NoSpace`. 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; }
test padTo { // A client's Initial, padded to §14.1's 1200 octets. 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 = &.{}, }, 0, 1); try b.add(.{ .crypto = .{ .offset = 0, .data = "ClientHello" } }); try b.padTo(1200); try testing.expectEqual(@as(usize, 1200), (try b.finish(&keys)).len); }
/// Encrypts the payload, fills in the Length, applies header protection, /// and returns the finished packet. /// /// The packet is the front of the builder's buffer, from its first octet /// to the end of the tag. Fewer than §5.4.2's sample needs is /// `TooShortToSample`, and the cure is `padTo`. A payload over 2032 /// octets is `NoSpace` whatever the size of the buffer, because the /// ciphertext is staged in a 2048-octet array on the stack. pub fn finish(b: *Builder, keys: *const protection.Keys) BuildError![]u8 { return b.finishOn(keys, 0); }
test finish { // §A.3's server Initial, built rather than read: the octets the // appendix prints. const keys: protection.Keys = .initialKeys(&rfc9001.destination_connection_id, .server); var buffer: [rfc9001.server_protected_packet.len]u8 = undefined; var b = try Builder.initLong(&buffer, .{ .kind = .initial, .destination = &.{}, .source = &.{ 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5 }, }, 1, 2); var it: frame.Iterator = .init(&rfc9001.server_payload); while (try it.next()) |f| try b.add(f);
try testing.expectEqualSlices(u8, &rfc9001.server_protected_packet, try b.finish(&keys)); }
/// `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]; }
test finishOn { // A packet sent on multipath path 1 is opened as a path 1 packet. const keys: protection.Keys = .initialKeys(&.{0xab}, .server); var buffer: [64]u8 = undefined; var b = try Builder.initShort(&buffer, &test_cid, 5, 1, false); try b.add(.handshake_done); try b.padTo(32); const wire = try b.finishOn(&keys, 1);
const revealed = try reveal(&keys, 4, wire, test_cid.len, false); var payload: [64]u8 = undefined; _ = try decryptOn(&keys, 1, revealed, wire, &payload); }};
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 = &@as([64]u8, @splat(0)) } }), ); 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));}