Coverage Report

Created: 2026-08-14 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/ssl/tls13_client.cc
Line
Count
Source
1
// Copyright 2016 The BoringSSL Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/ssl.h>
16
17
#include <assert.h>
18
#include <limits.h>
19
#include <string.h>
20
21
#include <algorithm>
22
#include <utility>
23
24
#include <openssl/bytestring.h>
25
#include <openssl/digest.h>
26
#include <openssl/err.h>
27
#include <openssl/mem.h>
28
#include <openssl/sha2.h>
29
#include <openssl/stack.h>
30
31
#include "../crypto/internal.h"
32
#include "internal.h"
33
34
35
BSSL_NAMESPACE_BEGIN
36
37
enum client_hs_state_t {
38
  state_read_hello_retry_request = 0,
39
  state_send_second_client_hello,
40
  state_read_server_hello,
41
  state_read_encrypted_extensions,
42
  state_read_certificate_request,
43
  state_read_server_certificate,
44
  state_read_server_certificate_verify,
45
  state_server_certificate_reverify,
46
  state_read_server_finished,
47
  state_send_end_of_early_data,
48
  state_send_client_encrypted_extensions,
49
  state_send_client_certificate,
50
  state_send_client_certificate_verify,
51
  state_complete_second_flight,
52
  state_done,
53
};
54
55
static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
56
57
// end_of_early_data closes the early data stream for `hs` and switches the
58
// encryption level to `level`. It returns true on success and false on error.
59
0
static bool close_early_data(SSL_HANDSHAKE *hs, ssl_encryption_level_t level) {
60
0
  SSLImpl *const ssl = hs->ssl;
61
0
  assert(hs->in_early_data);
62
63
  // Note `can_early_write` may already be false if `SSL_write` exceeded the
64
  // early data write limit.
65
0
  hs->can_early_write = false;
66
67
  // 0-RTT write states on the client differ between TLS 1.3, DTLS 1.3, and
68
  // QUIC. TLS 1.3 has one write encryption level at a time. 0-RTT write keys
69
  // overwrite the null cipher and defer handshake write keys. While a
70
  // HelloRetryRequest can cause us to rewind back to the null cipher, sequence
71
  // numbers have no effect, so we can install a "new" null cipher.
72
  //
73
  // In QUIC and DTLS 1.3, 0-RTT write state cannot override or defer the normal
74
  // write state. The two ClientHello sequence numbers must align, and handshake
75
  // write keys must be installed early to ACK the EncryptedExtensions.
76
  //
77
  // TODO(crbug.com/381113363): We do not support 0-RTT in DTLS 1.3 and, in
78
  // QUIC, the caller handles 0-RTT data, so we can skip installing 0-RTT keys
79
  // and act as if there is one write level. Now that we're implementing
80
  // DTLS 1.3, switch the abstraction to the DTLS/QUIC model where handshake
81
  // keys write keys are installed immediately, but the TLS record layer
82
  // internally waits to activate that epoch until the 0-RTT channel is closed.
83
0
  if (!SSL_is_quic(ssl)) {
84
0
    if (level == ssl_encryption_initial) {
85
0
      bssl::UniquePtr<SSLAEADContext> null_ctx =
86
0
          SSLAEADContext::CreateNullCipher();
87
0
      if (!null_ctx ||  //
88
0
          !ssl->method->set_write_state(ssl, ssl_encryption_initial,
89
0
                                        std::move(null_ctx),
90
0
                                        /*traffic_secret=*/{})) {
91
0
        return false;
92
0
      }
93
0
    } else {
94
0
      assert(level == ssl_encryption_handshake);
95
0
      if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
96
0
                                 hs->new_session.get(),
97
0
                                 hs->client_handshake_secret)) {
98
0
        return false;
99
0
      }
100
0
    }
101
0
  } else {
102
0
    assert(ssl->s3->quic_write_level == level);
103
0
  }
104
105
0
  return true;
106
0
}
107
108
static bool parse_server_hello_tls13(const SSL_HANDSHAKE *hs,
109
                                     ParsedServerHello *out, uint8_t *out_alert,
110
5.07k
                                     const SSLMessage &msg) {
111
5.07k
  if (!ssl_parse_server_hello(out, out_alert, msg)) {
112
6
    return false;
113
6
  }
114
5.06k
  uint16_t expected_version =
115
5.06k
      SSL_is_dtls(hs->ssl) ? DTLS1_2_VERSION : TLS1_2_VERSION;
116
  // DTLS 1.3 disables "compatibility mode" (RFC 8446, appendix D.4). When
117
  // disabled, servers MUST NOT echo the legacy_session_id (RFC 9147, section
118
  // 5). The client could have sent a session ID indicating its willingness to
119
  // resume a DTLS 1.2 session, so just checking that the session IDs match is
120
  // incorrect.
121
5.06k
  Span<const uint8_t> expected_session_id =
122
5.06k
      SSL_is_dtls(hs->ssl) ? Span<const uint8_t>() : Span(hs->session_id);
123
124
  // RFC 8446 fixes some legacy values. Check them.
125
5.06k
  if (out->legacy_version != expected_version ||  //
126
5.03k
      out->compression_method != 0 ||
127
5.02k
      Span<const uint8_t>(out->session_id) != expected_session_id ||
128
4.97k
      CBS_len(&out->extensions) == 0) {
129
94
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
130
94
    *out_alert = SSL_AD_DECODE_ERROR;
131
94
    return false;
132
94
  }
133
4.97k
  return true;
134
5.06k
}
135
136
7.71k
static bool is_hello_retry_request(const ParsedServerHello &server_hello) {
137
7.71k
  return Span<const uint8_t>(server_hello.random) == kHelloRetryRequest;
138
7.71k
}
139
140
static bool check_ech_confirmation(const SSL_HANDSHAKE *hs, bool *out_accepted,
141
                                   uint8_t *out_alert,
142
2.74k
                                   const ParsedServerHello &server_hello) {
143
2.74k
  const bool is_hrr = is_hello_retry_request(server_hello);
144
2.74k
  size_t offset;
145
2.74k
  if (is_hrr) {
146
    // We check for an unsolicited extension when parsing all of them.
147
648
    SSLExtension ech(TLSEXT_TYPE_encrypted_client_hello);
148
648
    if (!ssl_parse_extensions(&server_hello.extensions, out_alert, {&ech},
149
648
                              /*ignore_unknown=*/true)) {
150
1
      return false;
151
1
    }
152
647
    if (!ech.present) {
153
644
      *out_accepted = false;
154
644
      return true;
155
644
    }
156
3
    if (CBS_len(&ech.data) != ECH_CONFIRMATION_SIGNAL_LEN) {
157
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
158
1
      *out_alert = SSL_AD_DECODE_ERROR;
159
1
      return false;
160
1
    }
161
2
    offset = CBS_data(&ech.data) - CBS_data(&server_hello.raw);
162
2.09k
  } else {
163
2.09k
    offset = ssl_ech_confirmation_signal_hello_offset(hs->ssl);
164
2.09k
  }
165
166
2.09k
  if (!hs->selected_ech_config) {
167
2.09k
    *out_accepted = false;
168
2.09k
    return true;
169
2.09k
  }
170
171
0
  uint8_t expected[ECH_CONFIRMATION_SIGNAL_LEN];
172
0
  if (!ssl_ech_accept_confirmation(hs, expected, hs->inner_client_random,
173
0
                                   hs->inner_transcript, is_hrr,
174
0
                                   server_hello.raw, offset)) {
175
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
176
0
    return false;
177
0
  }
178
179
0
  *out_accepted = CRYPTO_memcmp(CBS_data(&server_hello.raw) + offset, expected,
180
0
                                sizeof(expected)) == 0;
181
0
  return true;
182
0
}
183
184
2.82k
static enum ssl_hs_wait_t do_read_hello_retry_request(SSL_HANDSHAKE *hs) {
185
2.82k
  SSLImpl *const ssl = hs->ssl;
186
2.82k
  assert(ssl->s3->version != 0);
187
2.82k
  SSLMessage msg;
188
2.82k
  if (!ssl->method->get_message(ssl, &msg)) {
189
0
    return ssl_hs_read_message;
190
0
  }
191
192
  // Queue up a ChangeCipherSpec for whenever we next send something. This
193
  // will be before the second ClientHello. If we offered early data, this was
194
  // already done.
195
2.82k
  if (!hs->early_data_offered &&  //
196
2.81k
      !ssl->method->add_change_cipher_spec(ssl)) {
197
0
    return ssl_hs_error;
198
0
  }
199
200
2.82k
  ParsedServerHello server_hello;
201
2.82k
  uint8_t alert = SSL_AD_DECODE_ERROR;
202
2.82k
  if (!parse_server_hello_tls13(hs, &server_hello, &alert, msg)) {
203
70
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
204
70
    return ssl_hs_error;
205
70
  }
206
207
  // The cipher suite must be one we offered. We currently offer all supported
208
  // TLS 1.3 ciphers unless policy controls limited it. So we check the version
209
  // and that it's ok per policy.
210
2.75k
  const SSL_CIPHER *cipher = SSL_get_cipher_by_value(server_hello.cipher_suite);
211
2.75k
  if (cipher == nullptr ||
212
2.74k
      SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
213
2.74k
      SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
214
2.74k
      !ssl_tls13_cipher_meets_policy(SSL_CIPHER_get_protocol_id(cipher),
215
2.74k
                                     ssl->config->compliance_policy)) {
216
6
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
217
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
218
6
    return ssl_hs_error;
219
6
  }
220
221
2.74k
  hs->new_cipher = cipher;
222
223
2.74k
  const bool is_hrr = is_hello_retry_request(server_hello);
224
2.74k
  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
225
2.74k
      (is_hrr && !hs->transcript.UpdateForHelloRetryRequest())) {
226
0
    return ssl_hs_error;
227
0
  }
