Coverage Report

Created: 2026-04-30 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/ssl/handshake_client.cc
Line
Count
Source
1
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2
// Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
3
// Copyright 2005 Nokia. All rights reserved.
4
//
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
//
9
//     https://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
16
17
#include <openssl/ssl.h>
18
19
#include <assert.h>
20
#include <limits.h>
21
#include <string.h>
22
23
#include <algorithm>
24
#include <utility>
25
26
#include <openssl/aead.h>
27
#include <openssl/bn.h>
28
#include <openssl/bytestring.h>
29
#include <openssl/ec_key.h>
30
#include <openssl/ecdsa.h>
31
#include <openssl/err.h>
32
#include <openssl/evp.h>
33
#include <openssl/hpke.h>
34
#include <openssl/md5.h>
35
#include <openssl/mem.h>
36
#include <openssl/rand.h>
37
#include <openssl/sha2.h>
38
39
#include "../crypto/bytestring/internal.h"
40
#include "../crypto/internal.h"
41
#include "internal.h"
42
43
44
BSSL_NAMESPACE_BEGIN
45
46
enum ssl_client_hs_state_t {
47
  state_start_connect = 0,
48
  state_enter_early_data,
49
  state_early_reverify_server_certificate,
50
  state_read_server_hello,
51
  state_tls13,
52
  state_read_server_certificate,
53
  state_read_certificate_status,
54
  state_verify_server_certificate,
55
  state_reverify_server_certificate,
56
  state_read_server_key_exchange,
57
  state_read_certificate_request,
58
  state_read_server_hello_done,
59
  state_send_client_certificate,
60
  state_send_client_key_exchange,
61
  state_send_client_certificate_verify,
62
  state_send_client_finished,
63
  state_finish_flight,
64
  state_read_session_ticket,
65
  state_process_change_cipher_spec,
66
  state_read_server_finished,
67
  state_finish_client_handshake,
68
  state_done,
69
};
70
71
// ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
72
// disabled algorithms.
73
static void ssl_get_client_disabled(const SSL_HANDSHAKE *hs,
74
                                    uint32_t *out_mask_a,
75
90.2k
                                    uint32_t *out_mask_k) {
76
90.2k
  *out_mask_a = 0;
77
90.2k
  *out_mask_k = 0;
78
79
  // PSK requires a client callback.
80
90.2k
  if (hs->config->psk_client_callback == nullptr) {
81
90.2k
    *out_mask_a |= SSL_aPSK;
82
90.2k
    *out_mask_k |= SSL_kPSK;
83
90.2k
  }
84
90.2k
}
85
86
static bool ssl_add_tls13_cipher(CBB *cbb, uint16_t cipher_id,
87
146k
                                 ssl_compliance_policy_t policy) {
88
146k
  if (ssl_tls13_cipher_meets_policy(cipher_id, policy)) {
89
146k
    return CBB_add_u16(cbb, cipher_id);
90
146k
  }
91
0
  return true;
92
146k
}
93
94
static bool ssl_write_client_cipher_list(const SSL_HANDSHAKE *hs, CBB *out,
95
48.8k
                                         ssl_client_hello_type_t type) {
96
48.8k
  const SSL *const ssl = hs->ssl;
97
48.8k
  uint32_t mask_a, mask_k;
98
48.8k
  ssl_get_client_disabled(hs, &mask_a, &mask_k);
99
100
48.8k
  CBB child;
101
48.8k
  if (!CBB_add_u16_length_prefixed(out, &child)) {
102
0
    return false;
103
0
  }
104
105
  // Add a fake cipher suite. See RFC 8701.
106
48.8k
  if (ssl->ctx->grease_enabled &&
107
0
      !CBB_add_u16(&child, ssl_get_grease_value(hs, ssl_grease_cipher))) {
108
0
    return false;
109
0
  }
110
111
  // Add TLS 1.3 ciphers. Order ChaCha20-Poly1305 relative to AES-GCM based on
112
  // hardware support.
113
48.8k
  if (hs->max_version >= TLS1_3_VERSION) {
114
48.8k
    static const uint16_t kCiphersNoAESHardware[] = {
115
48.8k
        SSL_CIPHER_CHACHA20_POLY1305_SHA256,
116
48.8k
        SSL_CIPHER_AES_128_GCM_SHA256,
117
48.8k
        SSL_CIPHER_AES_256_GCM_SHA384,
118
48.8k
    };
119
48.8k
    static const uint16_t kCiphersAESHardware[] = {
120
48.8k
        SSL_CIPHER_AES_128_GCM_SHA256,
121
48.8k
        SSL_CIPHER_AES_256_GCM_SHA384,
122
48.8k
        SSL_CIPHER_CHACHA20_POLY1305_SHA256,
123
48.8k
    };
124
48.8k
    static const uint16_t kCiphersCNSA[] = {
125
48.8k
        SSL_CIPHER_AES_256_GCM_SHA384,
126
48.8k
        SSL_CIPHER_AES_128_GCM_SHA256,
127
48.8k
        SSL_CIPHER_CHACHA20_POLY1305_SHA256,
128
48.8k
    };
129
130
48.8k
    const bool has_aes_hw = ssl->config->aes_hw_override
131
48.8k
                                ? ssl->config->aes_hw_override_value
132
48.8k
                                : EVP_has_aes_hardware();
133
48.8k
    const bssl::Span<const uint16_t> ciphers =
134
48.8k
        ssl->config->compliance_policy == ssl_compliance_policy_cnsa_202407
135
48.8k
            ? bssl::Span<const uint16_t>(kCiphersCNSA)
136
48.8k
            : (has_aes_hw ? bssl::Span<const uint16_t>(kCiphersAESHardware)
137
48.8k
                          : bssl::Span<const uint16_t>(kCiphersNoAESHardware));
138
139
146k
    for (auto cipher : ciphers) {
140
146k
      if (!ssl_add_tls13_cipher(&child, cipher,
141
146k
                                ssl->config->compliance_policy)) {
142
0
        return false;
143
0
      }
144
146k
    }
145
48.8k
  }
146
147
48.8k
  if (hs->min_version < TLS1_3_VERSION && type != ssl_client_hello_inner) {
148
48.8k
    bool any_enabled = false;
149
976k
    for (const SSL_CIPHER *cipher : SSL_get_ciphers(ssl)) {
150
      // Skip disabled ciphers
151
976k
      if ((cipher->algorithm_mkey & mask_k) ||
152
878k
          (cipher->algorithm_auth & mask_a)) {
153
244k
        continue;
154
244k
      }
155
732k
      if (SSL_CIPHER_get_min_version(cipher) > hs->max_version ||
156
732k
          SSL_CIPHER_get_max_version(cipher) < hs->min_version) {
157
0
        continue;
158
0
      }
159
732k
      any_enabled = true;
160
732k
      if (!CBB_add_u16(&child, SSL_CIPHER_get_protocol_id(cipher))) {
161
0
        return false;
162
0
      }
163
732k
    }
164
165
    // If all ciphers were disabled, return the error to the caller.
166
48.8k
    if (!any_enabled && hs->max_version < TLS1_3_VERSION) {
167
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
168
0
      return false;
169
0
    }
170
48.8k
  }
171
172
48.8k
  if (ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
173
0
    if (!CBB_add_u16(&child, SSL_CIPHER_FALLBACK_SCSV)) {
174
0
      return false;
175
0
    }
176
0
  }
177
178
48.8k
  return CBB_flush(out);
179
48.8k
}
180
181
bool ssl_write_client_hello_without_extensions(const SSL_HANDSHAKE *hs,
182
                                               CBB *cbb,
183
                                               ssl_client_hello_type_t type,
184
48.8k
                                               bool empty_session_id) {
185
48.8k
  const SSL *const ssl = hs->ssl;
186
48.8k
  CBB child;
187
48.8k
  if (!CBB_add_u16(cbb, hs->client_version) ||
188
48.8k
      !CBB_add_bytes(cbb,
189
48.8k
                     type == ssl_client_hello_inner ? hs->inner_client_random
190
48.8k
                                                    : ssl->s3->client_random,
191
48.8k
                     SSL3_RANDOM_SIZE) ||
192
48.8k
      !CBB_add_u8_length_prefixed(cbb, &child)) {
193
0
    return false;
194
0
  }
195
196
  // Do not send a session ID on renegotiation.
197
48.8k
  if (!ssl->s3->initial_handshake_complete &&  //
198
15.2k
      !empty_session_id &&                     //
199
15.2k
      !CBB_add_bytes(&child, hs->session_id.data(), hs->session_id.size())) {
200
0
    return false;
201
0
  }
202
203
48.8k
  if (SSL_is_dtls(ssl)) {
204
6.67k
    if (!CBB_add_u8_length_prefixed(cbb, &child) ||
205
6.67k
        !CBB_add_bytes(&child, hs->dtls_cookie.data(),
206
6.67k
                       hs->dtls_cookie.size())) {
207
0
      return false;
208
0
    }
209
6.67k
  }
210
211
48.8k
  if (!ssl_write_client_cipher_list(hs, cbb, type) ||
212
48.8k
      !CBB_add_u8(cbb, 1 /* one compression method */) ||
213
48.8k
      !CBB_add_u8(cbb, 0 /* null compression */)) {
214
0
    return false;
215
0
  }
216
48.8k
  return true;
217
48.8k
}
218
219
48.8k
bool ssl_add_client_hello(SSL_HANDSHAKE *hs) {
220
48.8k
  SSL *const ssl = hs->ssl;
221
48.8k
  ScopedCBB cbb;
222
48.8k
  CBB body;
223
48.8k
  ssl_client_hello_type_t type = hs->selected_ech_config
224
48.8k
                                     ? ssl_client_hello_outer
225
48.8k
                                     : ssl_client_hello_unencrypted;
226
48.8k
  Array<uint8_t> msg;
227
48.8k
  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO) ||
228
48.8k
      !ssl_write_client_hello_without_extensions(hs, &body, type,
229
48.8k
                                                 /*empty_session_id=*/false) ||
230
48.8k
      !ssl_add_clienthello_tlsext(hs, &body, /*out_encoded=*/nullptr, type) ||
231
48.8k
      !ssl->method->finish_message(ssl, cbb.get(), &msg)) {
232
0
    return false;
233
0
  }
234
235
48.8k
  return ssl->method->add_message(ssl, std::move(msg));
