Coverage Report

Created: 2026-05-11 06:45

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
  SSL *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.23k
                                     const SSLMessage &msg) {
111
5.23k
  if (!ssl_parse_server_hello(out, out_alert, msg)) {
112
5
    return false;
113
5
  }
114
5.22k
  uint16_t expected_version =
115
5.22k
      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.22k
  Span<const uint8_t> expected_session_id =
122
5.22k
      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.22k
  if (out->legacy_version != expected_version ||  //
126
5.18k
      out->compression_method != 0 ||
127
5.17k
      Span<const uint8_t>(out->session_id) != expected_session_id ||
128
5.12k
      CBS_len(&out->extensions) == 0) {
129
106
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
130
106
    *out_alert = SSL_AD_DECODE_ERROR;
131
106
    return false;
132
106
  }
133
5.12k
  return true;
134
5.22k
}
135
136
8.01k
static bool is_hello_retry_request(const ParsedServerHello &server_hello) {
137
8.01k
  return Span<const uint8_t>(server_hello.random) == kHelloRetryRequest;
138
8.01k
}
139
140
static bool check_ech_confirmation(const SSL_HANDSHAKE *hs, bool *out_accepted,
141
                                   uint8_t *out_alert,
142
2.89k
                                   const ParsedServerHello &server_hello) {
143
2.89k
  const bool is_hrr = is_hello_retry_request(server_hello);
144
2.89k
  size_t offset;
145
2.89k
  if (is_hrr) {
146
    // We check for an unsolicited extension when parsing all of them.
147
811
    SSLExtension ech(TLSEXT_TYPE_encrypted_client_hello);
148
811
    if (!ssl_parse_extensions(&server_hello.extensions, out_alert, {&ech},
149
811
                              /*ignore_unknown=*/true)) {
150
1
      return false;
151
1
    }
152
810
    if (!ech.present) {
153
807
      *out_accepted = false;
154
807
      return true;
155
807
    }
156
3
    if (CBS_len(&ech.data) != ECH_CONFIRMATION_SIGNAL_LEN) {
157
2
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
158
2
      *out_alert = SSL_AD_DECODE_ERROR;
159
2
      return false;
160
2
    }
161
1
    offset = CBS_data(&ech.data) - CBS_data(&server_hello.raw);
162
2.08k
  } else {
163
2.08k
    offset = ssl_ech_confirmation_signal_hello_offset(hs->ssl);
164
2.08k
  }
165
166
2.08k
  if (!hs->selected_ech_config) {
167
2.08k
    *out_accepted = false;
168
2.08k
    return true;
169
2.08k
  }
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.96k
static enum ssl_hs_wait_t do_read_hello_retry_request(SSL_HANDSHAKE *hs) {
185
2.96k
  SSL *const ssl = hs->ssl;
186
2.96k
  assert(ssl->s3->version != 0);
187
2.96k
  SSLMessage msg;
188
2.96k
  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.96k
  if (!hs->early_data_offered &&  //
196
2.96k
      !ssl->method->add_change_cipher_spec(ssl)) {
197
0
    return ssl_hs_error;
198
0
  }
199
200
2.96k
  ParsedServerHello server_hello;
201
2.96k
  uint8_t alert = SSL_AD_DECODE_ERROR;
202
2.96k
  if (!parse_server_hello_tls13(hs, &server_hello, &alert, msg)) {
203
68
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
204
68
    return ssl_hs_error;
205
68
  }
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.90k
  const SSL_CIPHER *cipher = SSL_get_cipher_by_value(server_hello.cipher_suite);
211
2.90k
  if (cipher == nullptr ||
212
2.89k
      SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
213
2.89k
      SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
214
2.89k
      !ssl_tls13_cipher_meets_policy(SSL_CIPHER_get_protocol_id(cipher),
215
2.89k
                                     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.89k
  hs->new_cipher = cipher;
222
223
2.89k
  const bool is_hrr = is_hello_retry_request(server_hello);
224
2.89k
  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
225
2.89k
      (is_hrr && !hs->transcript.UpdateForHelloRetryRequest())) {
226
0
    return ssl_hs_error;
227
0
  }
228
2.89k
  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.89k
  bool ech_accepted;
240
2.89k
  if (!check_ech_confirmation(hs, &ech_accepted, &alert, server_hello)) {
241
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
242
3
    return ssl_hs_error;
243
3
  }
244
2.89k
  if (hs->selected_ech_config) {
245
0
    ssl->s3->ech_status = ech_accepted ? ssl_ech_accepted : ssl_ech_rejected;
246
0
  }
247
248
2.89k
  if (!is_hrr) {
249
2.08k
    hs->tls13_state = state_read_server_hello;
250
2.08k
    return ssl_hs_ok;
251
2.08k
  }
252
253
  // The ECH extension, if present, was already parsed by
254
  // |check_ech_confirmation|.
255
808
  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
808
      key_share(TLSEXT_TYPE_key_share, !hs->pake_prover),
261
808
      supported_versions(TLSEXT_TYPE_supported_versions),
262
808
      ech_unused(TLSEXT_TYPE_encrypted_client_hello,
263
808
                 hs->selected_ech_config || hs->config->ech_grease_enabled);
264
808
  if (!ssl_parse_extensions(
265
808
          &server_hello.extensions, &alert,
266
808
          {&cookie, &key_share, &supported_versions, &ech_unused},
267
808
          /*ignore_unknown=*/false)) {
268
8
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
269
8
    return ssl_hs_error;
270
8
  }
271
272
800
  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
800
  if (cookie.present) {
278
145
    CBS cookie_value;
279
145
    if (!CBS_get_u16_length_prefixed(&cookie.data, &cookie_value) ||  //
280
142
        CBS_len(&cookie_value) == 0 ||                                //
281
139
        CBS_len(&cookie.data) != 0) {
282
9
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
283
9
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
284
9
      return ssl_hs_error;
285
9
    }
286
287
136
    if (!hs->cookie.CopyFrom(cookie_value)) {
288
0
      return ssl_hs_error;
289
0
    }
290
136
  }
291
292
791
  if (key_share.present) {
293
655
    assert(!hs->pake_prover);
294
295
655
    uint16_t group_id;
296
655
    if (!CBS_get_u16(&key_share.data, &group_id) ||
297
655
        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
652
    if (!tls1_check_group_id(hs, group_id)) {
305
61
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
306
61
      OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
307
61
      return ssl_hs_error;
308
61
    }
309
310
    // Check that the HelloRetryRequest does not request a key share that was
311
    // provided in the initial ClientHello.
312
591
    if (std::find_if(hs->key_shares.begin(), hs->key_shares.end(),
313
1.18k
                     [group_id](const auto &hs_key_share) {
314
1.18k
                       return hs_key_share->GroupID() == group_id;
315
1.18k
                     }) != 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
588
    if (!ssl_setup_key_shares(hs, group_id)) {
322
0
      return ssl_hs_error;
323
0
    }
324
588
  }
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
724
  if (!ssl_hash_message(hs, msg)) {
331
0
    return ssl_hs_error;
332
0
  }
333
724
  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
724
  const EVP_MD *cipher_md = SSL_CIPHER_get_handshake_digest(cipher);
342
724
  hs->pre_shared_keys.EraseIf([=](const SSLPreSharedKey &psk) {
343
12
    return ssl_pre_shared_key_hash(psk) != cipher_md;
344
12
  });
345
346
  // HelloRetryRequest should be the end of the flight.
347
724
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
348
9
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
349
9
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
350
9
    return ssl_hs_error;
351
9
  }
352
353
715
  ssl->method->next_message(ssl);
354
715
  ssl->s3->used_hello_retry_request = true;
355
715
  hs->tls13_state = state_send_second_client_hello;
356
  // 0-RTT is rejected if we receive a HelloRetryRequest.
357
715
  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
715
  return ssl_hs_ok;
365
715
}
366
367
715
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
715
  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
715
  if (!ssl_add_client_hello(hs)) {
376
0
    return ssl_hs_error;
377
0
  }
378
379
715
  ssl_done_writing_client_hello(hs);
380
715
  hs->tls13_state = state_read_server_hello;
381
715
  return ssl_hs_flush;
382
715
}
383
384
static bool check_session(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
385
55
                          const SSL_SESSION *session) {
386
55
  const SSL *const ssl = hs->ssl;
387
55
  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
55
  if (session->cipher->algorithm_prf != hs->new_cipher->algorithm_prf) {
394
2
    OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_PRF_HASH_MISMATCH);
395
2
    *out_alert = SSL_AD_ILLEGAL_PARAMETER;
396
2
    return false;
397
2
  }
398
399
53
  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
53
  return true;
406
53
}
407
408
static bool check_imported_psk(const SSL_HANDSHAKE *hs, uint8_t *out_alert,
409
0
                               const SSLImportedPSK &imported) {
410
0
  const SSL *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
11.8k
static bool using_certificate(const SSL_HANDSHAKE *hs) {
422
11.8k
  const SSL *const ssl = hs->ssl;
423
  // Resumption is not a certificate-based handshake.
424
11.8k
  if (ssl->s3->session_reused) {
425
136
    return false;
426
136
  }
427
  // Non-private-key credentials imply a non-certificate handshake (PSK, etc.).
428
11.6k
  if (hs->credential != nullptr && !hs->credential->UsesPrivateKey()) {
429
0
    return false;
430
0
  }
431
11.6k
  return true;
432
11.6k
}
433
434
5.40k
static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
435
5.40k
  SSL *const ssl = hs->ssl;
436
5.40k
  SSLMessage msg;
437
5.40k
  if (!ssl->method->get_message(ssl, &msg)) {
438
3.14k
    return ssl_hs_read_message;
439
3.14k
  }
440
2.26k
  ParsedServerHello server_hello;
441
2.26k
  uint8_t alert = SSL_AD_DECODE_ERROR;
442
2.26k
  if (!parse_server_hello_tls13(hs, &server_hello, &alert, msg)) {
443
43
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
444
43
    return ssl_hs_error;
445
43
  }
446
447
  // Forbid a second HelloRetryRequest.
448
2.22k
  if (is_hello_retry_request(server_hello)) {
449
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
450
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
451
3
    return ssl_hs_error;
452
3
  }
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
20
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
457
20
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
458
20
    return ssl_hs_error;
459
20
  }
460
461
2.19k
  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.19k
  OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_hello.random),
