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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! RFC 9001 §5: turning a traffic secret into the keys that protect a packet.//!//! Everything here is pure arithmetic over byte slices. There is no packet//! parsing in this file and no I/O: a secret goes in, a key, an IV and a//! header protection key come out, and the three functions that use them take//! the pieces of a packet as slices the caller has already located.//!//! Two things in here need no TLS at all, which is why this file can be//! finished long before anything is behind `tls.Handshake`://!//! * **Initial keys** (§5.2) come from the client's first Destination//! Connection ID and a fixed salt. That is what lets either endpoint read//! the other's first packet before a single handshake message has been//! understood — and equally, why an Initial packet has no confidentiality//! worth the name, since anyone who saw the connection ID can derive the//! same keys.//! * **Header protection** (§5.4) is a second, separate key schedule over the//! same secret, and exists because the packet number has to be readable by//! the endpoint and unreadable by everything in the path. Without it a//! middlebox could follow a connection across a migration by watching the//! numbers advance.//!//! The order matters and is easy to get backwards: **protect the payload//! first, then the header** (§5.4.1, "Header protection is applied after//! packet protection"), because the header protection mask is sampled *from//! the encrypted payload*. Removing protection is the mirror image, and//! `sampleOf` exists so that the sampling offset is worked out once rather//! than at every call site.
const std = @import("std");const assert = std.debug.assert;const crypto = std.crypto;
const tls = @import("tls.zig");const Suite = tls.Suite;
/// §5.2. "a salt of 0x38762cf7f55934b34d179ae6a4c80cadccbb7f0a".////// Version-specific on purpose: §5.2 asks future versions of QUIC to pick a/// new one "thus ensuring that the keys are different for each version",/// which stops a middlebox that understands version 1 from reading — or/// rewriting — a version it does not.pub const initial_salt_v1 = [_]u8{ 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a,};
/// §5.4.2: "The same number of bytes are always sampled" — sixteen, for every/// suite this implements.pub const sample_len = 16;
/// §5.4.1: the mask is five octets, one for the first byte and four for the/// longest packet number encoding.pub const mask_len = 5;
/// Which end of the connection a set of keys protects.pub const Side = enum { client, server,
/// §5.2's labels. "client in" derives what a client uses to *send*, which /// is also what a server uses to *read*. fn initialLabel(s: Side) []const u8 { return switch (s) { .client => "client in", .server => "server in", }; }};
/// The three values §5.1 derives from one traffic secret.pub const Keys = struct { suite: Suite, key_buf: [tls.max_key_len]u8 = @splat(0), iv_buf: [tls.iv_len]u8 = @splat(0), hp_buf: [tls.max_key_len]u8 = @splat(0),
/// The AEAD key, "quic key": as long as the suite's key, sixteen or /// thirty-two octets. The slice points into `k`. pub fn key(k: *const Keys) []const u8 { return k.key_buf[0..k.suite.keyLen()]; }
test key { // §A.1: the client's Initial key. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); var want: [16]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "1f369613dd76d5467730efcbe3b1a22d"); try testing.expectEqualSlices(u8, &want, keys.key()); }
/// The IV, "quic iv", that `nonce` combines with the packet number. The /// slice points into `k`. pub fn iv(k: *const Keys) []const u8 { return k.iv_buf[0..k.suite.ivLen()]; }
test iv { // §A.1: the client's Initial IV. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); var want: [12]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "fa044b2f42a3fd3b46fb255c"); try testing.expectEqualSlices(u8, &want, keys.iv()); }
/// The header protection key, "quic hp": as long as the suite's AEAD key, /// because §5.4 uses the same cipher. The slice points into `k`. pub fn hp(k: *const Keys) []const u8 { return k.hp_buf[0..k.suite.keyLen()]; }
test hp { // §A.1: the client's Initial header protection key. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); var want: [16]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "9f50449e04a0e810283a1e9933adedd2"); try testing.expectEqualSlices(u8, &want, keys.hp()); }
/// §5.1: the three labels, applied to a secret TLS handed over. /// /// The labels are what keep QUIC's keys separate from the TLS record /// keys derived from the very same secret — §9.6 — so a key recovered /// from one cannot be used against the other. /// /// Nothing is kept from `secret` but what is derived from it, so the /// handshake that lent it may move on as soon as this returns. pub fn fromSecret(secret: tls.Secret) Keys { var k: Keys = .{ .suite = secret.suite }; expandLabel(secret.suite, secret.material, "quic key", k.key_buf[0..secret.suite.keyLen()]); expandLabel(secret.suite, secret.material, "quic iv", k.iv_buf[0..secret.suite.ivLen()]); expandLabel(secret.suite, secret.material, "quic hp", k.hp_buf[0..secret.suite.keyLen()]); return k; }
test fromSecret { // §A.5: the ChaCha20-Poly1305 1-RTT secret, and the three values the // appendix derives from it. var secret: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&secret, "9ac312a7f877468ebe69422748ad00a15443f18203a07d6060f688f30f21632b"); const keys: Keys = .fromSecret(.{ .suite = .chacha20_poly1305_sha256, .material = &secret });
var want_key: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&want_key, "c6d98ff3441c3fe1b2182094f69caa2ed4b716b65488960a7a984979fb23e1c8"); try testing.expectEqualSlices(u8, &want_key, keys.key()); var want_iv: [12]u8 = undefined; _ = try std.fmt.hexToBytes(&want_iv, "e0459b3474bdd0e44a41c144"); try testing.expectEqualSlices(u8, &want_iv, keys.iv()); var want_hp: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&want_hp, "25a282b9e82f06f21f488917a4fc8f1b73573685608597d0efcb076b0ab7a7a4"); try testing.expectEqualSlices(u8, &want_hp, keys.hp()); }
/// §5.2. The Initial keys, from the client's first Destination Connection /// ID. /// /// `side` says whose keys these are for *sending*; an endpoint needs both, /// its own to write with and its peer's to read with. pub fn initialKeys(destination_connection_id: []const u8, side: Side) Keys { const Hkdf = crypto.kdf.hkdf.HkdfSha256; const initial_secret = Hkdf.extract(&initial_salt_v1, destination_connection_id);
// §5.2: "The hash function for HKDF when deriving initial secrets and // keys is SHA-256", whatever is negotiated later, and the AEAD is // fixed to AEAD_AES_128_GCM by §5. var secret: [32]u8 = undefined; expandLabel(.aes_128_gcm_sha256, &initial_secret, side.initialLabel(), &secret);
return .fromSecret(.{ .suite = .aes_128_gcm_sha256, .material = &secret }); }
test initialKeys { // A server reading §A.2's Initial derives the client's sending keys // from the connection ID on the packet, and its own from the same // value: no handshake message has been read yet. const read: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); const write: Keys = .initialKeys(&rfc9001.destination_connection_id, .server);
var payload: [rfc9001.client_payload_len]u8 = undefined; try decrypt(&read, 2, &rfc9001.client_header, rfc9001.client_protected_packet[rfc9001.client_header.len..], &payload); try testing.expect(!std.mem.eql(u8, read.key(), write.key())); }
/// §5.3: "The 62 bits of the reconstructed QUIC packet number in network /// byte order are left-padded with zeros to the size of the IV. The /// exclusive OR of the padded packet number and the IV forms the AEAD /// nonce." /// /// The *reconstructed* number, not the truncated one on the wire. A /// receiver that used the encoded value would derive a different nonce /// from the sender for every packet past the first wrap, and every /// decryption would fail. pub fn nonce(k: *const Keys, packet_number: u64) [tls.iv_len]u8 { return k.nonceOn(0, packet_number); }
test nonce { // §A.5: packet number 654360564 under the ChaCha20 1-RTT IV // e0459b3474bdd0e44a41c144. var keys: Keys = .{ .suite = .chacha20_poly1305_sha256 }; _ = try std.fmt.hexToBytes(&keys.iv_buf, "e0459b3474bdd0e44a41c144"); var want: [tls.iv_len]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "e0459b3474bdd0e46d417eb0"); try testing.expectEqualSlices(u8, &want, &keys.nonce(654360564)); }
/// draft-ietf-quic-multipath-21 §2.4: the nonce for a packet on a path /// other than the first, where each path numbers its packets from zero /// and the packet number alone no longer makes the nonce unique. /// /// "A 96-bit Path-and-Packet-Number (PPN) is composed of the 32 bits of /// the path ID in network byte order, two zero bits, and the 62 bits of /// the reconstructed QUIC packet number", XORed into the IV exactly as the /// packet number alone was. Path 0 contributes nothing, so its nonce is /// RFC 9001's -- which is why `nonce` is this with a zero, and why a /// connection that negotiates multipath and uses one path protects its /// packets exactly as one that did not. pub fn nonceOn(k: *const Keys, path: u32, packet_number: u64) [tls.iv_len]u8 { var out: [tls.iv_len]u8 = k.iv_buf; var ppn: [12]u8 = undefined; std.mem.writeInt(u32, ppn[0..4], path, .big); // A packet number is at most 2^62 - 1 (§17.1), so its top two bits // are the "two zero bits" without anything having to clear them. std.mem.writeInt(u64, ppn[4..12], packet_number, .big); for (0..12) |i| out[out.len - 12 + i] ^= ppn[i]; return out; }
test nonceOn { // The draft's Figure 3: IV 6b26114b9cba2b63a9e8dd4f, path 3, packet // number 54321. var keys: Keys = .{ .suite = .aes_128_gcm_sha256 }; _ = try std.fmt.hexToBytes(&keys.iv_buf, "6b26114b9cba2b63a9e8dd4f"); var want: [tls.iv_len]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "6b2611489cba2b63a9e8097e"); try testing.expectEqualSlices(u8, &want, &keys.nonceOn(3, 54321)); }};
/// A traffic secret this library owns.////// `tls.Secret` borrows from the handshake and is "valid only until the next/// call on this handshake", which is fine for deriving keys immediately and/// useless for a ratchet — §6.1 of RFC 9001 derives each key phase's secret/// from the one before it, so the secret has to outlive the handshake that/// produced the first one.pub const OwnedSecret = struct { suite: Suite, buf: [tls.max_secret_len]u8 = undefined, len: usize = 0,
/// Copies a secret the handshake has lent out, so that it survives the /// next call on that handshake. pub fn from(secret: tls.Secret) OwnedSecret { var s: OwnedSecret = .{ .suite = secret.suite, .len = secret.material.len }; @memcpy(s.buf[0..s.len], secret.material); return s; }
test from { var lent: [32]u8 = @splat(0x11); const owned: OwnedSecret = .from(.{ .suite = .aes_128_gcm_sha256, .material = &lent });
// The handshake moves on and reuses its buffer; the copy is unmoved. lent = @splat(0x22); try testing.expectEqualSlices(u8, &@as([32]u8, @splat(0x11)), owned.material()); }
/// The secret's octets: as many as the suite's hash produces. The slice /// points into `s`, so it lasts as long as `s` does and no longer. pub fn material(s: *const OwnedSecret) []const u8 { return s.buf[0..s.len]; }
test material { const owned: OwnedSecret = .from(.{ .suite = .aes_256_gcm_sha384, .material = &@as([48]u8, @splat(7)) }); // SHA-384's length, not the size of the buffer it is kept in. try testing.expectEqual(@as(usize, 48), owned.material().len); }
/// The secret in the shape `Keys.fromSecret` takes, borrowing from `s`: /// valid until `s` is changed, moved or goes out of scope. pub fn borrow(s: *const OwnedSecret) tls.Secret { return .{ .suite = s.suite, .material = s.material() }; }
test borrow { const owned: OwnedSecret = .from(.{ .suite = .aes_128_gcm_sha256, .material = &@as([32]u8, @splat(3)) }); const keys: Keys = .fromSecret(owned.borrow()); try testing.expectEqual(Suite.aes_128_gcm_sha256, keys.suite); }
/// The next secret in the ratchet. /// /// §6.1: `secret_<n+1> = HKDF-Expand-Label(secret_<n>, "quic ku", "", /// Hash.length)`. /// /// The ratchet that makes a key update one-way. The new secret is derived /// from the old one and the old one is thrown away, so an attacker who /// recovers a key learns nothing about the traffic before it — which is /// the whole point of updating keys at all, and the reason the derivation /// runs forwards only. Throwing the old one away is the caller's part: /// this leaves `s` as it was. pub fn next(s: *const OwnedSecret) OwnedSecret { var out: OwnedSecret = .{ .suite = s.suite, .len = s.len }; expandLabel(s.suite, s.material(), "quic ku", out.buf[0..s.len]); return out; }
test next { // RFC 9001 §A.5's ChaCha20 example: the 1-RTT secret, and the one // the first key update moves to. var current_secret: [32]u8 = undefined; _ = try std.fmt.hexToBytes(¤t_secret, "9ac312a7f877468ebe69422748ad00a15443f18203a07d6060f688f30f21632b"); const current: OwnedSecret = .from(.{ .suite = .chacha20_poly1305_sha256, .material = ¤t_secret });
var want: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "1223504755036d556342ee9361d253421a826c9ecdf3c7148684b36b714881f9"); try testing.expectEqualSlices(u8, &want, current.next().material()); }};
/// The keys for the next key phase.////// §6.1: "The corresponding key and IV are created from that secret as/// defined in Section 5.1. The header protection key is not updated." That/// last sentence is load-bearing: a receiver has to remove header protection/// before it can read the Key Phase bit that tells it which packet protection/// keys to use, so the header protection key cannot be one of the things the/// update changes.pub fn nextKeys(current: *const Keys, secret: OwnedSecret) Keys { var k: Keys = .fromSecret(secret.borrow()); k.hp_buf = current.hp_buf; return k;}
test nextKeys { // §A.5: a key update from the ChaCha20 1-RTT secret. var secret: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&secret, "9ac312a7f877468ebe69422748ad00a15443f18203a07d6060f688f30f21632b"); const owned: OwnedSecret = .from(.{ .suite = .chacha20_poly1305_sha256, .material = &secret }); const current: Keys = .fromSecret(owned.borrow());
const updated = nextKeys(¤t, owned.next()); // New packet protection keys... try testing.expect(!std.mem.eql(u8, current.key(), updated.key())); try testing.expect(!std.mem.eql(u8, current.iv(), updated.iv())); // ...and the same header protection key, which a receiver needs before // it can even see the Key Phase bit. try testing.expectEqualSlices(u8, current.hp(), updated.hp());}
/// TLS 1.3's HKDF-Expand-Label (RFC 8446 §7.1), with the zero-length context/// every use in QUIC has (§5.1).////// The structure being hashed is////// ```text/// struct {/// uint16 length;/// opaque label<7..255> = "tls13 " + Label;/// opaque context<0..255> = Context;/// } HkdfLabel;/// ```////// and RFC 9001 Appendix A.1 prints the four encodings QUIC produces, which/// `rfc9001.zig` checks byte for byte — it is the cheapest possible test that/// the framing above is right, and getting it wrong yields keys that are/// perfectly well-formed and wrong.////// `label` is given without the "tls13 " prefix, which this adds, and/// `out.len` is both how much is derived and the length written into the/// structure. `secret` is used as the HKDF pseudorandom key and must be at/// least as long as the suite's hash: thirty-two octets, or forty-eight for/// `aes_256_gcm_sha384`.pub fn expandLabel(suite: Suite, secret: []const u8, label: []const u8, out: []u8) void { var info: [max_hkdf_label_len]u8 = undefined; const len = hkdfLabel(&info, out.len, label);
switch (suite) { .aes_128_gcm_sha256, .chacha20_poly1305_sha256 => { const Hkdf = crypto.kdf.hkdf.HkdfSha256; var prk: [Hkdf.prk_length]u8 = undefined; @memcpy(&prk, secret[0..Hkdf.prk_length]); Hkdf.expand(out, info[0..len], prk); }, .aes_256_gcm_sha384 => { // `std.crypto.kdf.hkdf` names SHA-256 and SHA-512 and not this // one, so it is built from the HMAC the same way those two are. const Hkdf = crypto.kdf.hkdf.Hkdf(crypto.auth.hmac.sha2.HmacSha384); var prk: [Hkdf.prk_length]u8 = undefined; @memcpy(&prk, secret[0..Hkdf.prk_length]); Hkdf.expand(out, info[0..len], prk); }, }}
test expandLabel { // §A.1: the client's Initial secret, and the "quic key" derived from it. var client_initial: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&client_initial, "c00cf151ca5be075ed0ebfb5c80323c42d6b7db67881289af4008f1f6c357aea");
var key: [16]u8 = undefined; expandLabel(.aes_128_gcm_sha256, &client_initial, "quic key", &key);
var want: [16]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "1f369613dd76d5467730efcbe3b1a22d"); try testing.expectEqualSlices(u8, &want, &key);}
/// The longest `HkdfLabel` this produces: two length octets, the label with/// its own length octet, and the empty context's length octet.pub const max_hkdf_label_len = 2 + 1 + 255 + 1;
/// Builds the `HkdfLabel` structure into `out` and says how long it is.////// Separate from `expandLabel` because RFC 9001 Appendix A.1 prints these/// encodings on their own, so they can be checked without deriving anything —/// see `rfc9001.zig`.pub fn hkdfLabel(out: *[max_hkdf_label_len]u8, length: usize, label: []const u8) usize { const prefix = "tls13 "; assert(prefix.len + label.len <= 255); assert(length <= std.math.maxInt(u16));
std.mem.writeInt(u16, out[0..2], @intCast(length), .big); out[2] = @intCast(prefix.len + label.len); @memcpy(out[3..][0..prefix.len], prefix); @memcpy(out[3 + prefix.len ..][0..label.len], label); // The zero-length context: a length octet of zero, and no bytes after it. // Not "no context at all", which is a different encoding and the mistake // this is written out to make visible. out[3 + prefix.len + label.len] = 0; return 3 + prefix.len + label.len + 1;}
test hkdfLabel { // §A.1 prints this one: sixteen octets of "quic hp". var info: [max_hkdf_label_len]u8 = undefined; const len = hkdfLabel(&info, 16, "quic hp"); try testing.expectEqualSlices(u8, "\x00\x10\x0dtls13 quic hp\x00", info[0..len]);}
/// §5.4.3 and §5.4.4: the five-octet mask, from the header protection key and/// sixteen octets sampled out of the protected payload.////// The first octet masks the low bits of the packet's first octet and the/// other four mask the packet number, which is all `protectHeader` and/// `removeHeader` do with it. They call this themselves; it is public for/// checking against a published mask.pub fn headerProtectionMask(keys: *const Keys, sample: *const [sample_len]u8) [mask_len]u8 { var out: [mask_len]u8 = undefined; switch (keys.suite) { // §5.4.3: "mask = AES-ECB(hp_key, sample)". One block, and only the // first five octets of it are used. .aes_128_gcm_sha256 => { const ctx = crypto.core.aes.Aes128.initEnc(keys.hp_buf[0..16].*); var block: [16]u8 = undefined; ctx.encrypt(&block, sample); @memcpy(&out, block[0..mask_len]); }, .aes_256_gcm_sha384 => { const ctx = crypto.core.aes.Aes256.initEnc(keys.hp_buf[0..32].*); var block: [16]u8 = undefined; ctx.encrypt(&block, sample); @memcpy(&out, block[0..mask_len]); }, // §5.4.4: the first four octets of the sample are a little-endian // block counter and the remaining twelve are the nonce, and the mask // is ChaCha20 run over five zero bytes. .chacha20_poly1305_sha256 => { const counter = std.mem.readInt(u32, sample[0..4], .little); const nonce: [12]u8 = sample[4..16].*; const zeroes: [mask_len]u8 = @splat(0); crypto.stream.chacha.ChaCha20IETF.xor( &out, &zeroes, counter, keys.hp_buf[0..32].*, nonce, ); }, } return out;}
test headerProtectionMask { // §A.2: the client's Initial keys and the sample taken from its packet. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); const mask = headerProtectionMask(&keys, &rfc9001.client_sample); try testing.expectEqualSlices(u8, &.{ 0x43, 0x7b, 0x9a, 0xec, 0x36 }, &mask);}
/// §5.4.1, applied to a packet whose payload is already encrypted.////// `first` is the packet's first octet, `number` is the encoded packet number/// field — one to four octets, however many were written — and `sample` comes/// from `sampleOf`. Both are masked in place.////// The asymmetry between long and short headers is the part to read twice: a/// long header masks four bits of the first octet and a short header masks/// five, because a short header has a Key Phase bit to hide as well as the/// reserved bits and the packet number length.pub fn protectHeader( keys: *const Keys, sample: *const [sample_len]u8, first: *u8, number: []u8,) void { assert(number.len >= 1 and number.len <= 4); const mask = headerProtectionMask(keys, sample); first.* ^= mask[0] & firstByteMask(first.*); for (number, 0..) |*b, i| b.* ^= mask[1 + i];}
test protectHeader { // §A.2: the client's Initial, its payload already encrypted. The header // goes out with its first octet and its four-octet packet number masked. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); var header = rfc9001.client_header; const number_offset = header.len - 4;
protectHeader(&keys, &rfc9001.client_sample, &header[0], header[number_offset..]); try testing.expectEqualSlices(u8, &rfc9001.client_protected_header, &header);}
/// The mirror image, for a packet whose header protection has not been removed/// yet.////// The one difference from `protectHeader`, and §5.4.1 spells it out: the/// packet number length is read from the first octet *after* unmasking it,/// because before that the two bits saying how long it is are themselves/// protected. So the caller cannot know how much of `number` to unmask until/// this function has told it.////// `first` is unmasked in place. `number` is the four octets starting at the/// Packet Number field — four whatever the real length, since nobody knows it/// yet — and only as many as the result says are unmasked; the rest are/// payload and are left alone. Copying them back into the packet is the/// caller's job.////// Returns how many octets of `number` are the packet number.pub fn removeHeader( keys: *const Keys, sample: *const [sample_len]u8, first: *u8, number: *[4]u8,) usize { const mask = headerProtectionMask(keys, sample); first.* ^= mask[0] & firstByteMask(first.*); const len: usize = (first.* & 0x03) + 1; for (number[0..len], 0..) |*b, i| b.* ^= mask[1 + i]; return len;}
test removeHeader { // §A.3: the server's Initial as it arrives. Its packet number is two // octets, but nothing says so until the first octet is unmasked. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .server); const wire = rfc9001.server_protected_packet; const number_offset = rfc9001.server_header.len - 2; const sample = sampleOf(&wire, number_offset).?;
var first = wire[0]; var number: [4]u8 = wire[number_offset..][0..4].*; const len = removeHeader(&keys, sample, &first, &number);
try testing.expectEqual(@as(usize, 2), len); try testing.expectEqual(rfc9001.server_header[0], first); try testing.expectEqualSlices(u8, &.{ 0x00, 0x01 }, number[0..len]); // packet number 1}
/// §5.4.1: four bits for a long header, five for a short one.////// Read off the header form bit, which is *not* protected — it has to be/// readable or nothing could tell the two header shapes apart.fn firstByteMask(first: u8) u8 { return if (first & 0x80 != 0) 0x0f else 0x1f;}
/// §5.4.2: "The sample of ciphertext is taken starting from an offset of 4/// bytes after the start of the Packet Number field."////// Four, and not the actual packet number length, because a receiver removing/// protection does not yet know that length — which is the whole reason the/// offset is fixed. Returns null when the packet is too short to sample,/// which §5.4.2 says must be discarded.////// `packet` should end where the packet does rather than the datagram, so/// that a coalesced packet is not sampled from the one after it. The sample/// points into `packet`.pub fn sampleOf(packet: []const u8, number_offset: usize) ?*const [sample_len]u8 { const start = number_offset + 4; if (packet.len < start + sample_len) return null; return packet[start..][0..sample_len];}
test sampleOf { // §A.2's packet number is at offset 18 and four octets long, so the // sample is the first sixteen octets of the protected payload. const sample = sampleOf(&rfc9001.client_protected_packet, 18).?; try testing.expectEqualSlices(u8, &rfc9001.client_sample, sample);
// Too short to sample, so too short to be a packet at all. try testing.expectEqual(@as(?*const [sample_len]u8, null), sampleOf(rfc9001.client_protected_packet[0..30], 18));}
pub const Error = error{ /// The AEAD tag did not check out. §5.5: a packet that fails /// authentication "MUST" be discarded, and it is not a connection error — /// anyone can send rubbish to a UDP port. AuthenticationFailed,};
/// §5.3. Encrypts `payload` into `out`, with the packet header as associated/// data, and appends the authentication tag.////// `out` must be exactly `payload.len + tls.tag_len` (sixteen) octets, which/// is asserted. `packet_number` is the full number, not the truncated one/// the header carries. The header is everything "starting from the first/// byte of either the short or long header, up to and including the/// unprotected packet number" — unprotected, because header protection has/// not been applied yet and must not be until this has run.pub fn encrypt( keys: *const Keys, packet_number: u64, header: []const u8, payload: []const u8, out: []u8,) void { encryptOn(keys, 0, packet_number, header, payload, out);}
test encrypt { // §A.3: the server's Initial payload, under the server's Initial keys and // its packet number of 1, comes out as the octets the appendix prints // after the header. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .server); const payload = rfc9001.server_payload; var sealed: [payload.len + tls.tag_len]u8 = undefined; encrypt(&keys, 1, &rfc9001.server_header, &payload, &sealed);
try testing.expectEqualSlices(u8, rfc9001.server_protected_packet[rfc9001.server_header.len..], &sealed);}
/// `encrypt` for a packet on multipath path `path`, whose nonce carries the/// path ID (draft-ietf-quic-multipath-21 §2.4). Path 0 is `encrypt`.pub fn encryptOn( keys: *const Keys, path: u32, packet_number: u64, header: []const u8, payload: []const u8, out: []u8,) void { assert(out.len == payload.len + tls.tag_len); const nonce = keys.nonceOn(path, packet_number); const body = out[0..payload.len]; const tag: *[tls.tag_len]u8 = out[payload.len..][0..tls.tag_len];
switch (keys.suite) { .aes_128_gcm_sha256 => crypto.aead.aes_gcm.Aes128Gcm.encrypt( body, tag, payload, header, nonce, keys.key_buf[0..16].*, ), .aes_256_gcm_sha384 => crypto.aead.aes_gcm.Aes256Gcm.encrypt( body, tag, payload, header, nonce, keys.key_buf[0..32].*, ), .chacha20_poly1305_sha256 => crypto.aead.chacha_poly.ChaCha20Poly1305.encrypt( body, tag, payload, header, nonce, keys.key_buf[0..32].*, ), }}
test encryptOn { const keys: Keys = .fromSecret(.{ .suite = .aes_128_gcm_sha256, .material = &@as([32]u8, @splat(9)) }); const header = "\x40\x01\x02\x03\x04\x00\x07"; var on_path_0: [5 + tls.tag_len]u8 = undefined; var on_path_3: [5 + tls.tag_len]u8 = undefined; encryptOn(&keys, 0, 7, header, "hello", &on_path_0); encryptOn(&keys, 3, 7, header, "hello", &on_path_3);
// Packet 7 on path 3 is not packet 7 on path 0: each path numbers from // zero, and the path ID is what keeps the nonces apart. try testing.expect(!std.mem.eql(u8, &on_path_0, &on_path_3)); var opened: [5]u8 = undefined; try decryptOn(&keys, 3, 7, header, &on_path_3, &opened); try testing.expectEqualStrings("hello", &opened);}
/// The inverse: checks the tag and decrypts `ciphertext` into `out`.////// `ciphertext` includes the tag; `out` must be exactly `ciphertext.len - 16`/// octets, which is asserted. `header` and `packet_number` must be what the/// sender used — the header with protection already removed and the/// reconstructed packet number. A ciphertext shorter than a tag, or one whose/// tag does not check out, is `AuthenticationFailed`, and what is in `out`/// then is not to be used.pub fn decrypt( keys: *const Keys, packet_number: u64, header: []const u8, ciphertext: []const u8, out: []u8,) Error!void { return decryptOn(keys, 0, packet_number, header, ciphertext, out);}
test decrypt { // §A.2: the client's Initial, once header protection is off it, opens // under the client's Initial keys and packet number 2. const keys: Keys = .initialKeys(&rfc9001.destination_connection_id, .client); const ciphertext = rfc9001.client_protected_packet[rfc9001.client_header.len..]; var payload: [rfc9001.client_payload_len]u8 = undefined; try decrypt(&keys, 2, &rfc9001.client_header, ciphertext, &payload); try testing.expectEqualSlices(u8, &rfc9001.clientInitialPayload(), &payload);
// The same octets claimed as packet 3 do not. try testing.expectError(error.AuthenticationFailed, decrypt(&keys, 3, &rfc9001.client_header, ciphertext, &payload));}
/// `decrypt` for a packet on multipath path `path`. Path 0 is `decrypt`.pub fn decryptOn( keys: *const Keys, path: u32, packet_number: u64, header: []const u8, ciphertext: []const u8, out: []u8,) Error!void { if (ciphertext.len < tls.tag_len) return error.AuthenticationFailed; assert(out.len == ciphertext.len - tls.tag_len); const nonce = keys.nonceOn(path, packet_number); const body = ciphertext[0 .. ciphertext.len - tls.tag_len]; const tag: [tls.tag_len]u8 = ciphertext[ciphertext.len - tls.tag_len ..][0..tls.tag_len].*;
const result = switch (keys.suite) { .aes_128_gcm_sha256 => crypto.aead.aes_gcm.Aes128Gcm.decrypt( out, body, tag, header, nonce, keys.key_buf[0..16].*, ), .aes_256_gcm_sha384 => crypto.aead.aes_gcm.Aes256Gcm.decrypt( out, body, tag, header, nonce, keys.key_buf[0..32].*, ), .chacha20_poly1305_sha256 => crypto.aead.chacha_poly.ChaCha20Poly1305.decrypt( out, body, tag, header, nonce, keys.key_buf[0..32].*, ), }; result catch return error.AuthenticationFailed;}
test decryptOn { const keys: Keys = .fromSecret(.{ .suite = .aes_128_gcm_sha256, .material = &@as([32]u8, @splat(9)) }); const header = "\x40\x01\x02\x03\x04\x00\x07"; var sealed: [5 + tls.tag_len]u8 = undefined; encryptOn(&keys, 2, 7, header, "hello", &sealed);
// Opened on the path it was sent on, and refused on any other. var opened: [5]u8 = undefined; try decryptOn(&keys, 2, 7, header, &sealed, &opened); try testing.expectEqualStrings("hello", &opened); try testing.expectError(error.AuthenticationFailed, decryptOn(&keys, 1, 7, header, &sealed, &opened));}
const testing = std.testing;const rfc9001 = @import("rfc9001.zig");
test "the nonce is the IV with the packet number exclusive-ored into its tail" { var keys: Keys = .{ .suite = .aes_128_gcm_sha256 }; keys.iv_buf = .{ 0xfa, 0x04, 0x4b, 0x2f, 0x42, 0xa3, 0xfd, 0x3b, 0x46, 0xfb, 0x25, 0x5c };
// Packet number zero changes nothing. try testing.expectEqualSlices(u8, &keys.iv_buf, &keys.nonce(0));
// And a small one touches only the last octets, because the number is // left-padded to the width of the IV. const two = keys.nonce(2); try testing.expectEqualSlices(u8, keys.iv_buf[0..11], two[0..11]); try testing.expectEqual(@as(u8, 0x5c ^ 2), two[11]);
// The full 62 bits reach eight octets in and no further. const big = keys.nonce(0x3fffffffffffffff); try testing.expectEqualSlices(u8, keys.iv_buf[0..4], big[0..4]); try testing.expectEqual(@as(u8, 0x42 ^ 0x3f), big[4]);}
test "a packet too short to sample is not sampled" { const packet: [20]u8 = @splat(0); // Number at offset 0 needs 4 + 16 = 20 octets, which is exactly this. try testing.expect(sampleOf(&packet, 0) != null); try testing.expectEqual(@as(?*const [sample_len]u8, null), sampleOf(&packet, 1)); try testing.expectEqual(@as(?*const [sample_len]u8, null), sampleOf(packet[0..19], 0));}
test "a long header masks four bits of the first octet and a short one five" { try testing.expectEqual(@as(u8, 0x0f), firstByteMask(0xc3)); try testing.expectEqual(@as(u8, 0x1f), firstByteMask(0x43));}
test "protecting a header and removing it again is the identity" { var keys: Keys = .{ .suite = .aes_128_gcm_sha256 }; keys.hp_buf[0..16].* = .{ 0x9f, 0x50, 0x44, 0x9e, 0x04, 0xa0, 0xe8, 0x10, 0x28, 0x3a, 0x1e, 0x99, 0x33, 0xad, 0xed, 0xd2, }; const sample: [sample_len]u8 = @splat(0xab);
// Every packet number length, both header forms. for ([_]u8{ 0xc0, 0x40 }) |form| { for (1..5) |len| { const first_in: u8 = form | @as(u8, @intCast(len - 1)); var first = first_in; var number: [4]u8 = .{ 0xde, 0xad, 0xbe, 0xef }; const original = number;
protectHeader(&keys, &sample, &first, number[0..len]); try testing.expect(first != first_in or len == 0);
const got = removeHeader(&keys, &sample, &first, &number); try testing.expectEqual(len, got); try testing.expectEqual(first_in, first); try testing.expectEqualSlices(u8, original[0..len], number[0..len]); } }}
test "every suite encrypts and decrypts its own packets" { inline for (comptime std.enums.values(Suite)) |suite| { var secret: [tls.max_secret_len]u8 = undefined; for (&secret, 0..) |*b, i| b.* = @intCast(i); const keys: Keys = .fromSecret(.{ .suite = suite, .material = secret[0..suite.secretLen()], });
const header = "\xc3\x00\x00\x00\x01\x08header"; const payload = "the quick brown fox"; var sealed: [payload.len + tls.tag_len]u8 = undefined; encrypt(&keys, 42, header, payload, &sealed);
var opened: [payload.len]u8 = undefined; try decrypt(&keys, 42, header, &sealed, &opened); try testing.expectEqualStrings(payload, &opened);
// The packet number is in the nonce, so a packet replayed under a // different one does not open -- which is the property that makes a // QUIC packet number non-repeating rather than merely conventional. try testing.expectError( error.AuthenticationFailed, decrypt(&keys, 43, header, &sealed, &opened), ); // And the header is the associated data, so a header nobody may edit // in flight really cannot be. try testing.expectError( error.AuthenticationFailed, decrypt(&keys, 42, "\xc3\x00\x00\x00\x01\x08HEADER", &sealed, &opened), ); }}
test "draft-ietf-quic-multipath-21 2.4: the example nonce" { // Figure 3, as the draft prints it: IV 6b26114b9cba2b63a9e8dd4f, path 3, // packet number 54321. var keys: Keys = .{ .suite = .aes_128_gcm_sha256 }; _ = try std.fmt.hexToBytes(&keys.iv_buf, "6b26114b9cba2b63a9e8dd4f"); var want: [12]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "6b2611489cba2b63a9e8097e"); try testing.expectEqualSlices(u8, &want, &keys.nonceOn(3, 54321));
// And path 0 is RFC 9001's nonce, unchanged. try testing.expectEqualSlices(u8, &keys.nonce(54321), &keys.nonceOn(0, 54321));}