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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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,
pub fn order(a: Level, b: Level) std.math.Order { return std.math.order(@intFromEnum(a), @intFromEnum(b)); }};
/// 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, }; }
/// 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, }; }
/// §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; }
/// Every suite here expands its input by a 16-octet authentication tag. pub fn tagLen(s: Suite) usize { _ = s; return 16; }};
/// 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 handshake is complete when TLS says so, which for a /// server is before the client's Finished has been received. 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, };
pub fn provide(h: Handshake, level: Level, data: []const u8) Error!void { return h.vtable.provide(h.context, level, data); }
pub fn emit(h: Handshake, level: Level) Error!?[]const u8 { return h.vtable.emit(h.context, level); }
pub fn readSecret(h: Handshake, level: Level) ?Secret { return h.vtable.readSecret(h.context, level); }
pub fn writeSecret(h: Handshake, level: Level) ?Secret { return h.vtable.writeSecret(h.context, level); }
pub fn peerTransportParameters(h: Handshake) ?[]const u8 { return h.vtable.peerTransportParameters(h.context); }
pub fn isComplete(h: Handshake) bool { return h.vtable.isComplete(h.context); }
pub fn alert(h: Handshake) ?u8 { return h.vtable.alert(h.context); }
pub fn earlyDataAccepted(h: Handshake) bool { return h.vtable.earlyDataAccepted(h.context); }
pub fn peerPublicKey(h: Handshake) ?PublicKey { return h.vtable.peerPublicKey(h.context); }};
/// 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());}