228
2.74k
  if (hs->selected_ech_config) {
229
0
    if (!hs->inner_transcript.InitHash(ssl_protocol_version(ssl),
230
0
                                       hs->new_cipher) ||
231
0
        (is_hrr && !hs->inner_transcript.UpdateForHelloRetryRequest())) {
232
0
      return ssl_hs_error;
233
0
    }
234
0
  }
235
236
  // Determine which ClientHello the server is responding to. Run
237
  // `check_ech_confirmation` unconditionally, so we validate the extension
238
  // contents.
239
2.74k
  bool ech_accepted;
240
2.74k
  if (!check_ech_confirmation(hs, &ech_accepted, &alert, server_hello)) {
241
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
242
2
    return ssl_hs_error;
243
2
  }
244
2.74k
  if (hs->selected_ech_config) {
245
0
    ssl->s3->ech_status = ech_accepted ? ssl_ech_accepted : ssl_ech_rejected;
246
0
  }
247
248
2.74k
  if (!is_hrr) {
249
2.09k
    hs->tls13_state = state_read_server_hello;
250
2.09k
    return ssl_hs_ok;
251
2.09k
  }
252
253
  // The ECH extension, if present, was already parsed by
254
  // `check_ech_confirmation`.
255
646
  SSLExtension cookie(TLSEXT_TYPE_cookie),
256
      // If offering PAKE, we won't send key_share extensions and we should
257
      // reject key_share from the peer. Otherwise, it is valid to have sent an
258
      // empty key_share extension, and expect the HelloRetryRequest to contain
259
      // a key_share.
260
646
      key_share(TLSEXT_TYPE_key_share, !hs->pake_prover),
261
646
      supported_versions(TLSEXT_TYPE_supported_versions),
262
646
      ech_unused(TLSEXT_TYPE_encrypted_client_hello,
263
646
                 hs->selected_ech_config || hs->config->ech_grease_enabled);
264
646
  if (!ssl_parse_extensions(
265
646
          &server_hello.extensions, &alert,
266
646
          {&cookie, &key_share, &supported_versions, &ech_unused},
267
646
          /*ignore_unknown=*/false)) {
268
10
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
269
10
    return ssl_hs_error;
270
10
  }
271
272
636
  if (!cookie.present && !key_share.present) {
273
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_EMPTY_HELLO_RETRY_REQUEST);
274
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
275
0
    return ssl_hs_error;
276
0
  }
277
636
  if (cookie.present) {
278
169
    CBS cookie_value;
279
169
    if (!CBS_get_u16_length_prefixed(&cookie.data, &cookie_value) ||  //
280
166
        CBS_len(&cookie_value) == 0 ||                                //
281
163
        CBS_len(&cookie.data) != 0) {
282
11
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
283
11
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
284
11
      return ssl_hs_error;
285
11
    }
286
287
158
    if (!hs->cookie.CopyFrom(cookie_value)) {
288
0
      return ssl_hs_error;
289
0
    }
290
158
  }
291
292
625
  if (key_share.present) {
293
467
    assert(!hs->pake_prover);
294
295
467
    uint16_t group_id;
296
467
    if (!CBS_get_u16(&key_share.data, &group_id) ||
297
467
        CBS_len(&key_share.data) != 0) {
298
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
299
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
300
3
      return ssl_hs_error;
301
3
    }
302
303
    // The group must be supported.
304
464
    if (!tls1_check_group_id(hs, group_id)) {
305
29
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
306
29
      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
307
29
      return ssl_hs_error;
308
29
    }
309
310
    // Check that the HelloRetryRequest does not request a key share that was
311
    // provided in the initial ClientHello.
312
435
    if (std::find_if(hs->key_shares.begin(), hs->key_shares.end(),
313
869
                     [group_id](const auto &hs_key_share) {
314
869
                       return hs_key_share->GroupID() == group_id;
315
869
                     }) != hs->key_shares.end()) {
316
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
317
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
318
3
      return ssl_hs_error;
319
3
    }
320
321
432
    if (!ssl_setup_key_shares(hs, group_id)) {
322
0
      return ssl_hs_error;
323
0
    }
324
432
  }
325
326
  // Although we now know whether ClientHelloInner was used, we currently
327
  // maintain both transcripts up to ServerHello. We could swap transcripts
328
  // early, but then ClientHello construction and `check_ech_confirmation`
329
  // become more complex.
330
590
  if (!ssl_hash_message(hs, msg)) {
331
0
    return ssl_hs_error;
332
0
  }
333
590
  if (ssl->s3->ech_status == ssl_ech_accepted &&
334
0
      !hs->inner_transcript.Update(msg.raw)) {
335
0
    return ssl_hs_error;
336
0
  }
