Coverage Report

Created: 2025-06-11 06:41

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