also looking at this
Harden encrypted mail storage, recovery, and forwarding
#8
50 files
+1701
-9001
| @@ -1,594 +0,0 @@ | ||
| 1 | const std = @import("std"); | |
| 2 | const assert = std.debug.assert; | |
| 3 | const mem = std.mem; | |
| 4 | const crypto = std.crypto; | |
| 5 | const Certificate = crypto.Certificate; | |
| 6 | const Io = std.Io; | |
| 7 | ||
| 8 | const Transcript = @import("transcript.zig").Transcript; | |
| 9 | const PrivateKey = @import("PrivateKey.zig"); | |
| 10 | const record = @import("record.zig"); | |
| 11 | const rsa = @import("rsa/rsa.zig"); | |
| 12 | const proto = @import("protocol.zig"); | |
| 13 | ||
| 14 | const X25519 = crypto.dh.X25519; | |
| 15 | const EcdsaP256Sha256 = crypto.sign.ecdsa.EcdsaP256Sha256; | |
| 16 | const EcdsaP384Sha384 = crypto.sign.ecdsa.EcdsaP384Sha384; | |
| 17 | const MLKem768 = crypto.kem.ml_kem.MLKem768; | |
| 18 | ||
| 19 | pub const supported_signature_algorithms = &[_]proto.SignatureScheme{ | |
| 20 | .ecdsa_secp256r1_sha256, | |
| 21 | .ecdsa_secp384r1_sha384, | |
| 22 | .rsa_pss_rsae_sha256, | |
| 23 | .rsa_pss_rsae_sha384, | |
| 24 | .rsa_pss_rsae_sha512, | |
| 25 | .ed25519, | |
| 26 | .rsa_pkcs1_sha1, | |
| 27 | .rsa_pkcs1_sha256, | |
| 28 | .rsa_pkcs1_sha384, | |
| 29 | }; | |
| 30 | ||
| 31 | pub const CertKeyPair = struct { | |
| 32 | /// A chain of one or more certificates, leaf first. | |
| 33 | /// | |
| 34 | /// Each X.509 certificate contains the public key of a key pair, extra | |
| 35 | /// information (the name of the holder, the name of an issuer of the | |
| 36 | /// certificate, validity time spans) and a signature generated using the | |
| 37 | /// private key of the issuer of the certificate. | |
| 38 | /// | |
| 39 | /// All certificates from the bundle are sent to the other side when creating | |
| 40 | /// Certificate tls message. | |
| 41 | /// | |
| 42 | /// Leaf certificate and private key are used to create signature for | |
| 43 | /// CertifyVerify tls message. | |
| 44 | bundle: Certificate.Bundle, | |
| 45 | ||
| 46 | /// Private key corresponding to the public key in leaf certificate from the | |
| 47 | /// bundle. | |
| 48 | key: PrivateKey, | |
| 49 | ||
| 50 | /// Ecdsa key pair derived from key. Computed on init and cached because it | |
| 51 | /// is costly operation. Important for server which is creating many | |
| 52 | /// signatures with the same key to not repeat that operation. | |
| 53 | ecdsa_key_pair: ?EcdsaKeyPair = null, | |
| 54 | ||
| 55 | pub fn fromFilePath( | |
| 56 | allocator: mem.Allocator, | |
| 57 | io: Io, | |
| 58 | dir: std.Io.Dir, | |
| 59 | cert_path: []const u8, | |
| 60 | key_path: []const u8, | |
| 61 | ) !CertKeyPair { | |
| 62 | var bundle: cert.Bundle = .empty; | |
| 63 | try bundle.addCertsFromFilePath(allocator, dir, cert_path); | |
| 64 | ||
| 65 | const key_file = try dir.openFile(io, key_path, .{}); | |
| 66 | defer key_file.close(io); | |
| 67 | const key = try PrivateKey.fromFile(allocator, key_file); | |
| 68 | ||
| 69 | return .{ .bundle = bundle, .key = key, .ecdsa_key_pair = try EcdsaKeyPair.init(key) }; | |
| 70 | } | |
| 71 | ||
| 72 | pub fn fromFilePathAbsolute( | |
| 73 | allocator: mem.Allocator, | |
| 74 | io: Io, | |
| 75 | cert_path: []const u8, | |
| 76 | key_path: []const u8, | |
| 77 | ) !CertKeyPair { | |
| 78 | var bundle: cert.Bundle = .empty; | |
| 79 | const now = Io.Clock.real.now(io); | |
| 80 | try bundle.addCertsFromFilePathAbsolute(allocator, io, now, cert_path); | |
| 81 | ||
| 82 | const key_file = try std.Io.Dir.openFileAbsolute(io, key_path, .{}); | |
| 83 | defer key_file.close(io); | |
| 84 | const key = try PrivateKey.fromFile(allocator, key_file); | |
| 85 | ||
| 86 | return .{ .bundle = bundle, .key = key, .ecdsa_key_pair = try EcdsaKeyPair.init(key) }; | |
| 87 | } | |
| 88 | ||
| 89 | /// Reads certs directly from PEM files (delegates to fromFilePathAbsolute) | |
| 90 | pub fn fromFilePathAbsoluteSync( | |
| 91 | allocator: mem.Allocator, | |
| 92 | cert_path: []const u8, | |
| 93 | key_path: []const u8, | |
| 94 | ) !CertKeyPair { | |
| 95 | // This function is called from contexts that have io_compat initialized. | |
| 96 | // We use the same approach - read cert/key via Io. | |
| 97 | // Callers should use fromFilePathAbsolute directly when they have Io. | |
| 98 | ||
| 99 | // Read key file using posix fd operations (no Io needed) | |
| 100 | // For cert, manually parse PEM | |
| 101 | var cert_buf: [32768]u8 = undefined; | |
| 102 | var cert_len: usize = 0; | |
| 103 | ||
| 104 | // Use posix read since we may not have Io | |
| 105 | const cert_path_z = @as([*:0]const u8, @ptrCast(cert_path.ptr)); | |
| 106 | const cert_fd = std.c.open(cert_path_z, .{}, @as(std.c.mode_t, 0)); | |
| 107 | if (cert_fd < 0) return error.FileNotFound; | |
| 108 | defer _ = std.c.close(@intCast(cert_fd)); | |
| 109 | ||
| 110 | while (cert_len < cert_buf.len) { | |
| 111 | const n = std.posix.read(@intCast(cert_fd), cert_buf[cert_len..]) catch break; | |
| 112 | if (n == 0) break; | |
| 113 | cert_len += n; | |
| 114 | } | |
| 115 | ||
| 116 | // Parse PEM certificates manually | |
| 117 | var bundle: cert.Bundle = .empty; | |
| 118 | const pem_data = cert_buf[0..cert_len]; | |
| 119 | ||
| 120 | // Find and decode PEM blocks - add DER bytes directly to bundle | |
| 121 | const base64_decoder = std.base64.standard.decoderWithIgnore(" \t\r\n"); | |
| 122 | var start: usize = 0; | |
| 123 | while (std.mem.indexOfPos(u8, pem_data, start, "-----BEGIN CERTIFICATE-----")) |begin| { | |
| 124 | const content_start = begin + 27; // Length of "-----BEGIN CERTIFICATE-----" | |
| 125 | if (std.mem.indexOfPos(u8, pem_data, content_start, "-----END CERTIFICATE-----")) |end| { | |
| 126 | const base64_data = pem_data[content_start..end]; | |
| 127 | const decoded_start: u32 = @intCast(bundle.bytes.items.len); | |
| 128 | const dest_buf = bundle.bytes.addManyAsSlice(allocator, base64_decoder.calcSizeUpperBound(base64_data.len)) catch { | |
| 129 | start = end + 25; | |
| 130 | continue; | |
| 131 | }; | |
| 132 | const decoded_len = base64_decoder.decode(dest_buf, base64_data) catch { | |
| 133 | bundle.bytes.items.len = decoded_start; | |
| 134 | start = end + 25; | |
| 135 | continue; | |
| 136 | }; | |
| 137 | bundle.bytes.items.len = decoded_start + decoded_len; | |
| 138 | // Parse and add to map | |
| 139 | bundle.parseCert(allocator, decoded_start, 0) catch { | |
| 140 | bundle.bytes.items.len = decoded_start; | |
| 141 | }; | |
| 142 | start = end + 25; | |
| 143 | } else break; | |
| 144 | } | |
| 145 | ||
| 146 | // Read key file using posix fd | |
| 147 | const key_path_z = @as([*:0]const u8, @ptrCast(key_path.ptr)); | |
| 148 | const key_fd = std.c.open(key_path_z, .{}, @as(std.c.mode_t, 0)); | |
| 149 | if (key_fd < 0) return error.FileNotFound; | |
| 150 | defer _ = std.c.close(@intCast(key_fd)); | |
| 151 | ||
| 152 | var key_buf: [8192]u8 = undefined; | |
| 153 | var key_len: usize = 0; | |
| 154 | while (key_len < key_buf.len) { | |
| 155 | const n = std.posix.read(@intCast(key_fd), key_buf[key_len..]) catch break; | |
| 156 | if (n == 0) break; | |
| 157 | key_len += n; | |
| 158 | } | |
| 159 | const key = try PrivateKey.parsePem(key_buf[0..key_len]); | |
| 160 | ||
| 161 | return .{ .bundle = bundle, .key = key, .ecdsa_key_pair = try EcdsaKeyPair.init(key) }; | |
| 162 | } | |
| 163 | ||
| 164 | pub fn deinit(c: *CertKeyPair, allocator: mem.Allocator) void { | |
| 165 | c.bundle.deinit(allocator); | |
| 166 | } | |
| 167 | ||
| 168 | const EcdsaKeyPair = union(enum) { | |
| 169 | ecdsa_secp256r1_sha256: EcdsaP256Sha256.KeyPair, | |
| 170 | ecdsa_secp384r1_sha384: EcdsaP384Sha384.KeyPair, | |
| 171 | ||
| 172 | fn init(pk: PrivateKey) !?EcdsaKeyPair { | |
| 173 | switch (pk.signature_scheme) { | |
| 174 | inline .ecdsa_secp256r1_sha256, | |
| 175 | .ecdsa_secp384r1_sha384, | |
| 176 | => |comptime_scheme| { | |
| 177 | const Ecdsa = SchemeEcdsa(comptime_scheme); | |
| 178 | const key = pk.key.ecdsa; | |
| 179 | const key_len = Ecdsa.SecretKey.encoded_length; | |
| 180 | if (key.len < key_len) return error.InvalidEncoding; | |
| 181 | const secret_key = try Ecdsa.SecretKey.fromBytes(key[0..key_len].*); | |
| 182 | const key_pair = try Ecdsa.KeyPair.fromSecretKey(secret_key); | |
| 183 | return switch (comptime_scheme) { | |
| 184 | .ecdsa_secp256r1_sha256 => .{ .ecdsa_secp256r1_sha256 = key_pair }, | |
| 185 | .ecdsa_secp384r1_sha384 => .{ .ecdsa_secp384r1_sha384 = key_pair }, | |
| 186 | else => unreachable, | |
| 187 | }; | |
| 188 | }, | |
| 189 | else => return null, | |
| 190 | } | |
| 191 | } | |
| 192 | }; | |
| 193 | }; | |
| 194 | ||
| 195 | pub const cert = struct { | |
| 196 | // A chain of one or more certificates. | |
| 197 | // | |
| 198 | // They are used to verify that certificate chain sent by the other side | |
| 199 | // forms valid trust chain. | |
| 200 | pub const Bundle = crypto.Certificate.Bundle; | |
| 201 | ||
| 202 | pub fn fromFilePath(allocator: mem.Allocator, dir: std.fs.Dir, path: []const u8) !Bundle { | |
| 203 | var bundle: Bundle = .empty; | |
| 204 | try bundle.addCertsFromFilePath(allocator, dir, path); | |
| 205 | return bundle; | |
| 206 | } | |
| 207 | ||
| 208 | pub fn fromFilePathAbsolute(allocator: mem.Allocator, path: []const u8) !Bundle { | |
| 209 | var bundle: Bundle = .empty; | |
| 210 | try bundle.addCertsFromFilePathAbsolute(allocator, path); | |
| 211 | return bundle; | |
| 212 | } | |
| 213 | ||
| 214 | pub fn fromSystem(allocator: mem.Allocator) !Bundle { | |
| 215 | var bundle: Bundle = .empty; | |
| 216 | try bundle.rescan(allocator); | |
| 217 | return bundle; | |
| 218 | } | |
| 219 | }; | |
| 220 | ||
| 221 | pub const CertificateBuilder = struct { | |
| 222 | cert_key_pair: *CertKeyPair, | |
| 223 | transcript: *Transcript, | |
| 224 | tls_version: proto.Version = .tls_1_3, | |
| 225 | side: proto.Side = .client, | |
| 226 | ||
| 227 | pub fn makeCertificate(h: CertificateBuilder, w: *record.Writer) !void { | |
| 228 | const certs = h.cert_key_pair.bundle.bytes.items; | |
| 229 | const certs_count = h.cert_key_pair.bundle.map.size; | |
| 230 | ||
| 231 | // Differences between tls 1.3 and 1.2 | |
| 232 | // TLS 1.3 has request context in header and extensions for each certificate. | |
| 233 | // Here we use empty length for each field. | |
| 234 | // TLS 1.2 don't have these two fields. | |
| 235 | const request_context, const extensions = if (h.tls_version == .tls_1_3) | |
| 236 | .{ &[_]u8{0}, &[_]u8{ 0, 0 } } | |
| 237 | else | |
| 238 | .{ &[_]u8{}, &[_]u8{} }; | |
| 239 | const certs_len = certs.len + (3 + extensions.len) * certs_count; | |
| 240 | ||
| 241 | // Write handshake header | |
| 242 | try w.handshakeRecordHeader(.certificate, certs_len + request_context.len + 3); | |
| 243 | try w.slice(request_context); | |
| 244 | try w.int(u24, certs_len); | |
| 245 | ||
| 246 | // Write each certificate | |
| 247 | var index: u32 = 0; | |
| 248 | while (index < certs.len) { | |
| 249 | const e = try Certificate.der.Element.parse(certs, index); | |
| 250 | const crt = certs[index..e.slice.end]; | |
| 251 | try w.int(u24, crt.len); // certificate length | |
| 252 | try w.slice(crt); // certificate | |
| 253 | try w.slice(extensions); // certificate extensions | |
| 254 | index = e.slice.end; | |
| 255 | } | |
| 256 | } | |
| 257 | ||
| 258 | pub fn makeCertificateVerify(h: CertificateBuilder, w: *record.Writer) !void { | |
| 259 | // Creates signature for client certificate signature message. | |
| 260 | // Returns signature bytes and signature scheme. | |
| 261 | const signature, const signature_scheme = switch (h.cert_key_pair.key.signature_scheme) { | |
| 262 | inline .ecdsa_secp256r1_sha256, | |
| 263 | .ecdsa_secp384r1_sha384, | |
| 264 | => |comptime_scheme| brk: { | |
| 265 | const Ecdsa = SchemeEcdsa(comptime_scheme); | |
| 266 | const key_pair = switch (comptime_scheme) { | |
| 267 | .ecdsa_secp256r1_sha256 => h.cert_key_pair.ecdsa_key_pair.?.ecdsa_secp256r1_sha256, | |
| 268 | .ecdsa_secp384r1_sha384 => h.cert_key_pair.ecdsa_key_pair.?.ecdsa_secp384r1_sha384, | |
| 269 | else => unreachable, | |
| 270 | }; | |
| 271 | var signer = try key_pair.signer(null); | |
| 272 | h.setSignatureVerifyBytes(&signer); | |
| 273 | const signature = try signer.finalize(); | |
| 274 | var buf: [Ecdsa.Signature.der_encoded_length_max]u8 = undefined; | |
| 275 | break :brk .{ signature.toDer(&buf), comptime_scheme }; | |
| 276 | }, | |
| 277 | inline .rsa_pss_rsae_sha256, | |
| 278 | .rsa_pss_rsae_sha384, | |
| 279 | .rsa_pss_rsae_sha512, | |
| 280 | => |comptime_scheme| brk: { | |
| 281 | const Hash = SchemeHash(comptime_scheme); | |
| 282 | var signer = try h.cert_key_pair.key.key.rsa.signerOaep(Hash, null); | |
| 283 | h.setSignatureVerifyBytes(&signer); | |
| 284 | var buf: [512]u8 = undefined; | |
| 285 | const signature = try signer.finalize(&buf); | |
| 286 | break :brk .{ signature.bytes, comptime_scheme }; | |
| 287 | }, | |
| 288 | else => return error.TlsUnknownSignatureScheme, | |
| 289 | }; | |
| 290 | ||
| 291 | try w.handshakeRecordHeader(.certificate_verify, signature.len + 4); | |
| 292 | try w.enumValue(signature_scheme); | |
| 293 | try w.int(u16, signature.len); | |
| 294 | try w.slice(signature); | |
| 295 | } | |
| 296 | ||
| 297 | fn setSignatureVerifyBytes(h: CertificateBuilder, signer: anytype) void { | |
| 298 | if (h.tls_version == .tls_1_2) { | |
| 299 | // tls 1.2 signature uses current transcript hash value. | |
| 300 | // ref: https://datatracker.ietf.org/doc/html/rfc5246.html#section-7.4.8 | |
| 301 | const Hash = @TypeOf(signer.h); | |
| 302 | signer.h = h.transcript.hash(Hash); | |
| 303 | } else { | |
| 304 | // tls 1.3 signature is computed over concatenation of 64 spaces, | |
| 305 | // context, separator and content. | |
| 306 | // ref: https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.3 | |
| 307 | if (h.side == .server) { | |
| 308 | signer.update(h.transcript.serverCertificateVerify()); | |
| 309 | } else { | |
| 310 | signer.update(h.transcript.clientCertificateVerify()); | |
| 311 | } | |
| 312 | } | |
| 313 | } | |
| 314 | }; | |
| 315 | ||
| 316 | pub fn SchemeEcdsa(comptime scheme: proto.SignatureScheme) type { | |
| 317 | return switch (scheme) { | |
| 318 | .ecdsa_secp256r1_sha256 => EcdsaP256Sha256, | |
| 319 | .ecdsa_secp384r1_sha384 => EcdsaP384Sha384, | |
| 320 | else => unreachable, | |
| 321 | }; | |
| 322 | } | |
| 323 | ||
| 324 | pub const CertificateParser = struct { | |
| 325 | pub_key_algo: Certificate.Parsed.PubKeyAlgo = undefined, | |
| 326 | pub_key_buf: [1038]u8 = undefined, | |
| 327 | pub_key: []const u8 = undefined, | |
| 328 | ||
| 329 | signature_scheme: proto.SignatureScheme = @fromBackingInt(@intCast(0)), | |
| 330 | signature_buf: [1024]u8 = undefined, | |
| 331 | signature: []const u8 = undefined, | |
| 332 | ||
| 333 | root_ca: Certificate.Bundle, | |
| 334 | host: []const u8, | |
| 335 | skip_verify: bool = false, | |
| 336 | now_sec: i64 = 0, | |
| 337 | ||
| 338 | pub fn parseCertificate(h: *CertificateParser, d: *record.Decoder, tls_version: proto.Version) !void { | |
| 339 | if (h.now_sec == 0) { | |
| 340 | var ts: std.c.timespec = undefined; | |
| 341 | if (std.c.clock_gettime(.REALTIME, &ts) == 0) { | |
| 342 | h.now_sec = ts.sec; | |
| 343 | } | |
| 344 | } | |
| 345 | if (tls_version == .tls_1_3) { | |
| 346 | const request_context = try d.decode(u8); | |
| 347 | if (request_context != 0) return error.TlsIllegalParameter; | |
| 348 | } | |
| 349 | ||
| 350 | var trust_chain_established = false; | |
| 351 | var last_cert: ?Certificate.Parsed = null; | |
| 352 | const certs_len = try d.decode(u24); | |
| 353 | const start_idx = d.idx; | |
| 354 | while (d.idx - start_idx < certs_len) { | |
| 355 | const crt_len = try d.decode(u24); | |
| 356 | const crt = try d.slice(crt_len); | |
| 357 | if (tls_version == .tls_1_3) { | |
| 358 | // certificate extensions present in tls 1.3 | |
| 359 | try d.skip(try d.decode(u16)); | |
| 360 | } | |
| 361 | if (trust_chain_established) | |
| 362 | continue; | |
| 363 | ||
| 364 | const subject = try (Certificate{ .buffer = crt, .index = 0 }).parse(); | |
| 365 | if (last_cert) |pc| { | |
| 366 | if (pc.verify(subject, h.now_sec)) { | |
| 367 | last_cert = subject; | |
| 368 | } else |err| switch (err) { | |
| 369 | error.CertificateIssuerMismatch => { | |
| 370 | // skip certificate which is not part of the chain | |
| 371 | continue; | |
| 372 | }, | |
| 373 | else => return err, | |
| 374 | } | |
| 375 | } else { // first certificate | |
| 376 | if (!h.skip_verify and h.host.len > 0) { | |
| 377 | try subject.verifyHostName(h.host); | |
| 378 | } | |
| 379 | h.pub_key = try dupe(&h.pub_key_buf, subject.pubKey()); | |
| 380 | h.pub_key_algo = subject.pub_key_algo; | |
| 381 | last_cert = subject; | |
| 382 | } | |
| 383 | if (!h.skip_verify) { | |
| 384 | if (h.root_ca.verify(last_cert.?, h.now_sec)) |_| { | |
| 385 | trust_chain_established = true; | |
| 386 | } else |err| switch (err) { | |
| 387 | error.CertificateIssuerNotFound => {}, | |
| 388 | else => return err, | |
| 389 | } | |
| 390 | } | |
| 391 | } | |
| 392 | if (!h.skip_verify and !trust_chain_established) { | |
| 393 | return error.CertificateIssuerNotFound; | |
| 394 | } | |
| 395 | } | |
| 396 | ||
| 397 | pub fn parseCertificateVerify(h: *CertificateParser, d: *record.Decoder) !void { | |
| 398 | h.signature_scheme = try d.decode(proto.SignatureScheme); | |
| 399 | h.signature = try dupe(&h.signature_buf, try d.slice(try d.decode(u16))); | |
| 400 | } | |
| 401 | ||
| 402 | pub fn verifySignature(h: *CertificateParser, verify_bytes: []const u8) !void { | |
| 403 | switch (h.signature_scheme) { | |
| 404 | inline .ecdsa_secp256r1_sha256, | |
| 405 | .ecdsa_secp384r1_sha384, | |
| 406 | => |comptime_scheme| { | |
| 407 | if (h.pub_key_algo != .X9_62_id_ecPublicKey) return error.TlsBadSignatureScheme; | |
| 408 | const cert_named_curve = h.pub_key_algo.X9_62_id_ecPublicKey; | |
| 409 | switch (cert_named_curve) { | |
| 410 | inline .secp384r1, .X9_62_prime256v1 => |comptime_cert_named_curve| { | |
| 411 | const Ecdsa = SchemeEcdsaCert(comptime_scheme, comptime_cert_named_curve); | |
| 412 | const key = try Ecdsa.PublicKey.fromSec1(h.pub_key); | |
| 413 | const sig = try Ecdsa.Signature.fromDer(h.signature); | |
| 414 | try sig.verify(verify_bytes, key); | |
| 415 | }, | |
| 416 | else => return error.TlsUnknownSignatureScheme, | |
| 417 | } | |
| 418 | }, | |
| 419 | .ed25519 => { | |
| 420 | if (h.pub_key_algo != .curveEd25519) return error.TlsBadSignatureScheme; | |
| 421 | const Eddsa = crypto.sign.Ed25519; | |
| 422 | if (h.signature.len != Eddsa.Signature.encoded_length) return error.InvalidEncoding; | |
| 423 | const sig = Eddsa.Signature.fromBytes(h.signature[0..Eddsa.Signature.encoded_length].*); | |
| 424 | if (h.pub_key.len != Eddsa.PublicKey.encoded_length) return error.InvalidEncoding; | |
| 425 | const key = try Eddsa.PublicKey.fromBytes(h.pub_key[0..Eddsa.PublicKey.encoded_length].*); | |
| 426 | try sig.verify(verify_bytes, key); | |
| 427 | }, | |
| 428 | inline .rsa_pss_rsae_sha256, | |
| 429 | .rsa_pss_rsae_sha384, | |
| 430 | .rsa_pss_rsae_sha512, | |
| 431 | => |comptime_scheme| { | |
| 432 | if (h.pub_key_algo != .rsaEncryption) return error.TlsBadSignatureScheme; | |
| 433 | const Hash = SchemeHash(comptime_scheme); | |
| 434 | const pk = try rsa.PublicKey.fromDer(h.pub_key); | |
| 435 | const sig = rsa.Pss(Hash).Signature{ .bytes = h.signature }; | |
| 436 | try sig.verify(verify_bytes, pk, null); | |
| 437 | }, | |
| 438 | inline .rsa_pkcs1_sha1, | |
| 439 | .rsa_pkcs1_sha256, | |
| 440 | .rsa_pkcs1_sha384, | |
| 441 | .rsa_pkcs1_sha512, | |
| 442 | => |comptime_scheme| { | |
| 443 | if (h.pub_key_algo != .rsaEncryption) return error.TlsBadSignatureScheme; | |
| 444 | const Hash = SchemeHash(comptime_scheme); | |
| 445 | const pk = try rsa.PublicKey.fromDer(h.pub_key); | |
| 446 | const sig = rsa.PKCS1v1_5(Hash).Signature{ .bytes = h.signature }; | |
| 447 | try sig.verify(verify_bytes, pk); | |
| 448 | }, | |
| 449 | else => return error.TlsUnknownSignatureScheme, | |
| 450 | } | |
| 451 | } | |
| 452 | ||
| 453 | fn SchemeEcdsaCert(comptime scheme: proto.SignatureScheme, comptime cert_named_curve: Certificate.NamedCurve) type { | |
| 454 | const Sha256 = crypto.hash.sha2.Sha256; | |
| 455 | const Sha384 = crypto.hash.sha2.Sha384; | |
| 456 | const Ecdsa = crypto.sign.ecdsa.Ecdsa; | |
| 457 | ||
| 458 | return switch (scheme) { | |
| 459 | .ecdsa_secp256r1_sha256 => Ecdsa(cert_named_curve.Curve(), Sha256), | |
| 460 | .ecdsa_secp384r1_sha384 => Ecdsa(cert_named_curve.Curve(), Sha384), | |
| 461 | else => @compileError("bad scheme"), | |
| 462 | }; | |
| 463 | } | |
| 464 | }; | |
| 465 | ||
| 466 | pub fn SchemeHash(comptime scheme: proto.SignatureScheme) type { | |
| 467 | const Sha256 = crypto.hash.sha2.Sha256; | |
| 468 | const Sha384 = crypto.hash.sha2.Sha384; | |
| 469 | const Sha512 = crypto.hash.sha2.Sha512; | |
| 470 | ||
| 471 | return switch (scheme) { | |
| 472 | .rsa_pkcs1_sha1 => crypto.hash.Sha1, | |
| 473 | .rsa_pss_rsae_sha256, .rsa_pkcs1_sha256 => Sha256, | |
| 474 | .rsa_pss_rsae_sha384, .rsa_pkcs1_sha384 => Sha384, | |
| 475 | .rsa_pss_rsae_sha512, .rsa_pkcs1_sha512 => Sha512, | |
| 476 | else => @compileError("bad scheme"), | |
| 477 | }; | |
| 478 | } | |
| 479 | ||
| 480 | pub fn dupe(buf: []u8, data: []const u8) ![]u8 { | |
| 481 | if (buf.len < data.len) { | |
| 482 | return error.BufferUndersize; | |
| 483 | } | |
| 484 | @memcpy(buf[0..data.len], data); | |
| 485 | return buf[0..data.len]; | |
| 486 | } | |
| 487 | ||
| 488 | pub fn dupeMin(buf: []u8, data: []const u8) []u8 { | |
| 489 | const n = @min(data.len, buf.len); | |
| 490 | @memcpy(buf[0..n], data[0..n]); | |
| 491 | return buf[0..n]; | |
| 492 | } | |
| 493 | ||
| 494 | pub const DhKeyPair = struct { | |
| 495 | x25519_kp: X25519.KeyPair = undefined, | |
| 496 | secp256r1_kp: EcdsaP256Sha256.KeyPair = undefined, | |
| 497 | secp384r1_kp: EcdsaP384Sha384.KeyPair = undefined, | |
| 498 | ml_kem768: MLKem768.KeyPair = undefined, | |
| 499 | ||
| 500 | secp256r1_pk_buf: [EcdsaP256Sha256.PublicKey.uncompressed_sec1_encoded_length]u8 = undefined, //65 bytes | |
| 501 | secp384r1_pk_buf: [EcdsaP384Sha384.PublicKey.uncompressed_sec1_encoded_length]u8 = undefined, //97 | |
| 502 | ml_kem768_pk_buf: [MLKem768.PublicKey.encoded_length + X25519.public_length]u8 = undefined, // 1216 | |
| 503 | shared_key_buf: [64]u8 = undefined, | |
| 504 | ||
| 505 | pub const seed_len = 32 + 32 + 48 + 64 + 64; | |
| 506 | ||
| 507 | pub fn init(seed: [seed_len]u8, named_groups: []const proto.NamedGroup) !DhKeyPair { | |
| 508 | var kp: DhKeyPair = .{}; | |
| 509 | for (named_groups) |ng| | |
| 510 | switch (ng) { | |
| 511 | .x25519 => kp.x25519_kp = try X25519.KeyPair.generateDeterministic(seed[0..][0..X25519.seed_length].*), | |
| 512 | .secp256r1 => kp.secp256r1_kp = try EcdsaP256Sha256.KeyPair.generateDeterministic(seed[32..][0..EcdsaP256Sha256.KeyPair.seed_length].*), | |
| 513 | .secp384r1 => kp.secp384r1_kp = try EcdsaP384Sha384.KeyPair.generateDeterministic(seed[32 + 32 ..][0..EcdsaP384Sha384.KeyPair.seed_length].*), | |
| 514 | .x25519_ml_kem768 => kp.ml_kem768 = try MLKem768.KeyPair.generateDeterministic(seed[32 + 32 + 48 + 64 ..][0..MLKem768.seed_length].*), | |
| 515 | else => return error.TlsIllegalParameter, | |
| 516 | }; | |
| 517 | return kp; | |
| 518 | } | |
| 519 | ||
| 520 | // x25519: 32, secp256r1: 32, secp384r1: 48, x25519_ml_kem768: 64 | |
| 521 | pub fn sharedKey(self: *DhKeyPair, named_group: proto.NamedGroup, server_pub_key: []const u8) ![]const u8 { | |
| 522 | return switch (named_group) { | |
| 523 | .x25519 => { | |
| 524 | if (server_pub_key.len != X25519.public_length) | |
| 525 | return error.TlsIllegalParameter; | |
| 526 | self.shared_key_buf[0..32].* = try X25519.scalarmult( | |
| 527 | self.x25519_kp.secret_key, | |
| 528 | server_pub_key[0..X25519.public_length].*, | |
| 529 | ); | |
| 530 | return self.shared_key_buf[0..32]; | |
| 531 | }, | |
| 532 | .secp256r1 => { | |
| 533 | const pk = try EcdsaP256Sha256.PublicKey.fromSec1(server_pub_key); | |
| 534 | const mul = try pk.p.mulPublic(self.secp256r1_kp.secret_key.bytes, .big); | |
| 535 | self.shared_key_buf[0..32].* = mul.affineCoordinates().x.toBytes(.big); | |
| 536 | return self.shared_key_buf[0..32]; | |
| 537 | }, | |
| 538 | .secp384r1 => { | |
| 539 | const pk = try EcdsaP384Sha384.PublicKey.fromSec1(server_pub_key); | |
| 540 | const mul = try pk.p.mulPublic(self.secp384r1_kp.secret_key.bytes, .big); | |
| 541 | self.shared_key_buf[0..48].* = mul.affineCoordinates().x.toBytes(.big); | |
| 542 | return self.shared_key_buf[0..48]; | |
| 543 | }, | |
| 544 | .x25519_ml_kem768 => { | |
| 545 | const hksl = crypto.kem.ml_kem.MLKem768.ciphertext_length; | |
| 546 | const xksl = hksl + crypto.dh.X25519.public_length; | |
| 547 | if (server_pub_key.len != xksl) return error.TlsIllegalParameter; | |
| 548 | ||
| 549 | const hsk = self.ml_kem768.secret_key.decaps(server_pub_key[0..hksl]) catch | |
| 550 | return error.TlsDecryptFailure; | |
| 551 | const xsk = crypto.dh.X25519.scalarmult(self.x25519_kp.secret_key, server_pub_key[hksl..xksl].*) catch | |
| 552 | return error.TlsDecryptFailure; | |
| 553 | self.shared_key_buf = (hsk ++ xsk); | |
| 554 | return &self.shared_key_buf; | |
| 555 | }, | |
| 556 | else => return error.TlsIllegalParameter, | |
| 557 | }; | |
| 558 | } | |
| 559 | ||
| 560 | // Returns 32, 65, 97 or 1216 bytes ml_kem | |
| 561 | pub fn publicKey(self: *DhKeyPair, named_group: proto.NamedGroup) ![]const u8 { | |
| 562 | return switch (named_group) { | |
| 563 | .x25519 => &self.x25519_kp.public_key, | |
| 564 | .secp256r1 => { | |
| 565 | self.secp256r1_pk_buf = self.secp256r1_kp.public_key.toUncompressedSec1(); | |
| 566 | return &self.secp256r1_pk_buf; | |
| 567 | }, | |
| 568 | .secp384r1 => { | |
| 569 | self.secp384r1_pk_buf = self.secp384r1_kp.public_key.toUncompressedSec1(); | |
| 570 | return &self.secp384r1_pk_buf; | |
| 571 | }, | |
| 572 | .x25519_ml_kem768 => { | |
| 573 | self.ml_kem768_pk_buf = self.ml_kem768.public_key.toBytes() ++ self.x25519_kp.public_key; | |
| 574 | return &self.ml_kem768_pk_buf; | |
| 575 | }, | |
| 576 | else => return error.TlsIllegalParameter, | |
| 577 | }; | |
| 578 | } | |
| 579 | }; | |
| 580 | ||
| 581 | const testing = std.testing; | |
| 582 | const testu = @import("testu.zig"); | |
| 583 | ||
| 584 | test "DhKeyPair.x25519" { | |
| 585 | var seed: [DhKeyPair.seed_len]u8 = undefined; | |
| 586 | testu.fill(&seed); | |
| 587 | const server_pub_key = &testu.hexToBytes("3303486548531f08d91e675caf666c2dc924ac16f47a861a7f4d05919d143637"); | |
| 588 | const expected = &testu.hexToBytes( | |
| 589 | \\ F1 67 FB 4A 49 B2 91 77 08 29 45 A1 F7 08 5A 21 | |
| 590 | \\ AF FE 9E 78 C2 03 9B 81 92 40 72 73 74 7A 46 1E | |
| 591 | ); | |
| 592 | var kp = try DhKeyPair.init(seed, &.{.x25519}); | |
| 593 | try testing.expectEqualSlices(u8, expected, try kp.sharedKey(.x25519, server_pub_key)); | |
| 594 | } | |