337
338
  // Per RFC 8446 section 4.1.4, skip any PSKs whose hash does not match the
339
  // selected cipher. This avoids performing the transcript hash transformation
340
  // for multiple hashes.
341
590
  const EVP_MD *cipher_md = SSL_CIPHER_get_handshake_digest(cipher);
342
590
  hs->pre_shared_keys.EraseIf([=](const SSLPreSharedKey &psk) {
343
15
    return ssl_pre_shared_key_hash(psk) != cipher_md;
344
15
  });
345
346
  // HelloRetryRequest should be the end of the flight.
347
590
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
348
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
349
6
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
350
6
    return ssl_hs_error;
351
6
  }
352
353
584
  ssl->method->next_message(ssl);
354
584
  ssl->s3->used_hello_retry_request = true;
355
584
  hs->tls13_state = state_send_second_client_hello;
356
  // 0-RTT is rejected if we receive a HelloRetryRequest.
357
584
  if (hs->in_early_data) {
358
0
    ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
359
0
    if (!close_early_data(hs, ssl_encryption_initial)) {
360
0
      return ssl_hs_error;
361
0
    }
362
0
    return ssl_hs_early_data_rejected;
363
0
  }
364
584
  return ssl_hs_ok;
365
584
}
366
367
584
static enum ssl_hs_wait_t do_send_second_client_hello(SSL_HANDSHAKE *hs) {
368
  // Build the second ClientHelloInner, if applicable. The second ClientHello
369
  // uses an empty string for `enc`.
370
584
  if (hs->ssl->s3->ech_status == ssl_ech_accepted &&
371
0
      !ssl_encrypt_client_hello(hs, {})) {
372
0
    return ssl_hs_error;
373
0
  }
374
375
584
  if (!ssl_add_client_hello(hs)) {
376
0
    return ssl_hs_error;
377
0
  }
378
379
584
  ssl_done_writing_client_hello(hs);
380
584
  hs->tls13_state = state_read_server_hello;
381
584
  return ssl_hs_flush;
382
584
}
383
384
static bool check_session(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
385
57
                          const SSL_SESSION *session) {
386
57
  const SSLImpl *const ssl = hs->ssl;
387
57
  if (session->ssl_version != ssl->s3->version) {
388
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
389
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
390
0
    return false;
391
0
  }
392
393
57
  if (session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
394
1
    OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_PRF_HASH_MISMATCH);
395
1
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
396
1
    return false;
397
1
  }
398
399
56
  if (!ssl_session_is_context_valid(hs, session)) {
400
    // This is actually a client application bug.
401
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
402
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
403
0
    return false;
404
0
  }
405
56
  return true;
406
56
}
407
408
static bool check_imported_psk(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
409
0
                               const SSLImportedPSK &imported) {
410
0
  const SSLImpl *const ssl = hs->ssl;
411
0
  const EVP_MD *md =
412
0
      ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher);
413
0
  if (imported.md != md || imported.protocol != ssl->s3->version) {
414
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_PSK_FOR_CONNECTION);
415
0
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
416
0
    return false;
417
0
  }
418
0
  return true;
419
0
}
420
421
12.3k
static bool using_certificate(const SSL_HANDSHAKE *hs) {
422
12.3k
  const SSLImpl *const ssl = hs->ssl;
423
  // Resumption is not a certificate-based handshake.
424
12.3k
  if (ssl->s3->session_reused) {
425
142
    return false;
426
142
  }
427
  // Non-private-key credentials imply a non-certificate handshake (PSK, etc.).
428
12.1k
  if (hs->credential != nullptr && !hs->credential->UsesPrivateKey()) {
429
0
    return false;
430
0
  }
431
12.1k
  return true;
432
12.1k
}
433
434
5.75k
static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
435
5.75k
  SSLImpl *const ssl = hs->ssl;
436
5.75k
  SSLMessage msg;
437
5.75k
  if (!ssl->method->get_message(ssl, &msg)) {
438
3.50k
    return ssl_hs_read_message;
439
3.50k
  }
440
2.25k
  ParsedServerHello server_hello;
441
2.25k
  uint8_t alert = SSL_AD_DECODE_ERROR;
442
2.25k
  if (!parse_server_hello_tls13(hs, &server_hello, &alert, msg)) {
443
30
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
444
30
    return ssl_hs_error;
445
30
  }
446
447
  // Forbid a second HelloRetryRequest.
448
2.22k
  if (is_hello_retry_request(server_hello)) {
449
4
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
450
4
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
451
4
    return ssl_hs_error;
452
4
  }
453
454
  // Check the cipher suite, in case this is after HelloRetryRequest.
455
2.21k
  if (SSL_CIPHER_get_protocol_id(hs->new_cipher) != server_hello.cipher_suite) {
456
8
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
457
8
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
458
8
    return ssl_hs_error;
459
8
  }
460
461
2.21k
  if (ssl->s3->ech_status == ssl_ech_accepted) {
462
0
    if (ssl->s3->used_hello_retry_request) {
463
      // HelloRetryRequest and ServerHello must accept ECH consistently.
464
0
      bool ech_accepted;
465
0
      if (!check_ech_confirmation(hs, &ech_accepted, &alert, server_hello)) {
466
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
467
0
        return ssl_hs_error;
468
0
      }
469
0
      if (!ech_accepted) {
470
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_INCONSISTENT_ECH_NEGOTIATION);
471
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
472
0
        return ssl_hs_error;
473
0
      }
474
0
    }
475
476
0
    hs->transcript = std::move(hs->inner_transcript);
477
0
    hs->extensions.sent = hs->inner_extensions_sent;
478
    // Report the inner random value through `SSL_get_client_random`.
479
0
    OPENSSL_memcpy(ssl->s3->client_random, hs->inner_client_random,
480
0
                   SSL3_RANDOM_SIZE);
481
0
  }
482
483
2.21k
  OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_hello.random),
484
2.21k
                 SSL3_RANDOM_SIZE);
485
486
  // When offering ECH, pre-shared keys are only offered in ClientHelloInner.
487
2.21k
  const bool pre_shared_key_allowed =
488
2.21k
      !hs->pre_shared_keys.empty() && ssl->s3->ech_status != ssl_ech_rejected;
489
2.21k
  SSLExtension key_share(TLSEXT_TYPE_key_share, !hs->key_shares.empty()),
490
2.21k
      pake_share(TLSEXT_TYPE_pake, hs->pake_prover != nullptr),
491
2.21k
      pre_shared_key(TLSEXT_TYPE_pre_shared_key, pre_shared_key_allowed),
492
2.21k
      supported_versions(TLSEXT_TYPE_supported_versions);
493
2.21k
  if (!ssl_parse_extensions(
494
2.21k
          &server_hello.extensions, &alert,
495
2.21k
          {&key_share, &pre_shared_key, &supported_versions, &pake_share},
496
2.21k
          /*ignore_unknown=*/false)) {
497
45
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
498
45
    return ssl_hs_error;
499
45
  }
500
501
  // Recheck supported_versions, in case this is after HelloRetryRequest.
502
2.16k
  uint16_t version;
503
2.16k
  if (!supported_versions.present ||                       //
504
2.16k
      !CBS_get_u16(&supported_versions.data, &version) ||  //
505
2.16k
      CBS_len(&supported_versions.data) != 0 ||            //
506
2.16k
      version != ssl->s3->version) {
507
30
    OPENSSL_PUT_ERROR(SSL, SSL_R_SECOND_SERVERHELLO_VERSION_MISMATCH);
508
30
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
509
30
    return ssl_hs_error;
510
30
  }