236
48.8k
}
237
238
static bool parse_server_version(const SSL_HANDSHAKE *hs, uint16_t *out_version,
239
                                 uint8_t *out_alert,
240
44.5k
                                 const ParsedServerHello &server_hello) {
241
44.5k
  uint16_t legacy_version = TLS1_2_VERSION;
242
44.5k
  if (SSL_is_dtls(hs->ssl)) {
243
3.82k
    legacy_version = DTLS1_2_VERSION;
244
3.82k
  }
245
  // If the outer version is not TLS 1.2, use it.
246
  // TODO(davidben): This function doesn't quite match the RFC8446 formulation.
247
44.5k
  if (server_hello.legacy_version != legacy_version) {
248
3.14k
    *out_version = server_hello.legacy_version;
249
3.14k
    return true;
250
3.14k
  }
251
252
41.3k
  SSLExtension supported_versions(TLSEXT_TYPE_supported_versions);
253
41.3k
  CBS extensions = server_hello.extensions;
254
41.3k
  if (!ssl_parse_extensions(&extensions, out_alert, {&supported_versions},
255
41.3k
                            /*ignore_unknown=*/true)) {
256
44
    return false;
257
44
  }
258
259
41.3k
  if (!supported_versions.present) {
260
38.4k
    *out_version = server_hello.legacy_version;
261
38.4k
    return true;
262
38.4k
  }
263
264
2.91k
  if (!CBS_get_u16(&supported_versions.data, out_version) ||  //
265
2.90k
      CBS_len(&supported_versions.data) != 0) {
266
7
    *out_alert = SSL_AD_DECODE_ERROR;
267
7
    return false;
268
7
  }
269
270
2.90k
  return true;
271
2.91k
}
272
273
// should_offer_early_data returns |ssl_early_data_accepted| if |hs| should
274
// offer early data, and some other reason code otherwise.
275
static ssl_early_data_reason_t should_offer_early_data(
276
47.0k
    const SSL_HANDSHAKE *hs) {
277
47.0k
  const SSL *const ssl = hs->ssl;
278
47.0k
  assert(!ssl->server);
279
47.0k
  if (!ssl->enable_early_data) {
280
0
    return ssl_early_data_disabled;
281
0
  }
282
283
47.0k
  if (hs->max_version < TLS1_3_VERSION || SSL_is_dtls(ssl)) {
284
    // We discard inapplicable sessions, so this is redundant with the session
285
    // checks below, but reporting that TLS 1.3 was disabled is more useful.
286
    //
287
    // TODO(crbug.com/381113363): Support early data in DTLS 1.3.
288
5.00k
    return ssl_early_data_protocol_version;
289
5.00k
  }
290
291
42.0k
  if (ssl->session == nullptr) {
292
40.8k
    return ssl_early_data_no_session_offered;
293
40.8k
  }
294
295
1.18k
  if (ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION ||
296
1.11k
      ssl->session->ticket_max_early_data == 0) {
297
1.11k
    return ssl_early_data_unsupported_for_session;
298
1.11k
  }
299
300
71
  if (!ssl->session->early_alpn.empty()) {
301
7
    if (!ssl_is_alpn_protocol_allowed(hs, ssl->session->early_alpn)) {
302
      // Avoid reporting a confusing value in |SSL_get0_alpn_selected|.
303
5
      return ssl_early_data_alpn_mismatch;
304
5
    }
305
306
    // If the previous connection negotiated ALPS, only offer 0-RTT when the
307
    // local are settings are consistent with what we'd offer for this
308
    // connection.
309
2
    if (ssl->session->has_application_settings) {
310
0
      Span<const uint8_t> settings;
311
0
      if (!ssl_get_local_application_settings(hs, &settings,
312
0
                                              ssl->session->early_alpn) ||
313
0
          settings != ssl->session->local_application_settings) {
314
0
        return ssl_early_data_alps_mismatch;
315
0
      }
316
0
    }
317
2
  }
318
319
  // Early data has not yet been accepted, but we use it as a success code.
320
66
  return ssl_early_data_accepted;
321
71
}
322
323
42.1k
void ssl_done_writing_client_hello(SSL_HANDSHAKE *hs) {
324
42.1k
  hs->ech_client_outer.Reset();
325
42.1k
  hs->cookie.Reset();
326
42.1k
  hs->key_share_bytes.Reset();
327
42.1k
  hs->pake_share_bytes.Reset();
328
42.1k
}
329
330
94.3k
bool ssl_accepts_server_certificate_auth(const SSL_HANDSHAKE *hs) {
331
94.3k
  assert(!hs->ssl->server);
332
  // In PAKE mode, the server must respond with a PAKE. We do not support
333
  // accepting both PAKE and certificates together.
334
94.3k
  if (hs->pake_prover != nullptr) {
335
0
    return false;
336
0
  }
337
338
  // If the caller has explicitly asked for certificate verification, it is
339
  // willing to accept a certificate, even if it has non-certificate
340
  // credentials, such as a PSK.
341
94.3k
  if (hs->config->verify_mode != SSL_VERIFY_NONE) {
342
0
    return true;
343
0
  }
344
345
  // Otherwise, we fall back to default behavior: if there is at least one
346
  // non-certificate credential configured, assume by default that the caller is
347
  // only willing to use that non-certificate mode.
348
94.3k
  return std::none_of(hs->config->cert->credentials.begin(),
349
94.3k
                      hs->config->cert->credentials.end(),
350
94.3k
                      [](const auto &cred) { return !cred->UsesPrivateKey(); });
351
94.3k
}
352
353
47.0k
static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
354
47.0k
  SSL *const ssl = hs->ssl;
355
356
47.0k
  ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
357
  // |session_reused| must be reset in case this is a renegotiation.
358
47.0k
  ssl->s3->session_reused = false;
359
360
  // Freeze the version range.
361
47.0k
  if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
362
0
    return ssl_hs_error;
363
0
  }
364
365
47.0k
  uint8_t ech_enc[EVP_HPKE_MAX_ENC_LENGTH];
366
47.0k
  size_t ech_enc_len;
367
47.0k
  if (!ssl_select_ech_config(hs, ech_enc, &ech_enc_len)) {
368
0
    return ssl_hs_error;
369
0
  }
370
371
  // Always advertise the ClientHello version from the original maximum version,
372
  // even on renegotiation. The static RSA key exchange uses this field, and
373
  // some servers fail when it changes across handshakes.
374
47.0k
  if (SSL_is_dtls(hs->ssl)) {
375
5.00k
    hs->client_version =
376
5.00k
        hs->max_version >= TLS1_2_VERSION ? DTLS1_2_VERSION : DTLS1_VERSION;
377
42.0k
  } else {
378
42.0k
    hs->client_version =
379
42.0k
        hs->max_version >= TLS1_2_VERSION ? TLS1_2_VERSION : hs->max_version;
380
42.0k
  }
381
382
47.0k
  if (!ssl_setup_pake_shares(hs)) {
383
0
    return ssl_hs_error;
384
0
  }
385
386
  // If the configured session has expired or is not usable, drop it. We also do
387
  // not offer sessions on renegotiation.
388
47.0k
  SSLSessionType session_type = SSLSessionType::kNotResumable;