484
2.19k
                 SSL3_RANDOM_SIZE);
485
486
  // When offering ECH, pre-shared keys are only offered in ClientHelloInner.
487
2.19k
  const bool pre_shared_key_allowed =
488
2.19k
      !hs->pre_shared_keys.empty() && ssl->s3->ech_status != ssl_ech_rejected;
489
2.19k
  SSLExtension key_share(TLSEXT_TYPE_key_share, !hs->key_shares.empty()),
490
2.19k
      pake_share(TLSEXT_TYPE_pake, hs->pake_prover != nullptr),
491
2.19k
      pre_shared_key(TLSEXT_TYPE_pre_shared_key, pre_shared_key_allowed),
492
2.19k
      supported_versions(TLSEXT_TYPE_supported_versions);
493
2.19k
  if (!ssl_parse_extensions(
494
2.19k
          &server_hello.extensions, &alert,
495
2.19k
          {&key_share, &pre_shared_key, &supported_versions, &pake_share},
496
2.19k
          /*ignore_unknown=*/false)) {
497
40
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
498
40
    return ssl_hs_error;
499
40
  }
500
501
  // Recheck supported_versions, in case this is after HelloRetryRequest.
502
2.15k
  uint16_t version;
503
2.15k
  if (!supported_versions.present ||                       //
504
2.15k
      !CBS_get_u16(&supported_versions.data, &version) ||  //
505
2.15k
      CBS_len(&supported_versions.data) != 0 ||            //
506
2.15k
      version != ssl->s3->version) {
507
9
    OPENSSL_PUT_ERROR(SSL, SSL_R_SECOND_SERVERHELLO_VERSION_MISMATCH);
508
9
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
509
9
    return ssl_hs_error;
510
9
  }
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.15k
  if (!pake_share.present && !pre_shared_key.present &&
518
2.09k
      !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.15k
  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.15k
  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.15k
  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 imples 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.15k
  assert(
546
      // Full handshake
547
2.14k
      (key_share.present && !pake_share.present && !pre_shared_key.present) ||
548
      // PSK/resumption handshake
549
2.14k
      (key_share.present && !pake_share.present && pre_shared_key.present) ||
550
      // PAKE handshake
551
2.14k
      (!key_share.present && pake_share.present && !pre_shared_key.present));
552
553
  // Determine the PSK used.
554
2.14k
  const EVP_MD *cipher_md =
555
2.14k
      ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher);