511
512
  // The combination of ServerHello extensions determines the kind of handshake
513
  // that the server selected. Check for invalid combinations.
514
515
  // If the server specified no alternative authentication mode, it is using
516
  // certificate authentication. Check that this is acceptable.
517
2.13k
  if (!pake_share.present && !pre_shared_key.present &&
518
2.07k
      !ssl_accepts_server_certificate_auth(hs)) {
519
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
520
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
521
0
    return ssl_hs_error;
522
0
  }
523
  // pake replaces key_share and may not be used with pre_shared_key.
524
2.13k
  if (pake_share.present && (key_share.present || pre_shared_key.present)) {
525
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
526
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
527
0
    return ssl_hs_error;
528
0
  }
529
  // In PAKE mode, we require a PAKE handshake and do not support resumption.
530
2.13k
  if (hs->pake_prover != nullptr && !pake_share.present) {
531
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
532
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
533
0
    return ssl_hs_error;
534
0
  }
535
  // In non-PAKE modes, we require per-connection forward secrecy and do not
536
  // support psk_ke.
537
2.13k
  if (hs->pake_prover == nullptr && !key_share.present) {
538
1
    OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_KEY_SHARE);
539
1
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
540
1
    return ssl_hs_error;
541
1
  }
542
  // The above implies only one of three handshake forms will be allowed. The
543
  // checks for unsolicited extensions ensure the server did not select
544
  // something we cannot respond to.
545
2.13k
  assert(
546
      // Full handshake
547
2.13k
      (key_share.present && !pake_share.present && !pre_shared_key.present) ||
548
      // PSK/resumption handshake
549
2.13k
      (key_share.present && !pake_share.present && pre_shared_key.present) ||
550
      // PAKE handshake
551
2.13k
      (!key_share.present && pake_share.present && !pre_shared_key.present));
552
553
  // Determine the PSK used.
554
2.13k
  const EVP_MD *cipher_md =
555
2.13k
      ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher);
556
2.13k
  Span<const uint8_t> psk_secret = Span(kZeroes, EVP_MD_size(cipher_md));
557
2.13k
  alert = SSL_AD_DECODE_ERROR;
558
2.13k
  if (pre_shared_key.present) {
559
62
    const SSLPreSharedKey *psk = ssl_ext_pre_shared_key_parse_serverhello(
560
62
        hs, &alert, &pre_shared_key.data);
561
62
    if (psk == nullptr) {
562
5
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
563
5
      return ssl_hs_error;
564
5
    }
565
566
57
    if (const auto *imported = std::get_if<SSLImportedPSK>(psk);
567
57
        imported != nullptr) {
568
0
      if (!check_imported_psk(hs, &alert, *imported)) {
569
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
570
0
        return ssl_hs_error;
571
0
      }
572
573
0
      psk_secret = imported->ipskx;
574
0
      hs->credential = UpRef(imported->credential);
575
0
      if (!ssl_get_new_session(hs)) {
576
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
577
0
        return ssl_hs_error;
578
0
      }
579
57
    } else {
580
57
      const SSL_SESSION *session = std::get<UniquePtr<SSL_SESSION>>(*psk).get();
581
57
      assert(session == ssl->session.get());
582
57
      if (!check_session(hs, &alert, session)) {
583
1
        ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
584
1
        return ssl_hs_error;
585
1
      }
586
587
56
      psk_secret = session->secret;
588
56
      ssl->s3->session_reused = true;
589
      // Only authentication information carries over in TLS 1.3.
590
56
      hs->new_session = SSL_SESSION_dup(session, SSL_SESSION_DUP_AUTH_ONLY);
591
56
      if (!hs->new_session) {
592
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
593
0
        return ssl_hs_error;
594
0
      }
595
56
      ssl_set_session(ssl, nullptr);
596
597
      // Resumption incorporates fresh key material, so refresh the timeout.
598
56
      ssl_session_renew_timeout(ssl, hs->new_session.get(),
599
56
                                ssl->session_ctx->session_psk_dhe_timeout);
600
56
    }
601
2.07k
  } else if (!ssl_get_new_session(hs)) {
602
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
603
0
    return ssl_hs_error;
604
0
  }
605
606
2.12k
  hs->new_session->cipher = hs->new_cipher;
607
2.12k
  hs->can_release_private_key = !using_certificate(hs);
608
2.12k
  assert(!using_certificate(hs) || ssl_accepts_server_certificate_auth(hs));
609
610
  // Set up the key schedule and incorporate the PSK into the running secret.
611
2.12k
  if (!tls13_init_key_schedule(hs, psk_secret)) {
612
0
    return ssl_hs_error;
613
0
  }
614
615
  // Resolve ECDHE or PAKE and incorporate it into the secret.
616
2.12k
  Array<uint8_t> shared_secret;
617
2.12k
  alert = SSL_AD_DECODE_ERROR;
618
2.12k
  if (key_share.present) {
619
2.12k
    if (!ssl_ext_key_share_parse_serverhello(hs, &shared_secret, &alert,
620
2.12k
                                             &key_share.data)) {
621
147
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
622
147
      return ssl_hs_error;
623
147
    }
624
2.12k
  } else if (pake_share.present) {
625
0
    if (!ssl_ext_pake_parse_serverhello(hs, &shared_secret, &alert,
626
0
                                        &pake_share.data)) {
627
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
628
0
      return ssl_hs_error;
629
0
    }
630
0
  } else {
631
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
632
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
633
0
    return ssl_hs_error;
634
0
  }
635
636
1.98k
  if (!tls13_advance_key_schedule(hs, shared_secret) ||  //
637
1.98k
      !ssl_hash_message(hs, msg) ||                      //
638
1.98k
      !tls13_derive_handshake_secrets(hs)) {
639
0
    return ssl_hs_error;
640
0
  }
641
642
  // If currently sending early data over TCP, we defer installing client
643
  // traffic keys to when the early data stream is closed. See
644
  // `close_early_data`. Note if the server has already rejected 0-RTT via
645
  // HelloRetryRequest, `in_early_data` is already false.
646
1.98k
  if (!hs->in_early_data || SSL_is_quic(ssl)) {
647
1.98k
    if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
648
1.98k
                               hs->new_session.get(),
649
1.98k
                               hs->client_handshake_secret)) {
650
0
      return ssl_hs_error;
651
0
    }
652
1.98k
  }
653
654
1.98k
  if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
655
1.98k
                             hs->new_session.get(),
656
1.98k
                             hs->server_handshake_secret)) {
657
6
    return ssl_hs_error;
658
6
  }
659
660
1.97k
  ssl->method->next_message(ssl);
661
1.97k
  hs->tls13_state = state_read_encrypted_extensions;
662
1.97k
  return ssl_hs_ok;
663
1.98k
}
664
665
20.7k
static enum ssl_hs_wait_t do_read_encrypted_extensions(SSL_HANDSHAKE *hs) {
666
20.7k
  SSLImpl *const ssl = hs->ssl;
667
20.7k
  SSLMessage msg;
668
20.7k
  if (!ssl->method->get_message(ssl, &msg)) {
669
19.0k
    return ssl_hs_read_message;
670
19.0k
  }
671
1.70k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
672
6
    return ssl_hs_error;
673
6
  }