389
47.0k
  if (ssl->session != nullptr) {
390
1.84k
    session_type = ssl_session_get_type(ssl->session.get());
391
1.84k
    if (ssl->session->is_server ||
392
1.70k
        !ssl_supports_version(hs, ssl->session->ssl_version) ||
393
        // Do not offer TLS 1.2 sessions with ECH. ClientHelloInner does not
394
        // offer TLS 1.2, and the cleartext session ID may leak the server
395
        // identity.
396
1.67k
        (hs->selected_ech_config &&
397
0
         ssl_session_protocol_version(ssl->session.get()) < TLS1_3_VERSION) ||
398
1.67k
        session_type == SSLSessionType::kNotResumable ||
399
        // Don't offer TLS 1.2 tickets if disabled.
400
1.61k
        (session_type == SSLSessionType::kTicket &&
401
109
         (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) ||
402
        // Don't offer sessions and PAKEs at the same time. We do not currently
403
        // support resumption with PAKEs. (Offering both together would need
404
        // more logic to conditionally send the key_share extension.)
405
1.61k
        hs->pake_prover != nullptr ||
406
1.61k
        !ssl_session_is_time_valid(ssl, ssl->session.get()) ||
407
1.54k
        SSL_is_quic(ssl) != int{ssl->session->is_quic} ||
408
1.54k
        ssl->s3->initial_handshake_complete) {
409
325
      ssl_set_session(ssl, nullptr);
410
325
      session_type = SSLSessionType::kNotResumable;
411
325
    }
412
1.84k
  }
413
414
47.0k
  if (!RAND_bytes(ssl->s3->client_random, sizeof(ssl->s3->client_random))) {
415
0
    return ssl_hs_error;
416
0
  }
417
47.0k
  if (hs->selected_ech_config &&
418
0
      !RAND_bytes(hs->inner_client_random, sizeof(hs->inner_client_random))) {
419
0
    return ssl_hs_error;
420
0
  }
421
422
  // Compatibility mode sends a random session ID. Compatibility mode is
423
  // enabled for TLS 1.3, but not when it's run over QUIC or DTLS.
424
47.0k
  const bool enable_compatibility_mode = hs->max_version >= TLS1_3_VERSION &&
425
47.0k
                                         !SSL_is_quic(ssl) && !SSL_is_dtls(ssl);
426
47.0k
  if (session_type == SSLSessionType::kID) {
427
1.07k
    hs->session_id = ssl->session->session_id;
428
45.9k
  } else if (session_type == SSLSessionType::kTicket ||
429
45.8k
             enable_compatibility_mode) {
430
    // TLS 1.2 session tickets require a placeholder value to signal resumption.
431
41.1k
    hs->session_id.ResizeForOverwrite(SSL_MAX_SSL_SESSION_ID_LENGTH);
432
41.1k
    if (!RAND_bytes(hs->session_id.data(), hs->session_id.size())) {
433
0
      return ssl_hs_error;
434
0
    }
435
41.1k
  }
436
437
47.0k
  ssl_early_data_reason_t reason = should_offer_early_data(hs);
438
47.0k
  if (reason != ssl_early_data_accepted) {
439
46.9k
    ssl->s3->early_data_reason = reason;
440
46.9k
  } else {
441
66
    hs->early_data_offered = true;
442
66
  }
443
444
47.0k
  ssl_setup_client_certificate_type(hs);
445
47.0k
  if (!ssl_setup_pre_shared_keys(hs) ||  //
446
47.0k
      !ssl_setup_key_shares(hs, /*override_group_id=*/0) ||
447
47.0k
      !ssl_setup_extension_permutation(hs) ||
448
47.0k
      !ssl_encrypt_client_hello(hs, Span(ech_enc, ech_enc_len)) ||
449
47.0k
      !ssl_add_client_hello(hs)) {
450
0
    return ssl_hs_error;
451
0
  }
452
453
47.0k
  hs->state = state_enter_early_data;
454
47.0k
  return ssl_hs_flush;
455
47.0k
}
456
457
47.0k
static enum ssl_hs_wait_t do_enter_early_data(SSL_HANDSHAKE *hs) {
458
47.0k
  SSL *const ssl = hs->ssl;
459
47.0k
  if (!hs->early_data_offered) {
460
46.9k
    hs->state = state_read_server_hello;
461
46.9k
    return ssl_hs_ok;
462
46.9k
  }
463
464
  // Stash the early data session and activate the early version. This must
465
  // happen before |do_early_reverify_server_certificate|, so early connection
466
  // properties are available to the callback. Note the early version may be
467
  // overwritten later by the final version.
468
66
  hs->early_session = UpRef(ssl->session);
469
66
  ssl->s3->version = hs->early_session->ssl_version;
470
66
  hs->is_early_version = true;
471
66
  hs->state = state_early_reverify_server_certificate;
472
66
  return ssl_hs_ok;
473
47.0k
}
474
475
static enum ssl_hs_wait_t do_early_reverify_server_certificate(
476
66
    SSL_HANDSHAKE *hs) {
477
66
  SSL *const ssl = hs->ssl;
478
66
  if (ssl->ctx->reverify_on_resume) {
479
    // Don't send an alert on error. The alert would be in the clear, which the
480
    // server is not expecting anyway. Alerts in between ClientHello and
481
    // ServerHello cannot usefully be delivered in TLS 1.3.
482
    //
483
    // TODO(davidben): The client behavior should be to verify the certificate
484
    // before deciding whether to offer the session and, if invalid, decline to
485
    // send the session.
486
0
    switch (ssl_reverify_peer_cert(hs, /*send_alert=*/false)) {
487
0
      case ssl_verify_ok:
488
0
        break;
489
0
      case ssl_verify_invalid:
490
0
        return ssl_hs_error;
491
0
      case ssl_verify_retry:
492
0
        hs->state = state_early_reverify_server_certificate;
493
0
        return ssl_hs_certificate_verify;
494
0
    }
495
0
  }
496
497
66
  if (!ssl->method->add_change_cipher_spec(ssl)) {
498
0
    return ssl_hs_error;
499
0
  }
500
501
  // Defer releasing the 0-RTT key to after certificate reverification, so the
502
  // QUIC implementation does not accidentally write data too early.
503
66
  if (!tls13_init_early_key_schedule(hs, hs->early_session.get()) ||
504
66
      !tls13_derive_early_secret(hs) ||
505
66
      !tls13_set_traffic_key(hs->ssl, ssl_encryption_early_data, evp_aead_seal,
506
66
                             hs->early_session.get(),
507
66
                             hs->early_traffic_secret)) {
508
4
    return ssl_hs_error;
509
4
  }
510
511
62
  hs->in_early_data = true;
512
62
  hs->can_early_write = true;
513
62
  hs->state = state_read_server_hello;
514
62
  return ssl_hs_early_return;
515
66
}
516
517
static bool handle_hello_verify_request(SSL_HANDSHAKE *hs,
518
1.14k
                                        const SSLMessage &msg) {
519
1.14k
  SSL *const ssl = hs->ssl;
520
1.14k
  assert(SSL_is_dtls(ssl));
521
1.14k
  assert(msg.type == DTLS1_MT_HELLO_VERIFY_REQUEST);
522
1.14k
  assert(!hs->received_hello_verify_request);
523
524
1.14k
  CBS hello_verify_request = msg.body, cookie;
525
1.14k
  uint16_t server_version;
526
1.14k
  if (!CBS_get_u16(&hello_verify_request, &server_version) ||
527
1.14k
      !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
528
1.13k
      CBS_len(&hello_verify_request) != 0) {
529
12
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
530
12
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
531
12
    return false;
532
12
  }
533
534
1.13k
  if (!hs->dtls_cookie.CopyFrom(cookie)) {
535
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
536
0
    return false;
537
0
  }
538
1.13k
  hs->received_hello_verify_request = true;
539
540
1.13k
  ssl->method->next_message(ssl);
541
542
  // DTLS resets the handshake buffer after HelloVerifyRequest.
543
1.13k
  if (!hs->transcript.Init()) {
544
0
    return false;
545
0
  }
546
547
1.13k
  return ssl_add_client_hello(hs);
548
1.13k
}
549
550
bool ssl_parse_server_hello(ParsedServerHello *out, uint8_t *out_alert,
551
49.8k
                            const SSLMessage &msg) {
552
49.8k
  if (msg.type != SSL3_MT_SERVER_HELLO) {
553
39
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
554
39
    *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
555
39
    return false;
556
39
  }
557
49.7k
  out->raw = msg.raw;
558
49.7k
  CBS body = msg.body;
559
49.7k
  if (!CBS_get_u16(&body, &out->legacy_version) ||
560
49.7k
      !CBS_get_bytes(&body, &out->random, SSL3_RANDOM_SIZE) ||
561
49.7k
      !CBS_get_u8_length_prefixed(&body, &out->session_id) ||
562
49.7k
      CBS_len(&out->session_id) > SSL3_SESSION_ID_SIZE ||
563
49.7k
      !CBS_get_u16(&body, &out->cipher_suite) ||
564
49.7k
      !CBS_get_u8(&body, &out->compression_method)) {
565
66
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
566
66
    *out_alert = SSL_AD_DECODE_ERROR;
567
66
    return false;
568
66
  }
569
  // In TLS 1.2 and below, empty extensions blocks may be omitted. In TLS 1.3,
570
  // ServerHellos always have extensions, so this can be applied generically.
571
49.7k
  CBS_init(&out->extensions, nullptr, 0);
572
49.7k
  if ((CBS_len(&body) != 0 &&
573
49.1k
       !CBS_get_u16_length_prefixed(&body, &out->extensions)) ||
574
49.6k
      CBS_len(&body) != 0) {
575
81
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
576
81
    *out_alert = SSL_AD_DECODE_ERROR;
577
81
    return false;
578
81
  }
579
49.6k
  return true;
580
49.7k
}
581
582
120k
static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
583
120k
  SSL *const ssl = hs->ssl;
584
120k
  SSLMessage msg;
585
120k
  if (!ssl->method->get_message(ssl, &msg)) {
586
74.8k
    return ssl_hs_read_server_hello;
587
74.8k
  }
588
589
45.8k
  if (SSL_is_dtls(ssl) && !hs->received_hello_verify_request &&
590
3.91k
      msg.type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
591
1.14k
    if (!handle_hello_verify_request(hs, msg)) {
592
12
      return ssl_hs_error;
593
12
    }
594
1.13k
    hs->received_hello_verify_request = true;
595
1.13k
    hs->state = state_read_server_hello;
596
1.13k
    return ssl_hs_flush;
597
1.14k
  }
598
599
44.7k
  ParsedServerHello server_hello;
600
44.7k
  uint16_t server_version;
601
44.7k
  uint8_t alert = SSL_AD_DECODE_ERROR;
602
44.7k
  if (!ssl_parse_server_hello(&server_hello, &alert, msg) ||
603
44.5k
      !parse_server_version(hs, &server_version, &alert, server_hello)) {
604
232
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
605
232
    return ssl_hs_error;
606
232
  }
607
608
44.4k
  if (!ssl_supports_version(hs, server_version)) {
609
71
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
610
71
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
611
71
    return ssl_hs_error;
612
71
  }
613
614
44.4k
  if (!ssl->s3->initial_handshake_complete) {
615
    // |ssl->s3->version| may be set due to 0-RTT. If it was to a different
616
    // value, the check below will fire.
617
10.9k
    assert(ssl->s3->version == 0 ||
618
10.9k
           (hs->is_early_version &&
619
10.9k
            ssl->s3->version == hs->early_session->ssl_version));
620
10.9k
    ssl->s3->version = server_version;
621
10.9k
    hs->is_early_version = false;
622
33.4k
  } else if (server_version != ssl->s3->version) {
623
2
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
624
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
625
2
    return ssl_hs_error;
626
2
  }
627
628
  // If the version did not match, stop sending 0-RTT data.
629
44.4k
  if (hs->early_data_offered &&
630
7
      ssl->s3->version != hs->early_session->ssl_version) {
631
    // This is currently only possible by reading a TLS 1.2 (or earlier)
632
    // ServerHello in response to TLS 1.3. If there is ever a TLS 1.4, or
633
    // another variant of TLS 1.3, the fatal error below will need to be a clean
634
    // 0-RTT reject.
635
4
    assert(ssl_protocol_version(ssl) < TLS1_3_VERSION);
636
4
    assert(ssl_session_protocol_version(hs->early_session.get()) >=
637
4
           TLS1_3_VERSION);
638
639
    // A TLS 1.2 server would not know to skip the early data we offered, so
640
    // there is no point in continuing the handshake. Report an error code as
641
    // soon as we detect this. The caller may use this error code to implement
642
    // the fallback described in RFC 8446 appendix D.3.
643
    //
644
    // Disconnect early writes. This ensures subsequent |SSL_write| calls query
645
    // the handshake which, in turn, will replay the error code rather than fail
646
    // at the |write_shutdown| check. See https://crbug.com/1078515.
647
    // TODO(davidben): Should all handshake errors do this? What about record
648
    // decryption failures?
649
    //
650
    // TODO(crbug.com/381113363): Although missing from the spec, a DTLS 1.2
651
    // server will already naturally skip 0-RTT data. If we implement DTLS 1.3
652
    // 0-RTT, we may want a clean reject.
653
4
    assert(!SSL_is_dtls(ssl));
654
4
    hs->can_early_write = false;
655
4
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
656
4
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
657
4
    return ssl_hs_error;
658
4
  }
659
660
44.3k
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
661
2.91k
    if (hs->received_hello_verify_request) {
662
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_MESSAGE);
663
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
664
1
      return ssl_hs_error;
665
1
    }
666
667
2.91k
    hs->state = state_tls13;
668
2.91k
    return ssl_hs_ok;
669
2.91k
  }
670
671
  // If this client only accepts non-certificate modes, then the server must
672
  // support TLS 1.3.
673
41.4k
  if (!ssl_accepts_server_certificate_auth(hs)) {
674
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
675
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
676
0
    return ssl_hs_error;
677
0
  }
678
679
  // Clear some TLS 1.3 state that no longer needs to be retained.
680
41.4k
  hs->key_shares.clear();
681
41.4k
  hs->pre_shared_keys.clear();
682
41.4k
  ssl_done_writing_client_hello(hs);
683
684
  // TLS 1.2 handshakes cannot accept ECH.
685
41.4k
  if (hs->selected_ech_config) {
686
0
    ssl->s3->ech_status = ssl_ech_rejected;
687
0
  }
688
689
  // Copy over the server random.
690
41.4k
  OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_hello.random),
691
41.4k
                 SSL3_RANDOM_SIZE);
692
693
  // Enforce the TLS 1.3 anti-downgrade feature.