556
2.14k
  Span<const uint8_t> psk_secret = Span(kZeroes, EVP_MD_size(cipher_md));
557
2.14k
  alert = SSL_AD_DECODE_ERROR;
558
2.14k
  if (pre_shared_key.present) {
559
58
    const SSLPreSharedKey *psk = ssl_ext_pre_shared_key_parse_serverhello(
560
58
        hs, &alert, &pre_shared_key.data);
561
58
    if (psk == nullptr) {
562
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
563
3
      return ssl_hs_error;
564
3
    }
565
566
55
    if (const auto *imported = std::get_if<SSLImportedPSK>(psk);
567
55
        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
55
    } else {
580
55
      const SSL_SESSION *session = std::get<UniquePtr<SSL_SESSION>>(*psk).get();
581
55
      assert(session == ssl->session.get());
582
55
      if (!check_session(hs, &alert, session)) {
583
2
        ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
584
2
        return ssl_hs_error;
585
2
      }
586
587
53
      psk_secret = session->secret;
588
53
      ssl->s3->session_reused = true;
589
      // Only authentication information carries over in TLS 1.3.
590
53
      hs->new_session = SSL_SESSION_dup(session, SSL_SESSION_DUP_AUTH_ONLY);
591
53
      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
53
      ssl_set_session(ssl, nullptr);
596
597
      // Resumption incorporates fresh key material, so refresh the timeout.
598
53
      ssl_session_renew_timeout(ssl, hs->new_session.get(),
599
53
                                ssl->session_ctx->session_psk_dhe_timeout);
600
53
    }
601
2.09k
  } 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.14k
  hs->new_session->cipher = hs->new_cipher;