674
675
1.70k
  CBS body = msg.body, extensions;
676
1.70k
  if (!CBS_get_u16_length_prefixed(&body, &extensions) ||  //
677
1.69k
      CBS_len(&body) != 0) {
678
5
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
679
5
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
680
5
    return ssl_hs_error;
681
5
  }
682
683
1.69k
  if (!ssl_parse_serverhello_tlsext(hs, &extensions)) {
684
13
    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
685
13
    return ssl_hs_error;
686
13
  }
687
688
1.68k
  if (ssl->s3->early_data_accepted) {
689
    // The extension parser checks the server resumed the session.
690
0
    assert(ssl->s3->session_reused);
691
    // If offering ECH, the server may not accept early data with
692
    // ClientHelloOuter. We do not offer sessions with ClientHelloOuter, so this
693
    // this should be implied by checking `session_reused`.
694
0
    assert(ssl->s3->ech_status != ssl_ech_rejected);
695
696
0
    if (hs->early_session->cipher != hs->new_session->cipher) {
697
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_CIPHER_MISMATCH_ON_EARLY_DATA);
698
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
699
0
      return ssl_hs_error;
700
0
    }
701
0
    if (Span(hs->early_session->early_alpn) != ssl->s3->alpn_selected) {
702
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ALPN_MISMATCH_ON_EARLY_DATA);
703
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
704
0
      return ssl_hs_error;
705
0
    }
706
    // Channel ID is incompatible with 0-RTT. The ALPS extension should be
707
    // negotiated implicitly.
708
0
    if (hs->channel_id_negotiated ||
709
0
        hs->new_session->has_application_settings) {
710
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION_ON_EARLY_DATA);
711
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
712
0
      return ssl_hs_error;
713
0
    }
714
0
    hs->new_session->has_application_settings =
715
0
        hs->early_session->has_application_settings;
716
0
    if (!hs->new_session->local_application_settings.CopyFrom(
717
0
            hs->early_session->local_application_settings) ||
718
0
        !hs->new_session->peer_application_settings.CopyFrom(
719
0
            hs->early_session->peer_application_settings)) {
720
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
721
0
      return ssl_hs_error;
722
0
    }
723
0
  }
724
725
  // Store the negotiated ALPN in the session.
726
1.68k
  if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
727
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
728
0
    return ssl_hs_error;
729
0
  }
730
731
1.68k
  if (!ssl_hash_message(hs, msg)) {
732
0
    return ssl_hs_error;
733
0
  }
734
735
1.68k
  ssl->method->next_message(ssl);
736
1.68k
  hs->tls13_state = state_read_certificate_request;
737
1.68k
  if (hs->in_early_data && !ssl->s3->early_data_accepted) {
738
0
    if (!close_early_data(hs, ssl_encryption_handshake)) {
739
0
      return ssl_hs_error;
740
0
    }
741
0
    return ssl_hs_early_data_rejected;
742
0
  }
743
1.68k
  return ssl_hs_ok;
744
1.68k
}
745
746
8.05k
static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
747
8.05k
  SSLImpl *const ssl = hs->ssl;
748
  // CertificateRequest may only be sent in certificate-based handshakes.
749
8.05k
  if (!using_certificate(hs)) {
750
30
    if (ssl->s3->session_reused && ssl->ctx->reverify_on_resume &&
751
0
        !ssl->s3->early_data_accepted) {
752
0
      hs->tls13_state = state_server_certificate_reverify;
753
0
      return ssl_hs_ok;
754
0
    }
755
30
    hs->tls13_state = state_read_server_finished;
756
30
    return ssl_hs_ok;
757
30
  }
758
759
8.02k
  SSLMessage msg;
760
8.02k
  if (!ssl->method->get_message(ssl, &msg)) {
761
6.44k
    return ssl_hs_read_message;
762
6.44k
  }
763
764
  // CertificateRequest is optional.
765
1.57k
  if (msg.type != SSL3_MT_CERTIFICATE_REQUEST) {
766
1.33k
    hs->tls13_state = state_read_server_certificate;
767
1.33k
    return ssl_hs_ok;
768
1.33k
  }
769
770
242
  SSLExtension sigalgs(TLSEXT_TYPE_signature_algorithms),
771
242
      ca(TLSEXT_TYPE_certificate_authorities);
772
242
  CBS body = msg.body, context, extensions, supported_signature_algorithms;
773
242
  uint8_t alert = SSL_AD_DECODE_ERROR;
774
242
  if (!CBS_get_u8_length_prefixed(&body, &context) ||
775
      // The request context is always empty during the handshake.
776
240
      CBS_len(&context) != 0 ||
777
234
      !CBS_get_u16_length_prefixed(&body, &extensions) ||  //
778
232
      CBS_len(&body) != 0 ||
779
229
      !ssl_parse_extensions(&extensions, &alert, {&sigalgs, &ca},
780
229
                            /*ignore_unknown=*/true) ||
781
223
      !sigalgs.present ||
782
221
      !CBS_get_u16_length_prefixed(&sigalgs.data,
783
221
                                   &supported_signature_algorithms) ||
784
219
      !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
785
25
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
786
25
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
787
25
    return ssl_hs_error;
788
25
  }
789
790
217
  if (ca.present) {
791
163
    hs->ca_names = SSL_parse_CA_list(ssl, &alert, &ca.data);
792
163
    if (!hs->ca_names || sk_CRYPTO_BUFFER_num(hs->ca_names.get()) == 0 ||
793
147
        CBS_len(&ca.data) != 0) {
794
147
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
795
147
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
796
147
      return ssl_hs_error;
797
147
    }
798
163
  } else {
799
54
    hs->ca_names.reset(sk_CRYPTO_BUFFER_new_null());
800
54
    if (!hs->ca_names) {
801
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
802
0
      return ssl_hs_error;
803
0
    }
804
54
  }
805
806
70
  hs->cert_request = true;
807
70
  ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
808
809
70
  if (!ssl_hash_message(hs, msg)) {
810
0
    return ssl_hs_error;
811
0
  }
812
813
70
  ssl->method->next_message(ssl);
814
70
  hs->tls13_state = state_read_server_certificate;
815
70
  return ssl_hs_ok;
816
70
}
817
818
3.51k
static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
819
3.51k
  SSLImpl *const ssl = hs->ssl;
820
3.51k
  SSLMessage msg;
821
3.51k
  if (!ssl->method->get_message(ssl, &msg)) {
822
2.14k
    return ssl_hs_read_message;
823
2.14k
  }
824
825
1.37k
  if (msg.type != SSL3_MT_COMPRESSED_CERTIFICATE &&
826
1.33k
      !ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
827
10
    return ssl_hs_error;
828
10
  }
829
830
1.36k
  if (!tls13_process_certificate(hs, msg, false /* certificate required */) ||
831
947
      !ssl_hash_message(hs, msg)) {
832
415
    return ssl_hs_error;
833
415
  }
834
835
947
  ssl->method->next_message(ssl);
836
947
  hs->tls13_state = state_read_server_certificate_verify;
837
947
  return ssl_hs_ok;
