| ... | @@ -8,12 +8,12 @@ const assert = std.debug.assert; | ... | @@ -8,12 +8,12 @@ const assert = std.debug.assert; |
| 8 | const Certificate = std.crypto.Certificate; | 8 | const Certificate = std.crypto.Certificate; |
| 9 | | 9 | |
| 10 | const max_ciphertext_len = tls.max_ciphertext_len; | 10 | const max_ciphertext_len = tls.max_ciphertext_len; |
| | 11 | const hmacExpandLabel = tls.hmacExpandLabel; |
| 11 | const hkdfExpandLabel = tls.hkdfExpandLabel; | 12 | const hkdfExpandLabel = tls.hkdfExpandLabel; |
| 12 | const int2 = tls.int2; | 13 | const int = tls.int; |
| 13 | const int3 = tls.int3; | | |
| 14 | const array = tls.array; | 14 | const array = tls.array; |
| 15 | const enum_array = tls.enum_array; | | |
| 16 | | 15 | |
| | 16 | tls_version: tls.ProtocolVersion, |
| 17 | read_seq: u64, | 17 | read_seq: u64, |
| 18 | write_seq: u64, | 18 | write_seq: u64, |
| 19 | /// The starting index of cleartext bytes inside `partially_read_buffer`. | 19 | /// The starting index of cleartext bytes inside `partially_read_buffer`. |
| ... | @@ -33,7 +33,7 @@ received_close_notify: bool, | ... | @@ -33,7 +33,7 @@ received_close_notify: bool, |
| 33 | /// This makes the application vulnerable to truncation attacks unless the | 33 | /// This makes the application vulnerable to truncation attacks unless the |
| 34 | /// application layer itself verifies that the amount of data received equals | 34 | /// application layer itself verifies that the amount of data received equals |
| 35 | /// the amount of data expected, such as HTTP with the Content-Length header. | 35 | /// the amount of data expected, such as HTTP with the Content-Length header. |
| 36 | allow_truncation_attacks: bool = false, | 36 | allow_truncation_attacks: bool, |
| 37 | application_cipher: tls.ApplicationCipher, | 37 | application_cipher: tls.ApplicationCipher, |
| 38 | /// The size is enough to contain exactly one TLSCiphertext record. | 38 | /// The size is enough to contain exactly one TLSCiphertext record. |
| 39 | /// This buffer is segmented into four parts: | 39 | /// This buffer is segmented into four parts: |
| ... | @@ -44,6 +44,24 @@ application_cipher: tls.ApplicationCipher, | ... | @@ -44,6 +44,24 @@ application_cipher: tls.ApplicationCipher, |
| 44 | /// The fields `partial_cleartext_idx`, `partial_ciphertext_idx`, and | 44 | /// The fields `partial_cleartext_idx`, `partial_ciphertext_idx`, and |
| 45 | /// `partial_ciphertext_end` describe the span of the segments. | 45 | /// `partial_ciphertext_end` describe the span of the segments. |
| 46 | partially_read_buffer: [tls.max_ciphertext_record_len]u8, | 46 | partially_read_buffer: [tls.max_ciphertext_record_len]u8, |
| | 47 | /// If non-null, ssl secrets are logged to a file. Creating such a log file allows other |
| | 48 | /// programs with access to that file to decrypt all traffic over this connection. |
| | 49 | ssl_key_log: ?struct { |
| | 50 | client_key_seq: u64, |
| | 51 | server_key_seq: u64, |
| | 52 | client_random: [32]u8, |
| | 53 | file: std.fs.File, |
| | 54 | |
| | 55 | fn clientCounter(key_log: *@This()) u64 { |
| | 56 | defer key_log.client_key_seq += 1; |
| | 57 | return key_log.client_key_seq; |
| | 58 | } |
| | 59 | |
| | 60 | fn serverCounter(key_log: *@This()) u64 { |
| | 61 | defer key_log.server_key_seq += 1; |
| | 62 | return key_log.server_key_seq; |
| | 63 | } |
| | 64 | }, |
| 47 | | 65 | |
| 48 | /// This is an example of the type that is needed by the read and write | 66 | /// This is an example of the type that is needed by the read and write |
| 49 | /// functions. It can have any fields but it must at least have these | 67 | /// functions. It can have any fields but it must at least have these |
| ... | @@ -88,6 +106,32 @@ pub const StreamInterface = struct { | ... | @@ -88,6 +106,32 @@ pub const StreamInterface = struct { |
| 88 | } | 106 | } |
| 89 | }; | 107 | }; |
| 90 | | 108 | |
| | 109 | pub const Options = struct { |
| | 110 | /// How to perform host verification of server certificates. |
| | 111 | host: union(enum) { |
| | 112 | /// No host verification is performed, which prevents a trusted connection from |
| | 113 | /// being established. |
| | 114 | no_verification, |
| | 115 | /// Verify that the server certificate was issues for a given host. |
| | 116 | explicit: []const u8, |
| | 117 | }, |
| | 118 | /// How to verify the authenticity of server certificates. |
| | 119 | ca: union(enum) { |
| | 120 | /// No ca verification is performed, which prevents a trusted connection from |
| | 121 | /// being established. |
| | 122 | no_verification, |
| | 123 | /// Verify that the server certificate is a valid self-signed certificate. |
| | 124 | /// This provides no authorization guarantees, as anyone can create a |
| | 125 | /// self-signed certificate. |
| | 126 | self_signed, |
| | 127 | /// Verify that the server certificate is authorized by a given ca bundle. |
| | 128 | bundle: Certificate.Bundle, |
| | 129 | }, |
| | 130 | /// If non-null, ssl secrets are logged to this file. Creating such a log file allows |
| | 131 | /// other programs with access to that file to decrypt all traffic over this connection. |
| | 132 | ssl_key_log_file: ?std.fs.File = null, |
| | 133 | }; |
| | 134 | |
| 91 | pub fn InitError(comptime Stream: type) type { | 135 | pub fn InitError(comptime Stream: type) type { |
| 92 | return std.mem.Allocator.Error || Stream.WriteError || Stream.ReadError || tls.AlertDescription.Error || error{ | 136 | return std.mem.Allocator.Error || Stream.WriteError || Stream.ReadError || tls.AlertDescription.Error || error{ |
| 93 | InsufficientEntropy, | 137 | InsufficientEntropy, |
| ... | @@ -136,326 +180,186 @@ pub fn InitError(comptime Stream: type) type { | ... | @@ -136,326 +180,186 @@ pub fn InitError(comptime Stream: type) type { |
| 136 | }; | 180 | }; |
| 137 | } | 181 | } |
| 138 | | 182 | |
| 139 | /// Initiates a TLS handshake and establishes a TLSv1.3 session with `stream`, which | 183 | /// Initiates a TLS handshake and establishes a TLSv1.2 or TLSv1.3 session with `stream`, which |
| 140 | /// must conform to `StreamInterface`. | 184 | /// must conform to `StreamInterface`. |
| 141 | /// | 185 | /// |
| 142 | /// `host` is only borrowed during this function call. | 186 | /// `host` is only borrowed during this function call. |
| 143 | pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) InitError(@TypeOf(stream))!Client { | 187 | pub fn init(stream: anytype, options: Options) InitError(@TypeOf(stream))!Client { |
| | 188 | const host = switch (options.host) { |
| | 189 | .no_verification => "", |
| | 190 | .explicit => |host| host, |
| | 191 | }; |
| 144 | const host_len: u16 = @intCast(host.len); | 192 | const host_len: u16 = @intCast(host.len); |
| 145 | | 193 | |
| 146 | var random_buffer: [128]u8 = undefined; | 194 | var random_buffer: [176]u8 = undefined; |
| 147 | crypto.random.bytes(&random_buffer); | 195 | crypto.random.bytes(&random_buffer); |
| 148 | const hello_rand = random_buffer[0..32].*; | 196 | const client_hello_rand = random_buffer[0..32].*; |
| | 197 | var key_seq: u64 = 0; |
| | 198 | var server_hello_rand: [32]u8 = undefined; |
| 149 | const legacy_session_id = random_buffer[32..64].*; | 199 | 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 | | 200 | |
| 153 | const x25519_kp = crypto.dh.X25519.KeyPair.create(x25519_kp_seed) catch |err| switch (err) { | 201 | var key_share = KeyShare.init(random_buffer[64..176].*) catch |err| switch (err) { |
| 154 | // Only possible to happen if the private key is all zeroes. | 202 | // Only possible to happen if the seed is all zeroes. |
| 155 | error.IdentityElement => return error.InsufficientEntropy, | | |
| 156 | }; | | |
| 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, | 203 | error.IdentityElement => return error.InsufficientEntropy, |
| 160 | }; | 204 | }; |
| 161 | const ml_kem768_kp = crypto.kem.ml_kem.MLKem768.KeyPair.create(null) catch {}; | | |
| 162 | | 205 | |
| 163 | const extensions_payload = | 206 | const extensions_payload = tls.extension(.supported_versions, array(u8, tls.ProtocolVersion, .{ |
| 164 | tls.extension(.supported_versions, [_]u8{ | 207 | .tls_1_3, |
| 165 | 0x02, // byte length of supported versions | 208 | .tls_1_2, |
| 166 | 0x03, 0x04, // TLS 1.3 | 209 | })) ++ tls.extension(.signature_algorithms, array(u16, tls.SignatureScheme, .{ |
| 167 | }) ++ tls.extension(.signature_algorithms, enum_array(tls.SignatureScheme, &.{ | | |
| 168 | .ecdsa_secp256r1_sha256, | 210 | .ecdsa_secp256r1_sha256, |
| 169 | .ecdsa_secp384r1_sha384, | 211 | .ecdsa_secp384r1_sha384, |
| | 212 | .rsa_pkcs1_sha256, |
| | 213 | .rsa_pkcs1_sha384, |
| | 214 | .rsa_pkcs1_sha512, |
| 170 | .rsa_pss_rsae_sha256, | 215 | .rsa_pss_rsae_sha256, |
| 171 | .rsa_pss_rsae_sha384, | 216 | .rsa_pss_rsae_sha384, |
| 172 | .rsa_pss_rsae_sha512, | 217 | .rsa_pss_rsae_sha512, |
| | 218 | .rsa_pss_pss_sha256, |
| | 219 | .rsa_pss_pss_sha384, |
| | 220 | .rsa_pss_pss_sha512, |
| | 221 | .rsa_pkcs1_sha1, |
| 173 | .ed25519, | 222 | .ed25519, |
| 174 | })) ++ tls.extension(.supported_groups, enum_array(tls.NamedGroup, &.{ | 223 | })) ++ tls.extension(.supported_groups, array(u16, tls.NamedGroup, .{ |
| 175 | .x25519_ml_kem768, | 224 | .x25519_ml_kem768, |
| 176 | .secp256r1, | 225 | .secp256r1, |
| | 226 | .secp384r1, |
| 177 | .x25519, | 227 | .x25519, |
| 178 | })) ++ tls.extension( | 228 | })) ++ tls.extension(.psk_key_exchange_modes, array(u8, tls.PskKeyExchangeMode, .{ |
| 179 | .key_share, | 229 | .psk_dhe_ke, |
| 180 | array(1, int2(@intFromEnum(tls.NamedGroup.x25519)) ++ | 230 | })) ++ tls.extension(.key_share, array( |
| 181 | array(1, x25519_kp.public_key) ++ | 231 | u16, |
| 182 | int2(@intFromEnum(tls.NamedGroup.secp256r1)) ++ | 232 | u8, |
| 183 | array(1, secp256r1_kp.public_key.toUncompressedSec1()) ++ | 233 | int(u16, @intFromEnum(tls.NamedGroup.x25519_ml_kem768)) ++ |
| 184 | int2(@intFromEnum(tls.NamedGroup.x25519_ml_kem768)) ++ | 234 | array(u16, u8, key_share.ml_kem768_kp.public_key.toBytes() ++ key_share.x25519_kp.public_key) ++ |
| 185 | array(1, x25519_kp.public_key ++ ml_kem768_kp.public_key.toBytes())), | 235 | int(u16, @intFromEnum(tls.NamedGroup.secp256r1)) ++ |
| 186 | ) ++ | 236 | array(u16, u8, key_share.secp256r1_kp.public_key.toUncompressedSec1()) ++ |
| 187 | int2(@intFromEnum(tls.ExtensionType.server_name)) ++ | 237 | int(u16, @intFromEnum(tls.NamedGroup.secp384r1)) ++ |
| 188 | int2(host_len + 5) ++ // byte length of this extension payload | 238 | array(u16, u8, key_share.secp384r1_kp.public_key.toUncompressedSec1()) ++ |
| 189 | int2(host_len + 3) ++ // server_name_list byte count | 239 | int(u16, @intFromEnum(tls.NamedGroup.x25519)) ++ |
| 190 | [1]u8{0x00} ++ // name_type | 240 | array(u16, u8, key_share.x25519_kp.public_key), |
| 191 | int2(host_len); | 241 | )); |
| | 242 | const server_name_extension = int(u16, @intFromEnum(tls.ExtensionType.server_name)) ++ |
| | 243 | int(u16, 2 + 1 + 2 + host_len) ++ // byte length of this extension payload |
| | 244 | int(u16, 1 + 2 + host_len) ++ // server_name_list byte count |
| | 245 | .{0x00} ++ // name_type |
| | 246 | int(u16, host_len); |
| | 247 | const server_name_extension_len = switch (options.host) { |
| | 248 | .no_verification => 0, |
| | 249 | .explicit => server_name_extension.len + host_len, |
| | 250 | }; |
| 192 | | 251 | |
| 193 | const extensions_header = | 252 | const extensions_header = |
| 194 | int2(@intCast(extensions_payload.len + host_len)) ++ | 253 | int(u16, @intCast(extensions_payload.len + server_name_extension_len)) ++ |
| 195 | extensions_payload; | 254 | extensions_payload ++ |
| 196 | | 255 | server_name_extension; |
| 197 | const legacy_compression_methods = 0x0100; | | |
| 198 | | 256 | |
| 199 | const client_hello = | 257 | const client_hello = |
| 200 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ | 258 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 201 | hello_rand ++ | 259 | client_hello_rand ++ |
| 202 | [1]u8{32} ++ legacy_session_id ++ | 260 | [1]u8{32} ++ legacy_session_id ++ |
| 203 | cipher_suites ++ | 261 | cipher_suites ++ |
| 204 | int2(legacy_compression_methods) ++ | 262 | array(u8, tls.CompressionMethod, .{.null}) ++ |
| 205 | extensions_header; | 263 | extensions_header; |
| 206 | | 264 | |
| 207 | const out_handshake = | 265 | const out_handshake = .{@intFromEnum(tls.HandshakeType.client_hello)} ++ |
| 208 | [_]u8{@intFromEnum(tls.HandshakeType.client_hello)} ++ | 266 | int(u24, @intCast(client_hello.len - server_name_extension.len + server_name_extension_len)) ++ |
| 209 | int3(@intCast(client_hello.len + host_len)) ++ | | |
| 210 | client_hello; | 267 | client_hello; |
| 211 | | 268 | |
| 212 | const plaintext_header = [_]u8{ | 269 | const cleartext_header_buf = .{@intFromEnum(tls.ContentType.handshake)} ++ |
| 213 | @intFromEnum(tls.ContentType.handshake), | 270 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_0)) ++ |
| 214 | 0x03, 0x01, // legacy_record_version | 271 | int(u16, @intCast(out_handshake.len - server_name_extension.len + server_name_extension_len)) ++ |
| 215 | } ++ int2(@intCast(out_handshake.len + host_len)) ++ out_handshake; | 272 | out_handshake; |
| | 273 | const cleartext_header = switch (options.host) { |
| | 274 | .no_verification => cleartext_header_buf[0 .. cleartext_header_buf.len - server_name_extension.len], |
| | 275 | .explicit => &cleartext_header_buf, |
| | 276 | }; |
| 216 | | 277 | |
| 217 | { | 278 | { |
| 218 | var iovecs = [_]std.posix.iovec_const{ | 279 | var iovecs = [_]std.posix.iovec_const{ |
| 219 | .{ | 280 | .{ .base = cleartext_header.ptr, .len = cleartext_header.len }, |
| 220 | .base = &plaintext_header, | 281 | .{ .base = host.ptr, .len = host.len }, |
| 221 | .len = plaintext_header.len, | | |
| 222 | }, | | |
| 223 | .{ | | |
| 224 | .base = host.ptr, | | |
| 225 | .len = host.len, | | |
| 226 | }, | | |
| 227 | }; | 282 | }; |
| 228 | try stream.writevAll(&iovecs); | 283 | try stream.writevAll(iovecs[0..if (host.len == 0) 1 else 2]); |
| 229 | } | 284 | } |
| 230 | | 285 | |
| 231 | const client_hello_bytes1 = plaintext_header[5..]; | 286 | var tls_version: tls.ProtocolVersion = undefined; |
| 232 | | 287 | // These are used for two purposes: |
| 233 | var handshake_cipher: tls.HandshakeCipher = undefined; | | |
| 234 | var handshake_buffer: [8000]u8 = undefined; | | |
| 235 | var d: tls.Decoder = .{ .buf = &handshake_buffer }; | | |
| 236 | { | | |
| 237 | try d.readAtLeastOurAmt(stream, tls.record_header_len); | | |
| 238 | const ct = d.decode(tls.ContentType); | | |
| 239 | d.skip(2); // legacy_record_version | | |
| 240 | const record_len = d.decode(u16); | | |
| 241 | try d.readAtLeast(stream, record_len); | | |
| 242 | const server_hello_fragment = d.buf[d.idx..][0..record_len]; | | |
| 243 | var ptd = try d.sub(record_len); | | |
| 244 | switch (ct) { | | |
| 245 | .alert => { | | |
| 246 | try ptd.ensure(2); | | |
| 247 | const level = ptd.decode(tls.AlertLevel); | | |
| 248 | const desc = ptd.decode(tls.AlertDescription); | | |
| 249 | _ = level; | | |
| 250 | | | |
| 251 | // if this isn't a error alert, then it's a closure alert, which makes no sense in a handshake | | |
| 252 | try desc.toError(); | | |
| 253 | // TODO: handle server-side closures | | |
| 254 | return error.TlsUnexpectedMessage; | | |
| 255 | }, | | |
| 256 | .handshake => { | | |
| 257 | try ptd.ensure(4); | | |
| 258 | const handshake_type = ptd.decode(tls.HandshakeType); | | |
| 259 | if (handshake_type != .server_hello) return error.TlsUnexpectedMessage; | | |
| 260 | const length = ptd.decode(u24); | | |
| 261 | var hsd = try ptd.sub(length); | | |
| 262 | try hsd.ensure(2 + 32 + 1 + 32 + 2 + 1 + 2); | | |
| 263 | const legacy_version = hsd.decode(u16); | | |
| 264 | const random = hsd.array(32); | | |
| 265 | if (mem.eql(u8, random, &tls.hello_retry_request_sequence)) { | | |
| 266 | // This is a HelloRetryRequest message. This client implementation | | |
| 267 | // does not expect to get one. | | |
| 268 | return error.TlsUnexpectedMessage; | | |
| 269 | } | | |
| 270 | const legacy_session_id_echo_len = hsd.decode(u8); | | |
| 271 | if (legacy_session_id_echo_len != 32) return error.TlsIllegalParameter; | | |
| 272 | 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); | | |
| 276 | 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 => {}, | | |
| 343 | } | | |
| 344 | } | | |
| 345 | if (!have_shared_key) return error.TlsIllegalParameter; | | |
| 346 | | | |
| 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; | | |
| 350 | | | |
| 351 | switch (cipher_suite_tag) { | | |
| 352 | inline .AES_128_GCM_SHA256, | | |
| 353 | .AES_256_GCM_SHA384, | | |
| 354 | .CHACHA20_POLY1305_SHA256, | | |
| 355 | .AEGIS_256_SHA512, | | |
| 356 | .AEGIS_128L_SHA256, | | |
| 357 | => |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(.{}), | | |
| 369 | }); | | |
| 370 | const p = &@field(handshake_cipher, @tagName(tag)); | | |
| 371 | p.transcript_hash.update(client_hello_bytes1); // Client Hello part 1 | | |
| 372 | p.transcript_hash.update(host); // Client Hello part 2 | | |
| 373 | 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 | }, | | |
| 391 | else => { | | |
| 392 | return error.TlsIllegalParameter; | | |
| 393 | }, | | |
| 394 | } | | |
| 395 | }, | | |
| 396 | else => return error.TlsUnexpectedMessage, | | |
| 397 | } | | |
| 398 | } | | |
| 399 | | | |
| 400 | // This is used for two purposes: | | |
| 401 | // * Detect whether a certificate is the first one presented, in which case | 288 | // * Detect whether a certificate is the first one presented, in which case |
| 402 | // we need to verify the host name. | 289 | // we need to verify the host name. |
| | 290 | var cert_index: usize = 0; |
| 403 | // * Flip back and forth between the two cleartext buffers in order to keep | 291 | // * Flip back and forth between the two cleartext buffers in order to keep |
| 404 | // the previous certificate in memory so that it can be verified by the | 292 | // the previous certificate in memory so that it can be verified by the |
| 405 | // next one. | 293 | // next one. |
| 406 | var cert_index: usize = 0; | 294 | var cert_buf_index: usize = 0; |
| | 295 | var write_seq: u64 = 0; |
| 407 | var read_seq: u64 = 0; | 296 | var read_seq: u64 = 0; |
| 408 | var prev_cert: Certificate.Parsed = undefined; | 297 | var prev_cert: Certificate.Parsed = undefined; |
| 409 | // Set to true once a trust chain has been established from the first | 298 | const CipherState = enum { |
| 410 | // certificate to a root CA. | 299 | /// No cipher is in use |
| | 300 | cleartext, |
| | 301 | /// Handshake cipher is in use |
| | 302 | handshake, |
| | 303 | /// Application cipher is in use |
| | 304 | application, |
| | 305 | }; |
| | 306 | var pending_cipher_state: CipherState = .cleartext; |
| | 307 | var cipher_state = pending_cipher_state; |
| 411 | const HandshakeState = enum { | 308 | const HandshakeState = enum { |
| | 309 | /// In this state we expect only a server hello message. |
| | 310 | hello, |
| 412 | /// In this state we expect only an encrypted_extensions message. | 311 | /// In this state we expect only an encrypted_extensions message. |
| 413 | encrypted_extensions, | 312 | encrypted_extensions, |
| 414 | /// In this state we expect certificate messages. | 313 | /// In this state we expect certificate handshake messages. |
| 415 | certificate, | 314 | certificate, |
| 416 | /// In this state we expect certificate or certificate_verify messages. | 315 | /// In this state we expect certificate or certificate_verify messages. |
| 417 | /// certificate messages are ignored since the trust chain is already | 316 | /// certificate messages are ignored since the trust chain is already |
| 418 | /// established. | 317 | /// established. |
| 419 | trust_chain_established, | 318 | trust_chain_established, |
| 420 | /// In this state, we expect only the finished message. | 319 | /// In this state, we expect only the server_hello_done handshake message. |
| | 320 | server_hello_done, |
| | 321 | /// In this state, we expect only the finished handshake message. |
| 421 | finished, | 322 | finished, |
| 422 | }; | 323 | }; |
| 423 | var handshake_state: HandshakeState = .encrypted_extensions; | 324 | var handshake_state: HandshakeState = .hello; |
| 424 | var cleartext_bufs: [2][8000]u8 = undefined; | 325 | var handshake_cipher: tls.HandshakeCipher = undefined; |
| 425 | var main_cert_pub_key_algo: Certificate.AlgorithmCategory = undefined; | 326 | var main_cert_pub_key: CertificatePublicKey = undefined; |
| 426 | var main_cert_pub_key_buf: [600]u8 = undefined; | | |
| 427 | var main_cert_pub_key_len: u16 = undefined; | | |
| 428 | const now_sec = std.time.timestamp(); | 327 | const now_sec = std.time.timestamp(); |
| 429 | | 328 | |
| 430 | while (true) { | 329 | var cleartext_fragment_start: usize = 0; |
| | 330 | var cleartext_fragment_end: usize = 0; |
| | 331 | var cleartext_bufs: [2][tls.max_ciphertext_inner_record_len]u8 = undefined; |
| | 332 | var handshake_buffer: [tls.max_ciphertext_record_len]u8 = undefined; |
| | 333 | var d: tls.Decoder = .{ .buf = &handshake_buffer }; |
| | 334 | fragment: while (true) { |
| 431 | try d.readAtLeastOurAmt(stream, tls.record_header_len); | 335 | try d.readAtLeastOurAmt(stream, tls.record_header_len); |
| 432 | const record_header = d.buf[d.idx..][0..5]; | 336 | const record_header = d.buf[d.idx..][0..tls.record_header_len]; |
| 433 | const ct = d.decode(tls.ContentType); | 337 | const record_ct = d.decode(tls.ContentType); |
| 434 | d.skip(2); // legacy_version | 338 | d.skip(2); // legacy_version |
| 435 | const record_len = d.decode(u16); | 339 | const record_len = d.decode(u16); |
| 436 | try d.readAtLeast(stream, record_len); | 340 | try d.readAtLeast(stream, record_len); |
| 437 | var record_decoder = try d.sub(record_len); | 341 | var record_decoder = try d.sub(record_len); |
| 438 | switch (ct) { | 342 | var ctd, const ct = content: switch (cipher_state) { |
| 439 | .change_cipher_spec => { | 343 | .cleartext => .{ record_decoder, record_ct }, |
| 440 | try record_decoder.ensure(1); | 344 | .handshake => { |
| 441 | if (record_decoder.decode(u8) != 0x01) return error.TlsIllegalParameter; | 345 | std.debug.assert(tls_version == .tls_1_3); |
| 442 | }, | 346 | if (record_ct != .application_data) return error.TlsUnexpectedMessage; |
| 443 | .application_data => { | 347 | try record_decoder.ensure(record_len); |
| 444 | const cleartext_buf = &cleartext_bufs[cert_index % 2]; | 348 | const cleartext_buf = &cleartext_bufs[cert_buf_index % 2]; |
| 445 | | 349 | switch (handshake_cipher) { |
| 446 | const cleartext = switch (handshake_cipher) { | 350 | inline else => |*p| { |
| 447 | inline else => |*p| c: { | 351 | const pv = &p.version.tls_1_3; |
| 448 | const P = @TypeOf(p.*); | 352 | const P = @TypeOf(p.*).A; |
| 449 | const ciphertext_len = record_len - P.AEAD.tag_length; | 353 | if (record_len < P.AEAD.tag_length) return error.TlsRecordOverflow; |
| 450 | try record_decoder.ensure(ciphertext_len + P.AEAD.tag_length); | 354 | const ciphertext = record_decoder.slice(record_len - P.AEAD.tag_length); |
| 451 | const ciphertext = record_decoder.slice(ciphertext_len); | 355 | const cleartext_fragment_buf = cleartext_buf[cleartext_fragment_end..]; |
| 452 | if (ciphertext.len > cleartext_buf.len) return error.TlsRecordOverflow; | 356 | if (ciphertext.len > cleartext_fragment_buf.len) return error.TlsRecordOverflow; |
| 453 | const cleartext = cleartext_buf[0..ciphertext.len]; | 357 | const cleartext = cleartext_fragment_buf[0..ciphertext.len]; |
| 454 | const auth_tag = record_decoder.array(P.AEAD.tag_length).*; | 358 | const auth_tag = record_decoder.array(P.AEAD.tag_length).*; |
| 455 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and | 359 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 456 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) | 360 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 457 | nonce: { | 361 | nonce: { |
| 458 | var nonce = p.server_handshake_iv; | 362 | var nonce = pv.server_handshake_iv; |
| 459 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); | 363 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 460 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ read_seq, .big); | 364 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ read_seq, .big); |
| 461 | break :nonce nonce; | 365 | break :nonce nonce; |
| ... | @@ -463,268 +367,559 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In | ... | @@ -463,268 +367,559 @@ pub fn init(stream: anytype, ca_bundle: Certificate.Bundle, host: []const u8) In |
| 463 | const V = @Vector(P.AEAD.nonce_length, u8); | 367 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 464 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); | 368 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 465 | const operand: V = pad ++ @as([8]u8, @bitCast(big(read_seq))); | 369 | const operand: V = pad ++ @as([8]u8, @bitCast(big(read_seq))); |
| 466 | break :nonce @as(V, p.server_handshake_iv) ^ operand; | 370 | break :nonce @as(V, pv.server_handshake_iv) ^ operand; |
| 467 | }; | 371 | }; |
| 468 | read_seq += 1; | 372 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, record_header, nonce, pv.server_handshake_key) catch |
| 469 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, record_header, nonce, p.server_handshake_key) catch | | |
| 470 | return error.TlsBadRecordMac; | 373 | return error.TlsBadRecordMac; |
| 471 | break :c @constCast(mem.trimRight(u8, cleartext, "\x00")); | 374 | cleartext_fragment_end += std.mem.trimRight(u8, cleartext, "\x00").len; |
| 472 | }, | 375 | }, |
| 473 | }; | 376 | } |
| 474 | | 377 | read_seq += 1; |
| 475 | const inner_ct: tls.ContentType = @enumFromInt(cleartext[cleartext.len - 1]); | 378 | cleartext_fragment_end -= 1; |
| 476 | if (inner_ct != .handshake) return error.TlsUnexpectedMessage; | 379 | const ct: tls.ContentType = @enumFromInt(cleartext_buf[cleartext_fragment_end]); |
| | 380 | if (ct != .handshake) return error.TlsUnexpectedMessage; |
| | 381 | break :content .{ tls.Decoder.fromTheirSlice(@constCast(cleartext_buf[cleartext_fragment_start..cleartext_fragment_end])), ct }; |
| | 382 | }, |
| | 383 | .application => { |
| | 384 | std.debug.assert(tls_version == .tls_1_2); |
| | 385 | if (record_ct != .handshake) return error.TlsUnexpectedMessage; |
| | 386 | try record_decoder.ensure(record_len); |
| | 387 | const cleartext_buf = &cleartext_bufs[cert_buf_index % 2]; |
| | 388 | switch (handshake_cipher) { |
| | 389 | inline else => |*p| { |
| | 390 | const pv = &p.version.tls_1_2; |
| | 391 | const P = @TypeOf(p.*).A; |
| | 392 | if (record_len < P.record_iv_length + P.mac_length) return error.TlsRecordOverflow; |
| | 393 | const message_len: u16 = record_len - P.record_iv_length - P.mac_length; |
| | 394 | const cleartext_fragment_buf = cleartext_buf[cleartext_fragment_end..]; |
| | 395 | if (message_len > cleartext_fragment_buf.len) return error.TlsRecordOverflow; |
| | 396 | const cleartext = cleartext_fragment_buf[0..message_len]; |
| | 397 | const ad = std.mem.toBytes(big(read_seq)) ++ |
| | 398 | record_header[0 .. 1 + 2] ++ |
| | 399 | std.mem.toBytes(big(message_len)); |
| | 400 | const record_iv = record_decoder.array(P.record_iv_length).*; |
| | 401 | const masked_read_seq = read_seq & |
| | 402 | comptime std.math.shl(u64, std.math.maxInt(u64), 8 * P.record_iv_length); |
| | 403 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| | 404 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| | 405 | nonce: { |
| | 406 | var nonce = pv.app_cipher.server_write_IV ++ record_iv; |
| | 407 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| | 408 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ masked_read_seq, .big); |
| | 409 | break :nonce nonce; |
| | 410 | } else nonce: { |
| | 411 | const V = @Vector(P.AEAD.nonce_length, u8); |
| | 412 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| | 413 | const operand: V = pad ++ @as([8]u8, @bitCast(big(masked_read_seq))); |
| | 414 | break :nonce @as(V, pv.app_cipher.server_write_IV ++ record_iv) ^ operand; |
| | 415 | }; |
| | 416 | const ciphertext = record_decoder.slice(message_len); |
| | 417 | const auth_tag = record_decoder.array(P.mac_length); |
| | 418 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag.*, ad, nonce, pv.app_cipher.server_write_key) catch return error.TlsBadRecordMac; |
| | 419 | cleartext_fragment_end += message_len; |
| | 420 | }, |
| | 421 | } |
| | 422 | read_seq += 1; |
| | 423 | break :content .{ tls.Decoder.fromTheirSlice(cleartext_buf[cleartext_fragment_start..cleartext_fragment_end]), record_ct }; |
| | 424 | }, |
| | 425 | }; |
| | 426 | switch (ct) { |
| | 427 | .alert => { |
| | 428 | ctd.ensure(2) catch continue :fragment; |
| | 429 | const level = ctd.decode(tls.AlertLevel); |
| | 430 | const desc = ctd.decode(tls.AlertDescription); |
| | 431 | _ = level; |
| 477 | | 432 | |
| 478 | var ctd = tls.Decoder.fromTheirSlice(cleartext[0 .. cleartext.len - 1]); | 433 | // if this isn't a error alert, then it's a closure alert, which makes no sense in a handshake |
| 479 | while (true) { | 434 | try desc.toError(); |
| 480 | try ctd.ensure(4); | 435 | // TODO: handle server-side closures |
| 481 | const handshake_type = ctd.decode(tls.HandshakeType); | 436 | return error.TlsUnexpectedMessage; |
| 482 | const handshake_len = ctd.decode(u24); | 437 | }, |
| 483 | var hsd = try ctd.sub(handshake_len); | 438 | .change_cipher_spec => { |
| 484 | const wrapped_handshake = ctd.buf[ctd.idx - handshake_len - 4 .. ctd.idx]; | 439 | ctd.ensure(1) catch continue :fragment; |
| 485 | const handshake = ctd.buf[ctd.idx - handshake_len .. ctd.idx]; | 440 | if (ctd.decode(tls.ChangeCipherSpecType) != .change_cipher_spec) return error.TlsIllegalParameter; |
| 486 | switch (handshake_type) { | 441 | cipher_state = pending_cipher_state; |
| 487 | .encrypted_extensions => { | 442 | }, |
| 488 | if (handshake_state != .encrypted_extensions) return error.TlsUnexpectedMessage; | 443 | .handshake => while (true) { |
| 489 | handshake_state = .certificate; | 444 | ctd.ensure(4) catch continue :fragment; |
| 490 | switch (handshake_cipher) { | 445 | const handshake_type = ctd.decode(tls.HandshakeType); |
| 491 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), | 446 | const handshake_len = ctd.decode(u24); |
| 492 | } | 447 | var hsd = ctd.sub(handshake_len) catch continue :fragment; |
| | 448 | const wrapped_handshake = ctd.buf[ctd.idx - handshake_len - 4 .. ctd.idx]; |
| | 449 | switch (handshake_type) { |
| | 450 | .server_hello => { |
| | 451 | if (cipher_state != .cleartext) return error.TlsUnexpectedMessage; |
| | 452 | if (handshake_state != .hello) return error.TlsUnexpectedMessage; |
| | 453 | try hsd.ensure(2 + 32 + 1); |
| | 454 | const legacy_version = hsd.decode(u16); |
| | 455 | @memcpy(&server_hello_rand, hsd.array(32)); |
| | 456 | if (mem.eql(u8, &server_hello_rand, &tls.hello_retry_request_sequence)) { |
| | 457 | // This is a HelloRetryRequest message. This client implementation |
| | 458 | // does not expect to get one. |
| | 459 | return error.TlsUnexpectedMessage; |
| | 460 | } |
| | 461 | const legacy_session_id_echo_len = hsd.decode(u8); |
| | 462 | try hsd.ensure(legacy_session_id_echo_len + 2 + 1); |
| | 463 | const legacy_session_id_echo = hsd.slice(legacy_session_id_echo_len); |
| | 464 | const cipher_suite_tag = hsd.decode(tls.CipherSuite); |
| | 465 | hsd.skip(1); // legacy_compression_method |
| | 466 | var supported_version: ?u16 = null; |
| | 467 | if (!hsd.eof()) { |
| 493 | try hsd.ensure(2); | 468 | try hsd.ensure(2); |
| 494 | const total_ext_size = hsd.decode(u16); | 469 | const extensions_size = hsd.decode(u16); |
| 495 | var all_extd = try hsd.sub(total_ext_size); | 470 | var all_extd = try hsd.sub(extensions_size); |
| 496 | while (!all_extd.eof()) { | 471 | while (!all_extd.eof()) { |
| 497 | try all_extd.ensure(4); | 472 | try all_extd.ensure(2 + 2); |
| 498 | const et = all_extd.decode(tls.ExtensionType); | 473 | const et = all_extd.decode(tls.ExtensionType); |
| 499 | const ext_size = all_extd.decode(u16); | 474 | const ext_size = all_extd.decode(u16); |
| 500 | const extd = try all_extd.sub(ext_size); | 475 | var extd = try all_extd.sub(ext_size); |
| 501 | _ = extd; | | |
| 502 | switch (et) { | 476 | switch (et) { |
| 503 | .server_name => {}, | 477 | .supported_versions => { |
| | 478 | if (supported_version) |_| return error.TlsIllegalParameter; |
| | 479 | try extd.ensure(2); |
| | 480 | supported_version = extd.decode(u16); |
| | 481 | }, |
| | 482 | .key_share => { |
| | 483 | if (key_share.getSharedSecret()) |_| return error.TlsIllegalParameter; |
| | 484 | try extd.ensure(4); |
| | 485 | const named_group = extd.decode(tls.NamedGroup); |
| | 486 | const key_size = extd.decode(u16); |
| | 487 | try extd.ensure(key_size); |
| | 488 | try key_share.exchange(named_group, extd.slice(key_size)); |
| | 489 | }, |
| 504 | else => {}, | 490 | else => {}, |
| 505 | } | 491 | } |
| 506 | } | 492 | } |
| 507 | }, | 493 | } |
| 508 | .certificate => cert: { | | |
| 509 | switch (handshake_cipher) { | | |
| 510 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), | | |
| 511 | } | | |
| 512 | switch (handshake_state) { | | |
| 513 | .certificate => {}, | | |
| 514 | .trust_chain_established => break :cert, | | |
| 515 | else => return error.TlsUnexpectedMessage, | | |
| 516 | } | | |
| 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 | | 494 | |
| 548 | if (ca_bundle.verify(subject, now_sec)) |_| { | 495 | tls_version = @enumFromInt(supported_version orelse legacy_version); |
| 549 | handshake_state = .trust_chain_established; | 496 | switch (tls_version) { |
| 550 | break :cert; | 497 | .tls_1_3 => if (!mem.eql(u8, legacy_session_id_echo, &legacy_session_id)) return error.TlsIllegalParameter, |
| 551 | } else |err| switch (err) { | 498 | .tls_1_2 => if (mem.eql(u8, server_hello_rand[24..31], "DOWNGRD") and |
| 552 | error.CertificateIssuerNotFound => {}, | 499 | server_hello_rand[31] >> 1 == 0x00) return error.TlsIllegalParameter, |
| 553 | else => |e| return e, | 500 | else => return error.TlsIllegalParameter, |
| 554 | } | 501 | } |
| 555 | | 502 | |
| 556 | prev_cert = subject; | 503 | switch (cipher_suite_tag) { |
| 557 | cert_index += 1; | 504 | inline .AES_128_GCM_SHA256, |
| | 505 | .AES_256_GCM_SHA384, |
| | 506 | .CHACHA20_POLY1305_SHA256, |
| | 507 | .AEGIS_256_SHA512, |
| | 508 | .AEGIS_128L_SHA256, |
| | 509 | |
| | 510 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| | 511 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| | 512 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| | 513 | => |tag| { |
| | 514 | handshake_cipher = @unionInit(tls.HandshakeCipher, @tagName(tag.with()), .{ |
| | 515 | .transcript_hash = .init(.{}), |
| | 516 | .version = undefined, |
| | 517 | }); |
| | 518 | const p = &@field(handshake_cipher, @tagName(tag.with())); |
| | 519 | p.transcript_hash.update(cleartext_header[tls.record_header_len..]); // Client Hello part 1 |
| | 520 | p.transcript_hash.update(host); // Client Hello part 2 |
| | 521 | p.transcript_hash.update(wrapped_handshake); |
| | 522 | }, |
| | 523 | |
| | 524 | else => return error.TlsIllegalParameter, |
| | 525 | } |
| | 526 | switch (tls_version) { |
| | 527 | .tls_1_3 => { |
| | 528 | switch (cipher_suite_tag) { |
| | 529 | inline .AES_128_GCM_SHA256, |
| | 530 | .AES_256_GCM_SHA384, |
| | 531 | .CHACHA20_POLY1305_SHA256, |
| | 532 | .AEGIS_256_SHA512, |
| | 533 | .AEGIS_128L_SHA256, |
| | 534 | => |tag| { |
| | 535 | const sk = key_share.getSharedSecret() orelse return error.TlsIllegalParameter; |
| | 536 | const p = &@field(handshake_cipher, @tagName(tag.with())); |
| | 537 | const P = @TypeOf(p.*).A; |
| | 538 | const hello_hash = p.transcript_hash.peek(); |
| | 539 | const zeroes = [1]u8{0} ** P.Hash.digest_length; |
| | 540 | const early_secret = P.Hkdf.extract(&[1]u8{0}, &zeroes); |
| | 541 | const empty_hash = tls.emptyHash(P.Hash); |
| | 542 | p.version = .{ .tls_1_3 = undefined }; |
| | 543 | const pv = &p.version.tls_1_3; |
| | 544 | const hs_derived_secret = hkdfExpandLabel(P.Hkdf, early_secret, "derived", &empty_hash, P.Hash.digest_length); |
| | 545 | pv.handshake_secret = P.Hkdf.extract(&hs_derived_secret, sk); |
| | 546 | const ap_derived_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "derived", &empty_hash, P.Hash.digest_length); |
| | 547 | pv.master_secret = P.Hkdf.extract(&ap_derived_secret, &zeroes); |
| | 548 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "c hs traffic", &hello_hash, P.Hash.digest_length); |
| | 549 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.handshake_secret, "s hs traffic", &hello_hash, P.Hash.digest_length); |
| | 550 | if (options.ssl_key_log_file) |key_log_file| logSecrets(key_log_file, .{ |
| | 551 | .client_random = &client_hello_rand, |
| | 552 | }, .{ |
| | 553 | .SERVER_HANDSHAKE_TRAFFIC_SECRET = &server_secret, |
| | 554 | .CLIENT_HANDSHAKE_TRAFFIC_SECRET = &client_secret, |
| | 555 | }); |
| | 556 | pv.client_finished_key = hkdfExpandLabel(P.Hkdf, client_secret, "finished", "", P.Hmac.key_length); |
| | 557 | pv.server_finished_key = hkdfExpandLabel(P.Hkdf, server_secret, "finished", "", P.Hmac.key_length); |
| | 558 | pv.client_handshake_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| | 559 | pv.server_handshake_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| | 560 | pv.client_handshake_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| | 561 | pv.server_handshake_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| | 562 | }, |
| | 563 | else => return error.TlsIllegalParameter, |
| | 564 | } |
| | 565 | pending_cipher_state = .handshake; |
| | 566 | handshake_state = .encrypted_extensions; |
| | 567 | }, |
| | 568 | .tls_1_2 => switch (cipher_suite_tag) { |
| | 569 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| | 570 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| | 571 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| | 572 | => handshake_state = .certificate, |
| | 573 | else => return error.TlsIllegalParameter, |
| | 574 | }, |
| | 575 | else => return error.TlsIllegalParameter, |
| | 576 | } |
| | 577 | }, |
| | 578 | .encrypted_extensions => { |
| | 579 | if (tls_version != .tls_1_3) return error.TlsUnexpectedMessage; |
| | 580 | if (cipher_state != .handshake) return error.TlsUnexpectedMessage; |
| | 581 | if (handshake_state != .encrypted_extensions) return error.TlsUnexpectedMessage; |
| | 582 | switch (handshake_cipher) { |
| | 583 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| | 584 | } |
| | 585 | try hsd.ensure(2); |
| | 586 | const total_ext_size = hsd.decode(u16); |
| | 587 | var all_extd = try hsd.sub(total_ext_size); |
| | 588 | while (!all_extd.eof()) { |
| | 589 | try all_extd.ensure(4); |
| | 590 | const et = all_extd.decode(tls.ExtensionType); |
| | 591 | const ext_size = all_extd.decode(u16); |
| | 592 | const extd = try all_extd.sub(ext_size); |
| | 593 | _ = extd; |
| | 594 | switch (et) { |
| | 595 | .server_name => {}, |
| | 596 | else => {}, |
| | 597 | } |
| | 598 | } |
| | 599 | handshake_state = .certificate; |
| | 600 | }, |
| | 601 | .certificate => cert: { |
| | 602 | if (cipher_state == .application) return error.TlsUnexpectedMessage; |
| | 603 | switch (handshake_state) { |
| | 604 | .certificate => {}, |
| | 605 | .trust_chain_established => break :cert, |
| | 606 | else => return error.TlsUnexpectedMessage, |
| | 607 | } |
| | 608 | switch (handshake_cipher) { |
| | 609 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| | 610 | } |
| 558 | | 611 | |
| | 612 | switch (tls_version) { |
| | 613 | .tls_1_3 => { |
| | 614 | try hsd.ensure(1 + 3); |
| | 615 | const cert_req_ctx_len = hsd.decode(u8); |
| | 616 | if (cert_req_ctx_len != 0) return error.TlsIllegalParameter; |
| | 617 | }, |
| | 618 | .tls_1_2 => try hsd.ensure(3), |
| | 619 | else => unreachable, |
| | 620 | } |
| | 621 | const certs_size = hsd.decode(u24); |
| | 622 | var certs_decoder = try hsd.sub(certs_size); |
| | 623 | while (!certs_decoder.eof()) { |
| | 624 | try certs_decoder.ensure(3); |
| | 625 | const cert_size = certs_decoder.decode(u24); |
| | 626 | const certd = try certs_decoder.sub(cert_size); |
| | 627 | |
| | 628 | if (tls_version == .tls_1_3) { |
| 559 | try certs_decoder.ensure(2); | 629 | try certs_decoder.ensure(2); |
| 560 | const total_ext_size = certs_decoder.decode(u16); | 630 | const total_ext_size = certs_decoder.decode(u16); |
| 561 | const all_extd = try certs_decoder.sub(total_ext_size); | 631 | const all_extd = try certs_decoder.sub(total_ext_size); |
| 562 | _ = all_extd; | 632 | _ = all_extd; |
| 563 | } | 633 | } |
| 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 | } | | |
| 571 | | 634 | |
| 572 | try hsd.ensure(4); | 635 | const subject_cert: Certificate = .{ |
| 573 | const scheme = hsd.decode(tls.SignatureScheme); | 636 | .buffer = certd.buf, |
| 574 | const sig_len = hsd.decode(u16); | 637 | .index = @intCast(certd.idx), |
| 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 | }; | 638 | }; |
| 591 | const main_cert_pub_key = main_cert_pub_key_buf[0..main_cert_pub_key_len]; | 639 | const subject = try subject_cert.parse(); |
| 592 | | 640 | if (cert_index == 0) { |
| 593 | switch (scheme) { | 641 | // Verify the host on the first certificate. |
| 594 | inline .ecdsa_secp256r1_sha256, | 642 | switch (options.host) { |
| 595 | .ecdsa_secp384r1_sha384, | 643 | .no_verification => {}, |
| 596 | => |comptime_scheme| { | 644 | .explicit => try subject.verifyHostName(host), |
| 597 | if (main_cert_pub_key_algo != .X9_62_id_ecPublicKey) | 645 | } |
| 598 | return error.TlsBadSignatureScheme; | 646 | |
| 599 | const Ecdsa = SchemeEcdsa(comptime_scheme); | 647 | // Keep track of the public key for the |
| 600 | const sig = try Ecdsa.Signature.fromDer(encoded_sig); | 648 | // certificate_verify message later. |
| 601 | const key = try Ecdsa.PublicKey.fromSec1(main_cert_pub_key); | 649 | try main_cert_pub_key.init(subject.pub_key_algo, subject.pubKey()); |
| 602 | try sig.verify(verify_bytes, key); | 650 | } else { |
| 603 | }, | 651 | try prev_cert.verify(subject, now_sec); |
| 604 | inline .rsa_pss_rsae_sha256, | 652 | } |
| 605 | .rsa_pss_rsae_sha384, | 653 | |
| 606 | .rsa_pss_rsae_sha512, | 654 | switch (options.ca) { |
| 607 | => |comptime_scheme| { | 655 | .no_verification => { |
| 608 | if (main_cert_pub_key_algo != .rsaEncryption) | 656 | handshake_state = .trust_chain_established; |
| 609 | return error.TlsBadSignatureScheme; | 657 | break :cert; |
| 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 | }, | 658 | }, |
| 627 | inline .ed25519 => |comptime_scheme| { | 659 | .self_signed => { |
| 628 | if (main_cert_pub_key_algo != .curveEd25519) return error.TlsBadSignatureScheme; | 660 | try subject.verify(subject, now_sec); |
| 629 | const Eddsa = SchemeEddsa(comptime_scheme); | 661 | handshake_state = .trust_chain_established; |
| 630 | if (encoded_sig.len != Eddsa.Signature.encoded_length) return error.InvalidEncoding; | 662 | break :cert; |
| 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 | }, | 663 | }, |
| 636 | else => { | 664 | .bundle => |ca_bundle| if (ca_bundle.verify(subject, now_sec)) |_| { |
| 637 | return error.TlsBadSignatureScheme; | 665 | handshake_state = .trust_chain_established; |
| | 666 | break :cert; |
| | 667 | } else |err| switch (err) { |
| | 668 | error.CertificateIssuerNotFound => {}, |
| | 669 | else => |e| return e, |
| 638 | }, | 670 | }, |
| 639 | } | 671 | } |
| 640 | }, | 672 | |
| 641 | .finished => { | 673 | prev_cert = subject; |
| 642 | if (handshake_state != .finished) return error.TlsUnexpectedMessage; | 674 | cert_index += 1; |
| 643 | // This message is to trick buggy proxies into behaving correctly. | 675 | } |
| 644 | const client_change_cipher_spec_msg = [_]u8{ | 676 | cert_buf_index += 1; |
| 645 | @intFromEnum(tls.ContentType.change_cipher_spec), | 677 | }, |
| 646 | 0x03, 0x03, // legacy protocol version | 678 | .server_key_exchange => { |
| 647 | 0x00, 0x01, // length | 679 | if (tls_version != .tls_1_2) return error.TlsUnexpectedMessage; |
| 648 | 0x01, | 680 | if (cipher_state != .cleartext) return error.TlsUnexpectedMessage; |
| 649 | }; | 681 | switch (handshake_state) { |
| 650 | const app_cipher = switch (handshake_cipher) { | 682 | .trust_chain_established => {}, |
| 651 | inline else => |*p, tag| c: { | 683 | .certificate => return error.TlsCertificateNotVerified, |
| 652 | const P = @TypeOf(p.*); | 684 | else => return error.TlsUnexpectedMessage, |
| | 685 | } |
| | 686 | |
| | 687 | switch (handshake_cipher) { |
| | 688 | inline else => |*p| p.transcript_hash.update(wrapped_handshake), |
| | 689 | } |
| | 690 | try hsd.ensure(1 + 2 + 1); |
| | 691 | const curve_type = hsd.decode(u8); |
| | 692 | if (curve_type != 0x03) return error.TlsIllegalParameter; // named_curve |
| | 693 | const named_group = hsd.decode(tls.NamedGroup); |
| | 694 | const key_size = hsd.decode(u8); |
| | 695 | try hsd.ensure(key_size); |
| | 696 | const server_pub_key = hsd.slice(key_size); |
| | 697 | try main_cert_pub_key.verifySignature(&hsd, &.{ &client_hello_rand, &server_hello_rand, hsd.buf[0..hsd.idx] }); |
| | 698 | try key_share.exchange(named_group, server_pub_key); |
| | 699 | handshake_state = .server_hello_done; |
| | 700 | }, |
| | 701 | .server_hello_done => { |
| | 702 | if (tls_version != .tls_1_2) return error.TlsUnexpectedMessage; |
| | 703 | if (cipher_state != .cleartext) return error.TlsUnexpectedMessage; |
| | 704 | if (handshake_state != .server_hello_done) return error.TlsUnexpectedMessage; |
| | 705 | |
| | 706 | const client_key_exchange_msg = .{@intFromEnum(tls.ContentType.handshake)} ++ |
| | 707 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| | 708 | array(u16, u8, .{@intFromEnum(tls.HandshakeType.client_key_exchange)} ++ |
| | 709 | array(u24, u8, array(u8, u8, key_share.secp256r1_kp.public_key.toUncompressedSec1()))); |
| | 710 | const client_change_cipher_spec_msg = .{@intFromEnum(tls.ContentType.change_cipher_spec)} ++ |
| | 711 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| | 712 | array(u16, tls.ChangeCipherSpecType, .{.change_cipher_spec}); |
| | 713 | const pre_master_secret = key_share.getSharedSecret().?; |
| | 714 | switch (handshake_cipher) { |
| | 715 | inline else => |*p| { |
| | 716 | const P = @TypeOf(p.*).A; |
| | 717 | p.transcript_hash.update(wrapped_handshake); |
| | 718 | p.transcript_hash.update(client_key_exchange_msg[tls.record_header_len..]); |
| | 719 | const master_secret = hmacExpandLabel(P.Hmac, pre_master_secret, &.{ |
| | 720 | "master secret", |
| | 721 | &client_hello_rand, |
| | 722 | &server_hello_rand, |
| | 723 | }, 48); |
| | 724 | if (options.ssl_key_log_file) |key_log_file| logSecrets(key_log_file, .{ |
| | 725 | .client_random = &client_hello_rand, |
| | 726 | }, .{ |
| | 727 | .CLIENT_RANDOM = &master_secret, |
| | 728 | }); |
| | 729 | const key_block = hmacExpandLabel( |
| | 730 | P.Hmac, |
| | 731 | &master_secret, |
| | 732 | &.{ "key expansion", &server_hello_rand, &client_hello_rand }, |
| | 733 | @sizeOf(P.Tls_1_2), |
| | 734 | ); |
| | 735 | const client_verify_cleartext = .{@intFromEnum(tls.HandshakeType.finished)} ++ |
| | 736 | array(u24, u8, hmacExpandLabel( |
| | 737 | P.Hmac, |
| | 738 | &master_secret, |
| | 739 | &.{ "client finished", &p.transcript_hash.peek() }, |
| | 740 | P.verify_data_length, |
| | 741 | )); |
| | 742 | p.transcript_hash.update(&client_verify_cleartext); |
| | 743 | p.version = .{ .tls_1_2 = .{ |
| | 744 | .expected_server_verify_data = hmacExpandLabel( |
| | 745 | P.Hmac, |
| | 746 | &master_secret, |
| | 747 | &.{ "server finished", &p.transcript_hash.finalResult() }, |
| | 748 | P.verify_data_length, |
| | 749 | ), |
| | 750 | .app_cipher = std.mem.bytesToValue(P.Tls_1_2, &key_block), |
| | 751 | } }; |
| | 752 | const pv = &p.version.tls_1_2; |
| | 753 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| | 754 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| | 755 | nonce: { |
| | 756 | var nonce = pv.app_cipher.client_write_IV ++ pv.app_cipher.client_salt; |
| | 757 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| | 758 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ write_seq, .big); |
| | 759 | break :nonce nonce; |
| | 760 | } else nonce: { |
| | 761 | const V = @Vector(P.AEAD.nonce_length, u8); |
| | 762 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| | 763 | const operand: V = pad ++ @as([8]u8, @bitCast(big(write_seq))); |
| | 764 | break :nonce @as(V, pv.app_cipher.client_write_IV ++ pv.app_cipher.client_salt) ^ operand; |
| | 765 | }; |
| | 766 | var client_verify_msg = .{@intFromEnum(tls.ContentType.handshake)} ++ |
| | 767 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| | 768 | array(u16, u8, nonce[P.fixed_iv_length..].* ++ |
| | 769 | @as([client_verify_cleartext.len + P.mac_length]u8, undefined)); |
| | 770 | P.AEAD.encrypt( |
| | 771 | client_verify_msg[client_verify_msg.len - P.mac_length - |
| | 772 | client_verify_cleartext.len ..][0..client_verify_cleartext.len], |
| | 773 | client_verify_msg[client_verify_msg.len - P.mac_length ..][0..P.mac_length], |
| | 774 | &client_verify_cleartext, |
| | 775 | std.mem.toBytes(big(write_seq)) ++ client_verify_msg[0 .. 1 + 2] ++ int(u16, client_verify_cleartext.len), |
| | 776 | nonce, |
| | 777 | pv.app_cipher.client_write_key, |
| | 778 | ); |
| | 779 | const all_msgs = client_key_exchange_msg ++ client_change_cipher_spec_msg ++ client_verify_msg; |
| | 780 | var all_msgs_vec = [_]std.posix.iovec_const{ |
| | 781 | .{ .base = &all_msgs, .len = all_msgs.len }, |
| | 782 | }; |
| | 783 | try stream.writevAll(&all_msgs_vec); |
| | 784 | }, |
| | 785 | } |
| | 786 | write_seq += 1; |
| | 787 | pending_cipher_state = .application; |
| | 788 | handshake_state = .finished; |
| | 789 | }, |
| | 790 | .certificate_verify => { |
| | 791 | if (tls_version != .tls_1_3) return error.TlsUnexpectedMessage; |
| | 792 | if (cipher_state != .handshake) return error.TlsUnexpectedMessage; |
| | 793 | switch (handshake_state) { |
| | 794 | .trust_chain_established => {}, |
| | 795 | .certificate => return error.TlsCertificateNotVerified, |
| | 796 | else => return error.TlsUnexpectedMessage, |
| | 797 | } |
| | 798 | switch (handshake_cipher) { |
| | 799 | inline else => |*p| { |
| | 800 | try main_cert_pub_key.verifySignature(&hsd, &.{ |
| | 801 | " " ** 64 ++ "TLS 1.3, server CertificateVerify\x00", |
| | 802 | &p.transcript_hash.peek(), |
| | 803 | }); |
| | 804 | p.transcript_hash.update(wrapped_handshake); |
| | 805 | }, |
| | 806 | } |
| | 807 | handshake_state = .finished; |
| | 808 | }, |
| | 809 | .finished => { |
| | 810 | if (cipher_state == .cleartext) return error.TlsUnexpectedMessage; |
| | 811 | if (handshake_state != .finished) return error.TlsUnexpectedMessage; |
| | 812 | // This message is to trick buggy proxies into behaving correctly. |
| | 813 | const client_change_cipher_spec_msg = .{@intFromEnum(tls.ContentType.change_cipher_spec)} ++ |
| | 814 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| | 815 | array(u16, tls.ChangeCipherSpecType, .{.change_cipher_spec}); |
| | 816 | const app_cipher = app_cipher: switch (handshake_cipher) { |
| | 817 | inline else => |*p, tag| switch (tls_version) { |
| | 818 | .tls_1_3 => { |
| | 819 | const pv = &p.version.tls_1_3; |
| | 820 | const P = @TypeOf(p.*).A; |
| | 821 | try hsd.ensure(P.Hmac.mac_length); |
| 653 | const finished_digest = p.transcript_hash.peek(); | 822 | const finished_digest = p.transcript_hash.peek(); |
| 654 | p.transcript_hash.update(wrapped_handshake); | 823 | p.transcript_hash.update(wrapped_handshake); |
| 655 | const expected_server_verify_data = tls.hmac(P.Hmac, &finished_digest, p.server_finished_key); | 824 | const expected_server_verify_data = tls.hmac(P.Hmac, &finished_digest, pv.server_finished_key); |
| 656 | if (!mem.eql(u8, &expected_server_verify_data, handshake)) | 825 | if (!std.crypto.timing_safe.eql([P.Hmac.mac_length]u8, expected_server_verify_data, hsd.array(P.Hmac.mac_length).*)) return error.TlsDecryptError; |
| 657 | return error.TlsDecryptError; | | |
| 658 | const handshake_hash = p.transcript_hash.finalResult(); | 826 | const handshake_hash = p.transcript_hash.finalResult(); |
| 659 | const verify_data = tls.hmac(P.Hmac, &handshake_hash, p.client_finished_key); | 827 | const verify_data = tls.hmac(P.Hmac, &handshake_hash, pv.client_finished_key); |
| 660 | const out_cleartext = [_]u8{ | 828 | const out_cleartext = .{@intFromEnum(tls.HandshakeType.finished)} ++ |
| 661 | @intFromEnum(tls.HandshakeType.finished), | 829 | array(u24, u8, verify_data) ++ |
| 662 | 0, 0, verify_data.len, // length | 830 | .{@intFromEnum(tls.ContentType.handshake)}; |
| 663 | } ++ verify_data ++ [1]u8{@intFromEnum(tls.ContentType.handshake)}; | | |
| 664 | | 831 | |
| 665 | const wrapped_len = out_cleartext.len + P.AEAD.tag_length; | 832 | const wrapped_len = out_cleartext.len + P.AEAD.tag_length; |
| 666 | | 833 | |
| 667 | var finished_msg = [_]u8{ | 834 | var finished_msg = .{@intFromEnum(tls.ContentType.application_data)} ++ |
| 668 | @intFromEnum(tls.ContentType.application_data), | 835 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 669 | 0x03, 0x03, // legacy protocol version | 836 | array(u16, u8, @as([wrapped_len]u8, undefined)); |
| 670 | 0, wrapped_len, // byte length of encrypted record | | |
| 671 | } ++ @as([wrapped_len]u8, undefined); | | |
| 672 | | 837 | |
| 673 | const ad = finished_msg[0..5]; | 838 | const ad = finished_msg[0..tls.record_header_len]; |
| 674 | const ciphertext = finished_msg[5..][0..out_cleartext.len]; | 839 | const ciphertext = finished_msg[tls.record_header_len..][0..out_cleartext.len]; |
| 675 | const auth_tag = finished_msg[finished_msg.len - P.AEAD.tag_length ..]; | 840 | const auth_tag = finished_msg[finished_msg.len - P.AEAD.tag_length ..]; |
| 676 | const nonce = p.client_handshake_iv; | 841 | const nonce = pv.client_handshake_iv; |
| 677 | P.AEAD.encrypt(ciphertext, auth_tag, &out_cleartext, ad, nonce, p.client_handshake_key); | 842 | P.AEAD.encrypt(ciphertext, auth_tag, &out_cleartext, ad, nonce, pv.client_handshake_key); |
| 678 | | 843 | |
| 679 | const both_msgs = client_change_cipher_spec_msg ++ finished_msg; | 844 | const all_msgs = client_change_cipher_spec_msg ++ finished_msg; |
| 680 | var both_msgs_vec = [_]std.posix.iovec_const{.{ | 845 | var all_msgs_vec = [_]std.posix.iovec_const{ |
| 681 | .base = &both_msgs, | 846 | .{ .base = &all_msgs, .len = all_msgs.len }, |
| 682 | .len = both_msgs.len, | 847 | }; |
| 683 | }}; | 848 | try stream.writevAll(&all_msgs_vec); |
| 684 | try stream.writevAll(&both_msgs_vec); | 849 | |
| 685 | | 850 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.master_secret, "c ap traffic", &handshake_hash, P.Hash.digest_length); |
| 686 | const client_secret = hkdfExpandLabel(P.Hkdf, p.master_secret, "c ap traffic", &handshake_hash, P.Hash.digest_length); | 851 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.master_secret, "s 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); | 852 | if (options.ssl_key_log_file) |key_log_file| logSecrets(key_log_file, .{ |
| 688 | break :c @unionInit(tls.ApplicationCipher, @tagName(tag), .{ | 853 | .counter = key_seq, |
| | 854 | .client_random = &client_hello_rand, |
| | 855 | }, .{ |
| | 856 | .SERVER_TRAFFIC_SECRET = &server_secret, |
| | 857 | .CLIENT_TRAFFIC_SECRET = &client_secret, |
| | 858 | }); |
| | 859 | key_seq += 1; |
| | 860 | break :app_cipher @unionInit(tls.ApplicationCipher, @tagName(tag), .{ .tls_1_3 = .{ |
| 689 | .client_secret = client_secret, | 861 | .client_secret = client_secret, |
| 690 | .server_secret = server_secret, | 862 | .server_secret = server_secret, |
| 691 | .client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length), | 863 | .client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length), |
| 692 | .server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length), | 864 | .server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length), |
| 693 | .client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length), | 865 | .client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length), |
| 694 | .server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length), | 866 | .server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length), |
| 695 | }); | 867 | } }); |
| 696 | }, | 868 | }, |
| 697 | }; | 869 | .tls_1_2 => { |
| 698 | const leftover = d.rest(); | 870 | const pv = &p.version.tls_1_2; |
| 699 | var client: Client = .{ | 871 | const P = @TypeOf(p.*).A; |
| 700 | .read_seq = 0, | 872 | try hsd.ensure(P.verify_data_length); |
| 701 | .write_seq = 0, | 873 | if (!std.crypto.timing_safe.eql([P.verify_data_length]u8, pv.expected_server_verify_data, hsd.array(P.verify_data_length).*)) return error.TlsDecryptError; |
| 702 | .partial_cleartext_idx = 0, | 874 | break :app_cipher @unionInit(tls.ApplicationCipher, @tagName(tag), .{ .tls_1_2 = pv.app_cipher }); |
| 703 | .partial_ciphertext_idx = 0, | 875 | }, |
| 704 | .partial_ciphertext_end = @intCast(leftover.len), | 876 | else => unreachable, |
| 705 | .received_close_notify = false, | 877 | }, |
| 706 | .application_cipher = app_cipher, | 878 | }; |
| 707 | .partially_read_buffer = undefined, | 879 | const leftover = d.rest(); |
| 708 | }; | 880 | var client: Client = .{ |
| 709 | @memcpy(client.partially_read_buffer[0..leftover.len], leftover); | 881 | .tls_version = tls_version, |
| 710 | return client; | 882 | .read_seq = switch (tls_version) { |
| 711 | }, | 883 | .tls_1_3 => 0, |
| 712 | else => { | 884 | .tls_1_2 => read_seq, |
| 713 | return error.TlsUnexpectedMessage; | 885 | else => unreachable, |
| 714 | }, | 886 | }, |
| 715 | } | 887 | .write_seq = switch (tls_version) { |
| 716 | if (ctd.eof()) break; | 888 | .tls_1_3 => 0, |
| | 889 | .tls_1_2 => write_seq, |
| | 890 | else => unreachable, |
| | 891 | }, |
| | 892 | .partial_cleartext_idx = 0, |
| | 893 | .partial_ciphertext_idx = 0, |
| | 894 | .partial_ciphertext_end = @intCast(leftover.len), |
| | 895 | .received_close_notify = false, |
| | 896 | .allow_truncation_attacks = false, |
| | 897 | .application_cipher = app_cipher, |
| | 898 | .partially_read_buffer = undefined, |
| | 899 | .ssl_key_log = if (options.ssl_key_log_file) |key_log_file| .{ |
| | 900 | .client_key_seq = key_seq, |
| | 901 | .server_key_seq = key_seq, |
| | 902 | .client_random = client_hello_rand, |
| | 903 | .file = key_log_file, |
| | 904 | } else null, |
| | 905 | }; |
| | 906 | @memcpy(client.partially_read_buffer[0..leftover.len], leftover); |
| | 907 | return client; |
| | 908 | }, |
| | 909 | else => return error.TlsUnexpectedMessage, |
| 717 | } | 910 | } |
| | 911 | if (ctd.eof()) break; |
| | 912 | cleartext_fragment_start = ctd.idx; |
| 718 | }, | 913 | }, |
| 719 | else => { | 914 | else => return error.TlsUnexpectedMessage, |
| 720 | return error.TlsUnexpectedMessage; | | |
| 721 | }, | | |
| 722 | } | 915 | } |
| | 916 | cleartext_fragment_start = 0; |
| | 917 | cleartext_fragment_end = 0; |
| 723 | } | 918 | } |
| 724 | } | 919 | } |
| 725 | | 920 | |
| 726 | /// Sends TLS-encrypted data to `stream`, which must conform to `StreamInterface`. | 921 | /// 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`. | 922 | /// Returns the number of cleartext bytes sent, which may be fewer than `bytes.len`. |
| 728 | pub fn write(c: *Client, stream: anytype, bytes: []const u8) !usize { | 923 | pub fn write(c: *Client, stream: anytype, bytes: []const u8) !usize { |
| 729 | return writeEnd(c, stream, bytes, false); | 924 | return writeEnd(c, stream, bytes, false); |
| 730 | } | 925 | } |
| ... | @@ -749,7 +944,7 @@ pub fn writeAllEnd(c: *Client, stream: anytype, bytes: []const u8, end: bool) !v | ... | @@ -749,7 +944,7 @@ pub fn writeAllEnd(c: *Client, stream: anytype, bytes: []const u8, end: bool) !v |
| 749 | } | 944 | } |
| 750 | | 945 | |
| 751 | /// Sends TLS-encrypted data to `stream`, which must conform to `StreamInterface`. | 946 | /// 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`. | 947 | /// Returns the number of cleartext bytes sent, which may be fewer than `bytes.len`. |
| 753 | /// If `end` is true, then this function additionally sends a `close_notify` alert, | 948 | /// If `end` is true, then this function additionally sends a `close_notify` alert, |
| 754 | /// which is necessary for the server to distinguish between a properly finished | 949 | /// which is necessary for the server to distinguish between a properly finished |
| 755 | /// TLS session, or a truncation attack. | 950 | /// TLS session, or a truncation attack. |
| ... | @@ -813,62 +1008,126 @@ fn prepareCiphertextRecord( | ... | @@ -813,62 +1008,126 @@ fn prepareCiphertextRecord( |
| 813 | var iovec_end: usize = 0; | 1008 | var iovec_end: usize = 0; |
| 814 | var bytes_i: usize = 0; | 1009 | var bytes_i: usize = 0; |
| 815 | switch (c.application_cipher) { | 1010 | switch (c.application_cipher) { |
| 816 | inline else => |*p| { | 1011 | inline else => |*p| switch (c.tls_version) { |
| 817 | const P = @TypeOf(p.*); | 1012 | .tls_1_3 => { |
| 818 | const overhead_len = tls.record_header_len + P.AEAD.tag_length + 1; | 1013 | const pv = &p.tls_1_3; |
| 819 | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; | 1014 | const P = @TypeOf(p.*); |
| 820 | while (true) { | 1015 | const overhead_len = tls.record_header_len + P.AEAD.tag_length + 1; |
| 821 | const encrypted_content_len: u16 = @intCast(@min( | 1016 | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; |
| 822 | @min(bytes.len - bytes_i, tls.max_ciphertext_inner_record_len), | 1017 | while (true) { |
| 823 | ciphertext_buf.len -| | 1018 | const encrypted_content_len: u16 = @min( |
| 824 | (close_notify_alert_reserved + overhead_len + ciphertext_end), | 1019 | bytes.len - bytes_i, |
| 825 | )); | 1020 | tls.max_ciphertext_inner_record_len, |
| 826 | if (encrypted_content_len == 0) return .{ | 1021 | ciphertext_buf.len -| |
| 827 | .iovec_end = iovec_end, | 1022 | (close_notify_alert_reserved + overhead_len + ciphertext_end), |
| 828 | .ciphertext_end = ciphertext_end, | 1023 | ); |
| 829 | .overhead_len = overhead_len, | 1024 | if (encrypted_content_len == 0) return .{ |
| 830 | }; | 1025 | .iovec_end = iovec_end, |
| 831 | | 1026 | .ciphertext_end = ciphertext_end, |
| 832 | @memcpy(cleartext_buf[0..encrypted_content_len], bytes[bytes_i..][0..encrypted_content_len]); | 1027 | .overhead_len = overhead_len, |
| 833 | cleartext_buf[encrypted_content_len] = @intFromEnum(inner_content_type); | 1028 | }; |
| 834 | bytes_i += encrypted_content_len; | 1029 | |
| 835 | const ciphertext_len = encrypted_content_len + 1; | 1030 | @memcpy(cleartext_buf[0..encrypted_content_len], bytes[bytes_i..][0..encrypted_content_len]); |
| 836 | const cleartext = cleartext_buf[0..ciphertext_len]; | 1031 | cleartext_buf[encrypted_content_len] = @intFromEnum(inner_content_type); |
| 837 | | 1032 | bytes_i += encrypted_content_len; |
| 838 | const record_start = ciphertext_end; | 1033 | const ciphertext_len = encrypted_content_len + 1; |
| 839 | const ad = ciphertext_buf[ciphertext_end..][0..5]; | 1034 | const cleartext = cleartext_buf[0..ciphertext_len]; |
| 840 | ad.* = | 1035 | |
| 841 | [_]u8{@intFromEnum(tls.ContentType.application_data)} ++ | 1036 | const record_start = ciphertext_end; |
| 842 | int2(@intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ | 1037 | const ad = ciphertext_buf[ciphertext_end..][0..tls.record_header_len]; |
| 843 | int2(ciphertext_len + P.AEAD.tag_length); | 1038 | ad.* = .{@intFromEnum(tls.ContentType.application_data)} ++ |
| 844 | ciphertext_end += ad.len; | 1039 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| 845 | const ciphertext = ciphertext_buf[ciphertext_end..][0..ciphertext_len]; | 1040 | int(u16, ciphertext_len + P.AEAD.tag_length); |
| 846 | ciphertext_end += ciphertext_len; | 1041 | ciphertext_end += ad.len; |
| 847 | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.AEAD.tag_length]; | 1042 | const ciphertext = ciphertext_buf[ciphertext_end..][0..ciphertext_len]; |
| 848 | ciphertext_end += auth_tag.len; | 1043 | ciphertext_end += ciphertext_len; |
| 849 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and | 1044 | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.AEAD.tag_length]; |
| 850 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) | 1045 | ciphertext_end += auth_tag.len; |
| 851 | nonce: { | 1046 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| 852 | var nonce = p.client_iv; | 1047 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| 853 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); | 1048 | nonce: { |
| 854 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); | 1049 | var nonce = pv.client_iv; |
| 855 | break :nonce nonce; | 1050 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| 856 | } else nonce: { | 1051 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); |
| 857 | const V = @Vector(P.AEAD.nonce_length, u8); | 1052 | break :nonce nonce; |
| 858 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); | 1053 | } else nonce: { |
| 859 | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.write_seq))); | 1054 | const V = @Vector(P.AEAD.nonce_length, u8); |
| 860 | break :nonce @as(V, p.client_iv) ^ operand; | 1055 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| 861 | }; | 1056 | const operand: V = pad ++ std.mem.toBytes(big(c.write_seq)); |
| 862 | c.write_seq += 1; // TODO send key_update on overflow | 1057 | break :nonce @as(V, pv.client_iv) ^ operand; |
| 863 | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, p.client_key); | 1058 | }; |
| 864 | | 1059 | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, pv.client_key); |
| 865 | const record = ciphertext_buf[record_start..ciphertext_end]; | 1060 | c.write_seq += 1; // TODO send key_update on overflow |
| 866 | iovecs[iovec_end] = .{ | 1061 | |
| 867 | .base = record.ptr, | 1062 | const record = ciphertext_buf[record_start..ciphertext_end]; |
| 868 | .len = record.len, | 1063 | iovecs[iovec_end] = .{ |
| 869 | }; | 1064 | .base = record.ptr, |
| 870 | iovec_end += 1; | 1065 | .len = record.len, |
| 871 | } | 1066 | }; |
| | 1067 | iovec_end += 1; |
| | 1068 | } |
| | 1069 | }, |
| | 1070 | .tls_1_2 => { |
| | 1071 | const pv = &p.tls_1_2; |
| | 1072 | const P = @TypeOf(p.*); |
| | 1073 | const overhead_len = tls.record_header_len + P.record_iv_length + P.mac_length; |
| | 1074 | const close_notify_alert_reserved = tls.close_notify_alert.len + overhead_len; |
| | 1075 | while (true) { |
| | 1076 | const message_len: u16 = @min( |
| | 1077 | bytes.len - bytes_i, |
| | 1078 | tls.max_ciphertext_inner_record_len, |
| | 1079 | ciphertext_buf.len -| |
| | 1080 | (close_notify_alert_reserved + overhead_len + ciphertext_end), |
| | 1081 | ); |
| | 1082 | if (message_len == 0) return .{ |
| | 1083 | .iovec_end = iovec_end, |
| | 1084 | .ciphertext_end = ciphertext_end, |
| | 1085 | .overhead_len = overhead_len, |
| | 1086 | }; |
| | 1087 | |
| | 1088 | @memcpy(cleartext_buf[0..message_len], bytes[bytes_i..][0..message_len]); |
| | 1089 | bytes_i += message_len; |
| | 1090 | const cleartext = cleartext_buf[0..message_len]; |
| | 1091 | |
| | 1092 | const record_start = ciphertext_end; |
| | 1093 | const record_header = ciphertext_buf[ciphertext_end..][0..tls.record_header_len]; |
| | 1094 | ciphertext_end += tls.record_header_len; |
| | 1095 | record_header.* = .{@intFromEnum(inner_content_type)} ++ |
| | 1096 | int(u16, @intFromEnum(tls.ProtocolVersion.tls_1_2)) ++ |
| | 1097 | int(u16, P.record_iv_length + message_len + P.mac_length); |
| | 1098 | const ad = std.mem.toBytes(big(c.write_seq)) ++ record_header[0 .. 1 + 2] ++ int(u16, message_len); |
| | 1099 | const record_iv = ciphertext_buf[ciphertext_end..][0..P.record_iv_length]; |
| | 1100 | ciphertext_end += P.record_iv_length; |
| | 1101 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| | 1102 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| | 1103 | nonce: { |
| | 1104 | var nonce = pv.client_write_IV ++ pv.client_salt; |
| | 1105 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| | 1106 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.write_seq, .big); |
| | 1107 | break :nonce nonce; |
| | 1108 | } else nonce: { |
| | 1109 | const V = @Vector(P.AEAD.nonce_length, u8); |
| | 1110 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| | 1111 | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.write_seq))); |
| | 1112 | break :nonce @as(V, pv.client_write_IV ++ pv.client_salt) ^ operand; |
| | 1113 | }; |
| | 1114 | record_iv.* = nonce[P.fixed_iv_length..].*; |
| | 1115 | const ciphertext = ciphertext_buf[ciphertext_end..][0..message_len]; |
| | 1116 | ciphertext_end += message_len; |
| | 1117 | const auth_tag = ciphertext_buf[ciphertext_end..][0..P.mac_length]; |
| | 1118 | ciphertext_end += P.mac_length; |
| | 1119 | P.AEAD.encrypt(ciphertext, auth_tag, cleartext, ad, nonce, pv.client_write_key); |
| | 1120 | c.write_seq += 1; // TODO send key_update on overflow |
| | 1121 | |
| | 1122 | const record = ciphertext_buf[record_start..ciphertext_end]; |
| | 1123 | iovecs[iovec_end] = .{ |
| | 1124 | .base = record.ptr, |
| | 1125 | .len = record.len, |
| | 1126 | }; |
| | 1127 | iovec_end += 1; |
| | 1128 | } |
| | 1129 | }, |
| | 1130 | else => unreachable, |
| 872 | }, | 1131 | }, |
| 873 | } | 1132 | } |
| 874 | } | 1133 | } |
| ... | @@ -990,7 +1249,7 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove | ... | @@ -990,7 +1249,7 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove |
| 990 | // beginning of the buffer will be used for such purposes. | 1249 | // beginning of the buffer will be used for such purposes. |
| 991 | const cleartext_buf_len = free_size - ciphertext_buf_len; | 1250 | const cleartext_buf_len = free_size - ciphertext_buf_len; |
| 992 | | 1251 | |
| 993 | // Recoup `partially_read_buffer space`. This is necessary because it is assumed | 1252 | // Recoup `partially_read_buffer` space. This is necessary because it is assumed |
| 994 | // below that `frag0` is big enough to hold at least one record. | 1253 | // below that `frag0` is big enough to hold at least one record. |
| 995 | limitedOverlapCopy(c.partially_read_buffer[0..c.partial_ciphertext_end], c.partial_ciphertext_idx); | 1254 | limitedOverlapCopy(c.partially_read_buffer[0..c.partial_ciphertext_end], c.partial_ciphertext_idx); |
| 996 | c.partial_ciphertext_end -= c.partial_ciphertext_idx; | 1255 | c.partial_ciphertext_end -= c.partial_ciphertext_idx; |
| ... | @@ -1105,164 +1364,211 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove | ... | @@ -1105,164 +1364,211 @@ pub fn readvAdvanced(c: *Client, stream: anytype, iovecs: []const std.posix.iove |
| 1105 | in = 0; | 1364 | in = 0; |
| 1106 | continue; | 1365 | continue; |
| 1107 | } | 1366 | } |
| 1108 | switch (ct) { | 1367 | const cleartext, const inner_ct: tls.ContentType = cleartext: switch (c.application_cipher) { |
| | 1368 | inline else => |*p| switch (c.tls_version) { |
| | 1369 | .tls_1_3 => { |
| | 1370 | const pv = &p.tls_1_3; |
| | 1371 | const P = @TypeOf(p.*); |
| | 1372 | const ad = frag[in - tls.record_header_len ..][0..tls.record_header_len]; |
| | 1373 | const ciphertext_len = record_len - P.AEAD.tag_length; |
| | 1374 | const ciphertext = frag[in..][0..ciphertext_len]; |
| | 1375 | in += ciphertext_len; |
| | 1376 | const auth_tag = frag[in..][0..P.AEAD.tag_length].*; |
| | 1377 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and |
| | 1378 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| | 1379 | nonce: { |
| | 1380 | var nonce = pv.server_iv; |
| | 1381 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| | 1382 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.read_seq, .big); |
| | 1383 | break :nonce nonce; |
| | 1384 | } else nonce: { |
| | 1385 | const V = @Vector(P.AEAD.nonce_length, u8); |
| | 1386 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| | 1387 | const operand: V = pad ++ std.mem.toBytes(big(c.read_seq)); |
| | 1388 | break :nonce @as(V, pv.server_iv) ^ operand; |
| | 1389 | }; |
| | 1390 | const out_buf = vp.peek(); |
| | 1391 | const cleartext_buf = if (ciphertext.len <= out_buf.len) |
| | 1392 | out_buf |
| | 1393 | else |
| | 1394 | &cleartext_stack_buffer; |
| | 1395 | const cleartext = cleartext_buf[0..ciphertext.len]; |
| | 1396 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, pv.server_key) catch |
| | 1397 | return error.TlsBadRecordMac; |
| | 1398 | const msg = mem.trimRight(u8, cleartext, "\x00"); |
| | 1399 | break :cleartext .{ msg[0 .. msg.len - 1], @enumFromInt(msg[msg.len - 1]) }; |
| | 1400 | }, |
| | 1401 | .tls_1_2 => { |
| | 1402 | const pv = &p.tls_1_2; |
| | 1403 | const P = @TypeOf(p.*); |
| | 1404 | const message_len: u16 = record_len - P.record_iv_length - P.mac_length; |
| | 1405 | const ad = std.mem.toBytes(big(c.read_seq)) ++ |
| | 1406 | frag[in - tls.record_header_len ..][0 .. 1 + 2] ++ |
| | 1407 | std.mem.toBytes(big(message_len)); |
| | 1408 | const record_iv = frag[in..][0..P.record_iv_length].*; |
| | 1409 | in += P.record_iv_length; |
| | 1410 | const masked_read_seq = c.read_seq & |
| | 1411 | comptime std.math.shl(u64, std.math.maxInt(u64), 8 * P.record_iv_length); |
| | 1412 | const nonce: [P.AEAD.nonce_length]u8 = if (builtin.zig_backend == .stage2_x86_64 and |
| | 1413 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) |
| | 1414 | nonce: { |
| | 1415 | var nonce = pv.server_write_IV ++ record_iv; |
| | 1416 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); |
| | 1417 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ masked_read_seq, .big); |
| | 1418 | break :nonce nonce; |
| | 1419 | } else nonce: { |
| | 1420 | const V = @Vector(P.AEAD.nonce_length, u8); |
| | 1421 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); |
| | 1422 | const operand: V = pad ++ @as([8]u8, @bitCast(big(masked_read_seq))); |
| | 1423 | break :nonce @as(V, pv.server_write_IV ++ record_iv) ^ operand; |
| | 1424 | }; |
| | 1425 | const ciphertext = frag[in..][0..message_len]; |
| | 1426 | in += message_len; |
| | 1427 | const auth_tag = frag[in..][0..P.mac_length].*; |
| | 1428 | in += P.mac_length; |
| | 1429 | const out_buf = vp.peek(); |
| | 1430 | const cleartext_buf = if (message_len <= out_buf.len) |
| | 1431 | out_buf |
| | 1432 | else |
| | 1433 | &cleartext_stack_buffer; |
| | 1434 | const cleartext = cleartext_buf[0..ciphertext.len]; |
| | 1435 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, pv.server_write_key) catch |
| | 1436 | return error.TlsBadRecordMac; |
| | 1437 | break :cleartext .{ cleartext, ct }; |
| | 1438 | }, |
| | 1439 | else => unreachable, |
| | 1440 | }, |
| | 1441 | }; |
| | 1442 | c.read_seq = try std.math.add(u64, c.read_seq, 1); |
| | 1443 | switch (inner_ct) { |
| 1109 | .alert => { | 1444 | .alert => { |
| 1110 | if (in + 2 > frag.len) return error.TlsDecodeError; | 1445 | if (cleartext.len != 2) return error.TlsDecodeError; |
| 1111 | const level: tls.AlertLevel = @enumFromInt(frag[in]); | 1446 | const level: tls.AlertLevel = @enumFromInt(cleartext[0]); |
| 1112 | const desc: tls.AlertDescription = @enumFromInt(frag[in + 1]); | 1447 | const desc: tls.AlertDescription = @enumFromInt(cleartext[1]); |
| | 1448 | if (desc == .close_notify) { |
| | 1449 | c.received_close_notify = true; |
| | 1450 | c.partial_ciphertext_end = c.partial_ciphertext_idx; |
| | 1451 | return vp.total; |
| | 1452 | } |
| 1113 | _ = level; | 1453 | _ = level; |
| 1114 | | 1454 | |
| 1115 | try desc.toError(); | 1455 | try desc.toError(); |
| 1116 | // TODO: handle server-side closures | 1456 | // TODO: handle server-side closures |
| 1117 | return error.TlsUnexpectedMessage; | 1457 | return error.TlsUnexpectedMessage; |
| 1118 | }, | 1458 | }, |
| 1119 | .application_data => { | 1459 | .handshake => { |
| 1120 | const cleartext = switch (c.application_cipher) { | 1460 | var ct_i: usize = 0; |
| 1121 | inline else => |*p| c: { | 1461 | while (true) { |
| 1122 | const P = @TypeOf(p.*); | 1462 | const handshake_type: tls.HandshakeType = @enumFromInt(cleartext[ct_i]); |
| 1123 | const ad = frag[in - 5 ..][0..5]; | 1463 | ct_i += 1; |
| 1124 | const ciphertext_len = record_len - P.AEAD.tag_length; | 1464 | const handshake_len = mem.readInt(u24, cleartext[ct_i..][0..3], .big); |
| 1125 | const ciphertext = frag[in..][0..ciphertext_len]; | 1465 | ct_i += 3; |
| 1126 | in += ciphertext_len; | 1466 | const next_handshake_i = ct_i + handshake_len; |
| 1127 | const auth_tag = frag[in..][0..P.AEAD.tag_length].*; | 1467 | if (next_handshake_i > cleartext.len) |
| 1128 | const nonce = if (builtin.zig_backend == .stage2_x86_64 and | 1468 | return error.TlsBadLength; |
| 1129 | P.AEAD.nonce_length > comptime std.simd.suggestVectorLength(u8) orelse 1) | 1469 | const handshake = cleartext[ct_i..next_handshake_i]; |
| 1130 | nonce: { | 1470 | switch (handshake_type) { |
| 1131 | var nonce = p.server_iv; | 1471 | .new_session_ticket => { |
| 1132 | const operand = std.mem.readInt(u64, nonce[nonce.len - 8 ..], .big); | 1472 | // This client implementation ignores new session tickets. |
| 1133 | std.mem.writeInt(u64, nonce[nonce.len - 8 ..], operand ^ c.read_seq, .big); | 1473 | }, |
| 1134 | break :nonce nonce; | 1474 | .key_update => { |
| 1135 | } else nonce: { | 1475 | switch (c.application_cipher) { |
| 1136 | const V = @Vector(P.AEAD.nonce_length, u8); | 1476 | inline else => |*p| { |
| 1137 | const pad = [1]u8{0} ** (P.AEAD.nonce_length - 8); | 1477 | const pv = &p.tls_1_3; |
| 1138 | const operand: V = pad ++ @as([8]u8, @bitCast(big(c.read_seq))); | 1478 | const P = @TypeOf(p.*); |
| 1139 | break :nonce @as(V, p.server_iv) ^ operand; | 1479 | const server_secret = hkdfExpandLabel(P.Hkdf, pv.server_secret, "traffic upd", "", P.Hash.digest_length); |
| 1140 | }; | 1480 | if (c.ssl_key_log) |*key_log| logSecrets(key_log.file, .{ |
| 1141 | const out_buf = vp.peek(); | 1481 | .counter = key_log.serverCounter(), |
| 1142 | const cleartext_buf = if (ciphertext.len <= out_buf.len) | 1482 | .client_random = &key_log.client_random, |
| 1143 | out_buf | 1483 | }, .{ |
| 1144 | else | 1484 | .SERVER_TRAFFIC_SECRET = &server_secret, |
| 1145 | &cleartext_stack_buffer; | 1485 | }); |
| 1146 | const cleartext = cleartext_buf[0..ciphertext.len]; | 1486 | pv.server_secret = server_secret; |
| 1147 | P.AEAD.decrypt(cleartext, ciphertext, auth_tag, ad, nonce, p.server_key) catch | 1487 | pv.server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); |
| 1148 | return error.TlsBadRecordMac; | 1488 | pv.server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); |
| 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. | | |
| 1185 | }, | 1489 | }, |
| 1186 | .key_update => { | 1490 | } |
| | 1491 | c.read_seq = 0; |
| | 1492 | |
| | 1493 | switch (@as(tls.KeyUpdateRequest, @enumFromInt(handshake[0]))) { |
| | 1494 | .update_requested => { |
| 1187 | switch (c.application_cipher) { | 1495 | switch (c.application_cipher) { |
| 1188 | inline else => |*p| { | 1496 | inline else => |*p| { |
| | 1497 | const pv = &p.tls_1_3; |
| 1189 | const P = @TypeOf(p.*); | 1498 | const P = @TypeOf(p.*); |
| 1190 | const server_secret = hkdfExpandLabel(P.Hkdf, p.server_secret, "traffic upd", "", P.Hash.digest_length); | 1499 | const client_secret = hkdfExpandLabel(P.Hkdf, pv.client_secret, "traffic upd", "", P.Hash.digest_length); |
| 1191 | p.server_secret = server_secret; | 1500 | if (c.ssl_key_log) |*key_log| logSecrets(key_log.file, .{ |
| 1192 | p.server_key = hkdfExpandLabel(P.Hkdf, server_secret, "key", "", P.AEAD.key_length); | 1501 | .counter = key_log.clientCounter(), |
| 1193 | p.server_iv = hkdfExpandLabel(P.Hkdf, server_secret, "iv", "", P.AEAD.nonce_length); | 1502 | .client_random = &key_log.client_random, |
| | 1503 | }, .{ |
| | 1504 | .CLIENT_TRAFFIC_SECRET = &client_secret, |
| | 1505 | }); |
| | 1506 | pv.client_secret = client_secret; |
| | 1507 | pv.client_key = hkdfExpandLabel(P.Hkdf, client_secret, "key", "", P.AEAD.key_length); |
| | 1508 | pv.client_iv = hkdfExpandLabel(P.Hkdf, client_secret, "iv", "", P.AEAD.nonce_length); |
| 1194 | }, | 1509 | }, |
| 1195 | } | 1510 | } |
| 1196 | c.read_seq = 0; | 1511 | c.write_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; | | |
| 1210 | }, | | |
| 1211 | .update_not_requested => {}, | | |
| 1212 | _ => return error.TlsIllegalParameter, | | |
| 1213 | } | | |
| 1214 | }, | | |
| 1215 | else => { | | |
| 1216 | return error.TlsUnexpectedMessage; | | |
| 1217 | }, | 1512 | }, |
| | 1513 | .update_not_requested => {}, |
| | 1514 | _ => return error.TlsIllegalParameter, |
| 1218 | } | 1515 | } |
| 1219 | ct_i = next_handshake_i; | 1516 | }, |
| 1220 | if (ct_i >= cleartext.len - 1) break; | 1517 | else => { |
| 1221 | } | 1518 | return error.TlsUnexpectedMessage; |
| 1222 | }, | 1519 | }, |
| 1223 | .application_data => { | 1520 | } |
| 1224 | // Determine whether the output buffer or a stack | 1521 | ct_i = next_handshake_i; |
| 1225 | // buffer was used for storing the cleartext. | 1522 | if (ct_i >= cleartext.len) break; |
| 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 | } | | |
| 1245 | } | | |
| 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 | }, | | |
| 1256 | } | 1523 | } |
| 1257 | }, | 1524 | }, |
| 1258 | else => { | 1525 | .application_data => { |
| 1259 | return error.TlsUnexpectedMessage; | 1526 | // Determine whether the output buffer or a stack |
| | 1527 | // buffer was used for storing the cleartext. |
| | 1528 | if (cleartext.ptr == &cleartext_stack_buffer) { |
| | 1529 | // Stack buffer was used, so we must copy to the output buffer. |
| | 1530 | if (c.partial_ciphertext_idx > c.partial_cleartext_idx) { |
| | 1531 | // We have already run out of room in iovecs. Continue |
| | 1532 | // appending to `partially_read_buffer`. |
| | 1533 | @memcpy( |
| | 1534 | c.partially_read_buffer[c.partial_ciphertext_idx..][0..cleartext.len], |
| | 1535 | cleartext, |
| | 1536 | ); |
| | 1537 | c.partial_ciphertext_idx = @intCast(c.partial_ciphertext_idx + cleartext.len); |
| | 1538 | } else { |
| | 1539 | const amt = vp.put(cleartext); |
| | 1540 | if (amt < cleartext.len) { |
| | 1541 | const rest = cleartext[amt..]; |
| | 1542 | c.partial_cleartext_idx = 0; |
| | 1543 | c.partial_ciphertext_idx = @intCast(rest.len); |
| | 1544 | @memcpy(c.partially_read_buffer[0..rest.len], rest); |
| | 1545 | } |
| | 1546 | } |
| | 1547 | } else { |
| | 1548 | // Output buffer was used directly which means no |
| | 1549 | // memory copying needs to occur, and we can move |
| | 1550 | // on to the next ciphertext record. |
| | 1551 | vp.next(cleartext.len); |
| | 1552 | } |
| 1260 | }, | 1553 | }, |
| | 1554 | else => return error.TlsUnexpectedMessage, |
| 1261 | } | 1555 | } |
| 1262 | in = end; | 1556 | in = end; |
| 1263 | } | 1557 | } |
| 1264 | } | 1558 | } |
| 1265 | | 1559 | |
| | 1560 | fn logSecrets(key_log_file: std.fs.File, context: anytype, secrets: anytype) void { |
| | 1561 | const locked = if (key_log_file.lock(.exclusive)) |_| true else |_| false; |
| | 1562 | defer if (locked) key_log_file.unlock(); |
| | 1563 | key_log_file.seekFromEnd(0) catch {}; |
| | 1564 | inline for (@typeInfo(@TypeOf(secrets)).@"struct".fields) |field| key_log_file.writer().print("{s}" ++ |
| | 1565 | (if (@hasField(@TypeOf(context), "counter")) "_{d}" else "") ++ " {} {}\n", .{field.name} ++ |
| | 1566 | (if (@hasField(@TypeOf(context), "counter")) .{context.counter} else .{}) ++ .{ |
| | 1567 | std.fmt.fmtSliceHexLower(context.client_random), |
| | 1568 | std.fmt.fmtSliceHexLower(@field(secrets, field.name)), |
| | 1569 | }) catch {}; |
| | 1570 | } |
| | 1571 | |
| 1266 | fn finishRead(c: *Client, frag: []const u8, in: usize, out: usize) usize { | 1572 | fn finishRead(c: *Client, frag: []const u8, in: usize, out: usize) usize { |
| 1267 | const saved_buf = frag[in..]; | 1573 | const saved_buf = frag[in..]; |
| 1268 | if (c.partial_ciphertext_idx > c.partial_cleartext_idx) { | 1574 | if (c.partial_ciphertext_idx > c.partial_cleartext_idx) { |
| ... | @@ -1326,6 +1632,86 @@ inline fn big(x: anytype) @TypeOf(x) { | ... | @@ -1326,6 +1632,86 @@ inline fn big(x: anytype) @TypeOf(x) { |
| 1326 | }; | 1632 | }; |
| 1327 | } | 1633 | } |
| 1328 | | 1634 | |
| | 1635 | const KeyShare = struct { |
| | 1636 | ml_kem768_kp: crypto.kem.ml_kem.MLKem768.KeyPair, |
| | 1637 | secp256r1_kp: crypto.sign.ecdsa.EcdsaP256Sha256.KeyPair, |
| | 1638 | secp384r1_kp: crypto.sign.ecdsa.EcdsaP384Sha384.KeyPair, |
| | 1639 | x25519_kp: crypto.dh.X25519.KeyPair, |
| | 1640 | sk_buf: [sk_max_len]u8, |
| | 1641 | sk_len: std.math.IntFittingRange(0, sk_max_len), |
| | 1642 | |
| | 1643 | const sk_max_len = @max( |
| | 1644 | crypto.dh.X25519.shared_length + crypto.kem.ml_kem.MLKem768.shared_length, |
| | 1645 | crypto.ecc.P256.scalar.encoded_length, |
| | 1646 | crypto.ecc.P384.scalar.encoded_length, |
| | 1647 | crypto.dh.X25519.shared_length, |
| | 1648 | ); |
| | 1649 | |
| | 1650 | fn init(seed: [112]u8) error{IdentityElement}!KeyShare { |
| | 1651 | return .{ |
| | 1652 | .ml_kem768_kp = try .create(null), |
| | 1653 | .secp256r1_kp = try .create(seed[0..32].*), |
| | 1654 | .secp384r1_kp = try .create(seed[32..80].*), |
| | 1655 | .x25519_kp = try .create(seed[80..112].*), |
| | 1656 | .sk_buf = undefined, |
| | 1657 | .sk_len = 0, |
| | 1658 | }; |
| | 1659 | } |
| | 1660 | |
| | 1661 | fn exchange( |
| | 1662 | ks: *KeyShare, |
| | 1663 | named_group: tls.NamedGroup, |
| | 1664 | server_pub_key: []const u8, |
| | 1665 | ) error{ TlsIllegalParameter, TlsDecryptFailure }!void { |
| | 1666 | switch (named_group) { |
| | 1667 | .x25519_ml_kem768 => { |
| | 1668 | const hksl = crypto.kem.ml_kem.MLKem768.ciphertext_length; |
| | 1669 | const xksl = hksl + crypto.dh.X25519.public_length; |
| | 1670 | if (server_pub_key.len != xksl) return error.TlsIllegalParameter; |
| | 1671 | |
| | 1672 | const hsk = ks.ml_kem768_kp.secret_key.decaps(server_pub_key[0..hksl]) catch |
| | 1673 | return error.TlsDecryptFailure; |
| | 1674 | const xsk = crypto.dh.X25519.scalarmult(ks.x25519_kp.secret_key, server_pub_key[hksl..xksl].*) catch |
| | 1675 | return error.TlsDecryptFailure; |
| | 1676 | @memcpy(ks.sk_buf[0..hsk.len], &hsk); |
| | 1677 | @memcpy(ks.sk_buf[hsk.len..][0..xsk.len], &xsk); |
| | 1678 | ks.sk_len = hsk.len + xsk.len; |
| | 1679 | }, |
| | 1680 | .secp256r1 => { |
| | 1681 | const PublicKey = crypto.sign.ecdsa.EcdsaP256Sha256.PublicKey; |
| | 1682 | const pk = PublicKey.fromSec1(server_pub_key) catch return error.TlsDecryptFailure; |
| | 1683 | const mul = pk.p.mulPublic(ks.secp256r1_kp.secret_key.bytes, .big) catch |
| | 1684 | return error.TlsDecryptFailure; |
| | 1685 | const sk = mul.affineCoordinates().x.toBytes(.big); |
| | 1686 | @memcpy(ks.sk_buf[0..sk.len], &sk); |
| | 1687 | ks.sk_len = sk.len; |
| | 1688 | }, |
| | 1689 | .secp384r1 => { |
| | 1690 | const PublicKey = crypto.sign.ecdsa.EcdsaP384Sha384.PublicKey; |
| | 1691 | const pk = PublicKey.fromSec1(server_pub_key) catch return error.TlsDecryptFailure; |
| | 1692 | const mul = pk.p.mulPublic(ks.secp384r1_kp.secret_key.bytes, .big) catch |
| | 1693 | return error.TlsDecryptFailure; |
| | 1694 | const sk = mul.affineCoordinates().x.toBytes(.big); |
| | 1695 | @memcpy(ks.sk_buf[0..sk.len], &sk); |
| | 1696 | ks.sk_len = sk.len; |
| | 1697 | }, |
| | 1698 | .x25519 => { |
| | 1699 | const ksl = crypto.dh.X25519.public_length; |
| | 1700 | if (server_pub_key.len != ksl) return error.TlsIllegalParameter; |
| | 1701 | const sk = crypto.dh.X25519.scalarmult(ks.x25519_kp.secret_key, server_pub_key[0..ksl].*) catch |
| | 1702 | return error.TlsDecryptFailure; |
| | 1703 | @memcpy(ks.sk_buf[0..sk.len], &sk); |
| | 1704 | ks.sk_len = sk.len; |
| | 1705 | }, |
| | 1706 | else => return error.TlsIllegalParameter, |
| | 1707 | } |
| | 1708 | } |
| | 1709 | |
| | 1710 | fn getSharedSecret(ks: *const KeyShare) ?[]const u8 { |
| | 1711 | return if (ks.sk_len > 0) ks.sk_buf[0..ks.sk_len] else null; |
| | 1712 | } |
| | 1713 | }; |
| | 1714 | |
| 1329 | fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { | 1715 | fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { |
| 1330 | return switch (scheme) { | 1716 | return switch (scheme) { |
| 1331 | .ecdsa_secp256r1_sha256 => crypto.sign.ecdsa.EcdsaP256Sha256, | 1717 | .ecdsa_secp256r1_sha256 => crypto.sign.ecdsa.EcdsaP256Sha256, |
| ... | @@ -1334,11 +1720,20 @@ fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { | ... | @@ -1334,11 +1720,20 @@ fn SchemeEcdsa(comptime scheme: tls.SignatureScheme) type { |
| 1334 | }; | 1720 | }; |
| 1335 | } | 1721 | } |
| 1336 | | 1722 | |
| 1337 | fn SchemeHash(comptime scheme: tls.SignatureScheme) type { | 1723 | fn SchemeRsa(comptime scheme: tls.SignatureScheme) type { |
| 1338 | return switch (scheme) { | 1724 | return switch (scheme) { |
| 1339 | .rsa_pss_rsae_sha256 => crypto.hash.sha2.Sha256, | 1725 | .rsa_pkcs1_sha256, |
| 1340 | .rsa_pss_rsae_sha384 => crypto.hash.sha2.Sha384, | 1726 | .rsa_pkcs1_sha384, |
| 1341 | .rsa_pss_rsae_sha512 => crypto.hash.sha2.Sha512, | 1727 | .rsa_pkcs1_sha512, |
| | 1728 | .rsa_pkcs1_sha1, |
| | 1729 | => Certificate.rsa.PKCS1v1_5Signature, |
| | 1730 | .rsa_pss_rsae_sha256, |
| | 1731 | .rsa_pss_rsae_sha384, |
| | 1732 | .rsa_pss_rsae_sha512, |
| | 1733 | .rsa_pss_pss_sha256, |
| | 1734 | .rsa_pss_pss_sha384, |
| | 1735 | .rsa_pss_pss_sha512, |
| | 1736 | => Certificate.rsa.PSSSignature, |
| 1342 | else => @compileError("bad scheme"), | 1737 | else => @compileError("bad scheme"), |
| 1343 | }; | 1738 | }; |
| 1344 | } | 1739 | } |
| ... | @@ -1350,6 +1745,146 @@ fn SchemeEddsa(comptime scheme: tls.SignatureScheme) type { | ... | @@ -1350,6 +1745,146 @@ fn SchemeEddsa(comptime scheme: tls.SignatureScheme) type { |
| 1350 | }; | 1745 | }; |
| 1351 | } | 1746 | } |
| 1352 | | 1747 | |
| | 1748 | fn SchemeHash(comptime scheme: tls.SignatureScheme) type { |
| | 1749 | return switch (scheme) { |
| | 1750 | .rsa_pkcs1_sha256, |
| | 1751 | .ecdsa_secp256r1_sha256, |
| | 1752 | .rsa_pss_rsae_sha256, |
| | 1753 | .rsa_pss_pss_sha256, |
| | 1754 | => crypto.hash.sha2.Sha256, |
| | 1755 | .rsa_pkcs1_sha384, |
| | 1756 | .ecdsa_secp384r1_sha384, |
| | 1757 | .rsa_pss_rsae_sha384, |
| | 1758 | .rsa_pss_pss_sha384, |
| | 1759 | => crypto.hash.sha2.Sha384, |
| | 1760 | .rsa_pkcs1_sha512, |
| | 1761 | .ecdsa_secp521r1_sha512, |
| | 1762 | .rsa_pss_rsae_sha512, |
| | 1763 | .rsa_pss_pss_sha512, |
| | 1764 | => crypto.hash.sha2.Sha512, |
| | 1765 | .rsa_pkcs1_sha1, |
| | 1766 | .ecdsa_sha1, |
| | 1767 | => crypto.hash.Sha1, |
| | 1768 | else => @compileError("bad scheme"), |
| | 1769 | }; |
| | 1770 | } |
| | 1771 | |
| | 1772 | const CertificatePublicKey = struct { |
| | 1773 | algo: Certificate.AlgorithmCategory, |
| | 1774 | buf: [600]u8, |
| | 1775 | len: u16, |
| | 1776 | |
| | 1777 | fn init( |
| | 1778 | cert_pub_key: *CertificatePublicKey, |
| | 1779 | algo: Certificate.AlgorithmCategory, |
| | 1780 | pub_key: []const u8, |
| | 1781 | ) error{CertificatePublicKeyInvalid}!void { |
| | 1782 | if (pub_key.len > cert_pub_key.buf.len) return error.CertificatePublicKeyInvalid; |
| | 1783 | cert_pub_key.algo = algo; |
| | 1784 | @memcpy(cert_pub_key.buf[0..pub_key.len], pub_key); |
| | 1785 | cert_pub_key.len = @intCast(pub_key.len); |
| | 1786 | } |
| | 1787 | |
| | 1788 | const VerifyError = error{ TlsDecodeError, TlsBadSignatureScheme, InvalidEncoding } || |
| | 1789 | // ecdsa |
| | 1790 | crypto.errors.EncodingError || |
| | 1791 | crypto.errors.NotSquareError || |
| | 1792 | crypto.errors.NonCanonicalError || |
| | 1793 | SchemeEcdsa(.ecdsa_secp256r1_sha256).Signature.VerifyError || |
| | 1794 | SchemeEcdsa(.ecdsa_secp384r1_sha384).Signature.VerifyError || |
| | 1795 | // rsa |
| | 1796 | error{TlsBadRsaSignatureBitCount} || |
| | 1797 | Certificate.rsa.PublicKey.ParseDerError || |
| | 1798 | Certificate.rsa.PublicKey.FromBytesError || |
| | 1799 | Certificate.rsa.PSSSignature.VerifyError || |
| | 1800 | Certificate.rsa.PKCS1v1_5Signature.VerifyError || |
| | 1801 | // eddsa |
| | 1802 | SchemeEddsa(.ed25519).Signature.VerifyError; |
| | 1803 | |
| | 1804 | fn verifySignature( |
| | 1805 | cert_pub_key: *const CertificatePublicKey, |
| | 1806 | sigd: *tls.Decoder, |
| | 1807 | msg: []const []const u8, |
| | 1808 | ) VerifyError!void { |
| | 1809 | const pub_key = cert_pub_key.buf[0..cert_pub_key.len]; |
| | 1810 | |
| | 1811 | try sigd.ensure(2 + 2); |
| | 1812 | const scheme = sigd.decode(tls.SignatureScheme); |
| | 1813 | const sig_len = sigd.decode(u16); |
| | 1814 | try sigd.ensure(sig_len); |
| | 1815 | const encoded_sig = sigd.slice(sig_len); |
| | 1816 | |
| | 1817 | if (cert_pub_key.algo != @as(Certificate.AlgorithmCategory, switch (scheme) { |
| | 1818 | .ecdsa_secp256r1_sha256, |
| | 1819 | .ecdsa_secp384r1_sha384, |
| | 1820 | => .X9_62_id_ecPublicKey, |
| | 1821 | .rsa_pkcs1_sha256, |
| | 1822 | .rsa_pkcs1_sha384, |
| | 1823 | .rsa_pkcs1_sha512, |
| | 1824 | .rsa_pss_rsae_sha256, |
| | 1825 | .rsa_pss_rsae_sha384, |
| | 1826 | .rsa_pss_rsae_sha512, |
| | 1827 | .rsa_pkcs1_sha1, |
| | 1828 | => .rsaEncryption, |
| | 1829 | .rsa_pss_pss_sha256, |
| | 1830 | .rsa_pss_pss_sha384, |
| | 1831 | .rsa_pss_pss_sha512, |
| | 1832 | => .rsassa_pss, |
| | 1833 | else => return error.TlsBadSignatureScheme, |
| | 1834 | })) return error.TlsBadSignatureScheme; |
| | 1835 | |
| | 1836 | switch (scheme) { |
| | 1837 | inline .ecdsa_secp256r1_sha256, |
| | 1838 | .ecdsa_secp384r1_sha384, |
| | 1839 | => |comptime_scheme| { |
| | 1840 | const Ecdsa = SchemeEcdsa(comptime_scheme); |
| | 1841 | const sig = try Ecdsa.Signature.fromDer(encoded_sig); |
| | 1842 | const key = try Ecdsa.PublicKey.fromSec1(pub_key); |
| | 1843 | var ver = try sig.verifier(key); |
| | 1844 | for (msg) |part| ver.update(part); |
| | 1845 | try ver.verify(); |
| | 1846 | }, |
| | 1847 | inline .rsa_pkcs1_sha256, |
| | 1848 | .rsa_pkcs1_sha384, |
| | 1849 | .rsa_pkcs1_sha512, |
| | 1850 | .rsa_pss_rsae_sha256, |
| | 1851 | .rsa_pss_rsae_sha384, |
| | 1852 | .rsa_pss_rsae_sha512, |
| | 1853 | .rsa_pss_pss_sha256, |
| | 1854 | .rsa_pss_pss_sha384, |
| | 1855 | .rsa_pss_pss_sha512, |
| | 1856 | .rsa_pkcs1_sha1, |
| | 1857 | => |comptime_scheme| { |
| | 1858 | const RsaSignature = SchemeRsa(comptime_scheme); |
| | 1859 | const Hash = SchemeHash(comptime_scheme); |
| | 1860 | const PublicKey = Certificate.rsa.PublicKey; |
| | 1861 | const components = try PublicKey.parseDer(pub_key); |
| | 1862 | const exponent = components.exponent; |
| | 1863 | const modulus = components.modulus; |
| | 1864 | switch (modulus.len) { |
| | 1865 | inline 128, 256, 384, 512 => |modulus_len| { |
| | 1866 | const key: PublicKey = try .fromBytes(exponent, modulus); |
| | 1867 | const sig = RsaSignature.fromBytes(modulus_len, encoded_sig); |
| | 1868 | try RsaSignature.concatVerify(modulus_len, sig, msg, key, Hash); |
| | 1869 | }, |
| | 1870 | else => return error.TlsBadRsaSignatureBitCount, |
| | 1871 | } |
| | 1872 | }, |
| | 1873 | inline .ed25519 => |comptime_scheme| { |
| | 1874 | const Eddsa = SchemeEddsa(comptime_scheme); |
| | 1875 | if (encoded_sig.len != Eddsa.Signature.encoded_length) return error.InvalidEncoding; |
| | 1876 | const sig = Eddsa.Signature.fromBytes(encoded_sig[0..Eddsa.Signature.encoded_length].*); |
| | 1877 | if (pub_key.len != Eddsa.PublicKey.encoded_length) return error.InvalidEncoding; |
| | 1878 | const key = try Eddsa.PublicKey.fromBytes(pub_key[0..Eddsa.PublicKey.encoded_length].*); |
| | 1879 | var ver = try sig.verifier(key); |
| | 1880 | for (msg) |part| ver.update(part); |
| | 1881 | try ver.verify(); |
| | 1882 | }, |
| | 1883 | else => unreachable, |
| | 1884 | } |
| | 1885 | } |
| | 1886 | }; |
| | 1887 | |
| 1353 | /// Abstraction for sending multiple byte buffers to a slice of iovecs. | 1888 | /// Abstraction for sending multiple byte buffers to a slice of iovecs. |
| 1354 | const VecPut = struct { | 1889 | const VecPut = struct { |
| 1355 | iovecs: []const std.posix.iovec, | 1890 | iovecs: []const std.posix.iovec, |
| ... | @@ -1447,20 +1982,26 @@ fn limitVecs(iovecs: []std.posix.iovec, len: usize) []std.posix.iovec { | ... | @@ -1447,20 +1982,26 @@ fn limitVecs(iovecs: []std.posix.iovec, len: usize) []std.posix.iovec { |
| 1447 | /// aes128-gcm: 138 MiB/s | 1982 | /// aes128-gcm: 138 MiB/s |
| 1448 | /// aes256-gcm: 120 MiB/s | 1983 | /// aes256-gcm: 120 MiB/s |
| 1449 | const cipher_suites = if (crypto.core.aes.has_hardware_support) | 1984 | const cipher_suites = if (crypto.core.aes.has_hardware_support) |
| 1450 | enum_array(tls.CipherSuite, &.{ | 1985 | array(u16, tls.CipherSuite, .{ |
| 1451 | .AEGIS_128L_SHA256, | 1986 | .AEGIS_128L_SHA256, |
| 1452 | .AEGIS_256_SHA512, | 1987 | .AEGIS_256_SHA512, |
| 1453 | .AES_128_GCM_SHA256, | 1988 | .AES_128_GCM_SHA256, |
| | 1989 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1454 | .AES_256_GCM_SHA384, | 1990 | .AES_256_GCM_SHA384, |
| | 1991 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1455 | .CHACHA20_POLY1305_SHA256, | 1992 | .CHACHA20_POLY1305_SHA256, |
| | 1993 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 1456 | }) | 1994 | }) |
| 1457 | else | 1995 | else |
| 1458 | enum_array(tls.CipherSuite, &.{ | 1996 | array(u16, tls.CipherSuite, .{ |
| 1459 | .CHACHA20_POLY1305_SHA256, | 1997 | .CHACHA20_POLY1305_SHA256, |
| | 1998 | .ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, |
| 1460 | .AEGIS_128L_SHA256, | 1999 | .AEGIS_128L_SHA256, |
| 1461 | .AEGIS_256_SHA512, | 2000 | .AEGIS_256_SHA512, |
| 1462 | .AES_128_GCM_SHA256, | 2001 | .AES_128_GCM_SHA256, |
| | 2002 | .ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 1463 | .AES_256_GCM_SHA384, | 2003 | .AES_256_GCM_SHA384, |
| | 2004 | .ECDHE_RSA_WITH_AES_256_GCM_SHA384, |
| 1464 | }); | 2005 | }); |
| 1465 | | 2006 | |
| 1466 | test { | 2007 | test { |