694
41.4k
  if (!ssl->s3->initial_handshake_complete &&
695
8.04k
      hs->max_version >= TLS1_3_VERSION) {
696
8.04k
    static_assert(
697
8.04k
        sizeof(kTLS12DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
698
8.04k
        "downgrade signals have different size");
699
8.04k
    static_assert(
700
8.04k
        sizeof(kJDK11DowngradeRandom) == sizeof(kTLS13DowngradeRandom),
701
8.04k
        "downgrade signals have different size");
702
8.04k
    auto suffix =
703
8.04k
        Span(ssl->s3->server_random).last<sizeof(kTLS13DowngradeRandom)>();
704
8.04k
    if (suffix == kTLS12DowngradeRandom || suffix == kTLS13DowngradeRandom ||
705
8.03k
        suffix == kJDK11DowngradeRandom) {
706
10
      OPENSSL_PUT_ERROR(SSL, SSL_R_TLS13_DOWNGRADE);
707
10
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
708
10
      return ssl_hs_error;
709
10
    }
710
8.04k
  }
711
712
  // The cipher must be allowed in the selected version and enabled.
713
41.4k
  const SSL_CIPHER *cipher = SSL_get_cipher_by_value(server_hello.cipher_suite);
714
41.4k
  uint32_t mask_a, mask_k;
715
41.4k
  ssl_get_client_disabled(hs, &mask_a, &mask_k);
716
41.4k
  if (cipher == nullptr ||                                               //
717
41.3k
      (cipher->algorithm_mkey & mask_k) ||                               //
718
41.3k
      (cipher->algorithm_auth & mask_a) ||                               //
719
41.3k
      SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||  //
720
41.3k
      SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||  //
721
41.3k
      !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), nullptr, cipher)) {
722
121
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
723
121
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
724
121
    return ssl_hs_error;
725
121
  }
726
727
41.3k
  hs->new_cipher = cipher;
728
729
41.3k
  if (!hs->session_id.empty() &&
730
40.0k
      Span<const uint8_t>(server_hello.session_id) == hs->session_id) {
731
    // Echoing the ClientHello session ID in TLS 1.2, whether from the session
732
    // or a synthetic one, indicates resumption. If there was no session (or if
733
    // the session was only offered in ECH ClientHelloInner), this was the
734
    // TLS 1.3 compatibility mode session ID. As we know this is not a session
735
    // the server knows about, any server resuming it is in error. Reject the
736
    // first connection deterministicly, rather than installing an invalid
737
    // session into the session cache. https://crbug.com/796910
738
336
    if (ssl->session == nullptr || ssl->s3->ech_status == ssl_ech_rejected) {
739
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
740
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
741
0
      return ssl_hs_error;
742
0
    }
743
336
    if (ssl->session->ssl_version != ssl->s3->version) {
744
4
      OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
745
4
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
746
4
      return ssl_hs_error;
747
4
    }
748
332
    if (ssl->session->cipher != hs->new_cipher) {
749
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
750
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
751
3
      return ssl_hs_error;
752
3
    }
753
329
    if (!ssl_session_is_context_valid(hs, ssl->session.get())) {
754
      // This is actually a client application bug.
755
0
      OPENSSL_PUT_ERROR(SSL,
756
0
                        SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
757
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
758
0
      return ssl_hs_error;
759
0
    }
760
    // We never offer sessions on renegotiation.
761
329
    assert(!ssl->s3->initial_handshake_complete);
762
329
    ssl->s3->session_reused = true;
763
41.0k
  } else {
764
    // The session wasn't resumed. Create a fresh SSL_SESSION to fill out.
765
41.0k
    ssl_set_session(ssl, nullptr);
766
41.0k
    if (!ssl_get_new_session(hs)) {
767
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
768
0
      return ssl_hs_error;
769
0
    }
770
771
    // Save the session ID from the server. This may be empty if the session
772
    // isn't resumable, or if we'll receive a session ticket later. The
773
    // ServerHello parser ensures |server_hello.session_id| is within bounds.
774
41.0k
    hs->new_session->session_id.CopyFrom(server_hello.session_id);
775
41.0k
    hs->new_session->cipher = hs->new_cipher;
776
41.0k
  }
777
778
  // Now that the cipher is known, initialize the handshake hash and hash the
779
  // ServerHello.
780
41.3k
  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
781
41.3k
      !ssl_hash_message(hs, msg)) {
782
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
783
0
    return ssl_hs_error;
784
0
  }
785
786
  // If doing a full handshake, the server may request a client certificate
787
  // which requires hashing the handshake transcript. Otherwise, the handshake
788
  // buffer may be released.
789
41.3k
  if (ssl->session != nullptr ||
790
41.0k
      !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
791
329
    hs->transcript.FreeBuffer();
792
329
  }
793
794
  // Only the NULL compression algorithm is supported.
795
41.3k
  if (server_hello.compression_method != 0) {
796
49
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
797
49
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
798
49
    return ssl_hs_error;
799
49
  }
800
801
41.2k
  if (!ssl_parse_serverhello_tlsext(hs, &server_hello.extensions)) {
802
401
    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
803
401
    return ssl_hs_error;
804
401
  }
805
806
40.8k
  if (ssl->session != nullptr &&
807
329
      hs->extended_master_secret != ssl->session->extended_master_secret) {
808
6
    if (ssl->session->extended_master_secret) {
809
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
810
3
    } else {
811
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
812
3
    }
813
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
814
6
    return ssl_hs_error;
815
6
  }
816
817
40.8k
  ssl->method->next_message(ssl);
818
819
40.8k
  if (ssl->session != nullptr) {
820
323
    if (ssl->ctx->reverify_on_resume &&
821
0
        ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
822
0
      hs->state = state_reverify_server_certificate;
823
323
    } else {
824
323
      hs->state = state_read_session_ticket;
825
323
    }
826
323
    return ssl_hs_ok;
827
323
  }
828
829
40.5k
  hs->state = state_read_server_certificate;
830
40.5k
  return ssl_hs_ok;
831
40.8k
}
832
833
22.3k
static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
834
22.3k
  enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
835
22.3k
  if (wait == ssl_hs_ok) {
836
608
    hs->state = state_finish_client_handshake;
837
608
    return ssl_hs_ok;
838
608
  }
839
840
21.7k
  return wait;
841
22.3k
}
842
843
99.0k
static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
844
99.0k
  SSL *const ssl = hs->ssl;
845
846
99.0k
  if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
847
0
    hs->state = state_read_certificate_status;
848
0
    return ssl_hs_ok;
849
0
  }
850
851
99.0k
  SSLMessage msg;
852
99.0k
  if (!ssl->method->get_message(ssl, &msg)) {
853
58.8k
    return ssl_hs_read_message;
854
58.8k
  }
855
856
40.1k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
857
40.0k
      !ssl_hash_message(hs, msg)) {
858
21
    return ssl_hs_error;
859
21
  }
860
861
40.0k
  CBS body = msg.body;
862
40.0k
  uint8_t alert = SSL_AD_DECODE_ERROR;
863
864
40.0k
  bool parse_ok;
865
40.0k
  if (hs->peer_cert_type == TLSEXT_cert_type_rpk) {
866
0
    hs->new_session->peer_cert_type = TLSEXT_cert_type_rpk;
867
0
    parse_ok = ssl_parse_rpk_cert(&alert, &hs->new_session->peer_raw_public_key,
868
0
                                  &hs->peer_pubkey, nullptr, &body);
869
40.0k
  } else {
870
40.0k
    assert(hs->new_session->peer_cert_type == TLSEXT_cert_type_x509);
871
40.0k
    hs->new_session->peer_cert_type = TLSEXT_cert_type_x509;
872
40.0k
    parse_ok =
873
40.0k
        ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
874
40.0k
                             nullptr, &body, ssl->ctx->pool);
875
40.0k
  }
876
877
40.0k
  if (!parse_ok) {
878
829
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
879
829
    return ssl_hs_error;
880
829
  }
881
882
39.2k
  if (!ssl_session_has_peer_cred(hs->new_session.get()) ||
883
39.2k
      CBS_len(&body) != 0 ||
884
39.2k
      !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
885
1.28k
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
886
1.28k
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
887
1.28k
    return ssl_hs_error;
888
1.28k
  }
889
890
37.9k
  if (!ssl_check_leaf_certificate(
891
37.9k
          hs, hs->peer_pubkey.get(),
892
37.9k
          sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0))) {
893
12
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
894
12
    return ssl_hs_error;
895
12
  }
896
897
37.9k
  ssl->method->next_message(ssl);
898
899
37.9k
  hs->state = state_read_certificate_status;
900
37.9k
  return ssl_hs_ok;
901
37.9k
}
902
903
53.0k
static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
904
53.0k
  SSL *const ssl = hs->ssl;
905
906
53.0k
  if (!hs->certificate_status_expected) {
907
23.3k
    hs->state = state_verify_server_certificate;
908
23.3k
    return ssl_hs_ok;
909
23.3k
  }
910
911
29.6k
  SSLMessage msg;
912
29.6k
  if (!ssl->method->get_message(ssl, &msg)) {
913
15.1k
    return ssl_hs_read_message;
914
15.1k
  }
915
916
14.5k
  if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
917
    // A server may send status_request in ServerHello and then change its mind
918
    // about sending CertificateStatus.
919
13.9k
    hs->state = state_verify_server_certificate;
920
13.9k
    return ssl_hs_ok;
921
13.9k
  }
922
923
576
  if (!ssl_hash_message(hs, msg)) {
924
0
    return ssl_hs_error;
925
0
  }
926
927
576
  CBS certificate_status = msg.body, ocsp_response;
928
576
  uint8_t status_type;
929
576
  if (!CBS_get_u8(&certificate_status, &status_type) ||                     //
930
571
      status_type != TLSEXT_STATUSTYPE_ocsp ||                              //
931
568
      !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||  //
932
565
      CBS_len(&ocsp_response) == 0 ||                                       //
933
562
      CBS_len(&certificate_status) != 0) {
934
17
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
935
17
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
936
17
    return ssl_hs_error;
937
17
  }
938
939
559
  hs->new_session->ocsp_response.reset(
940
559
      CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool));
941
559
  if (hs->new_session->ocsp_response == nullptr) {
942
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
943
0
    return ssl_hs_error;
944
0
  }
945
946
559
  ssl->method->next_message(ssl);
947
948
559
  hs->state = state_verify_server_certificate;
949
559
  return ssl_hs_ok;
950
559
}
951
952
37.9k
static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
953
37.9k
  if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
954
0
    hs->state = state_read_server_key_exchange;
955
0
    return ssl_hs_ok;
956
0
  }
957
958
37.9k
  switch (ssl_verify_peer_cert(hs)) {
959
37.8k
    case ssl_verify_ok:
960
37.8k
      break;
961
77
    case ssl_verify_invalid:
962
77
      return ssl_hs_error;
963
0
    case ssl_verify_retry:
964
0
      hs->state = state_verify_server_certificate;
965
0
      return ssl_hs_certificate_verify;
966
37.9k
  }
967
968
37.8k
  hs->state = state_read_server_key_exchange;
969
37.8k
  return ssl_hs_ok;
970
37.9k
}
971
972
0
static enum ssl_hs_wait_t do_reverify_server_certificate(SSL_HANDSHAKE *hs) {
973
0
  assert(hs->ssl->ctx->reverify_on_resume);
974
975
0
  switch (ssl_reverify_peer_cert(hs, /*send_alert=*/true)) {
976
0
    case ssl_verify_ok:
977
0
      break;
978
0
    case ssl_verify_invalid:
979
0
      return ssl_hs_error;
980
0
    case ssl_verify_retry:
981
0
      hs->state = state_reverify_server_certificate;
982
0
      return ssl_hs_certificate_verify;
983
0
  }
984
985
0
  hs->state = state_read_session_ticket;
986
0
  return ssl_hs_ok;
987
0
}
988
989
103k
static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
990
103k
  SSL *const ssl = hs->ssl;