838
1.36k
}
839
840
2.76k
static enum ssl_hs_wait_t do_read_server_certificate_verify(SSL_HANDSHAKE *hs) {
841
2.76k
  SSLImpl *const ssl = hs->ssl;
842
2.76k
  SSLMessage msg;
843
2.76k
  if (!ssl->method->get_message(ssl, &msg)) {
844
1.85k
    return ssl_hs_read_message;
845
1.85k
  }
846
911
  switch (ssl_verify_peer_cert(hs)) {
847
911
    case ssl_verify_ok:
848
911
      break;
849
0
    case ssl_verify_invalid:
850
0
      return ssl_hs_error;
851
0
    case ssl_verify_retry:
852
0
      hs->tls13_state = state_read_server_certificate_verify;
853
0
      return ssl_hs_certificate_verify;
854
911
  }
855
856
911
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
857
909
      !tls13_process_certificate_verify(hs, msg) ||
858
895
      !ssl_hash_message(hs, msg)) {
859
16
    return ssl_hs_error;
860
16
  }
861
862
895
  ssl->method->next_message(ssl);
863
895
  hs->tls13_state = state_read_server_finished;
864
895
  return ssl_hs_ok;
865
911
}
866
867
0
static enum ssl_hs_wait_t do_server_certificate_reverify(SSL_HANDSHAKE *hs) {
868
0
  switch (ssl_reverify_peer_cert(hs, /*send_alert=*/true)) {
869
0
    case ssl_verify_ok:
870
0
      break;
871
0
    case ssl_verify_invalid:
872
0
      return ssl_hs_error;
873
0
    case ssl_verify_retry:
874
0
      hs->tls13_state = state_server_certificate_reverify;
875
0
      return ssl_hs_certificate_verify;
876
0
  }
877
0
  hs->tls13_state = state_read_server_finished;
878
0
  return ssl_hs_ok;
879
0
}
880
881
2.07k
static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
882
2.07k
  SSLImpl *const ssl = hs->ssl;
883
2.07k
  SSLMessage msg;
884
2.07k
  if (!ssl->method->get_message(ssl, &msg)) {
885
1.46k
    return ssl_hs_read_message;
886
1.46k
  }
887
610
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
888
606
      !tls13_process_finished(hs, msg, false /* don't use saved value */) ||
889
606
      !ssl_hash_message(hs, msg) ||
890
      // Update the secret to the master secret and derive traffic keys.
891
606
      !tls13_advance_key_schedule(hs,
892
606
                                  Span(kZeroes, hs->transcript.DigestLen())) ||
893
606
      !tls13_derive_application_secrets(hs)) {
894
4
    return ssl_hs_error;
895
4
  }
896
897
  // Finished should be the end of the flight.
898
606
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
899
5
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
900
5
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
901
5
    return ssl_hs_error;
902
5
  }
903
904
601
  ssl->method->next_message(ssl);
905
601
  hs->tls13_state = state_send_end_of_early_data;
906
601
  return ssl_hs_ok;
907
606
}
908
909
601
static enum ssl_hs_wait_t do_send_end_of_early_data(SSL_HANDSHAKE *hs) {
910
601
  SSLImpl *const ssl = hs->ssl;
911
912
601
  if (ssl->s3->early_data_accepted) {
913
    // DTLS and QUIC omit the EndOfEarlyData message. See RFC 9001, section 8.3,
914
    // and RFC 9147, section 5.6.
915
0
    if (!SSL_is_quic(ssl) && !SSL_is_dtls(ssl)) {
916
0
      ScopedCBB cbb;
917
0
      CBB body;
918
0
      if (!ssl->method->init_message(ssl, cbb.get(), &body,
919
0
                                     SSL3_MT_END_OF_EARLY_DATA) ||
920
0
          !ssl_add_message_cbb(ssl, cbb.get())) {
921
0
        return ssl_hs_error;
922
0
      }
923
0
    }
924
925
0
    if (!close_early_data(hs, ssl_encryption_handshake)) {
926
0
      return ssl_hs_error;
927
0
    }
928
0
  }
929
930
601
  hs->tls13_state = state_send_client_encrypted_extensions;
931
601
  return ssl_hs_ok;
932
601
}
933
934
static enum ssl_hs_wait_t do_send_client_encrypted_extensions(
935
601
    SSL_HANDSHAKE *hs) {
936
601
  SSLImpl *const ssl = hs->ssl;
937
  // For now, only one extension uses client EncryptedExtensions. This function
938
  // may be generalized if others use it in the future.
939
601
  if (hs->new_session->has_application_settings &&
940
0
      !ssl->s3->early_data_accepted) {
941
0
    ScopedCBB cbb;
942
0
    CBB body, extensions, extension;
943
0
    uint16_t extension_type = TLSEXT_TYPE_application_settings_old;
944
0
    if (hs->config->alps_use_new_codepoint) {
945
0
      extension_type = TLSEXT_TYPE_application_settings;
946
0
    }
947
0
    if (!ssl->method->init_message(ssl, cbb.get(), &body,
948
0
                                   SSL3_MT_ENCRYPTED_EXTENSIONS) ||
949
0
        !CBB_add_u16_length_prefixed(&body, &extensions) ||
950
0
        !CBB_add_u16(&extensions, extension_type) ||
951
0
        !CBB_add_u16_length_prefixed(&extensions, &extension) ||
952
0
        !CBB_add_bytes(&extension,
953
0
                       hs->new_session->local_application_settings.data(),
954
0
                       hs->new_session->local_application_settings.size()) ||
955
0
        !ssl_add_message_cbb(ssl, cbb.get())) {
956
0
      return ssl_hs_error;
957
0
    }
958
0
  }
959
960
601
  hs->tls13_state = state_send_client_certificate;
961
601
  return ssl_hs_ok;
962
601
}
963
964
static bool check_credential(SSL_HANDSHAKE *hs, const SSLCredential *cred,
965
28
                             uint16_t *out_sigalg) {
966
28
  bool cert_type_ok = false;
967
28
  if (hs->client_cert_type == TLSEXT_cert_type_x509) {
968
28
    cert_type_ok = cred->type == SSLCredentialType::kX509;
969
28
  } else if (hs->client_cert_type == TLSEXT_cert_type_rpk) {
970
0
    cert_type_ok = cred->type == SSLCredentialType::kRawPublicKey;
971
0
  }
972
28
  if (!cert_type_ok) {
973
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
974
0
    return false;
975
0
  }
976
977
  // All currently supported credentials require a signature.
978
28
  if (!tls1_choose_signature_algorithm(hs, cred, out_sigalg)) {
979
3
    return false;
980
3
  }
981
  // Use this credential if it either matches a requested issuer,
982
  // or does not require issuer matching.
983
25
  return ssl_credential_matches_requested_issuers(hs, cred);
984
28
}
985
986
601
static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
987
601
  SSLImpl *const ssl = hs->ssl;
988
989
  // The peer didn't request a certificate.
990
601
  if (!hs->cert_request) {
991
573
    hs->tls13_state = state_complete_second_flight;
992
573
    return ssl_hs_ok;
993
573
  }