607
2.14k
  hs->can_release_private_key = !using_certificate(hs);
608
2.14k
  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.14k
  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.14k
  Array<uint8_t> shared_secret;
617
2.14k
  alert = SSL_AD_DECODE_ERROR;
618
2.14k
  if (key_share.present) {
619
2.14k
    if (!ssl_ext_key_share_parse_serverhello(hs, &shared_secret, &alert,
620
2.14k
                                             &key_share.data)) {
621
150
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
622
150
      return ssl_hs_error;
623
150
    }
624
2.14k
  } 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.99k
  if (!tls13_advance_key_schedule(hs, shared_secret) ||  //
637
1.99k
      !ssl_hash_message(hs, msg) ||                      //
638
1.99k
      !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.99k
  if (!hs->in_early_data || SSL_is_quic(ssl)) {
647
1.99k
    if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
648
1.99k
                               hs->new_session.get(),
649
1.99k
                               hs->client_handshake_secret)) {
650
0
      return ssl_hs_error;
651
0
    }
652
1.99k
  }
653
654
1.99k
  if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
655
1.99k
                             hs->new_session.get(),
656
1.99k
                             hs->server_handshake_secret)) {
657
4
    return ssl_hs_error;
658
4
  }
659
660
1.99k
  ssl->method->next_message(ssl);
661
1.99k
  hs->tls13_state = state_read_encrypted_extensions;
662
1.99k
  return ssl_hs_ok;
663
1.99k
}
664
665
10.7k
static enum ssl_hs_wait_t do_read_encrypted_extensions(SSL_HANDSHAKE *hs) {
666
10.7k
  SSL *const ssl = hs->ssl;
667
10.7k
  SSLMessage msg;
668
10.7k
  if (!ssl->method->get_message(ssl, &msg)) {
669
9.01k
    return ssl_hs_read_message;
670
9.01k
  }
671
1.70k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
672
3
    return ssl_hs_error;
673
3
  }
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
16
    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
685
16
    return ssl_hs_error;
686
16
  }
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
7.52k
static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
747
7.52k
  SSL *const ssl = hs->ssl;
748
  // CertificateRequest may only be sent in certificate-based handshakes.
749
7.52k
  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
7.49k
  SSLMessage msg;
760
7.49k
  if (!ssl->method->get_message(ssl, &msg)) {
761
5.91k
    return ssl_hs_read_message;
762
5.91k
  }
763
764
  // CertificateRequest is optional.