991
103k
  SSLMessage msg;
992
103k
  if (!ssl->method->get_message(ssl, &msg)) {
993
65.8k
    return ssl_hs_read_message;
994
65.8k
  }
995
996
37.6k
  if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
997
    // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
998
2.80k
    if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
999
10
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1000
10
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1001
10
      return ssl_hs_error;
1002
10
    }
1003
1004
2.79k
    hs->state = state_read_certificate_request;
1005
2.79k
    return ssl_hs_ok;
1006
2.80k
  }
1007
1008
34.8k
  if (!ssl_hash_message(hs, msg)) {
1009
0
    return ssl_hs_error;
1010
0
  }
1011
1012
34.8k
  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1013
34.8k
  uint32_t alg_a = hs->new_cipher->algorithm_auth;
1014
34.8k
  CBS server_key_exchange = msg.body;
1015
34.8k
  if (alg_a & SSL_aPSK) {
1016
0
    CBS psk_identity_hint;
1017
1018
    // Each of the PSK key exchanges begins with a psk_identity_hint.
1019
0
    if (!CBS_get_u16_length_prefixed(&server_key_exchange,
1020
0
                                     &psk_identity_hint)) {
1021
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1022
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1023
0
      return ssl_hs_error;
1024
0
    }
1025
1026
    // Store the PSK identity hint for the ClientKeyExchange. Assume that the
1027
    // maximum length of a PSK identity hint can be as long as the maximum
1028
    // length of a PSK identity. Also do not allow NULL characters; identities
1029
    // are saved as C strings.
1030
    //
1031
    // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
1032
    // a specific identity.
1033
0
    if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
1034
0
        CBS_contains_zero_byte(&psk_identity_hint)) {
1035
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1036
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1037
0
      return ssl_hs_error;
1038
0
    }
1039
1040
    // Save non-empty identity hints as a C string. Empty identity hints we
1041
    // treat as missing. Plain PSK makes it possible to send either no hint
1042
    // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
1043
    // empty hint. Having different capabilities is odd, so we interpret empty
1044
    // and missing as identical.
1045
0
    char *raw = nullptr;
1046
0
    if (CBS_len(&psk_identity_hint) != 0 &&
1047
0
        !CBS_strdup(&psk_identity_hint, &raw)) {
1048
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1049
0
      return ssl_hs_error;
1050
0
    }
1051
0
    hs->peer_psk_identity_hint.reset(raw);
1052
0
  }
1053
1054
34.8k
  if (alg_k & SSL_kECDHE) {
1055
    // Parse the server parameters.
1056
34.8k
    uint8_t group_type;
1057
34.8k
    uint16_t group_id;
1058
34.8k
    CBS point;
1059
34.8k
    if (!CBS_get_u8(&server_key_exchange, &group_type) ||
1060
34.8k
        group_type != NAMED_CURVE_TYPE ||
1061
34.8k
        !CBS_get_u16(&server_key_exchange, &group_id) ||
1062
34.8k
        !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
1063
25
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1064
25
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1065
25
      return ssl_hs_error;
1066
25
    }
1067
1068
    // Ensure the group is consistent with preferences.
1069
34.8k
    if (!tls1_check_group_id(hs, group_id)) {
1070
97
      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
1071
97
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1072
97
      return ssl_hs_error;
1073
97
    }
1074
1075
    // Save the group and peer public key for later.
1076
34.7k
    hs->new_session->group_id = group_id;
1077
34.7k
    if (!hs->peer_key.CopyFrom(point)) {
1078
0
      return ssl_hs_error;
1079
0
    }
1080
34.7k
  } else if (!(alg_k & SSL_kPSK)) {
1081
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
1082
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1083
3
    return ssl_hs_error;
1084
3
  }
1085
1086
  // At this point, |server_key_exchange| contains the signature, if any, while
1087
  // |msg.body| contains the entire message. From that, derive a CBS containing
1088
  // just the parameter.
1089
34.7k
  CBS parameter;
1090
34.7k
  CBS_init(&parameter, CBS_data(&msg.body),
1091
34.7k
           CBS_len(&msg.body) - CBS_len(&server_key_exchange));
1092
1093
  // ServerKeyExchange should be signed by the server's public key.
1094
34.7k
  if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1095
34.7k
    uint16_t signature_algorithm = 0;
1096
34.7k
    if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1097
33.4k
      if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
1098
3
        OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1099
3
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1100
3
        return ssl_hs_error;
1101
3
      }
1102
33.4k
      uint8_t alert = SSL_AD_DECODE_ERROR;
1103
33.4k
      if (!tls12_check_peer_sigalg(hs, &alert, signature_algorithm,
1104
33.4k
                                   hs->peer_pubkey.get())) {
1105
46
        ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1106
46
        return ssl_hs_error;
1107
46
      }
1108
33.4k
      hs->new_session->peer_signature_algorithm = signature_algorithm;
1109
33.4k
    } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1110
1.25k
                                                    hs->peer_pubkey.get())) {
1111
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1112
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1113
3
      return ssl_hs_error;
1114
3
    }
1115
1116
    // The last field in |server_key_exchange| is the signature.
1117
34.6k
    CBS signature;
1118
34.6k
    if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1119
34.6k
        CBS_len(&server_key_exchange) != 0) {
1120
27
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1121
27
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1122
27
      return ssl_hs_error;
1123
27
    }
1124
1125
34.6k
    ScopedCBB transcript;
1126
34.6k
    Array<uint8_t> transcript_data;
1127
34.6k
    if (!CBB_init(transcript.get(),
1128
34.6k
                  2 * SSL3_RANDOM_SIZE + CBS_len(&parameter)) ||
1129
34.6k
        !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1130
34.6k
                       SSL3_RANDOM_SIZE) ||
1131
34.6k
        !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1132
34.6k
                       SSL3_RANDOM_SIZE) ||
1133
34.6k
        !CBB_add_bytes(transcript.get(), CBS_data(&parameter),
1134
34.6k
                       CBS_len(&parameter)) ||
1135
34.6k
        !CBBFinishArray(transcript.get(), &transcript_data)) {
1136
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1137
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1138
0
      return ssl_hs_error;
1139
0
    }
1140
1141
34.6k
    if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1142
34.6k
                               hs->peer_pubkey.get(), transcript_data)) {
1143
      // bad signature
1144
697
      OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1145
697
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1146
697
      return ssl_hs_error;
1147
697
    }
1148
34.6k
  } else {
1149
    // PSK ciphers are the only supported certificate-less ciphers.
1150
0
    assert(alg_a == SSL_aPSK);
1151
1152
0
    if (CBS_len(&server_key_exchange) > 0) {
1153
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1154
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1155
0
      return ssl_hs_error;
1156
0
    }
1157
0
  }
1158
1159
33.9k
  ssl->method->next_message(ssl);
1160
33.9k
  hs->state = state_read_certificate_request;
1161
33.9k
  return ssl_hs_ok;
1162
34.7k
}
1163
1164
70.1k
static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
1165
70.1k
  SSL *const ssl = hs->ssl;
1166
1167
70.1k
  if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1168
0
    hs->state = state_read_server_hello_done;
1169
0
    return ssl_hs_ok;
1170
0
  }
1171
1172
70.1k
  SSLMessage msg;
1173
70.1k
  if (!ssl->method->get_message(ssl, &msg)) {
1174
34.3k
    return ssl_hs_read_message;
1175
34.3k
  }
1176
1177
35.7k
  if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
1178
    // If we get here we don't need the handshake buffer as we won't be doing
1179
    // client auth.
1180
25.7k
    hs->transcript.FreeBuffer();
1181
25.7k
    hs->state = state_read_server_hello_done;
1182
25.7k
    return ssl_hs_ok;
1183
25.7k
  }
1184
1185
10.0k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
1186
10.0k
      !ssl_hash_message(hs, msg)) {
1187
7
    return ssl_hs_error;
1188
7
  }
1189
1190
  // Get the certificate types.
1191
10.0k
  CBS body = msg.body, certificate_types;
1192
10.0k
  if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
1193
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1194
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1195
3
    return ssl_hs_error;
1196
3
  }
1197
1198
10.0k
  if (!hs->certificate_types.CopyFrom(certificate_types)) {
1199
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1200
0
    return ssl_hs_error;
1201
0
  }
1202
1203
10.0k
  if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1204
9.97k
    CBS supported_signature_algorithms;
1205
9.97k
    if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
1206
9.95k
        !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1207
25
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1208
25
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1209
25
      return ssl_hs_error;
1210
25
    }
1211
9.97k
  }
1212
1213
10.0k
  uint8_t alert = SSL_AD_DECODE_ERROR;
1214
10.0k
  UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
1215
10.0k
      SSL_parse_CA_list(ssl, &alert, &body);
1216
10.0k
  if (!ca_names) {
1217
49
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1218
49
    return ssl_hs_error;
1219
49
  }
1220
1221
9.97k
  if (CBS_len(&body) != 0) {
1222
11
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1223
11
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1224
11
    return ssl_hs_error;
1225
11
  }
1226
1227
9.96k
  hs->cert_request = true;
1228
9.96k
  hs->ca_names = std::move(ca_names);
1229
9.96k
  ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
1230
1231
9.96k
  ssl->method->next_message(ssl);
1232
9.96k
  hs->state = state_read_server_hello_done;
1233
9.96k
  return ssl_hs_ok;
1234
9.97k
}
1235
1236
46.1k
static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
1237
46.1k
  SSL *const ssl = hs->ssl;
1238
46.1k
  SSLMessage msg;
1239
46.1k
  if (!ssl->method->get_message(ssl, &msg)) {
1240
10.5k
    return ssl_hs_read_message;
1241
10.5k
  }
1242
1243
35.6k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
1244
35.6k
      !ssl_hash_message(hs, msg)) {
1245
3
    return ssl_hs_error;
1246
3
  }
1247
1248
  // ServerHelloDone is empty.
1249
35.6k
  if (CBS_len(&msg.body) != 0) {
1250
8
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1251
8
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1252
8
    return ssl_hs_error;
1253
8
  }
1254
1255
  // ServerHelloDone should be the end of the flight.
1256
35.6k
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
1257
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1258
6
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
1259
6
    return ssl_hs_error;
1260
6
  }
1261
1262
35.6k
  ssl->method->next_message(ssl);
1263
35.6k
  hs->state = state_send_client_certificate;
1264
35.6k
  return ssl_hs_ok;
