// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `tls.Handshake`, implemented over the sans-I/O TLS 1.3 in tls.zig. //! //! This is the first thing behind the seam, and the seam existing is why it //! is only a hundred lines of adapter rather than a design. Everything hard //! about TLS — the key schedule, certificate verification, the message state //! machine — is in the library underneath; what is here is the translation //! between two ways of saying the same four things. //! //! ## Which secret is for reading depends on which end you are //! //! That is the whole of the interesting work in this file. TLS derives a pair //! of traffic secrets per level and calls them the client's and the server's, //! because that is what they are: each names the direction it protects. QUIC //! asks a different question — "what do I read with, and what do I write //! with" — and the answer inverts between the two ends. Getting it backwards //! produces a connection where both sides encrypt correctly and neither can //! decrypt anything, which is a failure with no good error message anywhere //! in it. //! //! ## Replacing it //! //! Nothing above this file names tls.zig. A different TLS — one with 0-RTT, //! or one that offloads to hardware, or one that is not written in Zig at all //! — is a different file of about this length, and `tls.Handshake` is what //! makes that true. const std = @import("std"); /// The TLS library this adapts. Named once, here, and nowhere else in the /// project. const backend = @import("tls"); /// The backend, for the one thing a caller cannot get any other way: a /// server's certificate and key. /// /// Everything else about TLS is behind `tls.Handshake`, and deliberately — /// nothing above `tls_handshake.zig` names tls.zig. A certificate chain is /// the exception, because there is no way to describe one without describing /// somebody's X.509 parser, and inventing a type to copy it into would be a /// seam with one implementation on each side of it. pub const CertKeyPair = backend.config.CertKeyPair; /// §4.6.1 of RFC 8446: what a client keeps between connections so that a /// later handshake can skip the certificate exchange. /// /// Exposed for the same reason as `CertKeyPair`: there is no way to describe a /// session ticket without describing somebody's TLS, and inventing a type to /// copy it into would be a seam with one implementation on each side. pub const Session = backend.quic.Session; /// The key a server seals its session tickets with. Only the server needs it, /// and a server that has none issues no tickets and resumes nothing. pub const TicketKey = backend.quic.TicketKey; /// RFC 7250: an endpoint's own Ed25519 key pair and, optionally, the key its /// peer must present. Exposed for the same reason as `CertKeyPair`: it is how /// an endpoint says who it is, and that is the backend's type. pub const RawPublicKey = backend.quic.RawPublicKey; /// Reads an Ed25519 private key from a PEM file, the PKCS#8 form `openssl /// genpkey -algorithm ed25519` writes, for use as `RawPublicKey.key_pair`. /// /// `path` is relative to `dir`, and `gpa` is used only while reading. A key /// of any other type is `error.NotEd25519`; a file that cannot be opened or /// parsed fails with whatever opening or parsing it said. /// /// Here rather than in a caller because reading a key file means naming the /// backend's key parser, and nothing above this file does that. pub fn rawKeyPairFromFile( gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, path: []const u8, ) !std.crypto.sign.Ed25519.KeyPair { const file = try dir.openFile(io, path, .{}); defer file.close(io); const key = try backend.config.PrivateKey.fromFile(gpa, io, file); // RFC 7250 would carry any key type, but the backend's raw-key path is // Ed25519 alone, and an RSA key here would otherwise fail later and less // legibly, in the middle of a handshake. if (key.signature_scheme != .ed25519) return error.NotEd25519; return key.key.ed25519; } test rawKeyPairFromFile { // RFC 8410 §10.3's example private key, as `openssl genpkey` would have // written it. var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "server.key", .data = \\-----BEGIN PRIVATE KEY----- \\MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC \\-----END PRIVATE KEY----- \\ , }); const key_pair = try rawKeyPairFromFile(std.testing.allocator, std.testing.io, tmp.dir, "server.key"); const seed = [_]u8{ 0xd4, 0xee, 0x72, 0xdb, 0xf9, 0x13, 0x58, 0x4a, 0xd5, 0xb6, 0xd8, 0xf1, 0xf7, 0x69, 0xf8, 0xad, 0x3a, 0xfe, 0x7c, 0x28, 0xcb, 0xf1, 0xd4, 0xfb, 0xe0, 0x97, 0xa8, 0x8f, 0x44, 0x75, 0x58, 0x42, }; try std.testing.expectEqualSlices(u8, &seed, &key_pair.secret_key.seed()); } const tls = @import("tls.zig"); /// Turns tls.zig's cipher suite into the three RFC 9001 §5.3 allows. /// /// The others exist in TLS and cannot be negotiated for QUIC: §5.3 excludes /// `TLS_AES_128_CCM_8_SHA256` outright, and the TLS 1.2 suites are ruled out /// by §4.2 requiring TLS 1.3. The backend refuses them during negotiation, so /// reaching the `else` here would mean it had agreed to something it said it /// would not. fn suiteOf(suite: backend.config.CipherSuite) tls.Suite { return switch (suite) { .AES_128_GCM_SHA256 => .aes_128_gcm_sha256, .AES_256_GCM_SHA384 => .aes_256_gcm_sha384, .CHACHA20_POLY1305_SHA256 => .chacha20_poly1305_sha256, else => unreachable, }; } fn levelOf(level: tls.Level) backend.quic.Level { return switch (level) { .initial => .initial, .early_data => .early_data, .handshake => .handshake, .application => .application, }; } /// A QUIC client's TLS handshake. pub const Client = struct { inner: backend.quic.Client, pub const Options = backend.quic.Client.Options; /// A client with its ClientHello already written, so that the first /// `emit(.initial)` on its `handshake()` returns it. /// /// Everything in `options` is borrowed for the life of the client -- /// `rng` included, which it draws on again during the handshake -- and /// `options.transport_parameters` is this endpoint's own, already /// encoded by `parameters.write`. Fails with `error.TlsIllegalParameter` /// for a raw-key client that does not name the key it is dialing, or with /// whatever building the ClientHello failed with. pub fn init(options: Options) !Client { return .{ .inner = try .init(options) }; } test init { var prng: std.Random.DefaultPrng = .init(1); var client: Client = try .init(.{ .host = "dns.example.net", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{ 0x04, 0x01, 0x10 }, .rng = prng.random(), .now_sec = 1_790_000_000, .insecure_skip_verify = true, }); // The ClientHello is ready to go in the first Initial packet. try std.testing.expect(try client.handshake().emit(.initial) != null); } /// The interface the rest of this library talks to. /// /// Must not be called on a `Client` that is about to move: the returned /// handshake holds a pointer to it, the same way `std.Io` implementations /// hand out a vtable over themselves. pub fn handshake(c: *Client) tls.Handshake { return .{ .context = c, .vtable = &vtable }; } test handshake { var prng: std.Random.DefaultPrng = .init(2); var client = try testClient(prng.random()); var server = testServer(prng.random(), "doq"); // Everything from here on goes through `tls.Handshake`. const c = client.handshake(); const s = server.handshake(); try exchange(c, s); try std.testing.expect(c.isComplete()); } const vtable: tls.Handshake.VTable = .{ .provide = provide, .emit = emit, // A client reads what the server wrote and writes what the server // will read, so the two are crossed here and uncrossed in `Server`. .readSecret = serverSecret, .writeSecret = clientSecret, .peerTransportParameters = peerTransportParameters, .isComplete = isComplete, .alert = alertCode, .earlyDataAccepted = earlyDataAccepted, .peerPublicKey = peerPublicKey, }; fn earlyDataAccepted(context: ?*anyopaque) bool { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.early_data_accepted; } fn peerPublicKey(context: ?*anyopaque) ?tls.PublicKey { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.peerPublicKey(); } fn provide(context: ?*anyopaque, level: tls.Level, data: []const u8) tls.Error!void { const c: *Client = @ptrCast(@alignCast(context.?)); c.inner.provide(levelOf(level), data) catch |err| return mapError(err); } fn emit(context: ?*anyopaque, level: tls.Level) tls.Error!?[]const u8 { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.emit(levelOf(level)); } fn clientSecret(context: ?*anyopaque, level: tls.Level) ?tls.Secret { const c: *Client = @ptrCast(@alignCast(context.?)); const s = c.inner.secret(levelOf(level)) orelse return null; return .{ .suite = suiteOf(s.cipher_suite), .material = s.client }; } fn serverSecret(context: ?*anyopaque, level: tls.Level) ?tls.Secret { const c: *Client = @ptrCast(@alignCast(context.?)); const s = c.inner.secret(levelOf(level)) orelse return null; return .{ .suite = suiteOf(s.cipher_suite), .material = s.server }; } fn peerTransportParameters(context: ?*anyopaque) ?[]const u8 { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.peerTransportParameters(); } fn isComplete(context: ?*anyopaque) bool { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.isComplete(); } fn alertCode(context: ?*anyopaque) ?u8 { const c: *Client = @ptrCast(@alignCast(context.?)); return c.inner.alertCode(); } /// The protocol the server selected from `Options.alpn_protocols`, which /// RFC 9001 §8.1 makes mandatory; null until EncryptedExtensions has /// been read. Borrowed from the client. pub fn alpnProtocol(c: *const Client) ?[]const u8 { return c.inner.alpnProtocol(); } test alpnProtocol { var prng: std.Random.DefaultPrng = .init(3); var client = try testClient(prng.random()); var server = testServer(prng.random(), "doq"); try std.testing.expectEqual(@as(?[]const u8, null), client.alpnProtocol()); try exchange(client.handshake(), server.handshake()); try std.testing.expectEqualStrings("doq", client.alpnProtocol().?); } }; /// A QUIC server's TLS handshake. pub const Server = struct { inner: backend.quic.Server, pub const Options = backend.quic.Server.Options; /// A server waiting for a ClientHello: one per connection, made when the /// first Initial packet arrives. /// /// Everything in `options` is borrowed for the life of the server -- /// `rng`, `auth` and the encoded `transport_parameters` alike. pub fn init(options: Options) Server { return .{ .inner = .init(options) }; } test init { var prng: std.Random.DefaultPrng = .init(4); var server: Server = .init(.{ // No certificate, which is only ever useful in a test. .auth = null, .transport_parameters = &.{ 0x04, 0x01, 0x10 }, .alpn_protocols = &.{"doq"}, .rng = prng.random(), }); // A server speaks second: nothing to send until a ClientHello arrives. try std.testing.expectEqual(@as(?[]const u8, null), try server.handshake().emit(.initial)); } /// The interface the rest of this library talks to. As with /// `Client.handshake`, the returned handshake points at this `Server`, /// which must not move while it is in use. pub fn handshake(s: *Server) tls.Handshake { return .{ .context = s, .vtable = &vtable }; } test handshake { var prng: std.Random.DefaultPrng = .init(5); var client = try testClient(prng.random()); var server = testServer(prng.random(), "doq"); const s = server.handshake(); try exchange(client.handshake(), s); // The server reads with what the client writes with. try std.testing.expectEqualSlices( u8, client.handshake().writeSecret(.application).?.material, s.readSecret(.application).?.material, ); } const vtable: tls.Handshake.VTable = .{ .provide = provide, .emit = emit, // The other way round from the client, which is the one thing this // file really decides. .readSecret = clientSecret, .writeSecret = serverSecret, .peerTransportParameters = peerTransportParameters, .isComplete = isComplete, .alert = alertCode, .earlyDataAccepted = earlyDataAccepted, .peerPublicKey = peerPublicKey, }; fn peerPublicKey(context: ?*anyopaque) ?tls.PublicKey { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.peerPublicKey(); } /// A server decides this rather than learning it, so what it reports is /// its own decision -- which is what a caller wanting to know whether /// this connection carried early data should be asking. fn earlyDataAccepted(context: ?*anyopaque) bool { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.early_data_accepted; } fn provide(context: ?*anyopaque, level: tls.Level, data: []const u8) tls.Error!void { const s: *Server = @ptrCast(@alignCast(context.?)); s.inner.provide(levelOf(level), data) catch |err| return mapError(err); } fn emit(context: ?*anyopaque, level: tls.Level) tls.Error!?[]const u8 { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.emit(levelOf(level)); } fn clientSecret(context: ?*anyopaque, level: tls.Level) ?tls.Secret { const s: *Server = @ptrCast(@alignCast(context.?)); const sec = s.inner.secret(levelOf(level)) orelse return null; return .{ .suite = suiteOf(sec.cipher_suite), .material = sec.client }; } fn serverSecret(context: ?*anyopaque, level: tls.Level) ?tls.Secret { const s: *Server = @ptrCast(@alignCast(context.?)); const sec = s.inner.secret(levelOf(level)) orelse return null; return .{ .suite = suiteOf(sec.cipher_suite), .material = sec.server }; } fn peerTransportParameters(context: ?*anyopaque) ?[]const u8 { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.peerTransportParameters(); } fn isComplete(context: ?*anyopaque) bool { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.isComplete(); } fn alertCode(context: ?*anyopaque) ?u8 { const s: *Server = @ptrCast(@alignCast(context.?)); return s.inner.alertCode(); } /// The protocol this server chose from the client's offer, or null /// until it has read the ClientHello. A client that offers nothing the /// server speaks fails the handshake with no_application_protocol rather /// than reaching here, as RFC 9001 §8.1 requires. Borrowed from the /// server. pub fn alpnProtocol(s: *const Server) ?[]const u8 { return s.inner.alpnProtocol(); } test alpnProtocol { var prng: std.Random.DefaultPrng = .init(6); var client = try testClient(prng.random()); var server = testServer(prng.random(), "doq"); try exchange(client.handshake(), server.handshake()); // What the server picked is what decides how to read the streams. try std.testing.expectEqualStrings("doq", server.alpnProtocol().?); } }; /// Test-only: a client offering "doq", with no certificate checking. fn testClient(rng: std.Random) !Client { return .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{1}, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); } /// Test-only: a server speaking `alpn`, with no certificate. fn testServer(rng: std.Random, comptime alpn: []const u8) Server { return .init(.{ .auth = null, .transport_parameters = &.{2}, .alpn_protocols = &.{alpn}, .rng = rng, }); } /// Test-only: carries each end's flights to the other, as a QUIC connection /// does in CRYPTO frames, until the handshake is complete. fn exchange(c: tls.Handshake, s: tls.Handshake) !void { try s.provide(.initial, (try c.emit(.initial)).?); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); } /// Everything the backend can fail with becomes one of the two errors the /// seam has. /// /// The detail is not lost: whatever went wrong has already set the alert, and /// §4.8 of RFC 9001 says the alert is what QUIC sends — a CONNECTION_CLOSE /// with an error code of 0x0100 plus its value. A caller that wants to know /// what happened asks `alert`, and a caller that wants to know whether to /// carry on asks this. fn mapError(err: anyerror) tls.Error { return switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.HandshakeFailed, }; } const testing = std.testing; test "a handshake runs to completion through the seam" { // The same handshake tls.zig's own tests drive, but reached only through // `tls.Handshake` — so what is being checked is the adapter rather than // the TLS underneath it. Nothing here names a type from the backend. var rng_impl = std.Random.DefaultPrng.init(0x9001); const rng = rng_impl.random(); const client_params = [_]u8{ 0x01, 0x02 }; const server_params = [_]u8{ 0x0a, 0x0b }; var client: Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &client_params, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server: Server = .init(.{ .auth = null, .transport_parameters = &server_params, .alpn_protocols = &.{"doq"}, .rng = rng, }); const c = client.handshake(); const s = server.handshake(); // The test plays QUIC: it carries bytes between the two at the level they // were produced at, which is all a QUIC connection does with CRYPTO // frames. try s.provide(.initial, (try c.emit(.initial)).?); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); try testing.expect(c.isComplete()); try testing.expect(s.isComplete()); try testing.expectEqualSlices(u8, &server_params, c.peerTransportParameters().?); try testing.expectEqualSlices(u8, &client_params, s.peerTransportParameters().?); } test "each end reads with what the other end writes with" { // The one thing this file decides, and the one that fails silently if it // is wrong: both ends would encrypt correctly and neither could decrypt // anything. var rng_impl = std.Random.DefaultPrng.init(42); const rng = rng_impl.random(); var client: Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{1}, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server: Server = .init(.{ .auth = null, .transport_parameters = &.{2}, .alpn_protocols = &.{"doq"}, .rng = rng, }); const c = client.handshake(); const s = server.handshake(); try s.provide(.initial, (try c.emit(.initial)).?); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); inline for ([_]tls.Level{ .handshake, .application }) |level| { const c_read = c.readSecret(level).?; const c_write = c.writeSecret(level).?; const s_read = s.readSecret(level).?; const s_write = s.writeSecret(level).?; // What one writes is what the other reads, in both directions. try testing.expectEqualSlices(u8, c_write.material, s_read.material); try testing.expectEqualSlices(u8, s_write.material, c_read.material); // And the two directions are not the same secret, which they would // be if the crossing were done by copying rather than by swapping. try testing.expect(!std.mem.eql(u8, c_read.material, c_write.material)); // Both ends agree which AEAD protects them. try testing.expectEqual(c_read.suite, s_read.suite); } } test "the Initial level never has a secret, however far the handshake gets" { // §5.2 of RFC 9001: Initial keys come from a connection ID, not from TLS. // An adapter that handed one over here would be offering a secret the // packet protection must not use. var rng_impl = std.Random.DefaultPrng.init(3); const rng = rng_impl.random(); var client: Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{1}, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); var server: Server = .init(.{ .auth = null, .transport_parameters = &.{2}, .alpn_protocols = &.{"doq"}, .rng = rng, }); const c = client.handshake(); const s = server.handshake(); try testing.expectEqual(@as(?tls.Secret, null), c.readSecret(.initial)); try s.provide(.initial, (try c.emit(.initial)).?); try c.provide(.initial, (try s.emit(.initial)).?); try c.provide(.handshake, (try s.emit(.handshake)).?); try s.provide(.handshake, (try c.emit(.handshake)).?); try testing.expectEqual(@as(?tls.Secret, null), c.readSecret(.initial)); try testing.expectEqual(@as(?tls.Secret, null), c.writeSecret(.initial)); try testing.expectEqual(@as(?tls.Secret, null), s.readSecret(.initial)); try testing.expectEqual(@as(?tls.Secret, null), s.writeSecret(.initial)); } test "a failed handshake surfaces as an error and an alert" { // §4.8: a TLS alert becomes a CONNECTION_CLOSE of 0x0100 plus its value, // so the number has to survive the adapter even though the error does // not. var rng_impl = std.Random.DefaultPrng.init(5); const rng = rng_impl.random(); var client: Client = try .init(.{ .host = "example.com", .root_ca = .{ .bytes = .empty, .map = .empty }, .alpn_protocols = &.{"doq"}, .transport_parameters = &.{1}, .rng = rng, .now_sec = 0, .insecure_skip_verify = true, }); // A server that speaks nothing the client offered. var server: Server = .init(.{ .auth = null, .transport_parameters = &.{2}, .alpn_protocols = &.{"h3"}, .rng = rng, }); const c = client.handshake(); const s = server.handshake(); try testing.expectError( error.HandshakeFailed, s.provide(.initial, (try c.emit(.initial)).?), ); try testing.expectEqual(@as(?u8, 120), s.alert()); // no_application_protocol try testing.expect(!s.isComplete()); }