// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What QUIC needs from TLS, and nothing else. //! //! QUIC does not use TLS as a protocol. It uses the TLS *handshake* as a //! component and throws the rest away — RFC 9001 §4.1 is blunt about it: //! "QUIC... does not use the TLS record protocol". Handshake messages travel //! in CRYPTO frames, packets are protected by QUIC's own AEAD construction //! with keys derived from TLS's traffic secrets, and TLS never sees a byte of //! application data. //! //! So this file is an interface and not an implementation. It is the whole of //! what RFC 9001 §4.1 calls for, written down so that the thing behind it can //! be replaced without anything above it noticing: //! //! * hand TLS the handshake bytes that arrived at an encryption level, and //! take back whatever it wants to send at one — `provide` and `emit` //! * be told when a level's keys become available, and with which secret and //! cipher suite — `readSecret` and `writeSecret` //! * carry the `quic_transport_parameters` extension in both directions //! * learn that the handshake is complete, or that it failed and with which //! alert //! //! ## Sans-I/O, and why that is the whole point //! //! Nothing here reads or writes anything. QUIC owns the loop: it decides when //! to read, what to put in a packet, when to retransmit a CRYPTO frame that //! was lost, and which encryption level to send at. A TLS implementation that //! owns its own I/O loop — which is nearly all of them, because that is the //! right shape for TLS over TCP — cannot be driven this way at all, and that //! is the single largest obstacle to putting an existing TLS library behind //! this interface. //! //! The consequence worth stating: an implementation of this interface must be //! prepared to be asked for output at a level, told nothing, and asked again. //! §4.1.4 is explicit that "the availability of new keys is always a result of //! providing inputs to TLS", so a caller polls after every `provide` and not //! on a schedule of its own. //! //! ## What this interface deliberately does not decide //! //! Who validates the peer's certificate. §4.1 says QUIC and TLS "need to agree //! on which is responsible", and this interface takes the ordinary answer: //! TLS does it, configured by whoever constructed the implementation, and a //! failure arrives here as an alert. A QUIC stack that wanted to do its own //! validation would be configuring the implementation rather than calling //! anything here. const std = @import("std"); /// RFC 9001 §4.1.4. Four levels, and QUIC may be using more than one at a /// time — §4.1.4 again: "Although TLS only uses one encryption level at a /// time, QUIC may use more than one." /// /// The order is the order they become available, which is also the order a /// packet number space discards them in (§4.9), so comparing two levels is /// meaningful and the enum is declared to make that work. pub const Level = enum(u2) { /// §5.2. Not derived by TLS at all: the keys come from the client's first /// Destination Connection ID, which is why an endpoint can read an /// Initial packet before it has agreed anything. initial = 0, /// 0-RTT. Write-only for a client and read-only for a server: there is no /// such thing as a 0-RTT packet from a server. early_data = 1, handshake = 2, /// 1-RTT, and the only level that outlives the handshake. application = 3, /// How `a` compares with `b` in the order the levels become available: /// `.lt` when `a` comes first. pub fn order(a: Level, b: Level) std.math.Order { return std.math.order(@backingInt(a), @backingInt(b)); } test order { // Handshake keys are discarded once 1-RTT keys arrive, and never the // other way round. try std.testing.expectEqual(std.math.Order.lt, Level.handshake.order(.application)); } }; /// The cipher suites RFC 9001 §5.3 allows, which is every TLS 1.3 suite bar /// one. /// /// `TLS_AES_128_CCM_8_SHA256` is excluded by §5.3 itself — its 8-byte /// authentication tag is too short for the packet protection construction, and /// the document defines no header protection for it. `TLS_AES_128_CCM_SHA256` /// *is* permitted and is absent here for a duller reason: Zig's standard /// library has no AES-CCM, and nothing in the wild negotiates it. pub const Suite = enum { aes_128_gcm_sha256, aes_256_gcm_sha384, chacha20_poly1305_sha256, /// The length of a traffic secret, which is the hash length of the suite. pub fn secretLen(s: Suite) usize { return switch (s) { .aes_128_gcm_sha256, .chacha20_poly1305_sha256 => 32, .aes_256_gcm_sha384 => 48, }; } test secretLen { // What a `Secret.material` handed over for this suite will measure. try std.testing.expectEqual(@as(usize, 48), Suite.aes_256_gcm_sha384.secretLen()); } /// The AEAD key length, and also the header protection key length: §5.4.3 /// uses AES in ECB mode with a key the same size as the AEAD's, and §5.4.4 /// uses ChaCha20's 256-bit key. pub fn keyLen(s: Suite) usize { return switch (s) { .aes_128_gcm_sha256 => 16, .aes_256_gcm_sha384, .chacha20_poly1305_sha256 => 32, }; } test keyLen { // A key buffer of `max_key_len` holds any suite's key. var key: [max_key_len]u8 = undefined; const suite: Suite = .aes_128_gcm_sha256; try std.testing.expectEqual(@as(usize, 16), key[0..suite.keyLen()].len); } /// §5.1: "The Length provided with 'quic iv' is the minimum length of the /// AEAD nonce or 8 bytes if that is larger." Every suite here has a /// 12-octet nonce. pub fn ivLen(s: Suite) usize { _ = s; return 12; } test ivLen { try std.testing.expectEqual(@as(usize, iv_len), Suite.chacha20_poly1305_sha256.ivLen()); } /// Every suite here expands its input by a 16-octet authentication tag, /// which is what a packet's payload grows by when it is protected. pub fn tagLen(s: Suite) usize { _ = s; return 16; } test tagLen { // A 1,000-octet payload is 1,016 on the wire. try std.testing.expectEqual(@as(usize, 1016), 1000 + Suite.aes_128_gcm_sha256.tagLen()); } }; /// The longest secret, key and tag any suite above uses, so that a caller can /// size a buffer without knowing which was negotiated. pub const max_secret_len = 48; pub const max_key_len = 32; pub const iv_len = 12; pub const tag_len = 16; /// What TLS hands over when a level's keys become available. /// /// §4.1.4 says TLS provides three things — "a secret, an AEAD function, and a /// KDF" — and the last two are both determined by the cipher suite, so they /// are one field here. pub const Secret = struct { suite: Suite, /// The traffic secret. Its length is `suite.secretLen()`. /// /// Borrowed, and valid only until the next call on this handshake. A /// caller derives packet protection keys from it immediately — see /// `protection.Keys.fromSecret` — and has no reason to keep it. material: []const u8, }; pub const Error = error{ /// The handshake failed. `alert` says which TLS alert would have been /// sent, which §4.8 turns into a CONNECTION_CLOSE with an error code of /// 0x0100 plus that value. HandshakeFailed, OutOfMemory, }; /// A TLS 1.3 handshake, driven by QUIC. /// /// The vtable shape rather than a generic parameter, for the same reason /// zig-http's `transport.Connection` uses one: what implements this is chosen /// at run time by whoever builds the endpoint, and a QUIC connection should /// compile once rather than once per TLS library. pub const Handshake = struct { context: ?*anyopaque, vtable: *const VTable, pub const VTable = struct { /// Hands TLS the CRYPTO stream bytes that arrived at `level`, in /// order and with no gaps — reassembly is QUIC's job, not TLS's. provide: *const fn (context: ?*anyopaque, level: Level, data: []const u8) Error!void, /// Whatever TLS wants to send at `level`, or null if it has nothing. /// /// The returned slice is borrowed and valid until the next call at /// *this level*. Calls at other levels do not disturb it, which is /// what lets a sender ask every level what it has before deciding how /// to coalesce them into one datagram (§12.2 of RFC 9000) -- a /// decision it cannot make without knowing all the answers, and /// cannot revisit because `emit` hands bytes over once. /// /// QUIC copies what it takes into CRYPTO frames, and must be able to /// retransmit those octets later without asking again, since TLS /// considers them sent. emit: *const fn (context: ?*anyopaque, level: Level) Error!?[]const u8, /// The secret for reading packets at `level`, once there is one. readSecret: *const fn (context: ?*anyopaque, level: Level) ?Secret, /// The secret for writing packets at `level`, once there is one. /// /// Separate from `readSecret` because the two do not arrive together: /// §4.1.4 notes that a server installs its 0-RTT read keys while a /// client installs 0-RTT write keys, and neither has the other. writeSecret: *const fn (context: ?*anyopaque, level: Level) ?Secret, /// The peer's `quic_transport_parameters` extension (§8.2), once the /// message carrying it has been processed. Borrowed like `emit`. peerTransportParameters: *const fn (context: ?*anyopaque) ?[]const u8, /// §4.1.1: "the TLS handshake is considered complete when the TLS /// stack has reported that the handshake is complete. This happens /// when the TLS stack has both sent a Finished message and verified /// the peer's Finished message." For a server that is after the /// client's Finished has been received and checked, even though the /// server had its 1-RTT keys as soon as it sent its own. isComplete: *const fn (context: ?*anyopaque) bool, /// The alert TLS would have sent, if the handshake failed. alert: *const fn (context: ?*anyopaque) ?u8, /// §4.6.3 of RFC 9001: whether the server agreed to read the 0-RTT /// data this endpoint sent. /// /// False until the server has said so, which means it is also false /// on an endpoint that offered nothing and on one whose answer has /// not arrived -- so it is the answer to "may I stop worrying about /// what I sent early?", and a caller that wants "was it refused?" /// has to know that it asked. Meaningless on a server, which decides /// this rather than learning it. earlyDataAccepted: *const fn (context: ?*anyopaque) bool, /// RFC 7250: the raw public key the peer authenticated with, once the /// handshake is complete. Null for a handshake that authenticated by /// certificate, or by nothing. peerPublicKey: *const fn (context: ?*anyopaque) ?PublicKey, }; /// Hands TLS the CRYPTO stream bytes that arrived at `level`, contiguous /// and in order; see `VTable.provide`. /// /// `error.HandshakeFailed` means the handshake is over and `alert` says /// why. Afterwards, ask every level for output with `emit` and check for /// new secrets, since §4.1.4 makes new keys always a result of input. pub fn provide(h: Handshake, level: Level, data: []const u8) Error!void { return h.vtable.provide(h.context, level, data); } test provide { var pair: TestPair = undefined; try pair.init(.{}); const client = pair.client.handshake(); const server = pair.server.handshake(); // The client's Initial CRYPTO data, which is its ClientHello... try server.provide(.initial, (try client.emit(.initial)).?); // ...gives the server something to say at Initial and Handshake. try std.testing.expect(try server.emit(.initial) != null); try std.testing.expect(try server.emit(.handshake) != null); } /// Whatever TLS wants to send at `level`, or null if it has nothing; see /// `VTable.emit` for how long the slice lasts. Bytes returned are /// handed over once, so the caller copies them into its own CRYPTO /// stream before asking again. pub fn emit(h: Handshake, level: Level) Error!?[]const u8 { return h.vtable.emit(h.context, level); } test emit { var pair: TestPair = undefined; try pair.init(.{}); const client = pair.client.handshake(); // A new client has its ClientHello ready, handshake type 1. const hello = (try client.emit(.initial)).?; try std.testing.expectEqual(@as(u8, 1), hello[0]); // Taken once: asked again, it has nothing new. try std.testing.expectEqual(@as(?[]const u8, null), try client.emit(.initial)); } /// The secret this end reads packets at `level` with, or null until TLS /// has derived it. Never anything at `.initial`, whose keys come from a /// connection ID (§5.2). The material is borrowed; see `Secret`. pub fn readSecret(h: Handshake, level: Level) ?Secret { return h.vtable.readSecret(h.context, level); } test readSecret { var pair: TestPair = undefined; try pair.init(.{}); try pair.finish(); const client = pair.client.handshake(); const server = pair.server.handshake(); // What the server reads 1-RTT packets with is what the client // writes them with. const read = server.readSecret(.application).?; try std.testing.expectEqualSlices(u8, client.writeSecret(.application).?.material, read.material); try std.testing.expectEqual(read.suite.secretLen(), read.material.len); } /// The secret this end writes packets at `level` with, or null until /// TLS has derived it; see `VTable.writeSecret`. pub fn writeSecret(h: Handshake, level: Level) ?Secret { return h.vtable.writeSecret(h.context, level); } test writeSecret { var pair: TestPair = undefined; try pair.init(.{}); const client = pair.client.handshake(); // Nothing to write Handshake packets with before the ServerHello. try std.testing.expectEqual(@as(?Secret, null), client.writeSecret(.handshake)); try pair.finish(); try std.testing.expect(client.writeSecret(.handshake) != null); } /// The peer's encoded `quic_transport_parameters`, for /// `parameters.parse`, or null until the message carrying them has been /// processed. pub fn peerTransportParameters(h: Handshake) ?[]const u8 { return h.vtable.peerTransportParameters(h.context); } test peerTransportParameters { var pair: TestPair = undefined; try pair.init(.{}); const client = pair.client.handshake(); try std.testing.expectEqual(@as(?[]const u8, null), client.peerTransportParameters()); try pair.finish(); try std.testing.expectEqualSlices(u8, TestPair.server_parameters, client.peerTransportParameters().?); } /// Whether TLS has finished the handshake; see `VTable.isComplete`. pub fn isComplete(h: Handshake) bool { return h.vtable.isComplete(h.context); } test isComplete { var pair: TestPair = undefined; try pair.init(.{}); try std.testing.expect(!pair.server.handshake().isComplete()); try pair.finish(); try std.testing.expect(pair.server.handshake().isComplete()); } /// The TLS alert the handshake failed with, or null while it has not. /// §4.8 sends it as a CONNECTION_CLOSE of 0x0100 plus its value -- /// `close.Code.crypto`. pub fn alert(h: Handshake) ?u8 { return h.vtable.alert(h.context); } test alert { // A server that speaks none of the client's application protocols. var pair: TestPair = undefined; try pair.init(.{ .server_alpn = "h3" }); const client = pair.client.handshake(); const server = pair.server.handshake(); try std.testing.expectError(error.HandshakeFailed, server.provide(.initial, (try client.emit(.initial)).?)); // no_application_protocol, as RFC 9001 §8.1 requires. try std.testing.expectEqual(@as(?u8, 120), server.alert()); } /// Whether the server accepted this endpoint's 0-RTT data; see /// `VTable.earlyDataAccepted` for why false does not mean refused. pub fn earlyDataAccepted(h: Handshake) bool { return h.vtable.earlyDataAccepted(h.context); } test earlyDataAccepted { // A first connection has no session to send early data under, so // there is nothing for the server to have accepted. var pair: TestPair = undefined; try pair.init(.{}); try pair.finish(); try std.testing.expect(!pair.client.handshake().earlyDataAccepted()); } /// The peer's RFC 7250 raw public key, once the handshake is complete; /// null for a certificate handshake. See `VTable.peerPublicKey`. pub fn peerPublicKey(h: Handshake) ?PublicKey { return h.vtable.peerPublicKey(h.context); } test peerPublicKey { // Both ends authenticate with raw keys, and the client dials the // server's. var pair: TestPair = undefined; try pair.init(.{ .raw_keys = true }); try pair.finish(); const server_key = pair.server_key.public_key.toBytes(); try std.testing.expectEqualSlices(u8, &server_key, &pair.client.handshake().peerPublicKey().?); } }; /// Test-only: a client and a server from `tls_handshake.zig`, the /// implementation this library ships, for the examples above to drive. /// /// Initialized in place, because both ends keep a pointer to `prng` and /// each `handshake()` keeps one to its end. const TestPair = struct { prng: std.Random.DefaultPrng, client: tls_handshake.Client, server: tls_handshake.Server, server_key: std.crypto.sign.Ed25519.KeyPair, client_key: std.crypto.sign.Ed25519.KeyPair, /// The server's ALPN list, here because the server borrows it. server_alpn: [1][]const u8, const client_parameters: []const u8 = &.{ 0x0e, 0x01, 0x04 }; const server_parameters: []const u8 = &.{ 0x0e, 0x01, 0x08 }; const Options = struct { server_alpn: []const u8 = "doq", /// RFC 7250 raw public keys on both ends rather than no /// authentication at all. raw_keys: bool = false, }; fn init(p: *TestPair, options: Options) !void { p.prng = .init(0x9001); const rng = p.prng.random(); p.server_key = try .generateDeterministic(@splat(1)); p.client_key = try .generateDeterministic(@splat(2)); p.client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = client_parameters, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, .raw_public_key = if (options.raw_keys) .{ .key_pair = p.client_key, .peer = p.server_key.public_key.toBytes(), } else null, }); p.server_alpn = .{options.server_alpn}; p.server = .init(.{ .auth = null, .transport_parameters = server_parameters, .alpn_protocols = &p.server_alpn, .rng = rng, .raw_public_key = if (options.raw_keys) .{ .key_pair = p.server_key } else null, }); } /// Carries each end's flights to the other, as a QUIC connection does /// in CRYPTO frames, until the handshake is complete. fn finish(p: *TestPair) !void { const c = p.client.handshake(); const s = p.server.handshake(); if (try c.emit(.initial)) |hello| try s.provide(.initial, hello); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); } }; const tls_handshake = @import("tls_handshake.zig"); /// An Ed25519 public key, which is what RFC 7250 raw-key authentication /// carries here. A bare 32 octets rather than a SubjectPublicKeyInfo, because /// the key *is* the identity: a caller compares it, stores it, or prints it, /// and none of those wants the ASN.1 wrapped round it on the wire. pub const PublicKey = [32]u8; /// A handshake that fails everything, for driving the parts of a connection /// that have no TLS in them. /// /// The same idea as `std.Io.failing`: the Initial encryption level needs no /// TLS at all — §5.2 derives its keys from a connection ID — so a great deal /// of a QUIC endpoint can be exercised with nothing behind this interface, and /// anything that reached for TLS anyway fails loudly rather than quietly /// doing nothing. pub const failing: Handshake = .{ .context = null, .vtable = &.{ .provide = failingProvide, .emit = failingEmit, .readSecret = failingSecret, .writeSecret = failingSecret, .peerTransportParameters = failingParameters, .isComplete = failingIsComplete, .alert = failingAlert, .earlyDataAccepted = failingEarlyData, .peerPublicKey = failingPublicKey, }, }; fn failingProvide(_: ?*anyopaque, _: Level, _: []const u8) Error!void { return error.HandshakeFailed; } fn failingEmit(_: ?*anyopaque, _: Level) Error!?[]const u8 { return error.HandshakeFailed; } fn failingSecret(_: ?*anyopaque, _: Level) ?Secret { return null; } fn failingParameters(_: ?*anyopaque) ?[]const u8 { return null; } fn failingIsComplete(_: ?*anyopaque) bool { return false; } fn failingEarlyData(_: ?*anyopaque) bool { return false; } fn failingPublicKey(_: ?*anyopaque) ?PublicKey { return null; } fn failingAlert(_: ?*anyopaque) ?u8 { // §4.8's `internal_error`, which is what a TLS stack that cannot run at // all would have to say. return 80; } const testing = std.testing; test "the levels are ordered the way they become available" { try testing.expectEqual(std.math.Order.lt, Level.initial.order(.handshake)); try testing.expectEqual(std.math.Order.lt, Level.early_data.order(.handshake)); try testing.expectEqual(std.math.Order.lt, Level.handshake.order(.application)); try testing.expectEqual(std.math.Order.eq, Level.application.order(.application)); try testing.expectEqual(std.math.Order.gt, Level.application.order(.initial)); } test "the suites agree with RFC 8446 about their own sizes" { // The hash length is the secret length, and it is what HKDF-Expand-Label // is asked for when deriving one traffic secret from another. try testing.expectEqual(@as(usize, 32), Suite.aes_128_gcm_sha256.secretLen()); try testing.expectEqual(@as(usize, 48), Suite.aes_256_gcm_sha384.secretLen()); try testing.expectEqual(@as(usize, 32), Suite.chacha20_poly1305_sha256.secretLen()); try testing.expectEqual(@as(usize, 16), Suite.aes_128_gcm_sha256.keyLen()); try testing.expectEqual(@as(usize, 32), Suite.aes_256_gcm_sha384.keyLen()); try testing.expectEqual(@as(usize, 32), Suite.chacha20_poly1305_sha256.keyLen()); inline for (comptime std.enums.values(Suite)) |s| { try testing.expectEqual(@as(usize, 12), s.ivLen()); try testing.expectEqual(@as(usize, 16), s.tagLen()); try testing.expect(s.secretLen() <= max_secret_len); try testing.expect(s.keyLen() <= max_key_len); } } test "the failing handshake fails rather than quietly doing nothing" { try testing.expectError(error.HandshakeFailed, failing.provide(.initial, "hello")); try testing.expectError(error.HandshakeFailed, failing.emit(.initial)); try testing.expectEqual(@as(?Secret, null), failing.readSecret(.handshake)); try testing.expectEqual(@as(?Secret, null), failing.writeSecret(.handshake)); try testing.expectEqual(@as(?[]const u8, null), failing.peerTransportParameters()); try testing.expect(!failing.isComplete()); try testing.expectEqual(@as(?u8, 80), failing.alert()); }