ReviewOS

also looking at this

mail-os/mail

Harden encrypted mail storage, recovery, and forwarding

#8
Merged chris wants to merge codex/mail-storage-hardening into main
50 files +1701 -9001
packages/zig/vendor/zig-tls/src/handshake_server.zigdeleted+0-1069
Changes to packages/zig/vendor/zig-tls/src/handshake_server.zig
@@ -1,1069 +0,0 @@
1const std = @import("std");
2const assert = std.debug.assert;
3const crypto = std.crypto;
4const mem = std.mem;
5const Io = std.Io;
6const Certificate = crypto.Certificate;
7
8const Cipher = @import("cipher.zig").Cipher;
9const CipherSuite = @import("cipher.zig").CipherSuite;
10const cipher_suites = @import("cipher.zig").cipher_suites;
11const max_cleartext_len = @import("cipher.zig").max_cleartext_len;
12
13const Transcript = @import("transcript.zig").Transcript;
14const record = @import("record.zig");
15const Record = record.Record;
16const PrivateKey = @import("PrivateKey.zig");
17const proto = @import("protocol.zig");
18
19const common = @import("handshake_common.zig");
20const CertificateBuilder = common.CertificateBuilder;
21const CertificateParser = common.CertificateParser;
22const DhKeyPair = common.DhKeyPair;
23const CertKeyPair = common.CertKeyPair;
24const cert = common.cert;
25
26const rng = @import("random.zig");
27const log = std.log.scoped(.tls);
28
29pub const Options = struct {
30 /// Server authentication. If null server will not send Certificate and
31 /// CertificateVerify message.
32 auth: ?*CertKeyPair,
33
34 /// If not null server will request client certificate. If auth_type is
35 /// .request empty client certificate message will be accepted.
36 /// Client certificate will be verified with root_ca certificates.
37 client_auth: ?ClientAuth = null,
38
39 /// List of supported cipher suites (TLS 1.3 and/or TLS 1.2)
40 /// Default includes both TLS 1.3 and TLS 1.2 secure ciphers for maximum compatibility.
41 cipher_suites: []const CipherSuite = cipher_suites.all,
42
43 /// Named groups (elliptic curves) to support for key exchange
44 named_groups: []const proto.NamedGroup = &[_]proto.NamedGroup{ .x25519, .secp256r1, .secp384r1 },
45};
46
47pub const ClientAuth = struct {
48 /// Set of root certificate authorities that server use when verifying
49 /// client certificates.
50 root_ca: cert.Bundle,
51
52 auth_type: Type = .require,
53
54 pub const Type = enum {
55 /// Client certificate will be requested during the handshake, but does
56 /// not require that the client send any certificates.
57 request,
58 /// Client certificate will be requested during the handshake, and client
59 /// has to send valid certificate.
60 require,
61 };
62};
63
64pub const Handshake = struct {
65 // public key len: x25519 = 32, secp256r1 = 65, secp384r1 = 97
66 const max_pub_key_len = 98;
67 const supported_named_groups = &[_]proto.NamedGroup{ .x25519, .secp256r1, .secp384r1 };
68
69 /// Underlying network connection stream reader/writer pair.
70 input: *Io.Reader,
71 output: *Io.Writer,
72
73 server_random: [32]u8 = undefined,
74 client_random: [32]u8 = undefined,
75 legacy_session_id_buf: [32]u8 = undefined,
76 legacy_session_id: []u8 = &.{},
77 cipher_suite: CipherSuite = @fromBackingInt(@intCast(0)),
78 signature_scheme: proto.SignatureScheme = @fromBackingInt(@intCast(0)),
79 named_group: proto.NamedGroup = @fromBackingInt(@intCast(0)),
80 client_pub_key_buf: [max_pub_key_len]u8 = undefined,
81 client_pub_key: []u8 = &.{},
82 server_pub_key_buf: [max_pub_key_len]u8 = undefined,
83 server_pub_key: []u8 = &.{},
84
85 cipher: Cipher = undefined,
86 transcript: Transcript = .{},
87
88 // TLS 1.2 specific fields
89 tls_version: proto.Version = .tls_1_3,
90 master_secret: [48]u8 = undefined,
91 key_material: [48 * 4]u8 = undefined,
92 dh_kp: DhKeyPair = undefined,
93
94 const Self = @This();
95
96 fn writeAlert(h: *Self, cph: ?*Cipher, err: anyerror) !void {
97 if (cph) |c| {
98 const cleartext = proto.alertFromError(err);
99 const ciphertext = try c.encrypt(h.output.unusedCapacitySlice(), .alert, &cleartext);
100 h.output.advance(ciphertext.len);
101 } else {
102 const alert = record.header(.alert, 2) ++ proto.alertFromError(err);
103 try h.output.writeAll(&alert);
104 }
105 try h.output.flush();
106 }
107
108 pub fn handshake(h: *Self, opt: Options) !Cipher {
109 h.initKeys(opt);
110
111 h.readClientHello(opt.cipher_suites, opt.named_groups) catch |err| {
112 try h.writeAlert(null, err);
113 return err;
114 };
115 h.transcript.use(h.cipher_suite.hash());
116
117 if (h.tls_version == .tls_1_3) {
118 // TLS 1.3 handshake
119 h.serverFlight(opt) catch |err| {
120 try h.writeAlert(null, err);
121 return err;
122 };
123 try h.output.flush();
124
125 h.clientFlight2(opt) catch |err| {
126 // Alert received from client
127 if (!mem.startsWith(u8, @errorName(err), "TlsAlert")) {
128 try h.writeAlert(&h.cipher, err);
129 }
130 return err;
131 };
132 } else {
133 // TLS 1.2 handshake
134 h.serverFlightTls12(opt) catch |err| {
135 try h.writeAlert(null, err);
136 return err;
137 };
138 try h.output.flush();
139
140 h.clientFlight2Tls12(opt) catch |err| {
141 if (!mem.startsWith(u8, @errorName(err), "TlsAlert")) {
142 try h.writeAlert(if (h.cipher_suite.validate() == null) &h.cipher else null, err);
143 }
144 return err;
145 };
146 }
147 return h.cipher;
148 }
149
150 fn initKeys(h: *Self, opt: Options) void {
151 rng.fill(&h.server_random);
152 if (opt.auth) |a| {
153 // required signature scheme in client hello
154 h.signature_scheme = a.key.signature_scheme;
155 }
156 // Initialize DH key pair for key exchange (used in TLS 1.2 ECDHE)
157 var seed: [DhKeyPair.seed_len]u8 = undefined;
158 rng.fill(&seed);
159 h.dh_kp = DhKeyPair.init(seed, opt.named_groups) catch unreachable;
160 }
161
162 fn clientFlight1(h: *Self, opt: Options) !void {
163 try h.readClientHello(opt.cipher_suites, opt.named_groups);
164 h.transcript.use(h.cipher_suite.hash());
165 }
166
167 /// TLS 1.2 server flight: ServerHello, Certificate, ServerKeyExchange, ServerHelloDone
168 fn serverFlightTls12(h: *Self, opt: Options) !void {
169 var w: record.Writer = .initFromIo(h.output);
170
171 // Debug: log the selected named_group (use info level to show in production)
172 log.info("TLS 1.2 serverFlightTls12: named_group={x}, cipher_suite={x}", .{ @backingInt(h.named_group), @backingInt(h.cipher_suite) });
173
174 // Generate server's DH public key
175 log.info("TLS 1.2: generating DH public key", .{});
176 h.server_pub_key = try common.dupe(&h.server_pub_key_buf, try h.dh_kp.publicKey(h.named_group));
177 log.info("TLS 1.2: DH public key generated, len={d}", .{h.server_pub_key.len});
178
179 // ServerHello
180 {
181 log.info("TLS 1.2: making ServerHello", .{});
182 const hello = try h.makeServerHelloTls12(&w);
183 h.transcript.update(hello[record.header_len..]);
184 log.info("TLS 1.2: ServerHello done, pos={d}", .{w.pos()});
185 }
186
187 // Certificate (if auth is enabled)
188 if (opt.auth) |auth| {
189 log.info("TLS 1.2: making Certificate at pos={d}", .{w.pos()});
190 const cb = CertificateBuilder{
191 .cert_key_pair = auth,
192 .transcript = &h.transcript,
193 .tls_version = .tls_1_2,
194 .side = .server,
195 };
196 // Skip space for record header (5 bytes)
197 const header_pos = try w.skip(record.header_len);
198 const content_start = w.pos();
199 try cb.makeCertificate(&w);
200 const content_len = w.pos() - content_start;
201 h.transcript.update(w.buffered()[content_start..]);
202 // Go back and write the record header
203 var hw = w.writerAt(header_pos);
204 try hw.recordHeader(.handshake, content_len);
205 log.info("TLS 1.2: Certificate done, content_len={d}, pos={d}", .{ content_len, w.pos() });
206 }
207
208 // ServerKeyExchange (for ECDHE cipher suites)
209 if (h.cipher_suite.keyExchange() == .ecdhe) {
210 if (opt.auth) |auth| {
211 log.info("TLS 1.2: making ServerKeyExchange at pos={d}", .{w.pos()});
212 // Skip space for record header (5 bytes)
213 const header_pos = try w.skip(record.header_len);
214 const content_start = w.pos();
215 try h.makeServerKeyExchange(&w, auth);
216 const content_len = w.pos() - content_start;
217 h.transcript.update(w.buffered()[content_start..]);
218 // Go back and write the record header
219 var hw = w.writerAt(header_pos);
220 try hw.recordHeader(.handshake, content_len);
221 log.info("TLS 1.2: ServerKeyExchange done, content_len={d}, pos={d}", .{ content_len, w.pos() });
222 }
223 }
224
225 // ServerHelloDone
226 {
227 log.info("TLS 1.2: making ServerHelloDone at pos={d}", .{w.pos()});
228 // Skip space for record header (5 bytes)
229 const header_pos = try w.skip(record.header_len);
230 const content_start = w.pos();
231 // ServerHelloDone is just a handshake header with 0 length body
232 try w.handshakeRecordHeader(.server_hello_done, 0);
233 const content_len = w.pos() - content_start;
234 h.transcript.update(w.buffered()[content_start..]);
235 // Go back and write the record header
236 var hw = w.writerAt(header_pos);
237 try hw.recordHeader(.handshake, content_len);
238 log.info("TLS 1.2: ServerHelloDone done, content_len={d}, pos={d}", .{ content_len, w.pos() });
239 }
240
241 log.info("TLS 1.2: serverFlightTls12 complete, total bytes={d}", .{w.buffered().len});
242 log.info("TLS 1.2: h.output.end before advance={d}", .{h.output.end});
243 h.output.advance(w.buffered().len);
244 log.info("TLS 1.2: h.output.end after advance={d}", .{h.output.end});
245 }
246
247 fn makeServerHelloTls12(h: *Self, w: *record.Writer) ![]const u8 {
248 const header_pos = try w.skip(9);
249
250 try w.enumValue(proto.Version.tls_1_2);
251 try w.slice(&h.server_random);
252 {
253 try w.int(u8, h.legacy_session_id.len);
254 if (h.legacy_session_id.len > 0) try w.slice(h.legacy_session_id);
255 }
256 try w.enumValue(h.cipher_suite);
257 try w.slice(&[_]u8{0}); // compression method (null)
258
259 // Extensions for TLS 1.2 ServerHello
260 // RFC 5746: renegotiation_info extension is required by modern clients
261 // Extension structure: type (2) + length (2) + data
262 // renegotiation_info: type=0xff01, length=1, renegotiated_connection_length=0
263 try w.int(u16, 5); // Extensions total length
264 try w.int(u16, 0xff01); // Extension type: renegotiation_info
265 try w.int(u16, 1); // Extension data length
266 try w.int(u8, 0); // renegotiated_connection length (0 for initial handshake)
267
268 var hw = w.writerAt(header_pos);
269 try hw.recordHeader(.handshake, w.pos() - 5);
270 try hw.handshakeRecordHeader(.server_hello, w.pos() - 9);
271
272 return w.buffered();
273 }
274
275 fn makeServerKeyExchange(h: *Self, hw: *record.Writer, auth: *CertKeyPair) !void {
276 const content_start = hw.pos();
277 // Skip handshake header, write it at end
278 _ = try hw.skip(4);
279
280 // ECParameters - named_curve type + curve ID
281 try hw.int(u8, @backingInt(proto.Curve.named_curve));
282 try hw.enumValue(h.named_group);
283
284 // ECPoint - public key
285 const pub_key = h.server_pub_key;
286 try hw.int(u8, pub_key.len);
287 try hw.slice(pub_key);
288
289 // Signature - sign (client_random + server_random + ec_params + ec_point)
290 const params_end = hw.pos();
291 const params = hw.buffered()[content_start + 4 .. params_end];
292
293 // Build data to sign: client_random || server_random || ec_params
294 var sign_buf: [32 + 32 + 256]u8 = undefined;
295 @memcpy(sign_buf[0..32], &h.client_random);
296 @memcpy(sign_buf[32..64], &h.server_random);
297 @memcpy(sign_buf[64 .. 64 + params.len], params);
298 const sign_data = sign_buf[0 .. 64 + params.len];
299
300 // Sign the data using the appropriate signing method based on key type
301 const signature_scheme = auth.key.signature_scheme;
302 log.info("TLS 1.2 ServerKeyExchange: signature_scheme={x}, ecdsa_key_pair_present={}", .{ @backingInt(signature_scheme), auth.ecdsa_key_pair != null });
303 try hw.enumValue(signature_scheme);
304
305 const signature = switch (signature_scheme) {
306 inline .ecdsa_secp256r1_sha256,
307 .ecdsa_secp384r1_sha384,
308 => |comptime_scheme| brk: {
309 log.info("TLS 1.2 ServerKeyExchange: entering ECDSA branch", .{});
310 const Ecdsa = common.SchemeEcdsa(comptime_scheme);
311 const key_pair = switch (comptime_scheme) {
312 .ecdsa_secp256r1_sha256 => auth.ecdsa_key_pair.?.ecdsa_secp256r1_sha256,
313 .ecdsa_secp384r1_sha384 => auth.ecdsa_key_pair.?.ecdsa_secp384r1_sha384,
314 else => unreachable,
315 };
316 log.info("TLS 1.2 ServerKeyExchange: got key_pair, creating signer", .{});
317 var signer = try key_pair.signer(null);
318 log.info("TLS 1.2 ServerKeyExchange: signer created, updating", .{});
319 signer.update(sign_data);
320 log.info("TLS 1.2 ServerKeyExchange: finalizing signature", .{});
321 const sig = try signer.finalize();
322 log.info("TLS 1.2 ServerKeyExchange: converting to DER", .{});
323 var buf: [Ecdsa.Signature.der_encoded_length_max]u8 = undefined;
324 break :brk sig.toDer(&buf);
325 },
326 inline .rsa_pss_rsae_sha256,
327 .rsa_pss_rsae_sha384,
328 .rsa_pss_rsae_sha512,
329 => |comptime_scheme| brk: {
330 const Hash = common.SchemeHash(comptime_scheme);
331 var signer = try auth.key.key.rsa.signerOaep(Hash, null);
332 signer.update(sign_data);
333 var buf: [512]u8 = undefined;
334 const sig = try signer.finalize(&buf);
335 break :brk sig.bytes;
336 },
337 else => return error.TlsUnknownSignatureScheme,
338 };
339
340 try hw.int(u16, signature.len);
341 try hw.slice(signature);
342
343 // Write handshake header
344 var header_w = hw.writerAt(content_start);
345 try header_w.handshakeRecordHeader(.server_key_exchange, hw.pos() - content_start - 4);
346 }
347
348 /// TLS 1.2 client flight 2: ClientKeyExchange, ChangeCipherSpec, Finished
349 fn clientFlight2Tls12(h: *Self, _: Options) !void {
350 log.info("TLS 1.2 clientFlight2Tls12: starting", .{});
351 // Read ClientKeyExchange
352 {
353 var d = Record.decoder(h.input) catch |err| {
354 log.err("TLS 1.2 clientFlight2Tls12: Record.decoder failed: {}", .{err});
355 return err;
356 };
357 log.info("TLS 1.2 clientFlight2Tls12: got record, content_type={x}", .{@backingInt(d.content_type)});
358 d.expectContentType(.handshake) catch |err| {
359 log.err("TLS 1.2 clientFlight2Tls12: expected handshake but got content_type={x}, payload_len={d}", .{ @backingInt(d.content_type), d.payload.len });
360 if (d.content_type == .alert and d.payload.len >= 2) {
361 log.err("TLS 1.2 clientFlight2Tls12: client sent alert: level={d}, desc={d}", .{ d.payload[0], d.payload[1] });
362 }
363 return err;
364 };
365 h.transcript.update(d.payload);
366
367 const handshake_type = try d.decode(proto.Handshake);
368 log.info("TLS 1.2 clientFlight2Tls12: handshake_type={x} (decimal={d}), expected client_key_exchange={x}", .{ @backingInt(handshake_type), @backingInt(handshake_type), @backingInt(proto.Handshake.client_key_exchange) });
369 if (handshake_type != .client_key_exchange) {
370 log.err("TLS 1.2 clientFlight2Tls12: handshake type mismatch! got={s}, expected=client_key_exchange", .{@tagName(handshake_type)});
371 return error.TlsUnexpectedMessage;
372 }
373 log.info("TLS 1.2 clientFlight2Tls12: handshake type check passed", .{});
374 const length = try d.decode(u24);
375 log.info("TLS 1.2 clientFlight2Tls12: ClientKeyExchange length={d}", .{length});
376
377 // For ECDHE, client sends its public key
378 if (h.cipher_suite.keyExchange() == .ecdhe) {
379 const client_pub_key_len = try d.decode(u8);
380 log.info("TLS 1.2 clientFlight2Tls12: client pub key len={d}, expected={d}", .{ client_pub_key_len, length - 1 });
381 if (client_pub_key_len != length - 1) return error.TlsDecodeError;
382 h.client_pub_key = try common.dupe(&h.client_pub_key_buf, try d.slice(client_pub_key_len));
383 log.info("TLS 1.2 clientFlight2Tls12: got client pub key, len={d}", .{h.client_pub_key.len});
384 } else {
385 // RSA key exchange - skip for now
386 try d.skip(length);
387 }
388 }
389 log.info("TLS 1.2 clientFlight2Tls12: finished reading ClientKeyExchange", .{});
390
391 // Generate pre-master secret and derive keys
392 if (h.cipher_suite.keyExchange() == .ecdhe) {
393 log.info("TLS 1.2 clientFlight2Tls12: generating shared key, named_group={x}", .{@backingInt(h.named_group)});
394 const pre_master_secret = try h.dh_kp.sharedKey(h.named_group, h.client_pub_key);
395 log.info("TLS 1.2 clientFlight2Tls12: got pre_master_secret, len={d}", .{pre_master_secret.len});
396 h.transcript.masterSecret(&h.master_secret, pre_master_secret, h.client_random, h.server_random);
397 h.transcript.keyMaterial(&h.key_material, &h.master_secret, h.client_random, h.server_random);
398 log.info("TLS 1.2 clientFlight2Tls12: derived keys", .{});
399 }
400
401 // Initialize cipher for decryption
402 log.info("TLS 1.2 clientFlight2Tls12: initializing cipher", .{});
403 h.cipher = try Cipher.initTls12(h.cipher_suite, &h.key_material, .server);
404 log.info("TLS 1.2 clientFlight2Tls12: cipher initialized", .{});
405
406 // Read ChangeCipherSpec
407 log.info("TLS 1.2 clientFlight2Tls12: reading ChangeCipherSpec", .{});
408 {
409 var d = try Record.decoder(h.input);
410 log.info("TLS 1.2 clientFlight2Tls12: got record, content_type={x}", .{@backingInt(d.content_type)});
411 try d.expectContentType(.change_cipher_spec);
412 log.info("TLS 1.2 clientFlight2Tls12: ChangeCipherSpec payload_len={d}, payload[0]={d}", .{ d.payload.len, if (d.payload.len > 0) d.payload[0] else 255 });
413 if (d.payload.len != 1 or d.payload[0] != 1) return error.TlsUnexpectedMessage;
414 }
415 log.info("TLS 1.2 clientFlight2Tls12: ChangeCipherSpec OK", .{});
416
417 // Read encrypted Finished
418 // In TLS 1.2, the encrypted Finished message uses content_type=handshake (0x16)
419 // The encryption is applied to the payload, but the record header type stays as handshake
420 log.info("TLS 1.2 clientFlight2Tls12: reading encrypted Finished", .{});
421 {
422 const rec = try Record.read(h.input);
423 log.info("TLS 1.2 clientFlight2Tls12: got record, content_type={x}", .{@backingInt(rec.content_type)});
424 // TLS 1.2 encrypted Finished uses handshake (0x16) content type, NOT application_data
425 if (rec.content_type != .handshake) {
426 log.err("TLS 1.2 clientFlight2Tls12: expected handshake, got {x}", .{@backingInt(rec.content_type)});
427 return error.TlsUnexpectedMessage;
428 }
429
430 var cleartext_buf: [128]u8 = undefined;
431 // For TLS 1.2, decrypt returns the record's content_type (which is handshake)
432 const content_type, const cleartext = try h.cipher.decrypt(&cleartext_buf, rec);
433 log.info("TLS 1.2 clientFlight2Tls12: decrypted, content_type={x}, cleartext_len={d}", .{ @backingInt(content_type), cleartext.len });
434 if (content_type != .handshake) return error.TlsUnexpectedMessage;
435
436 // Parse Finished message
437 var d = record.Decoder.init(content_type, cleartext);
438 const handshake_type = try d.decode(proto.Handshake);
439 if (handshake_type != .finished) return error.TlsUnexpectedMessage;
440 const length = try d.decode(u24);
441 if (length != 12) return error.TlsDecodeError;
442
443 const client_verify_data = try d.slice(12);
444 const expected_verify_data = h.transcript.clientFinishedTls12(&h.master_secret);
445 if (!mem.eql(u8, client_verify_data, &expected_verify_data))
446 return error.TlsDecryptError;
447
448 // Update transcript with Finished message
449 h.transcript.update(cleartext);
450 }
451
452 // Send ChangeCipherSpec and Finished
453 {
454 var w: record.Writer = .initFromIo(h.output);
455
456 // ChangeCipherSpec
457 try w.record(.change_cipher_spec, &[_]u8{1});
458
459 // Finished (encrypted)
460 const server_finished = &record.handshakeHeader(.finished, 12) ++
461 h.transcript.serverFinishedTls12(&h.master_secret);
462 const ciphertext = try h.cipher.encrypt(w.unused(), .handshake, server_finished);
463 w.advance(ciphertext.len);
464
465 h.output.advance(w.buffered().len);
466 try h.output.flush();
467 }
468 }
469
470 fn clientFlight2(h: *Self, opt: Options) !void {
471 // calculate application cipher before updating transcript in readClientFlight2
472 const application_secret = h.transcript.applicationSecret();
473 const app_cipher = try Cipher.initTls13(h.cipher_suite, application_secret, .server);
474 // set application cipher instead of EndOfStream error
475 h.readClientFlight2(opt) catch |err| {
476 if (err != error.EndOfStream and err != error.InputBufferUndersize) {
477 // don't change on short reads: https://github.com/ianic/tls.zig/commit/2f3f23485e01e4be8219c4a1ceda01ed961da61d
478 h.cipher = app_cipher;
479 }
480 return err;
481 };
482 h.cipher = app_cipher;
483 }
484
485 fn serverFlight(h: *Self, opt: Options) !void {
486 var w: record.Writer = .initFromIo(h.output);
487
488 const shared_key = brk: {
489 var seed: [DhKeyPair.seed_len]u8 = undefined;
490 rng.fill(&seed);
491 var kp = try DhKeyPair.init(seed, &[_]proto.NamedGroup{h.named_group});
492 h.server_pub_key = try common.dupe(&h.server_pub_key_buf, try kp.publicKey(h.named_group));
493 break :brk try kp.sharedKey(h.named_group, h.client_pub_key);
494 };
495 {
496 const hello = try h.makeServerHello(&w);
497 h.transcript.update(hello[record.header_len..]);
498 }
499 {
500 const handshake_secret = h.transcript.handshakeSecret(shared_key);
501 h.cipher = try Cipher.initTls13(h.cipher_suite, handshake_secret, .server);
502 }
503 try w.record(.change_cipher_spec, &[_]u8{1});
504 {
505 var hw = try w.writerAdvance(record.header_len);
506 try hw.handshakeRecord(.encrypted_extensions, &[_]u8{ 0, 0 });
507 h.transcript.update(hw.buffered());
508 try h.writeEncrypted(&w, hw.buffered());
509 }
510 if (opt.client_auth) |_| { // Certificate request
511 var hw = try w.writerAdvance(record.header_len);
512 try makeCertificateRequest(&hw);
513 h.transcript.update(hw.buffered());
514 try h.writeEncrypted(&w, hw.buffered());
515 }
516 if (opt.auth) |auth| {
517 const cb = CertificateBuilder{
518 .cert_key_pair = auth,
519 .transcript = &h.transcript,
520 .side = .server,
521 };
522 { // Certificate
523 var hw = try w.writerAdvance(record.header_len);
524 try cb.makeCertificate(&hw);
525 h.transcript.update(hw.buffered());
526 try h.writeEncrypted(&w, hw.buffered());
527 }
528 { // Certificate verify
529 var hw = try w.writerAdvance(record.header_len);
530 try cb.makeCertificateVerify(&hw);
531 h.transcript.update(hw.buffered());
532 try h.writeEncrypted(&w, hw.buffered());
533 }
534 }
535 { // Finished
536 var hw = try w.writerAdvance(record.header_len);
537 try hw.handshakeRecord(.finished, h.transcript.serverFinishedTls13());
538 h.transcript.update(hw.buffered());
539 try h.writeEncrypted(&w, hw.buffered());
540 }
541
542 h.output.advance(w.buffered().len);
543 }
544
545 fn readClientFlight2(h: *Self, opt: Options) !void {
546 // buffer for decrypted handshake records
547 var cleartext_buffer: [max_cleartext_len]u8 = undefined;
548 // cleartext writer
549 var cw = Io.Writer.fixed(&cleartext_buffer);
550
551 var handshake_state: proto.Handshake = .finished;
552 var crt_parser: CertificateParser = undefined;
553 if (opt.client_auth) |client_auth| {
554 crt_parser = .{ .root_ca = client_auth.root_ca, .host = "" };
555 handshake_state = .certificate;
556 }
557
558 outer: while (true) {
559 const rec = try Record.read(h.input);
560 if (rec.protocol_version != .tls_1_2 and rec.content_type != .alert)
561 return error.TlsProtocolVersion;
562
563 switch (rec.content_type) {
564 .change_cipher_spec => {
565 if (rec.payload.len != 1) return error.TlsUnexpectedMessage;
566 },
567 .application_data => {
568 const content_type, const cleartext = try h.cipher.decrypt(cw.unusedCapacitySlice(), rec);
569 cw.advance(cleartext.len);
570
571 var d = record.Decoder.init(content_type, cw.buffered());
572 try d.expectContentType(.handshake);
573 while (!d.eof()) {
574 const handshake_type = try d.decode(proto.Handshake);
575 const length = try d.decode(u24);
576
577 if (length > max_cleartext_len)
578 return error.TlsRecordOverflow;
579 if (length > d.rest().len)
580 continue :outer; // fragmented handshake into multiple records
581
582 defer {
583 h.transcript.update(d.payload[0..d.idx]);
584 _ = cw.consume(d.idx);
585 d = record.Decoder.init(content_type, cw.buffered());
586 }
587
588 if (handshake_state != handshake_type)
589 return error.TlsUnexpectedMessage;
590
591 switch (handshake_type) {
592 .certificate => {
593 if (length == 4) {
594 // got empty certificate message
595 if (opt.client_auth.?.auth_type == .require)
596 return error.TlsCertificateRequired;
597 try d.skip(length);
598 handshake_state = .finished;
599 } else {
600 try crt_parser.parseCertificate(&d, .tls_1_3);
601 handshake_state = .certificate_verify;
602 }
603 },
604 .certificate_verify => {
605 try crt_parser.parseCertificateVerify(&d);
606 crt_parser.verifySignature(h.transcript.clientCertificateVerify()) catch |err| return switch (err) {
607 error.TlsUnknownSignatureScheme => error.TlsIllegalParameter,
608 else => error.TlsDecryptError,
609 };
610 handshake_state = .finished;
611 },
612 .finished => {
613 const actual = try d.slice(length);
614 const expected = h.transcript.clientFinishedTls13();
615 if (!mem.eql(u8, expected, actual))
616 return if (expected.len == actual.len)
617 error.TlsDecryptError
618 else
619 error.TlsDecodeError;
620 return;
621 },
622 else => return error.TlsUnexpectedMessage,
623 }
624 }
625 },
626 .alert => {
627 var d = record.Decoder.init(rec.content_type, rec.payload);
628 return d.raiseAlert();
629 },
630 else => return error.TlsUnexpectedMessage,
631 }
632 }
633 }
634
635 /// Write encrypted handshake message into `w` Cleartext and write buffer
636 /// `w.unused()` are reusing same buffer. Cleartext is written 5 bytes ahead
637 /// (record header len) from w.unused() position to avoid memcopy in the
638 /// encrypt. Encrypt will add tls record head in first 5 bytes, encrypt
639 /// cleartext and add hmac at end.
640 fn writeEncrypted(h: *Self, w: *record.Writer, cleartext: []const u8) !void {
641 const ciphertext = try h.cipher.encrypt(w.unused(), .handshake, cleartext);
642 w.advance(ciphertext.len);
643 }
644
645 fn makeServerHello(h: *Self, w: *record.Writer) ![]const u8 {
646 const header_pos = try w.skip(9);
647
648 try w.enumValue(proto.Version.tls_1_2);
649 try w.slice(&h.server_random);
650 {
651 try w.int(u8, h.legacy_session_id.len);
652 if (h.legacy_session_id.len > 0) try w.slice(h.legacy_session_id);
653 }
654 try w.enumValue(h.cipher_suite);
655 try w.slice(&[_]u8{0}); // compression method
656
657 const ext_len_pos = try w.skip(2); // extensions length placeholder writer
658 { // supported versions extension
659 try w.enumValue(proto.Extension.supported_versions);
660 try w.int(u16, 2);
661 try w.enumValue(proto.Version.tls_1_3);
662 }
663 { // key share extension
664 const key_len: u16 = @intCast(h.server_pub_key.len);
665 try w.enumValue(proto.Extension.key_share);
666 try w.int(u16, key_len + 4);
667 try w.enumValue(h.named_group);
668 try w.int(u16, key_len);
669 try w.slice(h.server_pub_key);
670 }
671 var ew = w.writerAt(ext_len_pos);
672 try ew.int(u16, w.pos() - ext_len_pos - 2);
673 var hw = w.writerAt(header_pos);
674 try hw.recordHeader(.handshake, w.pos() - 5);
675 try hw.handshakeRecordHeader(.server_hello, w.pos() - 9);
676
677 return w.buffered();
678 }
679
680 fn makeCertificateRequest(w: *record.Writer) !void {
681 const header_pos = try w.skip(4 + 1 + 2);
682 const ext_head = w.pos();
683 try w.extension(.signature_algorithms, common.supported_signature_algorithms);
684 const ext_len = w.pos() - ext_head;
685 var hw = w.writerAt(header_pos);
686 try hw.handshakeRecordHeader(.certificate_request, ext_len + 3);
687 try hw.int(u8, 0); // certificate request context length = 0
688 try hw.int(u16, ext_len); // extensions length
689 }
690
691 fn readClientHello(h: *Self, supported_cipher_suites: []const CipherSuite, server_named_groups: []const proto.NamedGroup) !void {
692 log.info("readClientHello: starting to parse ClientHello", .{});
693 var d = try Record.decoder(h.input);
694 if (d.payload.len > max_cleartext_len) return error.TlsRecordOverflow;
695 try d.expectContentType(.handshake);
696 h.transcript.update(d.payload);
697
698 const handshake_type = try d.decode(proto.Handshake);
699 if (handshake_type != .client_hello) return error.TlsUnexpectedMessage;
700 _ = try d.decode(u24); // handshake length
701 if (try d.decode(proto.Version) != .tls_1_2) return error.TlsProtocolVersion;
702
703 h.client_random = try d.array(32);
704 { // legacy session id
705 const len = try d.decode(u8);
706 h.legacy_session_id = try common.dupe(&h.legacy_session_id_buf, try d.slice(len));
707 }
708 // Track cipher suite candidates for both TLS versions separately
709 // This is needed because we don't know which TLS version will be used yet
710 var tls13_cipher: CipherSuite = @fromBackingInt(@intCast(0));
711 var tls12_cipher: CipherSuite = @fromBackingInt(@intCast(0));
712 { // cipher suites
713 const end_idx = try d.decode(u16) + d.idx;
714
715 while (d.idx < end_idx) {
716 const cipher_suite = try d.decode(CipherSuite);
717 if (cipher_suites.includes(supported_cipher_suites, cipher_suite)) {
718 // Track TLS 1.3 and TLS 1.2 ciphers separately
719 if (cipher_suites.includes(cipher_suites.tls13, cipher_suite)) {
720 if (@backingInt(tls13_cipher) == 0) {
721 tls13_cipher = cipher_suite;
722 }
723 } else if (cipher_suites.includes(cipher_suites.tls12, cipher_suite)) {
724 if (@backingInt(tls12_cipher) == 0) {
725 tls12_cipher = cipher_suite;
726 }
727 }
728 }
729 }
730 // Must have at least one supported cipher
731 if (@backingInt(tls13_cipher) == 0 and @backingInt(tls12_cipher) == 0)
732 return error.TlsNoSupportedCiphers;
733 }
734 log.info("readClientHello: tls13_cipher={x}, tls12_cipher={x}", .{ @backingInt(tls13_cipher), @backingInt(tls12_cipher) });
735 try d.skip(2); // compression methods
736
737 var key_share_received = false;
738 var tls_1_3_supported = false;
739 var supported_groups_buf: [16]proto.NamedGroup = undefined;
740 var supported_groups_len: usize = 0;
741
742 // extensions
743 const extensions_end_idx = try d.decode(u16) + d.idx;
744 while (d.idx < extensions_end_idx) {
745 const extension_type = try d.decode(proto.Extension);
746 const extension_len = try d.decode(u16);
747
748 switch (extension_type) {
749 .supported_versions => {
750 const end_idx = try d.decode(u8) + d.idx;
751 while (d.idx < end_idx) {
752 const version = try d.decode(proto.Version);
753 if (version == proto.Version.tls_1_3) {
754 tls_1_3_supported = true;
755 }
756 }
757 },
758 .key_share => {
759 if (extension_len == 0) return error.TlsDecodeError;
760 key_share_received = true;
761 var selected_named_group_idx = supported_named_groups.len;
762 const end_idx = try d.decode(u16) + d.idx;
763 while (d.idx < end_idx) {
764 const named_group = try d.decode(proto.NamedGroup);
765 switch (@backingInt(named_group)) {
766 0x0001...0x0016,
767 0x001a...0x001c,
768 0xff01...0xff02,
769 => return error.TlsIllegalParameter,
770 else => {},
771 }
772 const client_pub_key = try d.slice(try d.decode(u16));
773 for (supported_named_groups, 0..) |supported, idx| {
774 if (named_group == supported and idx < selected_named_group_idx) {
775 h.named_group = named_group;
776 h.client_pub_key = try common.dupe(&h.client_pub_key_buf, client_pub_key);
777 selected_named_group_idx = idx;
778 }
779 }
780 }
781 if (@backingInt(h.named_group) == 0)
782 return error.TlsIllegalParameter;
783 },
784 .supported_groups => {
785 const end_idx = try d.decode(u16) + d.idx;
786 while (d.idx < end_idx) {
787 const named_group = try d.decode(proto.NamedGroup);
788 switch (@backingInt(named_group)) {
789 // Deprecated/insecure curves - skip silently for TLS 1.2 compatibility
790 // Some clients (including Apple SecureTransport) may include these
791 0x0001...0x0016,
792 0x001a...0x001c,
793 0xff01...0xff02,
794 => {},
795 else => {
796 // Store supported groups for TLS 1.2 fallback
797 if (supported_groups_len < supported_groups_buf.len) {
798 supported_groups_buf[supported_groups_len] = named_group;
799 supported_groups_len += 1;
800 }
801 },
802 }
803 }
804 },
805 .signature_algorithms => {
806 if (@backingInt(h.signature_scheme) == 0) {
807 try d.skip(extension_len);
808 } else {
809 var found = false;
810 const list_len = try d.decode(u16);
811 if (list_len == 0) return error.TlsDecodeError;
812 const end_idx = list_len + d.idx;
813 while (d.idx < end_idx) {
814 const signature_scheme = try d.decode(proto.SignatureScheme);
815 if (signature_scheme == h.signature_scheme) found = true;
816 }
817 if (!found) return error.TlsHandshakeFailure;
818 }
819 },
820 else => {
821 try d.skip(extension_len);
822 },
823 }
824 }
825
826 // Determine TLS version based on client capabilities
827 log.info("readClientHello: tls_1_3_supported={}, key_share_received={}, supported_groups_len={}", .{ tls_1_3_supported, key_share_received, supported_groups_len });
828 if (tls_1_3_supported and key_share_received and @backingInt(tls13_cipher) != 0) {
829 // TLS 1.3 handshake - requires TLS 1.3 cipher
830 h.tls_version = .tls_1_3;
831 h.cipher_suite = tls13_cipher;
832 if (@backingInt(h.named_group) == 0) return error.TlsIllegalParameter;
833 } else if (@backingInt(tls12_cipher) != 0) {
834 // TLS 1.2 handshake - need to select named group from supported_groups
835 h.tls_version = .tls_1_2;
836 h.cipher_suite = tls12_cipher;
837 log.info("readClientHello: TLS 1.2 path, cipher keyExchange={}", .{h.cipher_suite.keyExchange()});
838
839 // For TLS 1.2 ECDHE, select a named group from supported_groups extension
840 if (h.cipher_suite.keyExchange() == .ecdhe) {
841 // If no supported_groups extension was received, default to common curves
842 // per RFC 8422 - most TLS 1.2 clients support secp256r1/secp384r1
843 const client_groups = if (supported_groups_len > 0)
844 supported_groups_buf[0..supported_groups_len]
845 else
846 &[_]proto.NamedGroup{ .secp256r1, .secp384r1 };
847
848 log.info("readClientHello: client_groups count={}, server_named_groups count={}", .{ client_groups.len, server_named_groups.len });
849
850 // Find first matching named group between server and client
851 for (server_named_groups) |server_ng| {
852 for (client_groups) |client_ng| {
853 if (server_ng == client_ng) {
854 h.named_group = server_ng;
855 break;
856 }
857 }
858 if (@backingInt(h.named_group) != 0) break;
859 }
860 if (@backingInt(h.named_group) == 0) return error.TlsIllegalParameter;
861 }
862 log.info("TLS 1.2 readClientHello: selected named_group={x}", .{@backingInt(h.named_group)});
863 } else {
864 // No compatible cipher suite found
865 return error.TlsNoSupportedCiphers;
866 }
867 log.info("readClientHello complete: tls_version={}, cipher_suite={x}, named_group={x}", .{ h.tls_version, @backingInt(h.cipher_suite), @backingInt(h.named_group) });
868 }
869};
870
871const testing = std.testing;
872const data13 = @import("testdata/tls13.zig");
873const testu = @import("testu.zig");
874
875test "read client hello" {
876 var reader: Io.Reader = .fixed(&data13.client_hello);
877 var h: Handshake = .{
878 .input = &reader,
879 .output = undefined,
880 };
881 h.signature_scheme = .ecdsa_secp521r1_sha512; // this must be supported in signature_algorithms extension
882 try h.readClientHello(cipher_suites.tls13, &[_]proto.NamedGroup{ .x25519, .secp256r1, .secp384r1 });
883
884 try testing.expectEqual(CipherSuite.AES_256_GCM_SHA384, h.cipher_suite);
885 try testing.expectEqual(.x25519, h.named_group);
886 try testing.expectEqualSlices(u8, &data13.client_random, &h.client_random);
887 try testing.expectEqualSlices(u8, &data13.client_public_key, h.client_pub_key);
888}
889
890test "make server hello" {
891 var h: Handshake = .{ .input = undefined, .output = undefined };
892
893 h.cipher_suite = .AES_256_GCM_SHA384;
894 testu.fillFrom(&h.server_random, 0);
895 testu.fillFrom(&h.server_pub_key_buf, 0x20);
896 h.named_group = .x25519;
897 h.server_pub_key = h.server_pub_key_buf[0..32];
898
899 const expected = &testu.hexToBytes(
900 \\ 16 03 03 00 5a 02 00 00 56
901 \\ 03 03
902 \\ 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
903 \\ 00
904 \\ 13 02 00
905 \\ 00 2e 00 2b 00 02 03 04
906 \\ 00 33 00 24 00 1d 00 20
907 \\ 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
908 );
909
910 var buffer: [128]u8 = undefined;
911 var w: record.Writer = .init(&buffer);
912 const actual = try h.makeServerHello(&w);
913 try testing.expectEqual(95, actual.len);
914 try testing.expectEqualSlices(u8, expected, actual);
915}
916
917test "make certificate request" {
918 var buffer: [32]u8 = undefined;
919
920 const expected = testu.hexToBytes("0d 00 00 1b" ++ // handshake header
921 "00 00 18" ++ // extension length
922 "00 0d" ++ // signature algorithms extension
923 "00 14" ++ // extension length
924 "00 12" ++ // list length 6 * 2 bytes
925 "04 03 05 03 08 04 08 05 08 06 08 07 02 01 04 01 05 01" // signature schemes
926 );
927
928 var w: record.Writer = .init(&buffer);
929 try Handshake.makeCertificateRequest(&w);
930 try testing.expectEqualSlices(u8, &expected, w.buffered());
931}
932
933pub const NonBlock = struct {
934 const Self = @This();
935
936 // inner sync handshake
937 inner: Handshake = undefined,
938 opt: Options = undefined,
939 state: State = undefined,
940
941 const State = enum {
942 init,
943 client_flight_1,
944 server_flight,
945 client_flight_2,
946
947 fn next(self: *State) void {
948 self.* = @fromBackingInt(@intCast(@backingInt(self.*) + 1));
949 }
950 };
951
952 pub fn init(opt: Options) Self {
953 var inner: Handshake = .{
954 .input = undefined,
955 .output = undefined,
956 };
957 inner.initKeys(opt);
958 return .{
959 .opt = opt,
960 .inner = inner,
961 .state = .init,
962 };
963 }
964
965 fn recv(self: *Self) !void {
966 const prev: Transcript = self.inner.transcript;
967 errdefer self.inner.transcript = prev;
968
969 switch (self.state) {
970 .init => {
971 try self.inner.clientFlight1(self.opt);
972 self.state.next();
973 },
974 .server_flight => {
975 // Use appropriate client flight based on TLS version
976 if (self.inner.tls_version == .tls_1_2) {
977 try self.inner.clientFlight2Tls12(self.opt);
978 } else {
979 try self.inner.clientFlight2(self.opt);
980 }
981 self.state.next();
982 },
983 else => return,
984 }
985 }
986
987 /// True when handshake is successfully finished
988 pub fn done(self: Self) bool {
989 return self.state == .client_flight_2;
990 }
991
992 /// Runs next handshake step.
993 pub fn run(
994 self: *Self,
995 /// Data received from the peer
996 recv_buf: []const u8,
997 /// Scratch buffer where data to be sent to the peer will be prepared
998 send_buf: []u8,
999 ) !struct {
1000 /// Number of bytes consumed from recv_buf
1001 recv_pos: usize,
1002 /// Number of bytes prepared in send_buf
1003 send_pos: usize,
1004 /// Unused part of the recv_buf,
1005 unused_recv: []const u8,
1006 /// Part of the send_buf that should be sent to the peer
1007 send: []const u8,
1008 } {
1009 if (self.done()) return .{
1010 .recv_pos = 0,
1011 .send_pos = 0,
1012 .unused_recv = &.{},
1013 .send = &.{},
1014 };
1015
1016 var reader: Io.Reader = .fixed(recv_buf);
1017 self.inner.input = &reader;
1018 var writer: Io.Writer = .fixed(send_buf);
1019 self.inner.output = &writer;
1020
1021 var recv_pos: usize = 0;
1022 out: switch (self.state) {
1023 .init, .server_flight => {
1024 self.recv() catch |err| switch (err) {
1025 error.EndOfStream, error.InputBufferUndersize => {
1026 return .{
1027 .recv_pos = 0,
1028 .send_pos = 0,
1029 .unused_recv = recv_buf,
1030 .send = &.{},
1031 };
1032 },
1033 else => return err,
1034 };
1035 recv_pos = reader.seek;
1036 continue :out self.state;
1037 },
1038 .client_flight_1 => {
1039 if (recv_buf.ptr == send_buf.ptr and recv_pos != recv_buf.len) {
1040 // recv buffer is fully consumed, same buffer can be used for write
1041 return error.TlsUnexpectedMessage;
1042 }
1043 // Use appropriate server flight based on TLS version
1044 if (self.inner.tls_version == .tls_1_2) {
1045 try self.inner.serverFlightTls12(self.opt);
1046 } else {
1047 try self.inner.serverFlight(self.opt);
1048 }
1049 self.state.next();
1050 },
1051 .client_flight_2 => {
1052 // done
1053 },
1054 }
1055
1056 log.info("NonBlock run() returning: recv_pos={d}, writer.end={d}, send.len={d}", .{ recv_pos, writer.end, writer.buffered().len });
1057 return .{
1058 .recv_pos = recv_pos,
1059 .send_pos = writer.end,
1060 .unused_recv = recv_buf[recv_pos..],
1061 .send = writer.buffered(),
1062 };
1063 }
1064
1065 /// Cipher produced in handshake, null until successful handshake.
1066 pub fn cipher(self: Self) ?Cipher {
1067 return if (self.done()) self.inner.cipher else null;
1068 }
1069};