1265
35.6k
}
1266
1267
static bool check_credential(SSL_HANDSHAKE *hs, const SSLCredential *cred,
1268
9.92k
                             uint16_t *out_sigalg) {
1269
9.92k
  bool cert_type_ok = false;
1270
9.92k
  if (hs->client_cert_type == TLSEXT_cert_type_x509) {
1271
9.92k
    cert_type_ok = cred->type == SSLCredentialType::kX509;
1272
9.92k
  } else if (hs->client_cert_type == TLSEXT_cert_type_rpk) {
1273
0
    cert_type_ok = cred->type == SSLCredentialType::kRawPublicKey;
1274
0
  }
1275
9.92k
  if (!cert_type_ok) {
1276
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1277
0
    return false;
1278
0
  }
1279
1280
  // Check the certificate types advertised by the peer.
1281
9.92k
  uint8_t cert_type;
1282
9.92k
  switch (EVP_PKEY_id(cred->pubkey.get())) {
1283
9.92k
    case EVP_PKEY_RSA:
1284
9.92k
      cert_type = SSL3_CT_RSA_SIGN;
1285
9.92k
      break;
1286
0
    case EVP_PKEY_EC:
1287
0
    case EVP_PKEY_ED25519:
1288
0
      cert_type = TLS_CT_ECDSA_SIGN;
1289
0
      break;
1290
0
    default:
1291
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1292
0
      return false;
1293
9.92k
  }
1294
9.92k
  if (std::find(hs->certificate_types.begin(), hs->certificate_types.end(),
1295
9.92k
                cert_type) == hs->certificate_types.end()) {
1296
5
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1297
5
    return false;
1298
5
  }
1299
1300
  // All currently supported credentials require a signature. Note this does not
1301
  // check the ECDSA curve. Prior to TLS 1.3, there is no way to determine which
1302
  // ECDSA curves are supported by the peer, so we must assume all curves are
1303
  // supported.
1304
9.91k
  return tls1_choose_signature_algorithm(hs, cred, out_sigalg) &&
1305
9.90k
         ssl_credential_matches_requested_issuers(hs, cred);
1306
9.92k
}
1307
1308
35.6k
static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
1309
35.6k
  SSL *const ssl = hs->ssl;
1310
1311
  // The peer didn't request a certificate.
1312
35.6k
  if (!hs->cert_request) {
1313
25.7k
    hs->state = state_send_client_key_exchange;
1314
25.7k
    return ssl_hs_ok;
1315
25.7k
  }
1316
1317
9.92k
  if (ssl->s3->ech_status == ssl_ech_rejected) {
1318
    // Do not send client certificates on ECH reject. We have not authenticated
1319
    // the server for the name that can learn the certificate.
1320
0
    SSL_certs_clear(ssl);
1321
9.92k
  } else if (hs->config->cert->cert_cb != nullptr) {
1322
    // Call cert_cb to update the certificate.
1323
0
    int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
1324
0
    if (rv == 0) {
1325
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1326
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1327
0
      return ssl_hs_error;
1328
0
    }
1329
0
    if (rv < 0) {
1330
0
      hs->state = state_send_client_certificate;
1331
0
      return ssl_hs_x509_lookup;
1332
0
    }
1333
0
  }
1334
1335
9.92k
  Array<SSLCredential *> creds;
1336
9.92k
  if (!ssl_get_full_credential_list(hs, &creds)) {
1337
0
    return ssl_hs_error;
1338
0
  }
1339
1340
  // Select the credential, if any, to use.
1341
9.92k
  bool may_proceed_anonymously = true;
1342
9.92k
  for (SSLCredential *cred : creds) {
1343
9.92k
    if (!cred->UsesPrivateKey()) {
1344
      // Non-certificate credentials (e.g. PSKs) do not participate in deciding
1345
      // whether to error or proceed anonymously.
1346
0
      continue;
1347
0
    }
1348
1349
9.92k
    ERR_clear_error();
1350
9.92k
    may_proceed_anonymously = false;
1351
9.92k
    uint16_t sigalg;
1352
9.92k
    if (check_credential(hs, cred, &sigalg)) {
1353
9.90k
      hs->credential = UpRef(cred);
1354
9.90k
      hs->signature_algorithm = sigalg;
1355
9.90k
      break;
1356
9.90k
    }
1357
9.92k
  }
1358
1359
  // Fail the connection if no credentials matched, but only if the caller
1360
  // configured at least one certificate credential. If there were no
1361
  // candidates, proceed anonymously.
1362
9.92k
  if (hs->credential == nullptr) {
1363
16
    if (!may_proceed_anonymously) {
1364
      // The error from the last attempt is in the error queue.
1365
16
      assert(ERR_peek_error() != 0);
1366
16
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1367
16
      return ssl_hs_error;
1368
16
    }
1369
    // Without CertificateVerify, we can release the handshake buffer.
1370
0
    hs->transcript.FreeBuffer();
1371
0
  }
1372
1373
9.90k
  if (!ssl_send_tls12_certificate(hs)) {
1374
0
    return ssl_hs_error;
1375
0
  }
1376
1377
9.90k
  hs->state = state_send_client_key_exchange;
1378
9.90k
  return ssl_hs_ok;
1379
9.90k
}
1380
1381
static_assert(sizeof(size_t) >= sizeof(unsigned),
1382
              "size_t is smaller than unsigned");
1383
1384
35.6k
static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
1385
35.6k
  SSL *const ssl = hs->ssl;
1386
35.6k
  ScopedCBB cbb;
1387
35.6k
  CBB body;
1388
35.6k
  if (!ssl->method->init_message(ssl, cbb.get(), &body,
1389
35.6k
                                 SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1390
0
    return ssl_hs_error;
1391
0
  }
1392
1393
35.6k
  Array<uint8_t> pms;
1394
35.6k
  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1395
35.6k
  uint32_t alg_a = hs->new_cipher->algorithm_auth;
1396
35.6k
  if (ssl_cipher_uses_certificate_auth(hs->new_cipher) &&
1397
35.6k
      hs->new_session->peer_cert_type == TLSEXT_cert_type_x509) {
1398
35.6k
    const CRYPTO_BUFFER *leaf =
1399
35.6k
        sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1400
35.6k
    CBS leaf_cbs;
1401
35.6k
    CRYPTO_BUFFER_init_CBS(leaf, &leaf_cbs);
1402
1403
    // Check the key usage matches the cipher suite. We do this unconditionally
1404
    // for non-RSA certificates. In particular, it's needed to distinguish ECDH
1405
    // certificates, which we do not support, from ECDSA certificates.
1406
    // Historically, we have not checked RSA key usages, so it is controlled by
1407
    // a flag for now. See https://crbug.com/795089.
1408
    // Key usage is only checked for X.509 certs. (RPKs have no keyUsage to
1409
    // enforce.)
1410
35.6k
    ssl_key_usage_t intended_use = (alg_k & SSL_kRSA)
1411
35.6k
                                       ? key_usage_encipherment
1412
35.6k
                                       : key_usage_digital_signature;
1413
35.6k
    if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) {
1414
36
      if (hs->config->enforce_rsa_key_usage ||
1415
36
          EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) {
1416
36
        return ssl_hs_error;
1417
36
      }
1418
0
      ERR_clear_error();
1419
0
      ssl->s3->was_key_usage_invalid = true;
1420
0
    }
1421
35.6k
  }
1422
1423
  // If using a PSK key exchange, prepare the pre-shared key.
1424
35.5k
  unsigned psk_len = 0;
1425
35.5k
  uint8_t psk[PSK_MAX_PSK_LEN];
1426
35.5k
  if (alg_a & SSL_aPSK) {
1427
0
    if (hs->config->psk_client_callback == nullptr) {
1428
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1429
0
      return ssl_hs_error;
1430
0
    }
1431
1432
0
    char identity[PSK_MAX_IDENTITY_LEN + 1];
1433
0
    OPENSSL_memset(identity, 0, sizeof(identity));
1434
0
    psk_len = hs->config->psk_client_callback(
1435
0
        ssl, hs->peer_psk_identity_hint.get(), identity, sizeof(identity), psk,
1436
0
        sizeof(psk));
1437
0
    if (psk_len == 0) {
1438
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1439
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1440
0
      return ssl_hs_error;
1441
0
    }
1442
0
    assert(psk_len <= PSK_MAX_PSK_LEN);
1443
1444
0
    hs->new_session->psk_identity.reset(OPENSSL_strdup(identity));
1445
0
    if (hs->new_session->psk_identity == nullptr) {
1446
0
      return ssl_hs_error;
1447
0
    }
1448
1449
    // Write out psk_identity.
1450
0
    CBB child;
1451
0
    if (!CBB_add_u16_length_prefixed(&body, &child) ||
1452
0
        !CBB_add_bytes(&child, (const uint8_t *)identity,
1453
0
                       OPENSSL_strnlen(identity, sizeof(identity))) ||
1454
0
        !CBB_flush(&body)) {
1455
0
      return ssl_hs_error;
1456
0
    }
1457
0
  }
1458
1459
  // Depending on the key exchange method, compute |pms|.
1460
35.5k
  if (alg_k & SSL_kRSA) {
1461
2.70k
    RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
1462
2.70k
    if (rsa == nullptr) {
1463
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1464
0
      return ssl_hs_error;
1465
0
    }
1466
1467
2.70k
    if (!pms.InitForOverwrite(SSL_MAX_MASTER_KEY_LENGTH)) {
1468
0
      return ssl_hs_error;
1469
0
    }
1470
2.70k
    pms[0] = hs->client_version >> 8;
1471
2.70k
    pms[1] = hs->client_version & 0xff;
1472
2.70k
    if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1473
0
      return ssl_hs_error;
1474
0
    }
1475
1476
2.70k
    CBB enc_pms;
1477
2.70k
    uint8_t *ptr;
1478
2.70k
    size_t enc_pms_len;
1479
2.70k
    if (!CBB_add_u16_length_prefixed(&body, &enc_pms) ||  //
1480
2.70k
        !CBB_reserve(&enc_pms, &ptr, RSA_size(rsa)) ||    //
1481
2.70k
        !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
1482
2.70k
                     pms.size(), RSA_PKCS1_PADDING) ||  //
1483
2.70k
        !CBB_did_write(&enc_pms, enc_pms_len) ||        //
1484
2.70k
        !CBB_flush(&body)) {
1485
0
      return ssl_hs_error;
1486
0
    }
1487
32.8k
  } else if (alg_k & SSL_kECDHE) {
1488
32.8k
    CBB child;
1489
32.8k
    if (!CBB_add_u8_length_prefixed(&body, &child)) {
1490
0
      return ssl_hs_error;
1491
0
    }
1492
1493
    // Generate a premaster secret and encapsulate it.
1494
32.8k
    bssl::UniquePtr<SSLKeyShare> kem =
1495
32.8k
        SSLKeyShare::Create(hs->new_session->group_id);
1496
32.8k
    uint8_t alert = SSL_AD_DECODE_ERROR;
1497
32.8k
    if (!kem || !kem->Encap(&child, &pms, &alert, hs->peer_key)) {
1498
174
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1499
174
      return ssl_hs_error;
1500
174
    }
1501
32.7k
    if (!CBB_flush(&body)) {
1502
0
      return ssl_hs_error;
1503
0
    }
1504
1505
    // The peer key can now be discarded.
1506
32.7k
    hs->peer_key.Reset();
1507
32.7k
  } else if (alg_k & SSL_kPSK) {
1508
    // For plain PSK, other_secret is a block of 0s with the same length as
1509
    // the pre-shared key.
1510
0
    if (!pms.Init(psk_len)) {
1511
0
      return ssl_hs_error;
1512
0
    }
1513
0
  } else {
1514
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1515
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1516
0
    return ssl_hs_error;
1517
0
  }