994
995
28
  if (ssl->s3->ech_status == ssl_ech_rejected) {
996
    // Do not send client certificates on ECH reject. We have not authenticated
997
    // the server for the name that can learn the certificate.
998
0
    SSL_certs_clear(ssl);
999
28
  } else if (hs->config->cert->cert_cb != nullptr) {
1000
    // Call cert_cb to update the certificate.
1001
0
    int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
1002
0
    if (rv == 0) {
1003
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1004
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1005
0
      return ssl_hs_error;
1006
0
    }
1007
0
    if (rv < 0) {
1008
0
      hs->tls13_state = state_send_client_certificate;
1009
0
      return ssl_hs_x509_lookup;
1010
0
    }
1011
0
  }
1012
1013
28
  Array<SSLCredential *> creds;
1014
28
  if (!ssl_get_full_credential_list(hs, &creds)) {
1015
0
    return ssl_hs_error;
1016
0
  }
1017
1018
  // Select the credential, if any, to use.
1019
28
  bool may_proceed_anonymously = true;
1020
28
  for (SSLCredential *cred : creds) {
1021
28
    if (!cred->UsesPrivateKey()) {
1022
      // Non-certificate credentials (e.g. PSKs) do not participate in deciding
1023
      // whether to error or proceed anonymously.
1024
0
      continue;
1025
0
    }
1026
1027
28
    ERR_clear_error();
1028
28
    may_proceed_anonymously = false;
1029
28
    uint16_t sigalg;
1030
28
    if (check_credential(hs, cred, &sigalg)) {
1031
25
      hs->credential = UpRef(cred);
1032
25
      hs->signature_algorithm = sigalg;
1033
25
      break;
1034
25
    }
1035
28
  }
1036
1037
  // Fail the connection if no credentials matched, but only if the caller
1038
  // configured at least one certificate credential. If there were no
1039
  // candidates, proceed anonymously.
1040
28
  if (!may_proceed_anonymously && hs->credential == nullptr) {
1041
    // The error from the last attempt is in the error queue.
1042
3
    assert(ERR_peek_error() != 0);
1043
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1044
3
    return ssl_hs_error;
1045
3
  }
1046
1047
25
  if (!tls13_add_certificate(hs)) {
1048
0
    return ssl_hs_error;
1049
0
  }
1050
1051
25
  hs->tls13_state = state_send_client_certificate_verify;
1052
25
  return ssl_hs_ok;
1053
25
}
1054
1055
25
static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1056
  // Don't send CertificateVerify if there is no certificate.
1057
25
  if (hs->credential == nullptr) {
1058
0
    hs->tls13_state = state_complete_second_flight;
1059
0
    return ssl_hs_ok;
1060
0
  }
1061
1062
25
  switch (tls13_add_certificate_verify(hs)) {
1063
25
    case ssl_private_key_success:
1064
25
      hs->tls13_state = state_complete_second_flight;
1065
25
      return ssl_hs_ok;
1066
1067
0
    case ssl_private_key_retry:
1068
0
      hs->tls13_state = state_send_client_certificate_verify;
1069
0
      return ssl_hs_private_key_operation;
1070
1071
0
    case ssl_private_key_failure:
1072
0
      return ssl_hs_error;
1073
25
  }
1074
1075
25
  assert(0);
1076
0
  return ssl_hs_error;
1077
0
}
1078
1079
598
static enum ssl_hs_wait_t do_complete_second_flight(SSL_HANDSHAKE *hs) {
1080
598
  SSLImpl *const ssl = hs->ssl;
1081
598
  hs->can_release_private_key = true;
1082
1083
  // Send a Channel ID assertion if necessary.
1084
598
  if (hs->channel_id_negotiated) {
1085
0
    ScopedCBB cbb;
1086
0
    CBB body;
1087
0
    if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1088
0
        !tls1_write_channel_id(hs, &body) ||
1089
0
        !ssl_add_message_cbb(ssl, cbb.get())) {
1090
0
      return ssl_hs_error;
1091
0
    }
1092
0
  }
1093
1094
  // Send a Finished message.
1095
598
  if (!tls13_add_finished(hs)) {
1096
0
    return ssl_hs_error;
1097
0
  }
1098
1099
  // Derive the final keys and enable them.
1100
598
  if (!tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
1101
598
                             hs->new_session.get(),
1102
598
                             hs->client_traffic_secret_0) ||
1103
598
      !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
1104
598
                             hs->new_session.get(),
1105
598
                             hs->server_traffic_secret_0) ||
1106
598
      !tls13_derive_resumption_secret(hs)) {
1107
0
    return ssl_hs_error;
1108
0
  }
1109
1110
598
  hs->tls13_state = state_done;
1111
598
  return ssl_hs_flush;
