| ... | ... | @@ -8,12 +8,14 @@ const assert = std.debug.assert; |
| 8 | 8 | const Certificate = std.crypto.Certificate; |
| 9 | 9 | |
| 10 | 10 | const max_ciphertext_len = tls.max_ciphertext_len; |
| 11 | const hmacExpandLabel = tls.hmacExpandLabel; |
| 11 | 12 | const hkdfExpandLabel = tls.hkdfExpandLabel; |
| 12 | 13 | const int2 = tls.int2; |
| 13 | 14 | const int3 = tls.int3; |
| 14 | 15 | const array = tls.array; |
| 15 | 16 | const enum_array = tls.enum_array; |
| 16 | 17 | |
| 18 | tls_version: tls.ProtocolVersion, |
| 17 | 19 | read_seq: u64, |
| 18 | 20 | write_seq: u64, |
| 19 | 21 | /// The starting index of cleartext bytes inside `partially_read_buffer`. |
| ... | ... | @@ -136,7 +138,7 @@ pub fn InitError(comptime Stream: type) type { |
| 136 | 138 | }; |
| 137 | 139 | } |
| 138 | 140 | |
| 139 | | /// Initiates a TLS handshake and establishes a TLSv1.3 session with `stream`, which |
| 141 | /// Initiates a TLS handshake and establishes a TLSv1.2 or TLSv1.3 session with `stream`, which |
| 140 | 142 | /// must conform to `StreamInterface`. |
| 141 | 143 | /// |
| 142 | 144 | /// `host` is only borrowed during this function call. |
| ... | ... | @@ -145,26 +147,20 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 145 | 147 | |
| 146 | 148 | var random_buffer: [128]u8 = undefined; |
| 147 | 149 | crypto.random.bytes(&random_buffer); |
| 148 | | const hello_rand = random_buffer[0..32].*; |
| 150 | const client_hello_rand = random_buffer[0..32].*; |
| 151 | var server_hello_rand: [32]u8 = undefined; |
| 149 | 152 | const legacy_session_id = random_buffer[32..64].*; |
| 150 | | const x25519_kp_seed = random_buffer[64..96].*; |
| 151 | | const secp256r1_kp_seed = random_buffer[96..128].*; |
| 152 | 153 | |
| 153 | | const x25519_kp = crypto.dh.X25519.KeyPair.create(x25519_kp_seed) catch |err| switch (err) { |
| 154 | | // Only possible to happen if the private key is all zeroes. |
| 154 | var key_share = KeyShare.init(random_buffer[64..128].*) catch |err| switch (err) { |
| 155 | // Only possible to happen if the seed is all zeroes. |
| 155 | 156 | error.IdentityElement => return error.InsufficientEntropy, |
| 156 | 157 | }; |
| 157 | | const secp256r1_kp = crypto.sign.ecdsa.EcdsaP256Sha256.KeyPair.create(secp256r1_kp_seed) catch |err| switch (err) { |
| 158 | | // Only possible to happen if the private key is all zeroes. |
| 159 | | error.IdentityElement => return error.InsufficientEntropy, |
| 160 | | }; |
| 161 | | const ml_kem768_kp = crypto.kem.ml_kem.MLKem768.KeyPair.create(null) catch {}; |
| 162 | 158 | |
| 163 | 159 | const extensions_payload = |
| 164 | | tls.extension(.supported_versions, [_]u8{ |
| 165 | | 0x02, // byte length of supported versions |
| 166 | | 0x03, 0x04, // TLS 1.3 |
| 167 | | }) ++ tls.extension(.signature_algorithms, enum_array(tls.SignatureScheme, &.{ |
| 160 | tls.extension(.supported_versions, [_]u8{2 + 2} ++ // byte length of supported versions |
| 161 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_3)) ++ |
| 162 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2))) ++ |
| 163 | tls.extension(.signature_algorithms, enum_array(tls.SignatureScheme, &.{ |
| 168 | 164 | .ecdsa_secp256r1_sha256, |
| 169 | 165 | .ecdsa_secp384r1_sha384, |
| 170 | 166 | .rsa_pss_rsae_sha256, |
| ... | ... | @@ -178,11 +174,11 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 178 | 174 | })) ++ tls.extension( |
| 179 | 175 | .key_share, |
| 180 | 176 | array(1, int2(@intFromEnum(tls.NamedGroup.x25519)) ++ |
| 181 | | array(1, x25519_kp.public_key) ++ |
| 177 | array(1, key_share.x25519_kp.public_key) ++ |
| 182 | 178 | int2(@intFromEnum(tls.NamedGroup.secp256r1)) ++ |
| 183 | | array(1, secp256r1_kp.public_key.toUncompressedSec1()) ++ |
| 179 | array(1, key_share.secp256r1_kp.public_key.toUncompressedSec1()) ++ |
| 184 | 180 | int2(@intFromEnum(tls.NamedGroup.x25519_ml_kem768)) ++ |
| 185 | | array(1, x25519_kp.public_key ++ ml_kem768_kp.public_key.toBytes())), |
| 181 | array(1, key_share.x25519_kp.public_key ++ key_share.ml_kem768_kp.public_key.toBytes())), |
| 186 | 182 | ) ++ |
| 187 | 183 | int2(@intFromEnum(tls.ExtensionType.server_name)) ++ |
| 188 | 184 | int2(host_len + 5) ++ // byte length of this extension payload |
| ... | ... | @@ -198,7 +194,7 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 198 | 194 | |
| 199 | 195 | const client_hello = |
| 200 | 196 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 201 | | hello_rand ++ |
| 197 | client_hello_rand ++ |
| 202 | 198 | [1]u8{32} ++ legacy_session_id ++ |
| 203 | 199 | cipher_suites ++ |
| 204 | 200 | int2(legacy_compression_methods) ++ |
| ... | ... | @@ -209,16 +205,16 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 209 | 205 | int3(@intCast(client_hello.len + host_len)) ++ |
| 210 | 206 | client_hello; |
| 211 | 207 | |
| 212 | | const plaintext_header = [_]u8{ |
| 213 | | @intFromEnum(tls.ContentType.handshake), |
| 214 | | 0x03, 0x01, // legacy_record_version |
| 215 | | } ++ int2(@intCast(out_handshake.len + host_len)) ++ out_handshake; |
| 208 | const cleartext_header = [_]u8{@intFromEnum(tls.ContentType.handshake)} ++ |
| 209 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_0)) ++ // legacy_record_version |
| 210 | int2(@intCast(out_handshake.len + host_len)) ++ |
| 211 | out_handshake; |
| 216 | 212 | |
| 217 | 213 | { |
| 218 | 214 | var iovecs = [_]std.posix.iovec_const{ |
| 219 | 215 | .{ |
| 220 | | .base = &plaintext_header, |
| 221 | | .len = plaintext_header.len, |
| 216 | .base = &cleartext_header, |
| 217 | .len = cleartext_header.len, |
| 222 | 218 | }, |
| 223 | 219 | .{ |
| 224 | 220 | .base = host.ptr, |
| ... | ... | @@ -228,8 +224,10 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 228 | 224 | try stream.writevAll(&iovecs); |
| 229 | 225 | } |
| 230 | 226 | |
| 231 | | const client_hello_bytes1 = plaintext_header[5..]; |
| 227 | const client_hello_bytes1 = cleartext_header[tls.record_header_len..]; |
| 232 | 228 | |
| 229 | var tls_version: tls.ProtocolVersion = undefined; |
| 230 | var cipher_suite_tag: tls.CipherSuite = undefined; |
| 233 | 231 | var handshake_cipher: tls.HandshakeCipher = undefined; |
| 234 | 232 | var handshake_buffer: [8000]u8 = undefined; |
| 235 | 233 | var d: tls.Decoder = .{ .buf = &handshake_buffer }; |
| ... | ... | @@ -259,10 +257,10 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 259 | 257 | if (handshake_type != .server_hello) return error.TlsUnexpectedMessage; |
| 260 | 258 | const length = ptd.decode(u24); |
| 261 | 259 | var hsd = try ptd.sub(length); |
| 262 | | try hsd.ensure(2 + 32 + 1 + 32 + 2 + 1 + 2); |
| 260 | try hsd.ensure(2 + 32 + 1 + 32 + 2 + 1); |
| 263 | 261 | const legacy_version = hsd.decode(u16); |
| 264 | | const random = hsd.array(32); |
| 265 | | if (mem.eql(u8, random, &tls.hello_retry_request_sequence)) { |
| 262 | @memcpy(&server_hello_rand, hsd.array(32)); |
| 263 | if (mem.eql(u8, &server_hello_rand, &tls.hello_retry_request_sequence)) { |
| 266 | 264 | // This is a HelloRetryRequest message. This client implementation |
| 267 | 265 | // does not expect to get one. |
| 268 | 266 | return error.TlsUnexpectedMessage; |
| ... | ... | @@ -270,83 +268,44 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 270 | 268 | const legacy_session_id_echo_len = hsd.decode(u8); |
| 271 | 269 | if (legacy_session_id_echo_len != 32) return error.TlsIllegalParameter; |
| 272 | 270 | const legacy_session_id_echo = hsd.array(32); |
| 273 | | if (!mem.eql(u8, legacy_session_id_echo, &legacy_session_id)) |
| 274 | | return error.TlsIllegalParameter; |
| 275 | | const cipher_suite_tag = hsd.decode(tls.CipherSuite); |
| 271 | cipher_suite_tag = hsd.decode(tls.CipherSuite); |
| 276 | 272 | hsd.skip(1); // legacy_compression_method |
| 277 | | const extensions_size = hsd.decode(u16); |
| 278 | | var all_extd = try hsd.sub(extensions_size); |
| 279 | | var supported_version: u16 = 0; |
| 280 | | var shared_key: []const u8 = undefined; |
| 281 | | var have_shared_key = false; |
| 282 | | while (!all_extd.eof()) { |
| 283 | | try all_extd.ensure(2 + 2); |
| 284 | | const et = all_extd.decode(tls.ExtensionType); |
| 285 | | const ext_size = all_extd.decode(u16); |
| 286 | | var extd = try all_extd.sub(ext_size); |
| 287 | | switch (et) { |
| 288 | | .supported_versions => { |
| 289 | | if (supported_version != 0) return error.TlsIllegalParameter; |
| 290 | | try extd.ensure(2); |
| 291 | | supported_version = extd.decode(u16); |
| 292 | | }, |
| 293 | | .key_share => { |
| 294 | | if (have_shared_key) return error.TlsIllegalParameter; |
| 295 | | have_shared_key = true; |
| 296 | | try extd.ensure(4); |
| 297 | | const named_group = extd.decode(tls.NamedGroup); |
| 298 | | const key_size = extd.decode(u16); |
| 299 | | try extd.ensure(key_size); |
| 300 | | switch (named_group) { |
| 301 | | .x25519_ml_kem768 => { |
| 302 | | const xksl = crypto.dh.X25519.public_length; |
| 303 | | const hksl = xksl + crypto.kem.ml_kem.MLKem768.ciphertext_length; |
| 304 | | if (key_size != hksl) |
| 305 | | return error.TlsIllegalParameter; |
| 306 | | const server_ks = extd.array(hksl); |
| 307 | | |
| 308 | | shared_key = &((crypto.dh.X25519.scalarmult( |
| 309 | | x25519_kp.secret_key, |
| 310 | | server_ks[0..xksl].*, |
| 311 | | ) catch return error.TlsDecryptFailure) ++ (ml_kem768_kp.secret_key.decaps( |
| 312 | | server_ks[xksl..hksl], |
| 313 | | ) catch return error.TlsDecryptFailure)); |
| 314 | | }, |
| 315 | | .x25519 => { |
| 316 | | const ksl = crypto.dh.X25519.public_length; |
| 317 | | if (key_size != ksl) return error.TlsIllegalParameter; |
| 318 | | const server_pub_key = extd.array(ksl); |
| 319 | | |
| 320 | | shared_key = &(crypto.dh.X25519.scalarmult( |
| 321 | | x25519_kp.secret_key, |
| 322 | | server_pub_key.*, |
| 323 | | ) catch return error.TlsDecryptFailure); |
| 324 | | }, |
| 325 | | .secp256r1 => { |
| 326 | | const server_pub_key = extd.slice(key_size); |
| 327 | | |
| 328 | | const PublicKey = crypto.sign.ecdsa.EcdsaP256Sha256.PublicKey; |
| 329 | | const pk = PublicKey.fromSec1(server_pub_key) catch { |
| 330 | | return error.TlsDecryptFailure; |
| 331 | | }; |
| 332 | | const mul = pk.p.mulPublic(secp256r1_kp.secret_key.bytes, .big) catch { |
| 333 | | return error.TlsDecryptFailure; |
| 334 | | }; |
| 335 | | shared_key = &mul.affineCoordinates().x.toBytes(.big); |
| 336 | | }, |
| 337 | | else => { |
| 338 | | return error.TlsIllegalParameter; |
| 339 | | }, |
| 340 | | } |
| 341 | | }, |
| 342 | | else => {}, |
| 273 | var supported_version: ?u16 = null; |
| 274 | if (!hsd.eof()) { |
| 275 | try hsd.ensure(2); |
| 276 | const extensions_size = hsd.decode(u16); |
| 277 | var all_extd = try hsd.sub(extensions_size); |
| 278 | while (!all_extd.eof()) { |
| 279 | try all_extd.ensure(2 + 2); |
| 280 | const et = all_extd.decode(tls.ExtensionType); |
| 281 | const ext_size = all_extd.decode(u16); |
| 282 | var extd = try all_extd.sub(ext_size); |
| 283 | switch (et) { |
| 284 | .supported_versions => { |
| 285 | if (supported_version) |_| return error.TlsIllegalParameter; |
| 286 | try extd.ensure(2); |
| 287 | supported_version = extd.decode(u16); |
| 288 | }, |
| 289 | .key_share => { |
| 290 | if (key_share.getSharedSecret()) |_| return error.TlsIllegalParameter; |
| 291 | try extd.ensure(4); |
| 292 | const named_group = extd.decode(tls.NamedGroup); |
| 293 | const key_size = extd.decode(u16); |
| 294 | try extd.ensure(key_size); |
| 295 | try key_share.exchange(named_group, extd.slice(key_size)); |
| 296 | }, |
| 297 | else => {}, |
| 298 | } |
| 343 | 299 | } |
| 344 | 300 | } |
| 345 | | if (!have_shared_key) return error.TlsIllegalParameter; |
| 346 | 301 | |
| 347 | | const tls_version = if (supported_version == 0) legacy_version else supported_version; |
| 348 | | if (tls_version != @intFromEnum(tls.ProtocolVersion.tls_1_3)) |
| 349 | | return error.TlsIllegalParameter; |
| 302 | tls_version = @enumFromInt(supported_version orelse legacy_version); |
| 303 | switch (tls_version) { |
| 304 | .tls_1_3 => if (!mem.eql(u8, legacy_session_id_echo, &legacy_session_id)) return error.TlsIllegalParameter, |
| 305 | .tls_1_2 => if (mem.eql(u8, server_hello_rand[24..31], "DOWNGRD") and |
| 306 | server_hello_rand[31] >> 1 == 0x00) return error.TlsIllegalParameter, |
| 307 | else => return error.TlsIllegalParameter, |
| 308 | } |
| 350 | 309 | |
| 351 | 310 | switch (cipher_suite_tag) { |
| 352 | 311 | inline .AES_128_GCM_SHA256, |
| ... | ... | @@ -354,43 +313,63 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 354 | 313 | .CHACHA20_POLY1305_SHA256, |
| 355 | 314 | .AEGIS_256_SHA512, |
| 356 | 315 | .AEGIS_128L_SHA256, |
| 316 | |
| 317 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 318 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 319 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 357 | 320 | => |tag| { |
| 358 | | const P = std.meta.TagPayloadByName(tls.HandshakeCipher, @tagName(tag)); |
| 359 | | handshake_cipher = @unionInit(tls.HandshakeCipher, @tagName(tag), .{ |
| 360 | | .handshake_secret = undefined, |
| 361 | | .master_secret = undefined, |
| 362 | | .client_handshake_key = undefined, |
| 363 | | .server_handshake_key = undefined, |
| 364 | | .client_finished_key = undefined, |
| 365 | | .server_finished_key = undefined, |
| 366 | | .client_handshake_iv = undefined, |
| 367 | | .server_handshake_iv = undefined, |
| 368 | | .transcript_hash = P.Hash.init(.{}), |
| 321 | handshake_cipher = @unionInit(tls.HandshakeCipher, @tagName(tag.with()), .{ |
| 322 | .transcript_hash = .init(.{}), |
| 323 | .version = undefined, |
| 369 | 324 | }); |
| 370 | | const p = &@field(handshake_cipher, @tagName(tag)); |
| 325 | const p = &@field(handshake_cipher, @tagName(tag.with())); |
| 371 | 326 | p.transcript_hash.update(client_hello_bytes1); // Client Hello part 1 |
| 372 | 327 | p.transcript_hash.update(host); // Client Hello part 2 |
| 373 | 328 | p.transcript_hash.update(server_hello_fragment); |
| 374 | | const hello_hash = p.transcript_hash.peek(); |
| 375 | | const zeroes = [1]u8{0} ** P.Hash.digest_length; |
| 376 | | const early_secret = P.Hkdf.extract(&[1]u8{0}, &zeroes); |
| 377 | | const empty_hash = tls.emptyHash(P.Hash); |
| 378 | | const hs_derived_secret = hkdfExpandLabel(P.Hkdf, early_secret, "derived", &empty_hash, P.Hash.digest_length); |
| 379 | | p.handshake_secret = P.Hkdf.extract(&hs_derived_secret, shared_key); |
| 380 | | const ap_derived_secret = hkdfExpandLabel(P.Hkdf, p.handshake_secret, "derived", &empty_hash, P.Hash.digest_length); |
| 381 | | p.master_secret = P.Hkdf.extract(&ap_derived_secret, &zeroes); |
| 382 | | const client_secret = hkdfExpandLabel(P.Hkdf, p.handshake_secret, "c hs traffic", &hello_hash, P.Hash.digest_length); |
| 383 | | const server_secret = hkdfExpandLabel(P.Hkdf, p.handshake_secret, "s hs traffic", &hello_hash, P.Hash.digest_length); |
| 384 | | p.client_finished_key = hkdfExpandLabel(P.Hkdf, client_secret, "finished", "", P.Hmac.key_length); |
| 385 | | p.server_finished_key = hkdfExpandLabel(P.Hkdf, server_secret, "finished", "", P.Hmac.key_length); |
| 386 | | p.client_handshake_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| 387 | | p.server_handshake_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| 388 | | p.client_handshake_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| 389 | | p.server_handshake_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| 390 | 329 | }, |
| 391 | | else => { |
| 392 | | return error.TlsIllegalParameter; |
| 330 | |
| 331 | else => return error.TlsIllegalParameter, |
| 332 | } |
| 333 | switch (tls_version) { |
| 334 | .tls_1_3 => switch (cipher_suite_tag) { |
| 335 | inline .AES_128_GCM_SHA256, |
| 336 | .AES_256_GCM_SHA384, |
| 337 | .CHACHA20_POLY1305_SHA256, |
| 338 | .AEGIS_256_SHA512, |
| 339 | .AEGIS_128L_SHA256, |
| 340 | => |tag| { |
| 341 | const sk = key_share.getSharedSecret() orelse return error.TlsIllegalParameter; |
| 342 | const p = &@field(handshake_cipher, @tagName(tag.with())); |
| 343 | const P = @TypeOf(p.*).A; |
| 344 | const hello_hash = p.transcript_hash.peek(); |
| 345 | const zeroes = [1]u8{0} ** P.Hash.digest_length; |
| 346 | const early_secret = P.Hkdf.extract(&[1]u8{0}, &zeroes); |
| 347 | const empty_hash = tls.emptyHash(P.Hash); |
| 348 | p.version = .{ .tls_1_3 = undefined }; |
| 349 | const pv = &p.version.tls_1_3; |
| 350 | const hs_derived_secret = hkdfExpandLabel(P.Hkdf, early_secret, "derived", &empty_hash, P.Hash.digest_length); |
| 351 | pv.handshake_secret = P.Hkdf.extract(&hs_derived_secret, sk); |
| 352 | const ap_derived_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "derived", &empty_hash, P.Hash.digest_length); |
| 353 | pv.master_secret = P.Hkdf.extract(&ap_derived_secret, &zeroes); |
| 354 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "c hs traffic", &hello_hash, P.Hash.digest_length); |
| 355 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "s hs traffic", &hello_hash, P.Hash.digest_length); |
| 356 | pv.client_finished_key = hkdfExpandLabel(P.Hkdf, client_secret, "finished", "", P.Hmac.key_length); |
| 357 | pv.server_finished_key = hkdfExpandLabel(P.Hkdf, server_secret, "finished", "", P.Hmac.key_length); |
| 358 | pv.client_handshake_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| 359 | pv.server_handshake_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| 360 | pv.client_handshake_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| 361 | pv.server_handshake_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| 362 | }, |
| 363 | else => return error.TlsIllegalParameter, |
| 364 | }, |
| 365 | .tls_1_2 => switch (cipher_suite_tag) { |
| 366 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 367 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 368 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 369 | => {}, |
| 370 | else => return error.TlsIllegalParameter, |
| 393 | 371 | }, |
| 372 | else => return error.TlsIllegalParameter, |
| 394 | 373 | } |
| 395 | 374 | }, |
| 396 | 375 | else => return error.TlsUnexpectedMessage, |
| ... | ... | @@ -404,58 +383,74 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 404 | 383 | // the previous certificate in memory so that it can be verified by the |
| 405 | 384 | // next one. |
| 406 | 385 | var cert_index: usize = 0; |
| 386 | var write_seq: u64 = 0; |
| 407 | 387 | var read_seq: u64 = 0; |
| 408 | 388 | var prev_cert: Certificate.Parsed = undefined; |
| 409 | | // Set to true once a trust chain has been established from the first |
| 410 | | // certificate to a root CA. |
| 389 | const CipherState = enum { |
| 390 | /// No cipher is in use |
| 391 | cleartext, |
| 392 | /// Handshake cipher is in use |
| 393 | handshake, |
| 394 | /// Application cipher is in use |
| 395 | application, |
| 396 | }; |
| 397 | var pending_cipher_state: CipherState = switch (tls_version) { |
| 398 | .tls_1_3 => .handshake, |
| 399 | .tls_1_2 => .cleartext, |
| 400 | else => unreachable, |
| 401 | }; |
| 402 | var cipher_state: CipherState = .cleartext; |
| 411 | 403 | const HandshakeState = enum { |
| 412 | 404 | /// In this state we expect only an encrypted_extensions message. |
| 413 | 405 | encrypted_extensions, |
| 414 | | /// In this state we expect certificate messages. |
| 406 | /// In this state we expect certificate handshake messages. |
| 415 | 407 | certificate, |
| 416 | 408 | /// In this state we expect certificate or certificate_verify messages. |
| 417 | 409 | /// certificate messages are ignored since the trust chain is already |
| 418 | 410 | /// established. |
| 419 | 411 | trust_chain_established, |
| 420 | | /// In this state, we expect only the finished message. |
| 412 | /// In this state, we expect only the server_hello_done handshake message. |
| 413 | server_hello_done, |
| 414 | /// In this state, we expect only the finished handshake message. |
| 421 | 415 | finished, |
| 422 | 416 | }; |
| 423 | | var handshake_state: HandshakeState = .encrypted_extensions; |
| 417 | var handshake_state: HandshakeState = switch (tls_version) { |
| 418 | .tls_1_3 => .encrypted_extensions, |
| 419 | .tls_1_2 => .certificate, |
| 420 | else => unreachable, |
| 421 | }; |
| 424 | 422 | var cleartext_bufs: [2][8000]u8 = undefined; |
| 425 | | var main_cert_pub_key_algo: Certificate.AlgorithmCategory = undefined; |
| 426 | | var main_cert_pub_key_buf: [600]u8 = undefined; |
| 427 | | var main_cert_pub_key_len: u16 = undefined; |
| 423 | var main_cert_pub_key: CertificatePublicKey = undefined; |
| 428 | 424 | const now_sec = std.time.timestamp(); |
| 429 | 425 | |
| 430 | 426 | while (true) { |
| 431 | 427 | try d.readAtLeastOurAmt(stream, tls.record_header_len); |
| 432 | | const record_header = d.buf[d.idx..][0..5]; |
| 433 | | const ct = d.decode(tls.ContentType); |
| 428 | const record_header = d.buf[d.idx..][0..tls.record_header_len]; |
| 429 | const record_ct = d.decode(tls.ContentType); |
| 434 | 430 | d.skip(2); // legacy_version |
| 435 | 431 | const record_len = d.decode(u16); |
| 436 | 432 | try d.readAtLeast(stream, record_len); |
| 437 | 433 | var record_decoder = try d.sub(record_len); |
| 438 | | switch (ct) { |
| 439 | | .change_cipher_spec => { |
| 440 | | try record_decoder.ensure(1); |
| 441 | | if (record_decoder.decode(u8) != 0x01) return error.TlsIllegalParameter; |
| 442 | | }, |
| 443 | | .application_data => { |
| 434 | var ctd, const ct = content: switch (cipher_state) { |
| 435 | .cleartext => .{ record_decoder, record_ct }, |
| 436 | .handshake => { |
| 437 | std.debug.assert(tls_version == .tls_1_3); |
| 438 | if (record_ct != .application_data) return error.TlsUnexpectedMessage; |
| 439 | try record_decoder.ensure(record_len); |
| 444 | 440 | const cleartext_buf = &cleartext_bufs[cert_index % 2]; |
| 445 | | |
| 446 | | const cleartext = switch (handshake_cipher) { |
| 447 | | inline else => |*p| c: { |
| 448 | | const P = @TypeOf(p.*); |
| 449 | | const ciphertext_len = record_len - P.AEAD.tag_length; |
| 450 | | try record_decoder.ensure(ciphertext_len + P.AEAD.tag_length); |
| 451 | | const ciphertext = record_decoder.slice(ciphertext_len); |
| 441 | const cleartext = cleartext: switch (handshake_cipher) { |
| 442 | inline else => |*p| { |
| 443 | const pv = &p.version.tls_1_3; |
| 444 | const P = @TypeOf(p.*).A; |
| 445 | if (record_len < P.AEAD.tag_length) return error.TlsRecordOverflow; |
| 446 | const ciphertext = record_decoder.slice(record_len - P.AEAD.tag_length); |
| 452 | 447 | if (ciphertext.len > cleartext_buf.len) return error.TlsRecordOverflow; |
| 453 | 448 | const cleartext = cleartext_buf[0..ciphertext.len]; |
| 454 | 449 | const auth_tag = record_decoder.array(P.AEAD.tag_length).*; |
| 455 | 450 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 456 | 451 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 457 | 452 | nonce: { |
| 458 | | var nonce = p.server_handshake_iv; |
| 453 | var nonce = pv.server_handshake_iv; |
| 459 | 454 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 460 | 455 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ read_seq, .big); |
| 461 | 456 | break :nonce nonce; |
| ... | ... | @@ -463,200 +458,320 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 463 | 458 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 464 | 459 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 465 | 460 | const operand: V = pad ++ @as([8]u8, @bitCast(big(read_seq))); |
| 466 | | break :nonce @as(V, p.server_handshake_iv) ^ operand; |
| 461 | break :nonce @as(V, pv.server_handshake_iv) ^ operand; |
| 467 | 462 | }; |
| 468 | | read_seq += 1; |
| 469 | | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, record_header, nonce, p.server_handshake_key) catch |
| 463 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, record_header, nonce, pv.server_handshake_key) catch |
| 470 | 464 | return error.TlsBadRecordMac; |
| 471 | | break :c @constCast(mem.trimRight(u8, cleartext, "\x00")); |
| 465 | break :cleartext mem.trimRight(u8, cleartext, "\x00"); |
| 472 | 466 | }, |
| 473 | 467 | }; |
| 468 | read_seq += 1; |
| 469 | const ct: tls.ContentType = @enumFromInt(cleartext[cleartext.len - 1]); |
| 470 | if (ct != .handshake) return error.TlsUnexpectedMessage; |
| 471 | break :content .{ tls.Decoder.fromTheirSlice(@constCast(cleartext[0 .. cleartext.len - 1])), ct }; |
| 472 | }, |
| 473 | .application => { |
| 474 | std.debug.assert(tls_version == .tls_1_2); |
| 475 | if (record_ct != .handshake) return error.TlsUnexpectedMessage; |
| 476 | try record_decoder.ensure(record_len); |
| 477 | const cleartext_buf = &cleartext_bufs[cert_index % 2]; |
| 478 | const cleartext = cleartext: switch (handshake_cipher) { |
| 479 | inline else => |*p| { |
| 480 | const pv = &p.version.tls_1_2; |
| 481 | const P = @TypeOf(p.*).A; |
| 482 | if (record_len < P.record_iv_length + P.mac_length) return error.TlsRecordOverflow; |
| 483 | const message_len: u16 = record_len - P.record_iv_length - P.mac_length; |
| 484 | if (message_len > cleartext_buf.len) return error.TlsRecordOverflow; |
| 485 | const cleartext = cleartext_buf[0..message_len]; |
| 486 | const ad = std.mem.toBytes(big(read_seq)) ++ |
| 487 | record_header[0 .. 1 + 2] ++ |
| 488 | std.mem.toBytes(big(message_len)); |
| 489 | const record_iv = record_decoder.array(P.record_iv_length).*; |
| 490 | const masked_read_seq = read_seq & |
| 491 | comptime std.math.shl(u64, std.math.maxInt(u64), 8 * P.record_iv_length); |
| 492 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| 493 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 494 | nonce: { |
| 495 | var nonce = pv.app_cipher.server_write_IV ++ record_iv; |
| 496 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 497 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ masked_read_seq, .big); |
| 498 | break :nonce nonce; |
| 499 | } else nonce: { |
| 500 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 501 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 502 | const operand: V = pad ++ @as([8]u8, @bitCast(big(masked_read_seq))); |
| 503 | break :nonce @as(V, pv.app_cipher.server_write_IV ++ record_iv) ^ operand; |
| 504 | }; |
| 505 | const ciphertext = record_decoder.slice(message_len); |
| 506 | const auth_tag = record_decoder.array(P.mac_length); |
| 507 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag.*, ad, nonce, pv.app_cipher.server_write_key) catch return error.TlsBadRecordMac; |
| 508 | break :cleartext cleartext; |
| 509 | }, |
| 510 | }; |
| 511 | read_seq += 1; |
| 512 | break :content .{ tls.Decoder.fromTheirSlice(cleartext), record_ct }; |
| 513 | }, |
| 514 | }; |
| 515 | switch (ct) { |
| 516 | .alert => { |
| 517 | try ctd.ensure(2); |
| 518 | const level = ctd.decode(tls.AlertLevel); |
| 519 | const desc = ctd.decode(tls.AlertDescription); |
| 520 | _ = level; |
| 474 | 521 | |
| 475 | | const inner_ct: tls.ContentType = @enumFromInt(cleartext[cleartext.len - 1]); |
| 476 | | if (inner_ct != .handshake) return error.TlsUnexpectedMessage; |
| 477 | | |
| 478 | | var ctd = tls.Decoder.fromTheirSlice(cleartext[0 .. cleartext.len - 1]); |
| 479 | | while (true) { |
| 480 | | try ctd.ensure(4); |
| 481 | | const handshake_type = ctd.decode(tls.HandshakeType); |
| 482 | | const handshake_len = ctd.decode(u24); |
| 483 | | var hsd = try ctd.sub(handshake_len); |
| 484 | | const wrapped_handshake = ctd.buf[ctd.idx - handshake_len - 4 .. ctd.idx]; |
| 485 | | const handshake = ctd.buf[ctd.idx - handshake_len .. ctd.idx]; |
| 486 | | switch (handshake_type) { |
| 487 | | .encrypted_extensions => { |
| 488 | | if (handshake_state != .encrypted_extensions) return error.TlsUnexpectedMessage; |
| 489 | | handshake_state = .certificate; |
| 490 | | switch (handshake_cipher) { |
| 491 | | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| 492 | | } |
| 493 | | try hsd.ensure(2); |
| 494 | | const total_ext_size = hsd.decode(u16); |
| 495 | | var all_extd = try hsd.sub(total_ext_size); |
| 496 | | while (!all_extd.eof()) { |
| 497 | | try all_extd.ensure(4); |
| 498 | | const et = all_extd.decode(tls.ExtensionType); |
| 499 | | const ext_size = all_extd.decode(u16); |
| 500 | | const extd = try all_extd.sub(ext_size); |
| 501 | | _ = extd; |
| 502 | | switch (et) { |
| 503 | | .server_name => {}, |
| 504 | | else => {}, |
| 505 | | } |
| 522 | // if this isn't a error alert, then it's a closure alert, which makes no sense in a handshake |
| 523 | try desc.toError(); |
| 524 | // TODO: handle server-side closures |
| 525 | return error.TlsUnexpectedMessage; |
| 526 | }, |
| 527 | .change_cipher_spec => { |
| 528 | try ctd.ensure(1); |
| 529 | if (ctd.decode(u8) != 0x01) return error.TlsIllegalParameter; |
| 530 | cipher_state = pending_cipher_state; |
| 531 | }, |
| 532 | .handshake => while (true) { |
| 533 | try ctd.ensure(4); |
| 534 | const handshake_type = ctd.decode(tls.HandshakeType); |
| 535 | const handshake_len = ctd.decode(u24); |
| 536 | var hsd = try ctd.sub(handshake_len); |
| 537 | const wrapped_handshake = ctd.buf[ctd.idx - handshake_len - 4 .. ctd.idx]; |
| 538 | switch (handshake_type) { |
| 539 | .encrypted_extensions => { |
| 540 | if (tls_version != .tls_1_3) return error.TlsUnexpectedMessage; |
| 541 | if (cipher_state != .handshake) return error.TlsUnexpectedMessage; |
| 542 | if (handshake_state != .encrypted_extensions) return error.TlsUnexpectedMessage; |
| 543 | handshake_state = .certificate; |
| 544 | switch (handshake_cipher) { |
| 545 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| 546 | } |
| 547 | try hsd.ensure(2); |
| 548 | const total_ext_size = hsd.decode(u16); |
| 549 | var all_extd = try hsd.sub(total_ext_size); |
| 550 | while (!all_extd.eof()) { |
| 551 | try all_extd.ensure(4); |
| 552 | const et = all_extd.decode(tls.ExtensionType); |
| 553 | const ext_size = all_extd.decode(u16); |
| 554 | const extd = try all_extd.sub(ext_size); |
| 555 | _ = extd; |
| 556 | switch (et) { |
| 557 | .server_name => {}, |
| 558 | else => {}, |
| 506 | 559 | } |
| 507 | | }, |
| 508 | | .certificate => cert: { |
| 509 | | switch (handshake_cipher) { |
| 510 | | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| 560 | } |
| 561 | }, |
| 562 | .certificate => cert: { |
| 563 | switch (handshake_cipher) { |
| 564 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| 565 | } |
| 566 | switch (handshake_state) { |
| 567 | .certificate => {}, |
| 568 | .trust_chain_established => break :cert, |
| 569 | else => return error.TlsUnexpectedMessage, |
| 570 | } |
| 571 | |
| 572 | switch (tls_version) { |
| 573 | .tls_1_3 => { |
| 574 | try hsd.ensure(1 + 3); |
| 575 | const cert_req_ctx_len = hsd.decode(u8); |
| 576 | if (cert_req_ctx_len != 0) return error.TlsIllegalParameter; |
| 577 | }, |
| 578 | .tls_1_2 => try hsd.ensure(3), |
| 579 | else => unreachable, |
| 580 | } |
| 581 | const certs_size = hsd.decode(u24); |
| 582 | var certs_decoder = try hsd.sub(certs_size); |
| 583 | while (!certs_decoder.eof()) { |
| 584 | try certs_decoder.ensure(3); |
| 585 | const cert_size = certs_decoder.decode(u24); |
| 586 | const certd = try certs_decoder.sub(cert_size); |
| 587 | |
| 588 | const subject_cert: Certificate = .{ |
| 589 | .buffer = certd.buf, |
| 590 | .index = @intCast(certd.idx), |
| 591 | }; |
| 592 | const subject = try subject_cert.parse(); |
| 593 | if (cert_index == 0) { |
| 594 | // Verify the host on the first certificate. |
| 595 | try subject.verifyHostName(host); |
| 596 | |
| 597 | // Keep track of the public key for the |
| 598 | // certificate_verify message later. |
| 599 | try main_cert_pub_key.init(subject.pub_key_algo, subject.pubKey()); |
| 600 | } else { |
| 601 | try prev_cert.verify(subject, now_sec); |
| 511 | 602 | } |
| 512 | | switch (handshake_state) { |
| 513 | | .certificate => {}, |
| 514 | | .trust_chain_established => break :cert, |
| 515 | | else => return error.TlsUnexpectedMessage, |
| 603 | |
| 604 | if (ca_bundle.verify(subject, now_sec)) |_| { |
| 605 | handshake_state = .trust_chain_established; |
| 606 | break :cert; |
| 607 | } else |err| switch (err) { |
| 608 | error.CertificateIssuerNotFound => {}, |
| 609 | else => |e| return e, |
| 516 | 610 | } |
| 517 | | try hsd.ensure(1 + 4); |
| 518 | | const cert_req_ctx_len = hsd.decode(u8); |
| 519 | | if (cert_req_ctx_len != 0) return error.TlsIllegalParameter; |
| 520 | | const certs_size = hsd.decode(u24); |
| 521 | | var certs_decoder = try hsd.sub(certs_size); |
| 522 | | while (!certs_decoder.eof()) { |
| 523 | | try certs_decoder.ensure(3); |
| 524 | | const cert_size = certs_decoder.decode(u24); |
| 525 | | const certd = try certs_decoder.sub(cert_size); |
| 526 | | |
| 527 | | const subject_cert: Certificate = .{ |
| 528 | | .buffer = certd.buf, |
| 529 | | .index = @intCast(certd.idx), |
| 530 | | }; |
| 531 | | const subject = try subject_cert.parse(); |
| 532 | | if (cert_index == 0) { |
| 533 | | // Verify the host on the first certificate. |
| 534 | | try subject.verifyHostName(host); |
| 535 | | |
| 536 | | // Keep track of the public key for the |
| 537 | | // certificate_verify message later. |
| 538 | | main_cert_pub_key_algo = subject.pub_key_algo; |
| 539 | | const pub_key = subject.pubKey(); |
| 540 | | if (pub_key.len > main_cert_pub_key_buf.len) |
| 541 | | return error.CertificatePublicKeyInvalid; |
| 542 | | @memcpy(main_cert_pub_key_buf[0..pub_key.len], pub_key); |
| 543 | | main_cert_pub_key_len = @intCast(pub_key.len); |
| 544 | | } else { |
| 545 | | try prev_cert.verify(subject, now_sec); |
| 546 | | } |
| 547 | | |
| 548 | | if (ca_bundle.verify(subject, now_sec)) |_| { |
| 549 | | handshake_state = .trust_chain_established; |
| 550 | | break :cert; |
| 551 | | } else |err| switch (err) { |
| 552 | | error.CertificateIssuerNotFound => {}, |
| 553 | | else => |e| return e, |
| 554 | | } |
| 555 | | |
| 556 | | prev_cert = subject; |
| 557 | | cert_index += 1; |
| 558 | 611 | |
| 612 | prev_cert = subject; |
| 613 | cert_index += 1; |
| 614 | |
| 615 | if (tls_version == .tls_1_3) { |
| 559 | 616 | try certs_decoder.ensure(2); |
| 560 | 617 | const total_ext_size = certs_decoder.decode(u16); |
| 561 | 618 | const all_extd = try certs_decoder.sub(total_ext_size); |
| 562 | 619 | _ = all_extd; |
| 563 | 620 | } |
| 564 | | }, |
| 565 | | .certificate_verify => { |
| 566 | | switch (handshake_state) { |
| 567 | | .trust_chain_established => handshake_state = .finished, |
| 568 | | .certificate => return error.TlsCertificateNotVerified, |
| 569 | | else => return error.TlsUnexpectedMessage, |
| 570 | | } |
| 621 | } |
| 622 | }, |
| 623 | .server_key_exchange => { |
| 624 | if (tls_version != .tls_1_2) return error.TlsUnexpectedMessage; |
| 625 | if (cipher_state != .cleartext) return error.TlsUnexpectedMessage; |
| 626 | switch (handshake_state) { |
| 627 | .trust_chain_established => handshake_state = .server_hello_done, |
| 628 | .certificate => return error.TlsCertificateNotVerified, |
| 629 | else => return error.TlsUnexpectedMessage, |
| 630 | } |
| 571 | 631 | |
| 572 | | try hsd.ensure(4); |
| 573 | | const scheme = hsd.decode(tls.SignatureScheme); |
| 574 | | const sig_len = hsd.decode(u16); |
| 575 | | try hsd.ensure(sig_len); |
| 576 | | const encoded_sig = hsd.slice(sig_len); |
| 577 | | const max_digest_len = 64; |
| 578 | | var verify_buffer: [64 + 34 + max_digest_len]u8 = |
| 579 | | ([1]u8{0x20} ** 64) ++ |
| 580 | | "TLS 1.3, server CertificateVerify\x00".* ++ |
| 581 | | @as([max_digest_len]u8, undefined); |
| 582 | | |
| 583 | | const verify_bytes = switch (handshake_cipher) { |
| 584 | | inline else => |*p| v: { |
| 585 | | const transcript_digest = p.transcript_hash.peek(); |
| 586 | | verify_buffer[verify_buffer.len - max_digest_len ..][0..transcript_digest.len].* = transcript_digest; |
| 587 | | p.transcript_hash.update(wrapped_handshake); |
| 588 | | break :v verify_buffer[0 .. verify_buffer.len - max_digest_len + transcript_digest.len]; |
| 589 | | }, |
| 590 | | }; |
| 591 | | const main_cert_pub_key = main_cert_pub_key_buf[0..main_cert_pub_key_len]; |
| 592 | | |
| 593 | | switch (scheme) { |
| 594 | | inline .ecdsa_secp256r1_sha256, |
| 595 | | .ecdsa_secp384r1_sha384, |
| 596 | | => |comptime_scheme| { |
| 597 | | if (main_cert_pub_key_algo != .X9_62_id_ecPublicKey) |
| 598 | | return error.TlsBadSignatureScheme; |
| 599 | | const Ecdsa = SchemeEcdsa(comptime_scheme); |
| 600 | | const sig = try Ecdsa.Signature.fromDer(encoded_sig); |
| 601 | | const key = try Ecdsa.PublicKey.fromSec1(main_cert_pub_key); |
| 602 | | try sig.verify(verify_bytes, key); |
| 603 | | }, |
| 604 | | inline .rsa_pss_rsae_sha256, |
| 605 | | .rsa_pss_rsae_sha384, |
| 606 | | .rsa_pss_rsae_sha512, |
| 607 | | => |comptime_scheme| { |
| 608 | | if (main_cert_pub_key_algo != .rsaEncryption) |
| 609 | | return error.TlsBadSignatureScheme; |
| 610 | | |
| 611 | | const Hash = SchemeHash(comptime_scheme); |
| 612 | | const rsa = Certificate.rsa; |
| 613 | | const components = try rsa.PublicKey.parseDer(main_cert_pub_key); |
| 614 | | const exponent = components.exponent; |
| 615 | | const modulus = components.modulus; |
| 616 | | switch (modulus.len) { |
| 617 | | inline 128, 256, 512 => |modulus_len| { |
| 618 | | const key = try rsa.PublicKey.fromBytes(exponent, modulus); |
| 619 | | const sig = rsa.PSSSignature.fromBytes(modulus_len, encoded_sig); |
| 620 | | try rsa.PSSSignature.verify(modulus_len, sig, verify_bytes, key, Hash); |
| 621 | | }, |
| 622 | | else => { |
| 623 | | return error.TlsBadRsaSignatureBitCount; |
| 624 | | }, |
| 625 | | } |
| 626 | | }, |
| 627 | | inline .ed25519 => |comptime_scheme| { |
| 628 | | if (main_cert_pub_key_algo != .curveEd25519) return error.TlsBadSignatureScheme; |
| 629 | | const Eddsa = SchemeEddsa(comptime_scheme); |
| 630 | | if (encoded_sig.len != Eddsa.Signature.encoded_length) return error.InvalidEncoding; |
| 631 | | const sig = Eddsa.Signature.fromBytes(encoded_sig[0..Eddsa.Signature.encoded_length].*); |
| 632 | | if (main_cert_pub_key.len != Eddsa.PublicKey.encoded_length) return error.InvalidEncoding; |
| 633 | | const key = try Eddsa.PublicKey.fromBytes(main_cert_pub_key[0..Eddsa.PublicKey.encoded_length].*); |
| 634 | | try sig.verify(verify_bytes, key); |
| 635 | | }, |
| 636 | | else => { |
| 637 | | return error.TlsBadSignatureScheme; |
| 638 | | }, |
| 639 | | } |
| 640 | | }, |
| 641 | | .finished => { |
| 642 | | if (handshake_state != .finished) return error.TlsUnexpectedMessage; |
| 643 | | // This message is to trick buggy proxies into behaving correctly. |
| 644 | | const client_change_cipher_spec_msg = [_]u8{ |
| 645 | | @intFromEnum(tls.ContentType.change_cipher_spec), |
| 646 | | 0x03, 0x03, // legacy protocol version |
| 647 | | 0x00, 0x01, // length |
| 648 | | 0x01, |
| 649 | | }; |
| 650 | | const app_cipher = switch (handshake_cipher) { |
| 651 | | inline else => |*p, tag| c: { |
| 652 | | const P = @TypeOf(p.*); |
| 632 | switch (handshake_cipher) { |
| 633 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| 634 | } |
| 635 | try hsd.ensure(1 + 2 + 1); |
| 636 | const curve_type = hsd.decode(u8); |
| 637 | if (curve_type != 0x03) return error.TlsIllegalParameter; // named_curve |
| 638 | const named_group = hsd.decode(tls.NamedGroup); |
| 639 | if (named_group != .secp256r1) return error.TlsIllegalParameter; |
| 640 | const key_size = hsd.decode(u8); |
| 641 | try hsd.ensure(key_size); |
| 642 | const server_pub_key = hsd.slice(key_size); |
| 643 | try main_cert_pub_key.verifySignature(&hsd, &.{ &client_hello_rand, &server_hello_rand, hsd.buf[0..hsd.idx] }); |
| 644 | try key_share.exchange(named_group, server_pub_key); |
| 645 | }, |
| 646 | .server_hello_done => { |
| 647 | if (tls_version != .tls_1_2) return error.TlsUnexpectedMessage; |
| 648 | if (cipher_state != .cleartext) return error.TlsUnexpectedMessage; |
| 649 | if (handshake_state != .server_hello_done) return error.TlsUnexpectedMessage; |
| 650 | handshake_state = .finished; |
| 651 | |
| 652 | const client_key_exchange_msg = |
| 653 | [_]u8{@intFromEnum(tls.ContentType.handshake)} ++ // record content type |
| 654 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ // legacy protocol version |
| 655 | int2(0x46) ++ // record length |
| 656 | .{@intFromEnum(tls.HandshakeType.client_key_exchange)} ++ // handshake type |
| 657 | int3(0x42) ++ // params length |
| 658 | .{0x41} ++ // pubkey length |
| 659 | key_share.secp256r1_kp.public_key.toUncompressedSec1(); |
| 660 | // This message is to trick buggy proxies into behaving correctly. |
| 661 | const client_change_cipher_spec_msg = |
| 662 | [_]u8{@intFromEnum(tls.ContentType.change_cipher_spec)} ++ // record content type |
| 663 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ // legacy protocol version |
| 664 | int2(1) ++ // record length |
| 665 | .{0x01}; |
| 666 | const pre_master_secret = key_share.getSharedSecret().?; |
| 667 | switch (handshake_cipher) { |
| 668 | inline else => |*p| { |
| 669 | const P = @TypeOf(p.*).A; |
| 670 | p.transcript_hash.update(wrapped_handshake); |
| 671 | p.transcript_hash.update(client_key_exchange_msg[tls.record_header_len..]); |
| 672 | const master_secret = hmacExpandLabel(P.Hmac, pre_master_secret, &.{ |
| 673 | "master secret", |
| 674 | &client_hello_rand, |
| 675 | &server_hello_rand, |
| 676 | }, 48); |
| 677 | const key_block = hmacExpandLabel( |
| 678 | P.Hmac, |
| 679 | &master_secret, |
| 680 | &.{ "key expansion", &server_hello_rand, &client_hello_rand }, |
| 681 | @sizeOf(P.Tls_1_2), |
| 682 | ); |
| 683 | const verify_data_len = 12; |
| 684 | const client_verify_cleartext = |
| 685 | [_]u8{@intFromEnum(tls.HandshakeType.finished)} ++ // handshake type |
| 686 | int3(verify_data_len) ++ // verify data length |
| 687 | hmacExpandLabel(P.Hmac, &master_secret, &.{ "client finished", &p.transcript_hash.peek() }, verify_data_len); |
| 688 | p.transcript_hash.update(&client_verify_cleartext); |
| 689 | p.version = .{ .tls_1_2 = .{ |
| 690 | .server_verify_data = hmacExpandLabel( |
| 691 | P.Hmac, |
| 692 | &master_secret, |
| 693 | &.{ "server finished", &p.transcript_hash.finalResult() }, |
| 694 | verify_data_len, |
| 695 | ), |
| 696 | .app_cipher = std.mem.bytesToValue(P.Tls_1_2, &key_block), |
| 697 | } }; |
| 698 | const pv = &p.version.tls_1_2; |
| 699 | pending_cipher_state = .application; |
| 700 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| 701 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 702 | nonce: { |
| 703 | var nonce = pv.app_cipher.client_write_IV ++ pv.app_cipher.client_salt; |
| 704 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 705 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ write_seq, .big); |
| 706 | break :nonce nonce; |
| 707 | } else nonce: { |
| 708 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 709 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 710 | const operand: V = pad ++ @as([8]u8, @bitCast(big(write_seq))); |
| 711 | break :nonce @as(V, pv.app_cipher.client_write_IV ++ pv.app_cipher.client_salt) ^ operand; |
| 712 | }; |
| 713 | var client_verify_msg = [_]u8{@intFromEnum(tls.ContentType.handshake)} ++ // record content type |
| 714 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ // legacy protocol version |
| 715 | int2(P.record_iv_length + client_verify_cleartext.len + P.mac_length) ++ // record length |
| 716 | nonce[P.fixed_iv_length..].* ++ |
| 717 | @as([client_verify_cleartext.len + P.mac_length]u8, undefined); |
| 718 | P.AEAD.encrypt( |
| 719 | client_verify_msg[client_verify_msg.len - P.mac_length - |
| 720 | client_verify_cleartext.len ..][0..client_verify_cleartext.len], |
| 721 | client_verify_msg[client_verify_msg.len - P.mac_length ..][0..P.mac_length], |
| 722 | &client_verify_cleartext, |
| 723 | std.mem.toBytes(big(write_seq)) ++ client_verify_msg[0 .. 1 + 2] ++ int2(client_verify_cleartext.len), |
| 724 | nonce, |
| 725 | pv.app_cipher.client_write_key, |
| 726 | ); |
| 727 | const all_msgs = client_key_exchange_msg ++ client_change_cipher_spec_msg ++ client_verify_msg; |
| 728 | var all_msgs_vec = [_]std.posix.iovec_const{.{ |
| 729 | .base = &all_msgs, |
| 730 | .len = all_msgs.len, |
| 731 | }}; |
| 732 | try stream.writevAll(&all_msgs_vec); |
| 733 | }, |
| 734 | } |
| 735 | write_seq += 1; |
| 736 | }, |
| 737 | .certificate_verify => { |
| 738 | if (tls_version != .tls_1_3) return error.TlsUnexpectedMessage; |
| 739 | if (cipher_state != .handshake) return error.TlsUnexpectedMessage; |
| 740 | switch (handshake_state) { |
| 741 | .trust_chain_established => handshake_state = .finished, |
| 742 | .certificate => return error.TlsCertificateNotVerified, |
| 743 | else => return error.TlsUnexpectedMessage, |
| 744 | } |
| 745 | switch (handshake_cipher) { |
| 746 | inline else => |*p| { |
| 747 | try main_cert_pub_key.verifySignature(&hsd, &.{ |
| 748 | " " ** 64 ++ "TLS 1.3, server CertificateVerify\x00", |
| 749 | &p.transcript_hash.peek(), |
| 750 | }); |
| 751 | p.transcript_hash.update(wrapped_handshake); |
| 752 | }, |
| 753 | } |
| 754 | }, |
| 755 | .finished => { |
| 756 | if (cipher_state == .cleartext) return error.TlsUnexpectedMessage; |
| 757 | if (handshake_state != .finished) return error.TlsUnexpectedMessage; |
| 758 | // This message is to trick buggy proxies into behaving correctly. |
| 759 | const client_change_cipher_spec_msg = |
| 760 | [_]u8{@intFromEnum(tls.ContentType.change_cipher_spec)} ++ |
| 761 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ // legacy protocol version |
| 762 | int2(1) ++ // length |
| 763 | .{0x01}; |
| 764 | const app_cipher = app_cipher: switch (handshake_cipher) { |
| 765 | inline else => |*p, tag| switch (tls_version) { |
| 766 | .tls_1_3 => { |
| 767 | const pv = &p.version.tls_1_3; |
| 768 | const P = @TypeOf(p.*).A; |
| 653 | 769 | const finished_digest = p.transcript_hash.peek(); |
| 654 | 770 | p.transcript_hash.update(wrapped_handshake); |
| 655 | | const expected_server_verify_data = tls.hmac(P.Hmac, &finished_digest, p.server_finished_key); |
| 656 | | if (!mem.eql(u8, &expected_server_verify_data, handshake)) |
| 657 | | return error.TlsDecryptError; |
| 771 | const expected_server_verify_data = tls.hmac(P.Hmac, &finished_digest, pv.server_finished_key); |
| 772 | if (!mem.eql(u8, &expected_server_verify_data, hsd.buf)) return error.TlsDecryptError; |
| 658 | 773 | const handshake_hash = p.transcript_hash.finalResult(); |
| 659 | | const verify_data = tls.hmac(P.Hmac, &handshake_hash, p.client_finished_key); |
| 774 | const verify_data = tls.hmac(P.Hmac, &handshake_hash, pv.client_finished_key); |
| 660 | 775 | const out_cleartext = [_]u8{ |
| 661 | 776 | @intFromEnum(tls.HandshakeType.finished), |
| 662 | 777 | 0, 0, verify_data.len, // length |
| ... | ... | @@ -664,67 +779,78 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 664 | 779 | |
| 665 | 780 | const wrapped_len = out_cleartext.len + P.AEAD.tag_length; |
| 666 | 781 | |
| 667 | | var finished_msg = [_]u8{ |
| 668 | | @intFromEnum(tls.ContentType.application_data), |
| 669 | | 0x03, 0x03, // legacy protocol version |
| 670 | | 0, wrapped_len, // byte length of encrypted record |
| 671 | | } ++ @as([wrapped_len]u8, undefined); |
| 782 | var finished_msg = [_]u8{@intFromEnum(tls.ContentType.application_data)} ++ |
| 783 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ // legacy protocol version |
| 784 | int2(wrapped_len) ++ // byte length of encrypted record |
| 785 | @as([wrapped_len]u8, undefined); |
| 672 | 786 | |
| 673 | | const ad = finished_msg[0..5]; |
| 674 | | const ciphertext = finished_msg[5..][0..out_cleartext.len]; |
| 787 | const ad = finished_msg[0..tls.record_header_len]; |
| 788 | const ciphertext = finished_msg[tls.record_header_len..][0..out_cleartext.len]; |
| 675 | 789 | const auth_tag = finished_msg[finished_msg.len - P.AEAD.tag_length ..]; |
| 676 | | const nonce = p.client_handshake_iv; |
| 677 | | P.AEAD.encrypt(ciphertext, auth_tag, &out_cleartext, ad, nonce, p.client_handshake_key); |
| 790 | const nonce = pv.client_handshake_iv; |
| 791 | P.AEAD.encrypt(ciphertext, auth_tag, &out_cleartext, ad, nonce, pv.client_handshake_key); |
| 678 | 792 | |
| 679 | | const both_msgs = client_change_cipher_spec_msg ++ finished_msg; |
| 680 | | var both_msgs_vec = [_]std.posix.iovec_const{.{ |
| 681 | | .base = &both_msgs, |
| 682 | | .len = both_msgs.len, |
| 793 | const all_msgs = client_change_cipher_spec_msg ++ finished_msg; |
| 794 | var all_msgs_vec = [_]std.posix.iovec_const{.{ |
| 795 | .base = &all_msgs, |
| 796 | .len = all_msgs.len, |
| 683 | 797 | }}; |
| 684 | | try stream.writevAll(&both_msgs_vec); |
| 798 | try stream.writevAll(&all_msgs_vec); |
| 685 | 799 | |
| 686 | | const client_secret = hkdfExpandLabel(P.Hkdf, p.master_secret, "c ap traffic", &handshake_hash, P.Hash.digest_length); |
| 687 | | const server_secret = hkdfExpandLabel(P.Hkdf, p.master_secret, "s ap traffic", &handshake_hash, P.Hash.digest_length); |
| 688 | | break :c @unionInit(tls.ApplicationCipher, @tagName(tag), .{ |
| 800 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.master_secret, "c ap traffic", &handshake_hash, P.Hash.digest_length); |
| 801 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.master_secret, "s ap traffic", &handshake_hash, P.Hash.digest_length); |
| 802 | break :app_cipher @unionInit(tls.ApplicationCipher, @tagName(tag), .{ .tls_1_3 = .{ |
| 689 | 803 | .client_secret = client_secret, |
| 690 | 804 | .server_secret = server_secret, |
| 691 | 805 | .client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length), |
| 692 | 806 | .server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length), |
| 693 | 807 | .client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length), |
| 694 | 808 | .server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length), |
| 695 | | }); |
| 809 | } }); |
| 696 | 810 | }, |
| 697 | | }; |
| 698 | | const leftover = d.rest(); |
| 699 | | var client: Client = .{ |
| 700 | | .read_seq = 0, |
| 701 | | .write_seq = 0, |
| 702 | | .partial_cleartext_idx = 0, |
| 703 | | .partial_ciphertext_idx = 0, |
| 704 | | .partial_ciphertext_end = @intCast(leftover.len), |
| 705 | | .received_close_notify = false, |
| 706 | | .application_cipher = app_cipher, |
| 707 | | .partially_read_buffer = undefined, |
| 708 | | }; |
| 709 | | @memcpy(client.partially_read_buffer[0..leftover.len], leftover); |
| 710 | | return client; |
| 711 | | }, |
| 712 | | else => { |
| 713 | | return error.TlsUnexpectedMessage; |
| 714 | | }, |
| 715 | | } |
| 716 | | if (ctd.eof()) break; |
| 811 | .tls_1_2 => { |
| 812 | const pv = &p.version.tls_1_2; |
| 813 | try hsd.ensure(12); |
| 814 | if (!std.mem.eql(u8, hsd.array(12), &pv.server_verify_data)) return error.TlsDecryptError; |
| 815 | break :app_cipher @unionInit(tls.ApplicationCipher, @tagName(tag), .{ .tls_1_2 = pv.app_cipher }); |
| 816 | }, |
| 817 | else => unreachable, |
| 818 | }, |
| 819 | }; |
| 820 | const leftover = d.rest(); |
| 821 | var client: Client = .{ |
| 822 | .tls_version = tls_version, |
| 823 | .read_seq = switch (tls_version) { |
| 824 | .tls_1_3 => 0, |
| 825 | .tls_1_2 => read_seq, |
| 826 | else => unreachable, |
| 827 | }, |
| 828 | .write_seq = switch (tls_version) { |
| 829 | .tls_1_3 => 0, |
| 830 | .tls_1_2 => write_seq, |
| 831 | else => unreachable, |
| 832 | }, |
| 833 | .partial_cleartext_idx = 0, |
| 834 | .partial_ciphertext_idx = 0, |
| 835 | .partial_ciphertext_end = @intCast(leftover.len), |
| 836 | .received_close_notify = false, |
| 837 | .application_cipher = app_cipher, |
| 838 | .partially_read_buffer = undefined, |
| 839 | }; |
| 840 | @memcpy(client.partially_read_buffer[0..leftover.len], leftover); |
| 841 | return client; |
| 842 | }, |
| 843 | else => return error.TlsUnexpectedMessage, |
| 717 | 844 | } |
| 845 | if (ctd.eof()) break; |
| 718 | 846 | }, |
| 719 | | else => { |
| 720 | | return error.TlsUnexpectedMessage; |
| 721 | | }, |
| 847 | else => return error.TlsUnexpectedMessage, |
| 722 | 848 | } |
| 723 | 849 | } |
| 724 | 850 | } |
| 725 | 851 | |
| 726 | 852 | /// Sends TLS-encrypted data to `stream`, which must conform to `StreamInterface`. |
| 727 | | /// Returns the number of plaintext bytes sent, which may be fewer than `bytes.len`. |
| 853 | /// Returns the number of cleartext bytes sent, which may be fewer than `bytes.len`. |
| 728 | 854 | pub fn write(c: *Client, stream: anytype, bytes: []const u8) !usize { |
| 729 | 855 | return writeEnd(c, stream, bytes, false); |
| 730 | 856 | } |
| ... | ... | @@ -749,7 +875,7 @@ pub fn writeAllEnd(c: *Client, stream: anytype, bytes: []const u8, end: bool) !v |
| 749 | 875 | } |
| 750 | 876 | |
| 751 | 877 | /// Sends TLS-encrypted data to `stream`, which must conform to `StreamInterface`. |
| 752 | | /// Returns the number of plaintext bytes sent, which may be fewer than `bytes.len`. |
| 878 | /// Returns the number of cleartext bytes sent, which may be fewer than `bytes.len`. |
| 753 | 879 | /// If `end` is true, then this function additionally sends a `close_notify` alert, |
| 754 | 880 | /// which is necessary for the server to distinguish between a properly finished |
| 755 | 881 | /// TLS session, or a truncation attack. |
| ... | ... | @@ -813,62 +939,127 @@ fn prepareCiphertextRecord( |
| 813 | 939 | var iovec_end: usize = 0; |
| 814 | 940 | var bytes_i: usize = 0; |
| 815 | 941 | switch (c.application_cipher) { |
| 816 | | inline else => |*p| { |
| 817 | | const P = @TypeOf(p.*); |
| 818 | | const overhead_len = tls.record_header_len + P.AEAD.tag_length + 1; |
| 819 | | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; |
| 820 | | while (true) { |
| 821 | | const encrypted_content_len: u16 = @intCast(@min( |
| 822 | | @min(bytes.len - bytes_i, tls.max_ciphertext_inner_record_len), |
| 823 | | ciphertext_buf.len -| |
| 824 | | (close_notify_alert_reserved + overhead_len + ciphertext_end), |
| 825 | | )); |
| 826 | | if (encrypted_content_len == 0) return .{ |
| 827 | | .iovec_end = iovec_end, |
| 828 | | .ciphertext_end = ciphertext_end, |
| 829 | | .overhead_len = overhead_len, |
| 830 | | }; |
| 831 | | |
| 832 | | @memcpy(cleartext_buf[0..encrypted_content_len], bytes[bytes_i..][0..encrypted_content_len]); |
| 833 | | cleartext_buf[encrypted_content_len] = @intFromEnum(inner_content_type); |
| 834 | | bytes_i += encrypted_content_len; |
| 835 | | const ciphertext_len = encrypted_content_len + 1; |
| 836 | | const cleartext = cleartext_buf[0..ciphertext_len]; |
| 837 | | |
| 838 | | const record_start = ciphertext_end; |
| 839 | | const ad = ciphertext_buf[ciphertext_end..][0..5]; |
| 840 | | ad.* = |
| 841 | | [_]u8{@intFromEnum(tls.ContentType.application_data)} ++ |
| 842 | | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 843 | | int2(ciphertext_len + P.AEAD.tag_length); |
| 844 | | ciphertext_end += ad.len; |
| 845 | | const ciphertext = ciphertext_buf[ciphertext_end..][0..ciphertext_len]; |
| 846 | | ciphertext_end += ciphertext_len; |
| 847 | | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.AEAD.tag_length]; |
| 848 | | ciphertext_end += auth_tag.len; |
| 849 | | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 850 | | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 851 | | nonce: { |
| 852 | | var nonce = p.client_iv; |
| 853 | | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 854 | | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); |
| 855 | | break :nonce nonce; |
| 856 | | } else nonce: { |
| 857 | | const V = @Vector(P.AEAD.nonce_length, u8); |
| 858 | | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 859 | | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.write_seq))); |
| 860 | | break :nonce @as(V, p.client_iv) ^ operand; |
| 861 | | }; |
| 862 | | c.write_seq += 1; // TODO send key_update on overflow |
| 863 | | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, p.client_key); |
| 864 | | |
| 865 | | const record = ciphertext_buf[record_start..ciphertext_end]; |
| 866 | | iovecs[iovec_end] = .{ |
| 867 | | .base = record.ptr, |
| 868 | | .len = record.len, |
| 869 | | }; |
| 870 | | iovec_end += 1; |
| 871 | | } |
| 942 | inline else => |*p| switch (c.tls_version) { |
| 943 | .tls_1_3 => { |
| 944 | const pv = &p.tls_1_3; |
| 945 | const P = @TypeOf(p.*); |
| 946 | const overhead_len = tls.record_header_len + P.AEAD.tag_length + 1; |
| 947 | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; |
| 948 | while (true) { |
| 949 | const encrypted_content_len: u16 = @min( |
| 950 | bytes.len - bytes_i, |
| 951 | tls.max_ciphertext_inner_record_len, |
| 952 | ciphertext_buf.len -| |
| 953 | (close_notify_alert_reserved + overhead_len + ciphertext_end), |
| 954 | ); |
| 955 | if (encrypted_content_len == 0) return .{ |
| 956 | .iovec_end = iovec_end, |
| 957 | .ciphertext_end = ciphertext_end, |
| 958 | .overhead_len = overhead_len, |
| 959 | }; |
| 960 | |
| 961 | @memcpy(cleartext_buf[0..encrypted_content_len], bytes[bytes_i..][0..encrypted_content_len]); |
| 962 | cleartext_buf[encrypted_content_len] = @intFromEnum(inner_content_type); |
| 963 | bytes_i += encrypted_content_len; |
| 964 | const ciphertext_len = encrypted_content_len + 1; |
| 965 | const cleartext = cleartext_buf[0..ciphertext_len]; |
| 966 | |
| 967 | const record_start = ciphertext_end; |
| 968 | const ad = ciphertext_buf[ciphertext_end..][0..tls.record_header_len]; |
| 969 | ad.* = |
| 970 | [_]u8{@intFromEnum(tls.ContentType.application_data)} ++ |
| 971 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 972 | int2(ciphertext_len + P.AEAD.tag_length); |
| 973 | ciphertext_end += ad.len; |
| 974 | const ciphertext = ciphertext_buf[ciphertext_end..][0..ciphertext_len]; |
| 975 | ciphertext_end += ciphertext_len; |
| 976 | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.AEAD.tag_length]; |
| 977 | ciphertext_end += auth_tag.len; |
| 978 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 979 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 980 | nonce: { |
| 981 | var nonce = pv.client_iv; |
| 982 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 983 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); |
| 984 | break :nonce nonce; |
| 985 | } else nonce: { |
| 986 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 987 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 988 | const operand: V = pad ++ std.mem.toBytes(big(c.write_seq)); |
| 989 | break :nonce @as(V, pv.client_iv) ^ operand; |
| 990 | }; |
| 991 | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, pv.client_key); |
| 992 | c.write_seq += 1; // TODO send key_update on overflow |
| 993 | |
| 994 | const record = ciphertext_buf[record_start..ciphertext_end]; |
| 995 | iovecs[iovec_end] = .{ |
| 996 | .base = record.ptr, |
| 997 | .len = record.len, |
| 998 | }; |
| 999 | iovec_end += 1; |
| 1000 | } |
| 1001 | }, |
| 1002 | .tls_1_2 => { |
| 1003 | const pv = &p.tls_1_2; |
| 1004 | const P = @TypeOf(p.*); |
| 1005 | const overhead_len = tls.record_header_len + P.record_iv_length + P.mac_length; |
| 1006 | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; |
| 1007 | while (true) { |
| 1008 | const message_len: u16 = @min( |
| 1009 | bytes.len - bytes_i, |
| 1010 | tls.max_ciphertext_inner_record_len, |
| 1011 | ciphertext_buf.len -| |
| 1012 | (close_notify_alert_reserved + overhead_len + ciphertext_end), |
| 1013 | ); |
| 1014 | if (message_len == 0) return .{ |
| 1015 | .iovec_end = iovec_end, |
| 1016 | .ciphertext_end = ciphertext_end, |
| 1017 | .overhead_len = overhead_len, |
| 1018 | }; |
| 1019 | |
| 1020 | @memcpy(cleartext_buf[0..message_len], bytes[bytes_i..][0..message_len]); |
| 1021 | bytes_i += message_len; |
| 1022 | const cleartext = cleartext_buf[0..message_len]; |
| 1023 | |
| 1024 | const record_start = ciphertext_end; |
| 1025 | const record_header = ciphertext_buf[ciphertext_end..][0..tls.record_header_len]; |
| 1026 | ciphertext_end += tls.record_header_len; |
| 1027 | record_header.* = [_]u8{@intFromEnum(inner_content_type)} ++ |
| 1028 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 1029 | int2(P.record_iv_length + message_len + P.mac_length); |
| 1030 | const ad = std.mem.toBytes(big(c.write_seq)) ++ record_header[0 .. 1 + 2] ++ int2(message_len); |
| 1031 | const record_iv = ciphertext_buf[ciphertext_end..][0..P.record_iv_length]; |
| 1032 | ciphertext_end += P.record_iv_length; |
| 1033 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| 1034 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 1035 | nonce: { |
| 1036 | var nonce = pv.client_write_IV ++ pv.client_salt; |
| 1037 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 1038 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); |
| 1039 | break :nonce nonce; |
| 1040 | } else nonce: { |
| 1041 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 1042 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 1043 | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.write_seq))); |
| 1044 | break :nonce @as(V, pv.client_write_IV ++ pv.client_salt) ^ operand; |
| 1045 | }; |
| 1046 | record_iv.* = nonce[P.fixed_iv_length..].*; |
| 1047 | const ciphertext = ciphertext_buf[ciphertext_end..][0..message_len]; |
| 1048 | ciphertext_end += message_len; |
| 1049 | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.mac_length]; |
| 1050 | ciphertext_end += P.mac_length; |
| 1051 | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, pv.client_write_key); |
| 1052 | c.write_seq += 1; // TODO send key_update on overflow |
| 1053 | |
| 1054 | const record = ciphertext_buf[record_start..ciphertext_end]; |
| 1055 | iovecs[iovec_end] = .{ |
| 1056 | .base = record.ptr, |
| 1057 | .len = record.len, |
| 1058 | }; |
| 1059 | iovec_end += 1; |
| 1060 | } |
| 1061 | }, |
| 1062 | else => unreachable, |
| 872 | 1063 | }, |
| 873 | 1064 | } |
| 874 | 1065 | } |
| ... | ... | @@ -990,7 +1181,7 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove |
| 990 | 1181 | // beginning of the buffer will be used for such purposes. |
| 991 | 1182 | const cleartext_buf_len = free_size - ciphertext_buf_len; |
| 992 | 1183 | |
| 993 | | // Recoup `partially_read_buffer space`. This is necessary because it is assumed |
| 1184 | // Recoup `partially_read_buffer` space. This is necessary because it is assumed |
| 994 | 1185 | // below that `frag0` is big enough to hold at least one record. |
| 995 | 1186 | limitedOverlapCopy(c.partially_read_buffer[0..c.partial_ciphertext_end], c.partial_ciphertext_idx); |
| 996 | 1187 | c.partial_ciphertext_end -= c.partial_ciphertext_idx; |
| ... | ... | @@ -1105,159 +1296,182 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove |
| 1105 | 1296 | in = 0; |
| 1106 | 1297 | continue; |
| 1107 | 1298 | } |
| 1108 | | switch (ct) { |
| 1299 | const cleartext, const inner_ct: tls.ContentType = cleartext: switch (c.application_cipher) { |
| 1300 | inline else => |*p| switch (c.tls_version) { |
| 1301 | .tls_1_3 => { |
| 1302 | const pv = &p.tls_1_3; |
| 1303 | const P = @TypeOf(p.*); |
| 1304 | const ad = frag[in - tls.record_header_len ..][0..tls.record_header_len]; |
| 1305 | const ciphertext_len = record_len - P.AEAD.tag_length; |
| 1306 | const ciphertext = frag[in..][0..ciphertext_len]; |
| 1307 | in += ciphertext_len; |
| 1308 | const auth_tag = frag[in..][0..P.AEAD.tag_length].*; |
| 1309 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 1310 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 1311 | nonce: { |
| 1312 | var nonce = pv.server_iv; |
| 1313 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 1314 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.read_seq, .big); |
| 1315 | break :nonce nonce; |
| 1316 | } else nonce: { |
| 1317 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 1318 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 1319 | const operand: V = pad ++ std.mem.toBytes(big(c.read_seq)); |
| 1320 | break :nonce @as(V, pv.server_iv) ^ operand; |
| 1321 | }; |
| 1322 | const out_buf = vp.peek(); |
| 1323 | const cleartext_buf = if (ciphertext.len <= out_buf.len) |
| 1324 | out_buf |
| 1325 | else |
| 1326 | &cleartext_stack_buffer; |
| 1327 | const cleartext = cleartext_buf[0..ciphertext.len]; |
| 1328 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, pv.server_key) catch |
| 1329 | return error.TlsBadRecordMac; |
| 1330 | const msg = mem.trimRight(u8, cleartext, "\x00"); |
| 1331 | break :cleartext .{ msg[0 .. msg.len - 1], @enumFromInt(msg[msg.len - 1]) }; |
| 1332 | }, |
| 1333 | .tls_1_2 => { |
| 1334 | const pv = &p.tls_1_2; |
| 1335 | const P = @TypeOf(p.*); |
| 1336 | const message_len: u16 = record_len - P.record_iv_length - P.mac_length; |
| 1337 | const ad = std.mem.toBytes(big(c.read_seq)) ++ |
| 1338 | frag[in - tls.record_header_len ..][0 .. 1 + 2] ++ |
| 1339 | std.mem.toBytes(big(message_len)); |
| 1340 | const record_iv = frag[in..][0..P.record_iv_length].*; |
| 1341 | in += P.record_iv_length; |
| 1342 | const masked_read_seq = c.read_seq & |
| 1343 | comptime std.math.shl(u64, std.math.maxInt(u64), 8 * P.record_iv_length); |
| 1344 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| 1345 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 1346 | nonce: { |
| 1347 | var nonce = pv.server_write_IV ++ record_iv; |
| 1348 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 1349 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ masked_read_seq, .big); |
| 1350 | break :nonce nonce; |
| 1351 | } else nonce: { |
| 1352 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 1353 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 1354 | const operand: V = pad ++ @as([8]u8, @bitCast(big(masked_read_seq))); |
| 1355 | break :nonce @as(V, pv.server_write_IV ++ record_iv) ^ operand; |
| 1356 | }; |
| 1357 | const ciphertext = frag[in..][0..message_len]; |
| 1358 | in += message_len; |
| 1359 | const auth_tag = frag[in..][0..P.mac_length].*; |
| 1360 | in += P.mac_length; |
| 1361 | const out_buf = vp.peek(); |
| 1362 | const cleartext_buf = if (message_len <= out_buf.len) |
| 1363 | out_buf |
| 1364 | else |
| 1365 | &cleartext_stack_buffer; |
| 1366 | const cleartext = cleartext_buf[0..ciphertext.len]; |
| 1367 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, pv.server_write_key) catch |
| 1368 | return error.TlsBadRecordMac; |
| 1369 | break :cleartext .{ cleartext, ct }; |
| 1370 | }, |
| 1371 | else => unreachable, |
| 1372 | }, |
| 1373 | }; |
| 1374 | c.read_seq = try std.math.add(u64, c.read_seq, 1); |
| 1375 | switch (inner_ct) { |
| 1109 | 1376 | .alert => { |
| 1110 | | if (in + 2 > frag.len) return error.TlsDecodeError; |
| 1111 | | const level: tls.AlertLevel = @enumFromInt(frag[in]); |
| 1112 | | const desc: tls.AlertDescription = @enumFromInt(frag[in + 1]); |
| 1377 | if (cleartext.len != 2) return error.TlsDecodeError; |
| 1378 | const level: tls.AlertLevel = @enumFromInt(cleartext[0]); |
| 1379 | const desc: tls.AlertDescription = @enumFromInt(cleartext[1]); |
| 1380 | if (desc == .close_notify) { |
| 1381 | c.received_close_notify = true; |
| 1382 | c.partial_ciphertext_end = c.partial_ciphertext_idx; |
| 1383 | return vp.total; |
| 1384 | } |
| 1113 | 1385 | _ = level; |
| 1114 | 1386 | |
| 1115 | 1387 | try desc.toError(); |
| 1116 | 1388 | // TODO: handle server-side closures |
| 1117 | 1389 | return error.TlsUnexpectedMessage; |
| 1118 | 1390 | }, |
| 1119 | | .application_data => { |
| 1120 | | const cleartext = switch (c.application_cipher) { |
| 1121 | | inline else => |*p| c: { |
| 1122 | | const P = @TypeOf(p.*); |
| 1123 | | const ad = frag[in - 5 ..][0..5]; |
| 1124 | | const ciphertext_len = record_len - P.AEAD.tag_length; |
| 1125 | | const ciphertext = frag[in..][0..ciphertext_len]; |
| 1126 | | in += ciphertext_len; |
| 1127 | | const auth_tag = frag[in..][0..P.AEAD.tag_length].*; |
| 1128 | | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 1129 | | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 1130 | | nonce: { |
| 1131 | | var nonce = p.server_iv; |
| 1132 | | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 1133 | | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.read_seq, .big); |
| 1134 | | break :nonce nonce; |
| 1135 | | } else nonce: { |
| 1136 | | const V = @Vector(P.AEAD.nonce_length, u8); |
| 1137 | | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 1138 | | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.read_seq))); |
| 1139 | | break :nonce @as(V, p.server_iv) ^ operand; |
| 1140 | | }; |
| 1141 | | const out_buf = vp.peek(); |
| 1142 | | const cleartext_buf = if (ciphertext.len <= out_buf.len) |
| 1143 | | out_buf |
| 1144 | | else |
| 1145 | | &cleartext_stack_buffer; |
| 1146 | | const cleartext = cleartext_buf[0..ciphertext.len]; |
| 1147 | | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, p.server_key) catch |
| 1148 | | return error.TlsBadRecordMac; |
| 1149 | | break :c mem.trimRight(u8, cleartext, "\x00"); |
| 1150 | | }, |
| 1151 | | }; |
| 1152 | | |
| 1153 | | c.read_seq = try std.math.add(u64, c.read_seq, 1); |
| 1154 | | |
| 1155 | | const inner_ct: tls.ContentType = @enumFromInt(cleartext[cleartext.len - 1]); |
| 1156 | | switch (inner_ct) { |
| 1157 | | .alert => { |
| 1158 | | const level: tls.AlertLevel = @enumFromInt(cleartext[0]); |
| 1159 | | const desc: tls.AlertDescription = @enumFromInt(cleartext[1]); |
| 1160 | | if (desc == .close_notify) { |
| 1161 | | c.received_close_notify = true; |
| 1162 | | c.partial_ciphertext_end = c.partial_ciphertext_idx; |
| 1163 | | return vp.total; |
| 1164 | | } |
| 1165 | | _ = level; |
| 1166 | | |
| 1167 | | try desc.toError(); |
| 1168 | | // TODO: handle server-side closures |
| 1169 | | return error.TlsUnexpectedMessage; |
| 1170 | | }, |
| 1171 | | .handshake => { |
| 1172 | | var ct_i: usize = 0; |
| 1173 | | while (true) { |
| 1174 | | const handshake_type: tls.HandshakeType = @enumFromInt(cleartext[ct_i]); |
| 1175 | | ct_i += 1; |
| 1176 | | const handshake_len = mem.readInt(u24, cleartext[ct_i..][0..3], .big); |
| 1177 | | ct_i += 3; |
| 1178 | | const next_handshake_i = ct_i + handshake_len; |
| 1179 | | if (next_handshake_i > cleartext.len - 1) |
| 1180 | | return error.TlsBadLength; |
| 1181 | | const handshake = cleartext[ct_i..next_handshake_i]; |
| 1182 | | switch (handshake_type) { |
| 1183 | | .new_session_ticket => { |
| 1184 | | // This client implementation ignores new session tickets. |
| 1391 | .handshake => { |
| 1392 | var ct_i: usize = 0; |
| 1393 | while (true) { |
| 1394 | const handshake_type: tls.HandshakeType = @enumFromInt(cleartext[ct_i]); |
| 1395 | ct_i += 1; |
| 1396 | const handshake_len = mem.readInt(u24, cleartext[ct_i..][0..3], .big); |
| 1397 | ct_i += 3; |
| 1398 | const next_handshake_i = ct_i + handshake_len; |
| 1399 | if (next_handshake_i > cleartext.len) |
| 1400 | return error.TlsBadLength; |
| 1401 | const handshake = cleartext[ct_i..next_handshake_i]; |
| 1402 | switch (handshake_type) { |
| 1403 | .new_session_ticket => { |
| 1404 | // This client implementation ignores new session tickets. |
| 1405 | }, |
| 1406 | .key_update => { |
| 1407 | switch (c.application_cipher) { |
| 1408 | inline else => |*p| { |
| 1409 | const pv = &p.tls_1_3; |
| 1410 | const P = @TypeOf(p.*); |
| 1411 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.server_secret, "traffic upd", "", P.Hash.digest_length); |
| 1412 | pv.server_secret = server_secret; |
| 1413 | pv.server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| 1414 | pv.server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| 1185 | 1415 | }, |
| 1186 | | .key_update => { |
| 1416 | } |
| 1417 | c.read_seq = 0; |
| 1418 | |
| 1419 | switch (@as(tls.KeyUpdateRequest, @enumFromInt(handshake[0]))) { |
| 1420 | .update_requested => { |
| 1187 | 1421 | switch (c.application_cipher) { |
| 1188 | 1422 | inline else => |*p| { |
| 1423 | const pv = &p.tls_1_3; |
| 1189 | 1424 | const P = @TypeOf(p.*); |
| 1190 | | const server_secret = hkdfExpandLabel(P.Hkdf, p.server_secret, "traffic upd", "", P.Hash.digest_length); |
| 1191 | | p.server_secret = server_secret; |
| 1192 | | p.server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| 1193 | | p.server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| 1194 | | }, |
| 1195 | | } |
| 1196 | | c.read_seq = 0; |
| 1197 | | |
| 1198 | | switch (@as(tls.KeyUpdateRequest, @enumFromInt(handshake[0]))) { |
| 1199 | | .update_requested => { |
| 1200 | | switch (c.application_cipher) { |
| 1201 | | inline else => |*p| { |
| 1202 | | const P = @TypeOf(p.*); |
| 1203 | | const client_secret = hkdfExpandLabel(P.Hkdf, p.client_secret, "traffic upd", "", P.Hash.digest_length); |
| 1204 | | p.client_secret = client_secret; |
| 1205 | | p.client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| 1206 | | p.client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| 1207 | | }, |
| 1208 | | } |
| 1209 | | c.write_seq = 0; |
| 1425 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.client_secret, "traffic upd", "", P.Hash.digest_length); |
| 1426 | pv.client_secret = client_secret; |
| 1427 | pv.client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| 1428 | pv.client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| 1210 | 1429 | }, |
| 1211 | | .update_not_requested => {}, |
| 1212 | | _ => return error.TlsIllegalParameter, |
| 1213 | 1430 | } |
| 1431 | c.write_seq = 0; |
| 1214 | 1432 | }, |
| 1215 | | else => { |
| 1216 | | return error.TlsUnexpectedMessage; |
| 1217 | | }, |
| 1218 | | } |
| 1219 | | ct_i = next_handshake_i; |
| 1220 | | if (ct_i >= cleartext.len - 1) break; |
| 1221 | | } |
| 1222 | | }, |
| 1223 | | .application_data => { |
| 1224 | | // Determine whether the output buffer or a stack |
| 1225 | | // buffer was used for storing the cleartext. |
| 1226 | | if (cleartext.ptr == &cleartext_stack_buffer) { |
| 1227 | | // Stack buffer was used, so we must copy to the output buffer. |
| 1228 | | const msg = cleartext[0 .. cleartext.len - 1]; |
| 1229 | | if (c.partial_ciphertext_idx > c.partial_cleartext_idx) { |
| 1230 | | // We have already run out of room in iovecs. Continue |
| 1231 | | // appending to `partially_read_buffer`. |
| 1232 | | @memcpy( |
| 1233 | | c.partially_read_buffer[c.partial_ciphertext_idx..][0..msg.len], |
| 1234 | | msg, |
| 1235 | | ); |
| 1236 | | c.partial_ciphertext_idx = @intCast(c.partial_ciphertext_idx + msg.len); |
| 1237 | | } else { |
| 1238 | | const amt = vp.put(msg); |
| 1239 | | if (amt < msg.len) { |
| 1240 | | const rest = msg[amt..]; |
| 1241 | | c.partial_cleartext_idx = 0; |
| 1242 | | c.partial_ciphertext_idx = @intCast(rest.len); |
| 1243 | | @memcpy(c.partially_read_buffer[0..rest.len], rest); |
| 1244 | | } |
| 1433 | .update_not_requested => {}, |
| 1434 | _ => return error.TlsIllegalParameter, |
| 1245 | 1435 | } |
| 1246 | | } else { |
| 1247 | | // Output buffer was used directly which means no |
| 1248 | | // memory copying needs to occur, and we can move |
| 1249 | | // on to the next ciphertext record. |
| 1250 | | vp.next(cleartext.len - 1); |
| 1251 | | } |
| 1252 | | }, |
| 1253 | | else => { |
| 1254 | | return error.TlsUnexpectedMessage; |
| 1255 | | }, |
| 1436 | }, |
| 1437 | else => { |
| 1438 | return error.TlsUnexpectedMessage; |
| 1439 | }, |
| 1440 | } |
| 1441 | ct_i = next_handshake_i; |
| 1442 | if (ct_i >= cleartext.len) break; |
| 1256 | 1443 | } |
| 1257 | 1444 | }, |
| 1258 | | else => { |
| 1259 | | return error.TlsUnexpectedMessage; |
| 1445 | .application_data => { |
| 1446 | // Determine whether the output buffer or a stack |
| 1447 | // buffer was used for storing the cleartext. |
| 1448 | if (cleartext.ptr == &cleartext_stack_buffer) { |
| 1449 | // Stack buffer was used, so we must copy to the output buffer. |
| 1450 | if (c.partial_ciphertext_idx > c.partial_cleartext_idx) { |
| 1451 | // We have already run out of room in iovecs. Continue |
| 1452 | // appending to `partially_read_buffer`. |
| 1453 | @memcpy( |
| 1454 | c.partially_read_buffer[c.partial_ciphertext_idx..][0..cleartext.len], |
| 1455 | cleartext, |
| 1456 | ); |
| 1457 | c.partial_ciphertext_idx = @intCast(c.partial_ciphertext_idx + cleartext.len); |
| 1458 | } else { |
| 1459 | const amt = vp.put(cleartext); |
| 1460 | if (amt < cleartext.len) { |
| 1461 | const rest = cleartext[amt..]; |
| 1462 | c.partial_cleartext_idx = 0; |
| 1463 | c.partial_ciphertext_idx = @intCast(rest.len); |
| 1464 | @memcpy(c.partially_read_buffer[0..rest.len], rest); |
| 1465 | } |
| 1466 | } |
| 1467 | } else { |
| 1468 | // Output buffer was used directly which means no |
| 1469 | // memory copying needs to occur, and we can move |
| 1470 | // on to the next ciphertext record. |
| 1471 | vp.next(cleartext.len); |
| 1472 | } |
| 1260 | 1473 | }, |
| 1474 | else => return error.TlsUnexpectedMessage, |
| 1261 | 1475 | } |
| 1262 | 1476 | in = end; |
| 1263 | 1477 | } |
| ... | ... | @@ -1326,6 +1540,74 @@ inline fn big(x: anytype) @TypeOf(x) { |
| 1326 | 1540 | }; |
| 1327 | 1541 | } |
| 1328 | 1542 | |
| 1543 | const KeyShare = struct { |
| 1544 | x25519_kp: crypto.dh.X25519.KeyPair, |
| 1545 | secp256r1_kp: crypto.sign.ecdsa.EcdsaP256Sha256.KeyPair, |
| 1546 | ml_kem768_kp: crypto.kem.ml_kem.MLKem768.KeyPair, |
| 1547 | sk_buf: [sk_max_len]u8, |
| 1548 | sk_len: std.math.IntFittingRange(0, sk_max_len), |
| 1549 | |
| 1550 | const sk_max_len = @max( |
| 1551 | crypto.dh.X25519.shared_length + crypto.kem.ml_kem.MLKem768.shared_length, |
| 1552 | crypto.dh.X25519.shared_length, |
| 1553 | crypto.ecc.P256.scalar.encoded_length, |
| 1554 | ); |
| 1555 | |
| 1556 | fn init(seed: [64]u8) error{IdentityElement}!KeyShare { |
| 1557 | return .{ |
| 1558 | .x25519_kp = try .create(seed[0..32].*), |
| 1559 | .secp256r1_kp = try .create(seed[32..64].*), |
| 1560 | .ml_kem768_kp = try .create(null), |
| 1561 | .sk_buf = undefined, |
| 1562 | .sk_len = 0, |
| 1563 | }; |
| 1564 | } |
| 1565 | |
| 1566 | fn exchange( |
| 1567 | ks: *KeyShare, |
| 1568 | named_group: tls.NamedGroup, |
| 1569 | server_pub_key: []const u8, |
| 1570 | ) error{ TlsIllegalParameter, TlsDecryptFailure }!void { |
| 1571 | switch (named_group) { |
| 1572 | .x25519_ml_kem768 => { |
| 1573 | const xksl = crypto.dh.X25519.public_length; |
| 1574 | const hksl = xksl + crypto.kem.ml_kem.MLKem768.ciphertext_length; |
| 1575 | if (server_pub_key.len != hksl) return error.TlsIllegalParameter; |
| 1576 | |
| 1577 | const xsk = crypto.dh.X25519.scalarmult(ks.x25519_kp.secret_key, server_pub_key[0..xksl].*) catch |
| 1578 | return error.TlsDecryptFailure; |
| 1579 | const hsk = ks.ml_kem768_kp.secret_key.decaps(server_pub_key[xksl..hksl]) catch |
| 1580 | return error.TlsDecryptFailure; |
| 1581 | @memcpy(ks.sk_buf[0..xsk.len], &xsk); |
| 1582 | @memcpy(ks.sk_buf[xsk.len..][0..hsk.len], &hsk); |
| 1583 | ks.sk_len = xsk.len + hsk.len; |
| 1584 | }, |
| 1585 | .x25519 => { |
| 1586 | const ksl = crypto.dh.X25519.public_length; |
| 1587 | if (server_pub_key.len != ksl) return error.TlsIllegalParameter; |
| 1588 | const sk = crypto.dh.X25519.scalarmult(ks.x25519_kp.secret_key, server_pub_key[0..ksl].*) catch |
| 1589 | return error.TlsDecryptFailure; |
| 1590 | @memcpy(ks.sk_buf[0..sk.len], &sk); |
| 1591 | ks.sk_len = sk.len; |
| 1592 | }, |
| 1593 | .secp256r1 => { |
| 1594 | const PublicKey = crypto.sign.ecdsa.EcdsaP256Sha256.PublicKey; |
| 1595 | const pk = PublicKey.fromSec1(server_pub_key) catch return error.TlsDecryptFailure; |
| 1596 | const mul = pk.p.mulPublic(ks.secp256r1_kp.secret_key.bytes, .big) catch |
| 1597 | return error.TlsDecryptFailure; |
| 1598 | const sk = mul.affineCoordinates().x.toBytes(.big); |
| 1599 | @memcpy(ks.sk_buf[0..sk.len], &sk); |
| 1600 | ks.sk_len = sk.len; |
| 1601 | }, |
| 1602 | else => return error.TlsIllegalParameter, |
| 1603 | } |
| 1604 | } |
| 1605 | |
| 1606 | fn getSharedSecret(ks: *const KeyShare) ?[]const u8 { |
| 1607 | return if (ks.sk_len > 0) ks.sk_buf[0..ks.sk_len] else null; |
| 1608 | } |
| 1609 | }; |
| 1610 | |
| 1329 | 1611 | fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { |
| 1330 | 1612 | return switch (scheme) { |
| 1331 | 1613 | .ecdsa_secp256r1_sha256 => crypto.sign.ecdsa.EcdsaP256Sha256, |
| ... | ... | @@ -1334,11 +1616,20 @@ fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { |
| 1334 | 1616 | }; |
| 1335 | 1617 | } |
| 1336 | 1618 | |
| 1337 | | fn SchemeHash(comptime scheme: tls.SignatureScheme) type { |
| 1619 | fn SchemeRsa(comptime scheme: tls.SignatureScheme) type { |
| 1338 | 1620 | return switch (scheme) { |
| 1339 | | .rsa_pss_rsae_sha256 => crypto.hash.sha2.Sha256, |
| 1340 | | .rsa_pss_rsae_sha384 => crypto.hash.sha2.Sha384, |
| 1341 | | .rsa_pss_rsae_sha512 => crypto.hash.sha2.Sha512, |
| 1621 | .rsa_pkcs1_sha256, |
| 1622 | .rsa_pkcs1_sha384, |
| 1623 | .rsa_pkcs1_sha512, |
| 1624 | .rsa_pkcs1_sha1, |
| 1625 | => Certificate.rsa.PKCS1v1_5Signature, |
| 1626 | .rsa_pss_rsae_sha256, |
| 1627 | .rsa_pss_rsae_sha384, |
| 1628 | .rsa_pss_rsae_sha512, |
| 1629 | .rsa_pss_pss_sha256, |
| 1630 | .rsa_pss_pss_sha384, |
| 1631 | .rsa_pss_pss_sha512, |
| 1632 | => Certificate.rsa.PSSSignature, |
| 1342 | 1633 | else => @compileError("bad scheme"), |
| 1343 | 1634 | }; |
| 1344 | 1635 | } |
| ... | ... | @@ -1350,6 +1641,142 @@ fn SchemeEddsa(comptime scheme: tls.SignatureScheme) type { |
| 1350 | 1641 | }; |
| 1351 | 1642 | } |
| 1352 | 1643 | |
| 1644 | fn SchemeHash(comptime scheme: tls.SignatureScheme) type { |
| 1645 | return switch (scheme) { |
| 1646 | .rsa_pkcs1_sha256, |
| 1647 | .ecdsa_secp256r1_sha256, |
| 1648 | .rsa_pss_rsae_sha256, |
| 1649 | .rsa_pss_pss_sha256, |
| 1650 | => crypto.hash.sha2.Sha256, |
| 1651 | .rsa_pkcs1_sha384, |
| 1652 | .ecdsa_secp384r1_sha384, |
| 1653 | .rsa_pss_rsae_sha384, |
| 1654 | .rsa_pss_pss_sha384, |
| 1655 | => crypto.hash.sha2.Sha384, |
| 1656 | .rsa_pkcs1_sha512, |
| 1657 | .ecdsa_secp521r1_sha512, |
| 1658 | .rsa_pss_rsae_sha512, |
| 1659 | .rsa_pss_pss_sha512, |
| 1660 | => crypto.hash.sha2.Sha512, |
| 1661 | .rsa_pkcs1_sha1, |
| 1662 | .ecdsa_sha1, |
| 1663 | => crypto.hash.Sha1, |
| 1664 | else => @compileError("bad scheme"), |
| 1665 | }; |
| 1666 | } |
| 1667 | |
| 1668 | const CertificatePublicKey = struct { |
| 1669 | algo: Certificate.AlgorithmCategory, |
| 1670 | buf: [600]u8, |
| 1671 | len: u16, |
| 1672 | |
| 1673 | fn init( |
| 1674 | cert_pub_key: *CertificatePublicKey, |
| 1675 | algo: Certificate.AlgorithmCategory, |
| 1676 | pub_key: []const u8, |
| 1677 | ) error{CertificatePublicKeyInvalid}!void { |
| 1678 | if (pub_key.len > cert_pub_key.buf.len) return error.CertificatePublicKeyInvalid; |
| 1679 | cert_pub_key.algo = algo; |
| 1680 | @memcpy(cert_pub_key.buf[0..pub_key.len], pub_key); |
| 1681 | cert_pub_key.len = @intCast(pub_key.len); |
| 1682 | } |
| 1683 | |
| 1684 | const VerifyError = error{ TlsDecodeError, TlsBadSignatureScheme, InvalidEncoding } || |
| 1685 | // ecdsa |
| 1686 | crypto.errors.EncodingError || |
| 1687 | crypto.errors.NotSquareError || |
| 1688 | crypto.errors.NonCanonicalError || |
| 1689 | SchemeEcdsa(.ecdsa_secp256r1_sha256).Signature.VerifyError || |
| 1690 | SchemeEcdsa(.ecdsa_secp384r1_sha384).Signature.VerifyError || |
| 1691 | // rsa |
| 1692 | error{TlsBadRsaSignatureBitCount} || |
| 1693 | Certificate.rsa.PublicKey.ParseDerError || |
| 1694 | Certificate.rsa.PublicKey.FromBytesError || |
| 1695 | Certificate.rsa.PSSSignature.VerifyError || |
| 1696 | Certificate.rsa.PKCS1v1_5Signature.VerifyError || |
| 1697 | // eddsa |
| 1698 | SchemeEddsa(.ed25519).Signature.VerifyError; |
| 1699 | |
| 1700 | fn verifySignature( |
| 1701 | cert_pub_key: *const CertificatePublicKey, |
| 1702 | sigd: *tls.Decoder, |
| 1703 | msg: []const []const u8, |
| 1704 | ) VerifyError!void { |
| 1705 | const pub_key = cert_pub_key.buf[0..cert_pub_key.len]; |
| 1706 | |
| 1707 | try sigd.ensure(2 + 2); |
| 1708 | const scheme = sigd.decode(tls.SignatureScheme); |
| 1709 | const sig_len = sigd.decode(u16); |
| 1710 | try sigd.ensure(sig_len); |
| 1711 | const encoded_sig = sigd.slice(sig_len); |
| 1712 | |
| 1713 | if (cert_pub_key.algo != @as(Certificate.AlgorithmCategory, switch (scheme) { |
| 1714 | .ecdsa_secp256r1_sha256, |
| 1715 | .ecdsa_secp384r1_sha384, |
| 1716 | => .X9_62_id_ecPublicKey, |
| 1717 | .rsa_pkcs1_sha256, |
| 1718 | .rsa_pkcs1_sha384, |
| 1719 | .rsa_pkcs1_sha512, |
| 1720 | .rsa_pss_rsae_sha256, |
| 1721 | .rsa_pss_rsae_sha384, |
| 1722 | .rsa_pss_rsae_sha512, |
| 1723 | .rsa_pkcs1_sha1, |
| 1724 | => .rsaEncryption, |
| 1725 | .rsa_pss_pss_sha256, |
| 1726 | .rsa_pss_pss_sha384, |
| 1727 | .rsa_pss_pss_sha512, |
| 1728 | => .rsassa_pss, |
| 1729 | else => return error.TlsBadSignatureScheme, |
| 1730 | })) return error.TlsBadSignatureScheme; |
| 1731 | |
| 1732 | switch (scheme) { |
| 1733 | inline .ecdsa_secp256r1_sha256, |
| 1734 | .ecdsa_secp384r1_sha384, |
| 1735 | => |comptime_scheme| { |
| 1736 | const Ecdsa = SchemeEcdsa(comptime_scheme); |
| 1737 | const sig = try Ecdsa.Signature.fromDer(encoded_sig); |
| 1738 | const key = try Ecdsa.PublicKey.fromSec1(pub_key); |
| 1739 | try sig.concatVerify(msg, key); |
| 1740 | }, |
| 1741 | inline .rsa_pkcs1_sha256, |
| 1742 | .rsa_pkcs1_sha384, |
| 1743 | .rsa_pkcs1_sha512, |
| 1744 | .rsa_pss_rsae_sha256, |
| 1745 | .rsa_pss_rsae_sha384, |
| 1746 | .rsa_pss_rsae_sha512, |
| 1747 | .rsa_pss_pss_sha256, |
| 1748 | .rsa_pss_pss_sha384, |
| 1749 | .rsa_pss_pss_sha512, |
| 1750 | .rsa_pkcs1_sha1, |
| 1751 | => |comptime_scheme| { |
| 1752 | const RsaSignature = SchemeRsa(comptime_scheme); |
| 1753 | const Hash = SchemeHash(comptime_scheme); |
| 1754 | const PublicKey = Certificate.rsa.PublicKey; |
| 1755 | const components = try PublicKey.parseDer(pub_key); |
| 1756 | const exponent = components.exponent; |
| 1757 | const modulus = components.modulus; |
| 1758 | switch (modulus.len) { |
| 1759 | inline 128, 256, 512 => |modulus_len| { |
| 1760 | const key: PublicKey = try .fromBytes(exponent, modulus); |
| 1761 | const sig = RsaSignature.fromBytes(modulus_len, encoded_sig); |
| 1762 | try RsaSignature.concatVerify(modulus_len, sig, msg, key, Hash); |
| 1763 | }, |
| 1764 | else => return error.TlsBadRsaSignatureBitCount, |
| 1765 | } |
| 1766 | }, |
| 1767 | inline .ed25519 => |comptime_scheme| { |
| 1768 | const Eddsa = SchemeEddsa(comptime_scheme); |
| 1769 | if (encoded_sig.len != Eddsa.Signature.encoded_length) return error.InvalidEncoding; |
| 1770 | const sig = Eddsa.Signature.fromBytes(encoded_sig[0..Eddsa.Signature.encoded_length].*); |
| 1771 | if (pub_key.len != Eddsa.PublicKey.encoded_length) return error.InvalidEncoding; |
| 1772 | const key = try Eddsa.PublicKey.fromBytes(pub_key[0..Eddsa.PublicKey.encoded_length].*); |
| 1773 | try sig.concatVerify(msg, key); |
| 1774 | }, |
| 1775 | else => unreachable, |
| 1776 | } |
| 1777 | } |
| 1778 | }; |
| 1779 | |
| 1353 | 1780 | /// Abstraction for sending multiple byte buffers to a slice of iovecs. |
| 1354 | 1781 | const VecPut = struct { |
| 1355 | 1782 | iovecs: []const std.posix.iovec, |
| ... | ... | @@ -1451,16 +1878,22 @@ const cipher_suites = if (crypto.core.aes.has_hardware_support) |
| 1451 | 1878 | .AEGIS_128L_SHA256, |
| 1452 | 1879 | .AEGIS_256_SHA512, |
| 1453 | 1880 | .AES_128_GCM_SHA256, |
| 1881 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1454 | 1882 | .AES_256_GCM_SHA384, |
| 1883 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1455 | 1884 | .CHACHA20_POLY1305_SHA256, |
| 1885 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 1456 | 1886 | }) |
| 1457 | 1887 | else |
| 1458 | 1888 | enum_array(tls.CipherSuite, &.{ |
| 1459 | 1889 | .CHACHA20_POLY1305_SHA256, |
| 1890 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 1460 | 1891 | .AEGIS_128L_SHA256, |
| 1461 | 1892 | .AEGIS_256_SHA512, |
| 1462 | 1893 | .AES_128_GCM_SHA256, |
| 1894 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1463 | 1895 | .AES_256_GCM_SHA384, |
| 1896 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1464 | 1897 | }); |
| 1465 | 1898 | |
| 1466 | 1899 | test { |