1518
1519
  // For a PSK cipher suite, other_secret is combined with the pre-shared
1520
  // key.
1521
35.4k
  if (alg_a & SSL_aPSK) {
1522
0
    ScopedCBB pms_cbb;
1523
0
    CBB child;
1524
0
    if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
1525
0
        !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1526
0
        !CBB_add_bytes(&child, pms.data(), pms.size()) ||
1527
0
        !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1528
0
        !CBB_add_bytes(&child, psk, psk_len) ||
1529
0
        !CBBFinishArray(pms_cbb.get(), &pms)) {
1530
0
      return ssl_hs_error;
1531
0
    }
1532
0
  }
1533
1534
  // The message must be added to the finished hash before calculating the
1535
  // master secret.
1536
35.4k
  if (!ssl_add_message_cbb(ssl, cbb.get())) {
1537
0
    return ssl_hs_error;
1538
0
  }
1539
1540
35.4k
  hs->new_session->secret.ResizeForOverwrite(SSL3_MASTER_SECRET_SIZE);
1541
35.4k
  if (!tls1_generate_master_secret(hs, Span(hs->new_session->secret), pms)) {
1542
0
    return ssl_hs_error;
1543
0
  }
1544
1545
35.4k
  hs->new_session->extended_master_secret = hs->extended_master_secret;
1546
35.4k
  hs->state = state_send_client_certificate_verify;
1547
35.4k
  return ssl_hs_ok;
1548
35.4k
}
1549
1550
35.4k
static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1551
35.4k
  SSL *const ssl = hs->ssl;
1552
1553
35.4k
  if (!hs->cert_request || hs->credential == nullptr) {
1554
25.5k
    hs->state = state_send_client_finished;
1555
25.5k
    return ssl_hs_ok;
1556
25.5k
  }
1557
1558
9.83k
  ScopedCBB cbb;
1559
9.83k
  CBB body, child;
1560
9.83k
  if (!ssl->method->init_message(ssl, cbb.get(), &body,
1561
9.83k
                                 SSL3_MT_CERTIFICATE_VERIFY)) {
1562
0
    return ssl_hs_error;
1563
0
  }
1564
1565
9.83k
  assert(hs->signature_algorithm != 0);
1566
9.83k
  if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1567
    // Write out the digest type in TLS 1.2.
1568
9.81k
    if (!CBB_add_u16(&body, hs->signature_algorithm)) {
1569
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1570
0
      return ssl_hs_error;
1571
0
    }
1572
9.81k
  }
1573
1574
  // Set aside space for the signature.
1575
9.83k
  const size_t max_sig_len = EVP_PKEY_size(hs->credential->pubkey.get());
1576
9.83k
  uint8_t *ptr;
1577
9.83k
  if (!CBB_add_u16_length_prefixed(&body, &child) ||
1578
9.83k
      !CBB_reserve(&child, &ptr, max_sig_len)) {
1579
0
    return ssl_hs_error;
1580
0
  }
1581
1582
9.83k
  size_t sig_len = max_sig_len;
1583
9.83k
  switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1584
9.83k
                               hs->signature_algorithm,
1585
9.83k
                               hs->transcript.buffer())) {
1586
9.83k
    case ssl_private_key_success:
1587
9.83k
      break;
1588
0
    case ssl_private_key_failure:
1589
0
      return ssl_hs_error;
1590
0
    case ssl_private_key_retry:
1591
0
      hs->state = state_send_client_certificate_verify;
1592
0
      return ssl_hs_private_key_operation;
1593
9.83k
  }
1594
1595
9.83k
  if (!CBB_did_write(&child, sig_len) ||  //
1596
9.83k
      !ssl_add_message_cbb(ssl, cbb.get())) {
1597
0
    return ssl_hs_error;
1598
0
  }
1599
1600
  // The handshake buffer is no longer necessary.
1601
9.83k
  hs->transcript.FreeBuffer();
1602
1603
9.83k
  hs->state = state_send_client_finished;
1604
9.83k
  return ssl_hs_ok;
1605
9.83k
}
1606
1607
35.6k
static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
1608
35.6k
  SSL *const ssl = hs->ssl;
1609
35.6k
  hs->can_release_private_key = true;
1610
35.6k
  if (!ssl->method->add_change_cipher_spec(ssl) ||
1611
35.6k
      !tls1_change_cipher_state(hs, evp_aead_seal)) {
1612
0
    return ssl_hs_error;
1613
0
  }
1614
1615
35.6k
  if (hs->next_proto_neg_seen) {
1616
40
    static const uint8_t kZero[32] = {0};
1617
40
    size_t padding_len =
1618
40
        32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
1619
1620
40
    ScopedCBB cbb;
1621
40
    CBB body, child;
1622
40
    if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
1623
40
        !CBB_add_u8_length_prefixed(&body, &child) ||
1624
40
        !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
1625
40
                       ssl->s3->next_proto_negotiated.size()) ||
1626
40
        !CBB_add_u8_length_prefixed(&body, &child) ||
1627
40
        !CBB_add_bytes(&child, kZero, padding_len) ||
1628
40
        !ssl_add_message_cbb(ssl, cbb.get())) {
1629
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1630
0
      return ssl_hs_error;
1631
0
    }
1632
40
  }
1633
1634
35.6k
  if (hs->channel_id_negotiated) {
1635
497
    ScopedCBB cbb;
1636
497
    CBB body;
1637
497
    if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1638
497
        !tls1_write_channel_id(hs, &body) ||
1639
497
        !ssl_add_message_cbb(ssl, cbb.get())) {
1640
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1641
0
      return ssl_hs_error;
1642
0
    }
1643
497
  }
1644
1645
35.6k
  if (!ssl_send_finished(hs)) {
1646
0
    return ssl_hs_error;
1647
0
  }
1648
1649
35.6k
  hs->state = state_finish_flight;
1650
35.6k
  return ssl_hs_flush;
1651
35.6k
}
1652
1653
0
static bool can_false_start(const SSL_HANDSHAKE *hs) {
1654
0
  const SSL *const ssl = hs->ssl;
1655
1656
  // False Start bypasses the Finished check's downgrade protection. This can
1657
  // enable attacks where we send data under weaker settings than supported
1658
  // (e.g. the Logjam attack). Thus we require TLS 1.2 with an ECDHE+AEAD
1659
  // cipher, our strongest settings before TLS 1.3.
1660
  //
1661
  // Now that TLS 1.3 exists, we would like to avoid similar attacks between
1662
  // TLS 1.2 and TLS 1.3, but there are too many TLS 1.2 deployments to
1663
  // sacrifice False Start on them. Instead, we rely on the ServerHello.random
1664
  // downgrade signal, which we unconditionally enforce.
1665
0
  if (SSL_is_dtls(ssl) ||                              //
1666
0
      SSL_version(ssl) != TLS1_2_VERSION ||            //
1667
0
      hs->new_cipher->algorithm_mkey != SSL_kECDHE ||  //
1668
0
      hs->new_cipher->algorithm_mac != SSL_AEAD) {
1669
0
    return false;
1670
0
  }
1671
1672
  // If ECH was rejected, disable False Start. We run the handshake to
1673
  // completion, including the Finished downgrade check, to authenticate the
1674
  // recovery flow.
1675
0
  if (ssl->s3->ech_status == ssl_ech_rejected) {
1676
0
    return false;
1677
0
  }
1678
1679
  // Additionally require ALPN or NPN by default.
1680
  //
1681
  // TODO(davidben): Can this constraint be relaxed globally now that cipher
1682
  // suite requirements have been tightened?
1683
0
  if (!ssl->ctx->false_start_allowed_without_alpn &&
1684
0
      ssl->s3->alpn_selected.empty() &&
1685
0
      ssl->s3->next_proto_negotiated.empty()) {
1686
0
    return false;
1687
0
  }
1688
1689
0
  return true;
1690
0
}
1691
1692
35.6k
static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
1693
35.6k
  SSL *const ssl = hs->ssl;
1694
35.6k
  if (ssl->session != nullptr) {
1695
197
    hs->state = state_finish_client_handshake;
1696
197
    return ssl_hs_ok;
1697
197
  }
1698
1699
  // This is a full handshake. If it involves ChannelID, then record the
1700
  // handshake hashes at this point in the session so that any resumption of
1701
  // this session with ChannelID can sign those hashes.
1702
35.4k
  if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
1703
0
    return ssl_hs_error;
1704
0
  }
1705
1706
35.4k
  hs->state = state_read_session_ticket;
1707
1708
35.4k
  if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
1709
0
      can_false_start(hs) &&
1710
      // No False Start on renegotiation (would complicate the state machine).
1711
0
      !ssl->s3->initial_handshake_complete) {
1712
0
    hs->in_false_start = true;
1713
0
    hs->can_early_write = true;
1714
0
    return ssl_hs_early_return;
1715
0
  }
1716
1717
35.4k
  return ssl_hs_ok;
1718
35.4k
}
1719
1720
72.0k
static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
1721
72.0k
  SSL *const ssl = hs->ssl;
1722
1723
72.0k
  if (!hs->ticket_expected) {
1724
855
    hs->state = state_process_change_cipher_spec;
1725
855
    return ssl_hs_read_change_cipher_spec;
1726
855
  }
1727
1728
71.1k
  SSLMessage msg;
1729
71.1k
  if (!ssl->method->get_message(ssl, &msg)) {
1730
37.2k
    return ssl_hs_read_message;
1731
37.2k
  }
1732
1733
33.9k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
1734
33.9k
      !ssl_hash_message(hs, msg)) {
1735
8
    return ssl_hs_error;
1736
8
  }
1737
1738
33.9k
  CBS new_session_ticket = msg.body, ticket;
1739
33.9k
  uint32_t ticket_lifetime_hint;
1740
33.9k
  if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
1741
33.9k
      !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1742
33.8k
      CBS_len(&new_session_ticket) != 0) {
1743
38
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1744
38
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1745
38
    return ssl_hs_error;
1746
38
  }
1747
1748
33.8k
  if (CBS_len(&ticket) == 0) {
1749
    // RFC 5077 allows a server to change its mind and send no ticket after
1750
    // negotiating the extension. The value of |ticket_expected| is checked in
1751
    // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
1752
3
    hs->ticket_expected = false;
1753
3
    ssl->method->next_message(ssl);
1754
3
    hs->state = state_process_change_cipher_spec;
1755
3
    return ssl_hs_read_change_cipher_spec;
1756
3
  }