1112
598
}
1113
1114
37.3k
enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs) {
1115
49.3k
  while (hs->tls13_state != state_done) {
1116
48.7k
    enum ssl_hs_wait_t ret = ssl_hs_error;
1117
48.7k
    enum client_hs_state_t state =
1118
48.7k
        static_cast<enum client_hs_state_t>(hs->tls13_state);
1119
48.7k
    switch (state) {
1120
2.82k
      case state_read_hello_retry_request:
1121
2.82k
        ret = do_read_hello_retry_request(hs);
1122
2.82k
        break;
1123
584
      case state_send_second_client_hello:
1124
584
        ret = do_send_second_client_hello(hs);
1125
584
        break;
1126
5.75k
      case state_read_server_hello:
1127
5.75k
        ret = do_read_server_hello(hs);
1128
5.75k
        break;
1129
20.7k
      case state_read_encrypted_extensions:
1130
20.7k
        ret = do_read_encrypted_extensions(hs);
1131
20.7k
        break;
1132
8.05k
      case state_read_certificate_request:
1133
8.05k
        ret = do_read_certificate_request(hs);
1134
8.05k
        break;
1135
3.51k
      case state_read_server_certificate:
1136
3.51k
        ret = do_read_server_certificate(hs);
1137
3.51k
        break;
1138
2.76k
      case state_read_server_certificate_verify:
1139
2.76k
        ret = do_read_server_certificate_verify(hs);
1140
2.76k
        break;
1141
0
      case state_server_certificate_reverify:
1142
0
        ret = do_server_certificate_reverify(hs);
1143
0
        break;
1144
2.07k
      case state_read_server_finished:
1145
2.07k
        ret = do_read_server_finished(hs);
1146
2.07k
        break;
1147
601
      case state_send_end_of_early_data:
1148
601
        ret = do_send_end_of_early_data(hs);
1149
601
        break;
1150
601
      case state_send_client_certificate:
1151
601
        ret = do_send_client_certificate(hs);
1152
601
        break;
1153
601
      case state_send_client_encrypted_extensions:
1154
601
        ret = do_send_client_encrypted_extensions(hs);
1155
601
        break;
1156
25
      case state_send_client_certificate_verify:
1157
25
        ret = do_send_client_certificate_verify(hs);
1158
25
        break;
1159
598
      case state_complete_second_flight:
1160
598
        ret = do_complete_second_flight(hs);
1161
598
        break;
1162
0
      case state_done:
1163
0
        ret = ssl_hs_ok;
1164
0
        break;
1165
48.7k
    }
1166
1167
48.7k
    if (hs->tls13_state != state) {
1168
13.2k
      ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1169
13.2k
    }
1170
1171
48.7k
    if (ret != ssl_hs_ok) {
1172
36.7k
      return ret;
1173
36.7k
    }
1174
48.7k
  }
1175
1176
598
  return ssl_hs_ok;
1177
37.3k
}
1178
1179
0
const char *tls13_client_handshake_state(SSL_HANDSHAKE *hs) {
1180
0
  enum client_hs_state_t state =
1181
0
      static_cast<enum client_hs_state_t>(hs->tls13_state);
1182
0
  switch (state) {
1183
0
    case state_read_hello_retry_request:
1184
0
      return "TLS 1.3 client read_hello_retry_request";
1185
0
    case state_send_second_client_hello:
1186
0
      return "TLS 1.3 client send_second_client_hello";
1187
0
    case state_read_server_hello:
1188
0
      return "TLS 1.3 client read_server_hello";
1189
0
    case state_read_encrypted_extensions:
1190
0
      return "TLS 1.3 client read_encrypted_extensions";
1191
0
    case state_read_certificate_request:
1192
0
      return "TLS 1.3 client read_certificate_request";
1193
0
    case state_read_server_certificate:
1194
0
      return "TLS 1.3 client read_server_certificate";
1195
0
    case state_read_server_certificate_verify:
1196
0
      return "TLS 1.3 client read_server_certificate_verify";
1197
0
    case state_server_certificate_reverify:
1198
0
      return "TLS 1.3 client server_certificate_reverify";
1199
0
    case state_read_server_finished:
1200
0
      return "TLS 1.3 client read_server_finished";
1201
0
    case state_send_end_of_early_data:
1202
0
      return "TLS 1.3 client send_end_of_early_data";
1203
0
    case state_send_client_encrypted_extensions:
1204
0
      return "TLS 1.3 client send_client_encrypted_extensions";
1205
0
    case state_send_client_certificate:
1206
0
      return "TLS 1.3 client send_client_certificate";
1207
0
    case state_send_client_certificate_verify:
1208
0
      return "TLS 1.3 client send_client_certificate_verify";
1209
0
    case state_complete_second_flight:
1210
0
      return "TLS 1.3 client complete_second_flight";
1211
0
    case state_done:
1212
0
      return "TLS 1.3 client done";
1213
0
  }
1214
1215
0
  return "TLS 1.3 client unknown";
1216
0
}
1217
1218
6.77k
bool tls13_process_new_session_ticket(SSLImpl *ssl, const SSLMessage &msg) {
1219
6.77k
  if (ssl->s3->write_shutdown != ssl_shutdown_none) {
1220
    // Ignore tickets on shutdown. Callers tend to indiscriminately call
1221
    // `SSL_shutdown` before destroying an `SSL`, at which point calling the new
1222
    // session callback may be confusing.
1223
0
    return true;
1224
0
  }
1225
1226
6.77k
  CBS body = msg.body;
1227
6.77k
  UniquePtr<SSL_SESSION> session = tls13_create_session_with_ticket(ssl, &body);
1228
6.77k
  if (!session) {
1229
47
    return false;
1230
47
  }
1231
1232
6.73k
  if ((ssl->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) &&
1233
0
      ssl->session_ctx->new_session_cb != nullptr &&
1234
0
      ssl->session_ctx->new_session_cb(ssl, session.get())) {
1235
    // `new_session_cb`'s return value signals that it took ownership.
1236
0
    session.release();
1237
0
  }
1238
1239
6.73k
  return true;
1240
6.77k
}
1241
1242
UniquePtr<SSL_SESSION> tls13_create_session_with_ticket(SSLImpl *ssl,
1243
6.77k
                                                        CBS *body) {
1244
6.77k
  UniquePtr<SSL_SESSION> session = SSL_SESSION_dup(
1245
6.77k
      ssl->s3->established_session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1246
6.77k
  if (!session) {
1247
0
    return nullptr;
1248
0
  }
1249
1250
6.77k
  ssl_session_rebase_time(ssl, session.get());
1251
1252
6.77k
  uint32_t server_timeout;
1253
6.77k
  CBS ticket_nonce, ticket, extensions;
1254
6.77k
  if (!CBS_get_u32(body, &server_timeout) ||
1255
6.77k
      !CBS_get_u32(body, &session->ticket_age_add) ||
1256
6.77k
      !CBS_get_u8_length_prefixed(body, &ticket_nonce) ||
1257
6.76k
      !CBS_get_u16_length_prefixed(body, &ticket) ||
1258
6.76k
      CBS_len(&ticket) == 0 ||  //
1259
6.76k
      !session->ticket.CopyFrom(ticket) ||
1260
6.76k
      !CBS_get_u16_length_prefixed(body, &extensions) ||  //
1261
6.74k
      CBS_len(body) != 0) {
1262
41
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1263
41
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1264
41
    return nullptr;
1265
41
  }
1266
1267
  // Cap the renewable lifetime by the server advertised value. This avoids
1268
  // wasting bandwidth on 0-RTT when we know the server will reject it.
1269
6.73k
  if (session->timeout > server_timeout) {
1270
1.84k
    session->timeout = server_timeout;
1271
1.84k
  }
1272
1273
6.73k
  if (!tls13_derive_session_psk(session.get(), ticket_nonce,
1274
6.73k
                                SSL_is_dtls(ssl))) {
1275
0
    return nullptr;
1276
0
  }
1277
1278
6.73k
  SSLExtension early_data(TLSEXT_TYPE_early_data);
1279
6.73k
  SSLExtension flags(TLSEXT_TYPE_tls_flags);
1280
6.73k
  uint8_t alert = SSL_AD_DECODE_ERROR;
1281
6.73k
  if (!ssl_parse_extensions(&extensions, &alert, {&early_data, &flags},
1282
6.73k
                            /*ignore_unknown=*/true)) {
1283
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1284
2
    return nullptr;
1285
2
  }
1286
1287
6.73k
  if (early_data.present) {
1288
4
    if (!CBS_get_u32(&early_data.data, &session->ticket_max_early_data) ||
1289
3
        CBS_len(&early_data.data) != 0) {
1290
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1291
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1292
1
      return nullptr;
1293
1
    }
1294
1295
    // QUIC does not use the max_early_data_size parameter and always sets it to
1296
    // a fixed value. See RFC 9001, section 4.6.1.
1297
3
    if (SSL_is_quic(ssl) && session->ticket_max_early_data != 0xffffffff) {
1298
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1299
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1300
0
      return nullptr;
1301
0
    }
1302
3
  }
1303
1304
6.73k
  if (flags.present) {
1305
5
    SSLFlags parsed;
1306
5
    if (!ssl_parse_flags_extension_request(&flags.data, &parsed, &alert)) {
1307
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1308
3
      return nullptr;
1309
3
    }
1310
2
    if (parsed & kSSLFlagResumptionAcrossNames) {
1311
1
      session->is_resumable_across_names = true;
1312
1
    }
1313
2
  }
1314
1315
  // Historically, OpenSSL filled in fake session IDs for ticket-based sessions.
1316
  // Envoy's tests depend on this, although perhaps they shouldn't.
1317
6.73k
  session->session_id.ResizeForOverwrite(SHA256_DIGEST_LENGTH);
1318
6.73k
  SHA256(CBS_data(&ticket), CBS_len(&ticket), session->session_id.data());
1319
1320
6.73k
  session->ticket_age_add_valid = true;
1321
6.73k
  session->not_resumable = false;
1322
1323
6.73k
  return session;
1324
6.73k
}
1325
1326
BSSL_NAMESPACE_END