// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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 //! `remove` 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), pub fn key(k: *const Keys) []const u8 { return k.key_buf[0..k.suite.keyLen()]; } pub fn iv(k: *const Keys) []const u8 { return k.iv_buf[0..k.suite.ivLen()]; } pub fn hp(k: *const Keys) []const u8 { return k.hp_buf[0..k.suite.keyLen()]; } /// §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. 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; } /// §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 }); } /// §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); } /// 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; } }; /// 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. /// 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. /// /// §6.1: `secret_ = HKDF-Expand-Label(secret_, "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. pub const OwnedSecret = struct { suite: Suite, buf: [tls.max_secret_len]u8 = undefined, len: usize = 0, 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; } pub fn material(s: *const OwnedSecret) []const u8 { return s.buf[0..s.len]; } pub fn borrow(s: *const OwnedSecret) tls.Secret { return .{ .suite = s.suite, .material = s.material() }; } /// The next secret in the ratchet. 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; } }; /// 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; } 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); }, } } /// §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 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; } 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 = [_]u8{0} ** mask_len; crypto.stream.chacha.ChaCha20IETF.xor( &out, &zeroes, counter, keys.hp_buf[0..32].*, nonce, ); }, } return out; } /// §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`. /// /// 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]; } /// 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. /// /// 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; } /// §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. 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]; } 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` in place of itself into `out`, with the packet /// header as associated data, and appends the authentication tag. /// /// `out` must be `payload.len + 16` octets. 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); } /// `encrypt` for a packet on multipath path `path`, whose nonce carries the /// path ID (draft-ietf-quic-multipath-21 §2.4). 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].*, ), } } /// The inverse. `ciphertext` includes the tag; `out` must be /// `ciphertext.len - 16` octets. 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); } /// `decrypt` for a packet on multipath path `path`. 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; } const testing = std.testing; 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 = [_]u8{0} ** 20; // 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 = [_]u8{0xab} ** sample_len; // 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)); }