765
1.58k
  if (msg.type != SSL3_MT_CERTIFICATE_REQUEST) {
766
1.35k
    hs->tls13_state = state_read_server_certificate;
767
1.35k
    return ssl_hs_ok;
768
1.35k
  }
769
770
230
  SSLExtension sigalgs(TLSEXT_TYPE_signature_algorithms),
771
230
      ca(TLSEXT_TYPE_certificate_authorities);
772
230
  CBS body = msg.body, context, extensions, supported_signature_algorithms;
773
230
  uint8_t alert = SSL_AD_DECODE_ERROR;
774
230
  if (!CBS_get_u8_length_prefixed(&body, &context) ||
775
      // The request context is always empty during the handshake.
776
228
      CBS_len(&context) != 0 ||
777
222
      !CBS_get_u16_length_prefixed(&body, &extensions) ||  //
778
220
      CBS_len(&body) != 0 ||
779
218
      !ssl_parse_extensions(&extensions, &alert, {&sigalgs, &ca},
780
218
                            /*ignore_unknown=*/true) ||
781
213
      !sigalgs.present ||
782
211
      !CBS_get_u16_length_prefixed(&sigalgs.data,
783
211
                                   &supported_signature_algorithms) ||
784
208
      !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
785
24
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
786
24
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
787
24
    return ssl_hs_error;
788
24
  }
789
790
206
  if (ca.present) {
791
150
    hs->ca_names = SSL_parse_CA_list(ssl, &alert, &ca.data);
792
150
    if (!hs->ca_names || sk_CRYPTO_BUFFER_num(hs->ca_names.get()) == 0 ||
793
129
        CBS_len(&ca.data) != 0) {
794
129
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
795
129
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
796
129
      return ssl_hs_error;
797
129
    }
798
150
  } else {
799
56
    hs->ca_names.reset(sk_CRYPTO_BUFFER_new_null());
800
56
    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
56
  }
805
806
77
  hs->cert_request = true;
807
77
  ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
808
809
77
  if (!ssl_hash_message(hs, msg)) {
810
0
    return ssl_hs_error;
811
0
  }
812
813
77
  ssl->method->next_message(ssl);
814
77
  hs->tls13_state = state_read_server_certificate;
815
77
  return ssl_hs_ok;
816
77
}
817
818
2.63k
static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
819
2.63k
  SSL *const ssl = hs->ssl;
820
2.63k
  SSLMessage msg;
821
2.63k
  if (!ssl->method->get_message(ssl, &msg)) {
822
1.24k
    return ssl_hs_read_message;
823
1.24k
  }
824
825
1.39k
  if (msg.type != SSL3_MT_COMPRESSED_CERTIFICATE &&
826
1.36k
      !ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
827
12
    return ssl_hs_error;
828
12
  }
829
830
1.37k
  if (!tls13_process_certificate(hs, msg, false /* certificate required */) ||
831
980
      !ssl_hash_message(hs, msg)) {
832
399
    return ssl_hs_error;
833
399
  }
834
835
980
  ssl->method->next_message(ssl);
836
980
  hs->tls13_state = state_read_server_certificate_verify;
837
980
  return ssl_hs_ok;
838
1.37k
}
839
840
2.66k
static enum ssl_hs_wait_t do_read_server_certificate_verify(SSL_HANDSHAKE *hs) {
841
2.66k
  SSL *const ssl = hs->ssl;
842
2.66k
  SSLMessage msg;
843
2.66k
  if (!ssl->method->get_message(ssl, &msg)) {
844
1.73k
    return ssl_hs_read_message;
845
1.73k
  }
846
936
  switch (ssl_verify_peer_cert(hs)) {
847
936
    case ssl_verify_ok:
848
936
      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
936
  }
855
856
936
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
857
934
      !tls13_process_certificate_verify(hs, msg) ||
858
917
      !ssl_hash_message(hs, msg)) {
859
19
    return ssl_hs_error;
860
19
  }
861
862
917
  ssl->method->next_message(ssl);
863
917
  hs->tls13_state = state_read_server_finished;
864
917
  return ssl_hs_ok;
865
936
}
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.14k
static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
882
2.14k
  SSL *const ssl = hs->ssl;
883
2.14k
  SSLMessage msg;
884
2.14k
  if (!ssl->method->get_message(ssl, &msg)) {
885
1.52k
    return ssl_hs_read_message;
886
1.52k
  }