1757
1758
33.8k
  if (ssl->session != nullptr) {
1759
    // The server is sending a new ticket for an existing session. Sessions are
1760
    // immutable once established, so duplicate all but the ticket of the
1761
    // existing session.
1762
22
    assert(!hs->new_session);
1763
22
    hs->new_session =
1764
22
        SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1765
22
    if (!hs->new_session) {
1766
0
      return ssl_hs_error;
1767
0
    }
1768
22
  }
1769
1770
  // |ticket_lifetime_hint| is measured from when the ticket was issued.
1771
33.8k
  ssl_session_rebase_time(ssl, hs->new_session.get());
1772
1773
33.8k
  if (!hs->new_session->ticket.CopyFrom(ticket)) {
1774
0
    return ssl_hs_error;
1775
0
  }
1776
33.8k
  hs->new_session->ticket_lifetime_hint = ticket_lifetime_hint;
1777
1778
  // Historically, OpenSSL filled in fake session IDs for ticket-based sessions.
1779
  // TODO(davidben): Are external callers relying on this? Try removing this.
1780
33.8k
  hs->new_session->session_id.ResizeForOverwrite(SHA256_DIGEST_LENGTH);
1781
33.8k
  SHA256(CBS_data(&ticket), CBS_len(&ticket),
1782
33.8k
         hs->new_session->session_id.data());
1783
1784
33.8k
  ssl->method->next_message(ssl);
1785
33.8k
  hs->state = state_process_change_cipher_spec;
1786
33.8k
  return ssl_hs_read_change_cipher_spec;
1787
33.8k
}
1788
1789
34.1k
static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1790
34.1k
  if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1791
4
    return ssl_hs_error;
1792
4
  }
1793
1794
34.1k
  hs->state = state_read_server_finished;
1795
34.1k
  return ssl_hs_ok;
1796
34.1k
}
1797
1798
68.3k
static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
1799
68.3k
  SSL *const ssl = hs->ssl;
1800
68.3k
  enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1801
68.3k
  if (wait != ssl_hs_ok) {
1802
34.5k
    return wait;
1803
34.5k
  }
1804
1805
33.8k
  if (ssl->session != nullptr) {
1806
197
    hs->state = state_send_client_finished;
1807
197
    return ssl_hs_ok;
1808
197
  }
1809
1810
33.6k
  hs->state = state_finish_client_handshake;
1811
33.6k
  return ssl_hs_ok;
1812
33.8k
}
1813
1814
34.4k
static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
1815
34.4k
  SSL *const ssl = hs->ssl;
1816
34.4k
  if (ssl->s3->ech_status == ssl_ech_rejected) {
1817
    // Release the retry configs.
1818
0
    hs->ech_authenticated_reject = true;
1819
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ECH_REQUIRED);
1820
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_ECH_REJECTED);
1821
0
    return ssl_hs_error;
1822
0
  }
1823
1824
34.4k
  ssl->method->on_handshake_complete(ssl);
1825
1826
  // Note TLS 1.2 resumptions with ticket renewal have both |ssl->session| (the
1827
  // resumed session) and |hs->new_session| (the session with the new ticket).
1828
34.4k
  bool has_new_session = hs->new_session != nullptr;
1829
34.4k
  if (has_new_session) {
1830
    // When False Start is enabled, the handshake reports completion early. The
1831
    // caller may then have passed the (then unresuable) |hs->new_session| to
1832
    // another thread via |SSL_get0_session| for resumption. To avoid potential
1833
    // race conditions in such callers, we duplicate the session before
1834
    // clearing |not_resumable|.
1835
34.3k
    ssl->s3->established_session =
1836
34.3k
        SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
1837
34.3k
    if (!ssl->s3->established_session) {
1838
0
      return ssl_hs_error;
1839
0
    }
1840
    // Renegotiations do not participate in session resumption.
1841
34.3k
    if (!ssl->s3->initial_handshake_complete) {
1842
1.78k
      ssl->s3->established_session->not_resumable = false;
1843
1.78k
    }
1844
1845
34.3k
    hs->new_session.reset();
1846
34.3k
  } else {
1847
197
    assert(ssl->session != nullptr);
1848
197
    ssl->s3->established_session = UpRef(ssl->session);
1849
197
  }
1850
1851
34.4k
  hs->handshake_finalized = true;
1852
34.4k
  ssl->s3->initial_handshake_complete = true;
1853
34.4k
  if (has_new_session) {
1854
34.3k
    ssl_update_cache(ssl);
1855
34.3k
  }
1856
1857
34.4k
  hs->state = state_done;
1858
34.4k
  return ssl_hs_ok;
1859
34.4k
}
1860
1861
510k
enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
1862
1.06M
  while (hs->state != state_done) {
1863
1.03M
    enum ssl_hs_wait_t ret = ssl_hs_error;
1864
1.03M
    enum ssl_client_hs_state_t state =
1865
1.03M
        static_cast<enum ssl_client_hs_state_t>(hs->state);
1866
1.03M
    switch (state) {
1867
47.0k
      case state_start_connect:
1868
47.0k
        ret = do_start_connect(hs);
1869
47.0k
        break;
1870
47.0k
      case state_enter_early_data:
1871
47.0k
        ret = do_enter_early_data(hs);
1872
47.0k
        break;
1873
66
      case state_early_reverify_server_certificate:
1874
66
        ret = do_early_reverify_server_certificate(hs);
1875
66
        break;
1876
120k
      case state_read_server_hello:
1877
120k
        ret = do_read_server_hello(hs);
1878
120k
        break;
1879
22.3k
      case state_tls13:
1880
22.3k
        ret = do_tls13(hs);
1881
22.3k
        break;
1882
99.0k
      case state_read_server_certificate:
1883
99.0k
        ret = do_read_server_certificate(hs);
1884
99.0k
        break;
1885
53.0k
      case state_read_certificate_status:
1886
53.0k
        ret = do_read_certificate_status(hs);
1887
53.0k
        break;
1888
37.9k
      case state_verify_server_certificate:
1889
37.9k
        ret = do_verify_server_certificate(hs);
1890
37.9k
        break;
1891
0
      case state_reverify_server_certificate:
1892
0
        ret = do_reverify_server_certificate(hs);
1893
0
        break;
1894
103k
      case state_read_server_key_exchange:
1895
103k
        ret = do_read_server_key_exchange(hs);
1896
103k
        break;
1897
70.1k
      case state_read_certificate_request:
1898
70.1k
        ret = do_read_certificate_request(hs);
1899
70.1k
        break;
1900
46.1k
      case state_read_server_hello_done:
1901
46.1k
        ret = do_read_server_hello_done(hs);
1902
46.1k
        break;
1903
35.6k
      case state_send_client_certificate:
1904
35.6k
        ret = do_send_client_certificate(hs);
1905
35.6k
        break;
1906
35.6k
      case state_send_client_key_exchange:
1907
35.6k
        ret = do_send_client_key_exchange(hs);
1908
35.6k
        break;
1909
35.4k
      case state_send_client_certificate_verify:
1910
35.4k
        ret = do_send_client_certificate_verify(hs);
1911
35.4k
        break;
1912
35.6k
      case state_send_client_finished:
1913
35.6k
        ret = do_send_client_finished(hs);
1914
35.6k
        break;
1915
35.6k
      case state_finish_flight:
1916
35.6k
        ret = do_finish_flight(hs);
1917
35.6k
        break;
1918
72.0k
      case state_read_session_ticket:
1919
72.0k
        ret = do_read_session_ticket(hs);
1920
72.0k
        break;
1921
34.1k
      case state_process_change_cipher_spec:
1922
34.1k
        ret = do_process_change_cipher_spec(hs);
1923
34.1k
        break;
1924
68.3k
      case state_read_server_finished:
1925
68.3k
        ret = do_read_server_finished(hs);
1926
68.3k
        break;
1927
34.4k
      case state_finish_client_handshake:
1928
34.4k
        ret = do_finish_client_handshake(hs);
1929
34.4k
        break;
1930
0
      case state_done:
1931
0
        ret = ssl_hs_ok;
1932
0
        break;
1933
1.03M
    }
1934
1935
1.03M
    if (hs->state != state) {
1936
675k
      ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1937
675k
    }
1938
1939
1.03M
    if (ret != ssl_hs_ok) {
1940
476k
      return ret;
1941
476k
    }
1942
1.03M
  }
1943
1944
34.4k
  ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1945
34.4k
  return ssl_hs_ok;
1946
510k
}
1947
1948
0
const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
1949
0
  enum ssl_client_hs_state_t state =
1950
0
      static_cast<enum ssl_client_hs_state_t>(hs->state);
1951
0
  switch (state) {
1952
0
    case state_start_connect:
1953
0
      return "TLS client start_connect";
1954
0
    case state_enter_early_data:
1955
0
      return "TLS client enter_early_data";
1956
0
    case state_early_reverify_server_certificate:
1957
0
      return "TLS client early_reverify_server_certificate";
1958
0
    case state_read_server_hello:
1959
0
      return "TLS client read_server_hello";
1960
0
    case state_tls13:
1961
0
      return tls13_client_handshake_state(hs);
1962
0
    case state_read_server_certificate:
1963
0
      return "TLS client read_server_certificate";
1964
0
    case state_read_certificate_status:
1965
0
      return "TLS client read_certificate_status";
1966
0
    case state_verify_server_certificate:
1967
0
      return "TLS client verify_server_certificate";
1968
0
    case state_reverify_server_certificate:
1969
0
      return "TLS client reverify_server_certificate";
1970
0
    case state_read_server_key_exchange:
1971
0
      return "TLS client read_server_key_exchange";
1972
0
    case state_read_certificate_request:
1973
0
      return "TLS client read_certificate_request";
1974
0
    case state_read_server_hello_done:
1975
0
      return "TLS client read_server_hello_done";
1976
0
    case state_send_client_certificate:
1977
0
      return "TLS client send_client_certificate";
1978
0
    case state_send_client_key_exchange:
1979
0
      return "TLS client send_client_key_exchange";
1980
0
    case state_send_client_certificate_verify:
1981
0
      return "TLS client send_client_certificate_verify";
1982
0
    case state_send_client_finished:
1983
0
      return "TLS client send_client_finished";
1984
0
    case state_finish_flight:
1985
0
      return "TLS client finish_flight";
1986
0
    case state_read_session_ticket:
1987
0
      return "TLS client read_session_ticket";
1988
0
    case state_process_change_cipher_spec:
1989
0
      return "TLS client process_change_cipher_spec";
1990
0
    case state_read_server_finished:
1991
0
      return "TLS client read_server_finished";
1992
0
    case state_finish_client_handshake:
1993
0
      return "TLS client finish_client_handshake";
1994
0
    case state_done:
1995
0
      return "TLS client done";
1996
0
  }
1997
1998
0
  return "TLS client unknown";
1999
0
}
2000
2001
BSSL_NAMESPACE_END