887
620
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
888
618
      !tls13_process_finished(hs, msg, false /* don't use saved value */) ||
889
618
      !ssl_hash_message(hs, msg) ||
890
      // Update the secret to the master secret and derive traffic keys.
891
618
      !tls13_advance_key_schedule(hs,
892
618
                                  Span(kZeroes, hs->transcript.DigestLen())) ||
893
618
      !tls13_derive_application_secrets(hs)) {
894
2
    return ssl_hs_error;
895
2
  }
896
897
  // Finished should be the end of the flight.
898
618
  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
613
  ssl->method->next_message(ssl);
905
613
  hs->tls13_state = state_send_end_of_early_data;
906
613
  return ssl_hs_ok;
907
618
}
908
909
613
static enum ssl_hs_wait_t do_send_end_of_early_data(SSL_HANDSHAKE *hs) {
910
613
  SSL *const ssl = hs->ssl;
911
912
613
  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
613
  hs->tls13_state = state_send_client_encrypted_extensions;
931
613
  return ssl_hs_ok;
932
613
}
933
934
static enum ssl_hs_wait_t do_send_client_encrypted_extensions(
935
613
    SSL_HANDSHAKE *hs) {
936
613
  SSL *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
613
  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
613
  hs->tls13_state = state_send_client_certificate;
961
613
  return ssl_hs_ok;
962
613
}
963
964
static bool check_credential(SSL_HANDSHAKE *hs, const SSLCredential *cred,
965
29
                             uint16_t *out_sigalg) {
966
29
  bool cert_type_ok = false;
967
29
  if (hs->client_cert_type == TLSEXT_cert_type_x509) {
968
29
    cert_type_ok = cred->type == SSLCredentialType::kX509;
969
29
  } else if (hs->client_cert_type == TLSEXT_cert_type_rpk) {
970
0
    cert_type_ok = cred->type == SSLCredentialType::kRawPublicKey;
971
0
  }
972
29
  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
29
  if (!tls1_choose_signature_algorithm(hs, cred, out_sigalg)) {
979
1
    return false;
980
1
  }
981
  // Use this credential if it either matches a requested issuer,
982
  // or does not require issuer matching.
983
28
  return ssl_credential_matches_requested_issuers(hs, cred);
984
29
}
985
986
613
static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
987
613
  SSL *const ssl = hs->ssl;
988
989
  // The peer didn't request a certificate.
990
613
  if (!hs->cert_request) {
991
584
    hs->tls13_state = state_complete_second_flight;
992
584
    return ssl_hs_ok;
993
584
  }
994
995
29
  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
29
  } 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
29
  Array<SSLCredential *> creds;
1014
29
  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
29
  bool may_proceed_anonymously = true;
1020
29
  for (SSLCredential *cred : creds) {
1021
29
    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
29
    ERR_clear_error();
1028
29
    may_proceed_anonymously = false;
1029
29
    uint16_t sigalg;
1030
29
    if (check_credential(hs, cred, &sigalg)) {
1031
28
      hs->credential = UpRef(cred);
1032
28
      hs->signature_algorithm = sigalg;
1033
28
      break;
1034
28
    }
1035
29
  }
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
29
  if (!may_proceed_anonymously && hs->credential == nullptr) {
1041
    // The error from the last attempt is in the error queue.
1042
1
    assert(ERR_peek_error() != 0);
1043
1
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1044
1
    return ssl_hs_error;
1045
1
  }
1046
1047
28
  if (!tls13_add_certificate(hs)) {
1048
0
    return ssl_hs_error;
1049
0
  }
1050
1051
28
  hs->tls13_state = state_send_client_certificate_verify;
1052
28
  return ssl_hs_ok;
1053
28
}
1054
1055
28
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
28
  if (hs->credential == nullptr) {
1058
0
    hs->tls13_state = state_complete_second_flight;
1059
0
    return ssl_hs_ok;
1060
0
  }
1061
1062
28
  switch (tls13_add_certificate_verify(hs)) {
1063
28
    case ssl_private_key_success:
1064
28
      hs->tls13_state = state_complete_second_flight;
1065
28
      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
28
  }
1074
1075
28
  assert(0);
1076
0
  return ssl_hs_error;
1077
0
}
1078
1079
612
static enum ssl_hs_wait_t do_complete_second_flight(SSL_HANDSHAKE *hs) {
1080
612
  SSL *const ssl = hs->ssl;
1081
612
  hs->can_release_private_key = true;
1082
1083
  // Send a Channel ID assertion if necessary.
1084
612
  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
612
  if (!tls13_add_finished(hs)) {
1096
0
    return ssl_hs_error;
1097
0
  }
1098
1099
  // Derive the final keys and enable them.
1100
612
  if (!tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
1101
612
                             hs->new_session.get(),
1102
612
                             hs->client_traffic_secret_0) ||
1103
612
      !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
1104
612
                             hs->new_session.get(),
1105
612
                             hs->server_traffic_secret_0) ||
1106
612
      !tls13_derive_resumption_secret(hs)) {
1107
0
    return ssl_hs_error;
1108
0
  }
1109
1110
612
  hs->tls13_state = state_done;
1111
612
  return ssl_hs_flush;
1112
612
}
1113
1114
25.5k
enum ssl_hs_wait_t tls13_client_handshake(SSL_HANDSHAKE *hs) {
1115
37.8k
  while (hs->tls13_state != state_done) {
1116
37.2k
    enum ssl_hs_wait_t ret = ssl_hs_error;
1117
37.2k
    enum client_hs_state_t state =
1118
37.2k
        static_cast<enum client_hs_state_t>(hs->tls13_state);
1119
37.2k
    switch (state) {
1120
2.96k
      case state_read_hello_retry_request:
1121
2.96k
        ret = do_read_hello_retry_request(hs);
1122
2.96k
        break;
1123
715
      case state_send_second_client_hello:
1124
715
        ret = do_send_second_client_hello(hs);
1125
715
        break;
1126
5.40k
      case state_read_server_hello:
1127
5.40k
        ret = do_read_server_hello(hs);
1128
5.40k
        break;
1129
10.7k
      case state_read_encrypted_extensions:
1130
10.7k
        ret = do_read_encrypted_extensions(hs);
1131
10.7k
        break;
1132
7.52k
      case state_read_certificate_request:
1133
7.52k
        ret = do_read_certificate_request(hs);
1134
7.52k
        break;
1135
2.63k
      case state_read_server_certificate:
1136
2.63k
        ret = do_read_server_certificate(hs);
1137
2.63k
        break;
1138
2.66k
      case state_read_server_certificate_verify:
1139
2.66k
        ret = do_read_server_certificate_verify(hs);
1140
2.66k
        break;
1141
0
      case state_server_certificate_reverify:
1142
0
        ret = do_server_certificate_reverify(hs);
1143
0
        break;
1144
2.14k
      case state_read_server_finished:
1145
2.14k
        ret = do_read_server_finished(hs);
1146
2.14k
        break;
1147
613
      case state_send_end_of_early_data:
1148
613
        ret = do_send_end_of_early_data(hs);
1149
613
        break;
1150
613
      case state_send_client_certificate:
1151
613
        ret = do_send_client_certificate(hs);
1152
613
        break;
1153
613
      case state_send_client_encrypted_extensions:
1154
613
        ret = do_send_client_encrypted_extensions(hs);
1155
613
        break;
1156
28
      case state_send_client_certificate_verify:
1157
28
        ret = do_send_client_certificate_verify(hs);
1158
28
        break;
1159
612
      case state_complete_second_flight:
1160
612
        ret = do_complete_second_flight(hs);
1161
612
        break;
1162
0
      case state_done:
1163
0
        ret = ssl_hs_ok;
1164
0
        break;
1165
37.2k
    }
1166
1167
37.2k
    if (hs->tls13_state != state) {
1168
13.6k
      ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1169
13.6k
    }
1170
1171
37.2k
    if (ret != ssl_hs_ok) {
1172
24.9k
      return ret;
1173
24.9k
    }
1174
37.2k
  }
1175
1176
612
  return ssl_hs_ok;
1177
25.5k
}
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.32k
bool tls13_process_new_session_ticket(SSL *ssl, const SSLMessage &msg) {
1219
6.32k
  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.32k
  CBS body = msg.body;
1227
6.32k
  UniquePtr<SSL_SESSION> session = tls13_create_session_with_ticket(ssl, &body);
1228
6.32k
  if (!session) {
1229
46
    return false;
1230
46
  }
1231
1232
6.27k
  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.27k
  return true;
1240
6.32k
}
1241
1242
6.32k
UniquePtr<SSL_SESSION> tls13_create_session_with_ticket(SSL *ssl, CBS *body) {
1243
6.32k
  UniquePtr<SSL_SESSION> session = SSL_SESSION_dup(
1244
6.32k
      ssl->s3->established_session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1245
6.32k
  if (!session) {
1246
0
    return nullptr;
1247
0
  }
1248
1249
6.32k
  ssl_session_rebase_time(ssl, session.get());
1250
1251
6.32k
  uint32_t server_timeout;
1252
6.32k
  CBS ticket_nonce, ticket, extensions;
1253
6.32k
  if (!CBS_get_u32(body, &server_timeout) ||
1254
6.32k
      !CBS_get_u32(body, &session->ticket_age_add) ||
1255
6.31k
      !CBS_get_u8_length_prefixed(body, &ticket_nonce) ||
1256
6.31k
      !CBS_get_u16_length_prefixed(body, &ticket) ||
1257
6.31k
      CBS_len(&ticket) == 0 ||  //
1258
6.30k
      !session->ticket.CopyFrom(ticket) ||
1259
6.30k
      !CBS_get_u16_length_prefixed(body, &extensions) ||  //
1260
6.29k
      CBS_len(body) != 0) {
1261
40
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1262
40
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1263
40
    return nullptr;
1264
40
  }
1265
1266
  // Cap the renewable lifetime by the server advertised value. This avoids
1267
  // wasting bandwidth on 0-RTT when we know the server will reject it.
1268
6.28k
  if (session->timeout > server_timeout) {
1269
1.70k
    session->timeout = server_timeout;
1270
1.70k
  }
1271
1272
6.28k
  if (!tls13_derive_session_psk(session.get(), ticket_nonce,
1273
6.28k
                                SSL_is_dtls(ssl))) {
1274
0
    return nullptr;
1275
0
  }
1276
1277
6.28k
  SSLExtension early_data(TLSEXT_TYPE_early_data);
1278
6.28k
  SSLExtension flags(TLSEXT_TYPE_tls_flags);
1279
6.28k
  uint8_t alert = SSL_AD_DECODE_ERROR;
1280
6.28k
  if (!ssl_parse_extensions(&extensions, &alert, {&early_data, &flags},
1281
6.28k
                            /*ignore_unknown=*/true)) {
1282
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1283
2
    return nullptr;
1284
2
  }
1285
1286
6.28k
  if (early_data.present) {
1287
4
    if (!CBS_get_u32(&early_data.data, &session->ticket_max_early_data) ||
1288
3
        CBS_len(&early_data.data) != 0) {
1289
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1290
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1291
1
      return nullptr;
1292
1
    }
1293
1294
    // QUIC does not use the max_early_data_size parameter and always sets it to
1295
    // a fixed value. See RFC 9001, section 4.6.1.
1296
3
    if (SSL_is_quic(ssl) && session->ticket_max_early_data != 0xffffffff) {
1297
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1298
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1299
0
      return nullptr;
1300
0
    }
1301
3
  }
1302
1303
6.27k
  if (flags.present) {
1304
5
    SSLFlags parsed;
1305
5
    if (!ssl_parse_flags_extension_request(&flags.data, &parsed, &alert)) {
1306
3
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1307
3
      return nullptr;
1308
3
    }
1309
2
    if (parsed & kSSLFlagResumptionAcrossNames) {
1310
1
      session->is_resumable_across_names = true;
1311
1
    }
1312
2
  }
1313
1314
  // Historically, OpenSSL filled in fake session IDs for ticket-based sessions.
1315
  // Envoy's tests depend on this, although perhaps they shouldn't.
1316
6.27k
  session->session_id.ResizeForOverwrite(SHA256_DIGEST_LENGTH);
1317
6.27k
  SHA256(CBS_data(&ticket), CBS_len(&ticket), session->session_id.data());
1318
1319
6.27k
  session->ticket_age_add_valid = true;
1320
6.27k
  session->not_resumable = false;
1321
1322
6.27k
  return session;
1323
6.27k
}
1324
1325
BSSL_NAMESPACE_END