Coverage Report

Created: 2023-06-29 07:23

/src/boringssl/ssl/tls13_server.cc
Line
Count
Source (jump to first uncovered line)
1
/* Copyright (c) 2016, Google Inc.
2
 *
3
 * Permission to use, copy, modify, and/or distribute this software for any
4
 * purpose with or without fee is hereby granted, provided that the above
5
 * copyright notice and this permission notice appear in all copies.
6
 *
7
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15
#include <openssl/ssl.h>
16
17
#include <assert.h>
18
#include <string.h>
19
20
#include <tuple>
21
22
#include <openssl/aead.h>
23
#include <openssl/bytestring.h>
24
#include <openssl/digest.h>
25
#include <openssl/err.h>
26
#include <openssl/hpke.h>
27
#include <openssl/mem.h>
28
#include <openssl/rand.h>
29
#include <openssl/stack.h>
30
31
#include "../crypto/internal.h"
32
#include "internal.h"
33
34
35
BSSL_NAMESPACE_BEGIN
36
37
static const uint8_t kZeroes[EVP_MAX_MD_SIZE] = {0};
38
39
// Allow a minute of ticket age skew in either direction. This covers
40
// transmission delays in ClientHello and NewSessionTicket, as well as
41
// drift between client and server clock rate since the ticket was issued.
42
// See RFC 8446, section 8.3.
43
static const int32_t kMaxTicketAgeSkewSeconds = 60;
44
45
static bool resolve_ecdhe_secret(SSL_HANDSHAKE *hs,
46
517
                                 const SSL_CLIENT_HELLO *client_hello) {
47
517
  SSL *const ssl = hs->ssl;
48
517
  const uint16_t group_id = hs->new_session->group_id;
49
50
517
  bool found_key_share;
51
517
  Span<const uint8_t> peer_key;
52
517
  uint8_t alert = SSL_AD_DECODE_ERROR;
53
517
  if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share, &peer_key,
54
517
                                           &alert, client_hello)) {
55
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
56
3
    return false;
57
3
  }
58
59
514
  if (!found_key_share) {
60
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
61
2
    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
62
2
    return false;
63
2
  }
64
65
512
  Array<uint8_t> secret;
66
512
  SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
67
512
  if (hints && !hs->hints_requested && hints->key_share_group_id == group_id &&
68
512
      !hints->key_share_secret.empty()) {
69
    // Copy the key_share secret from hints.
70
21
    if (!hs->key_share_ciphertext.CopyFrom(hints->key_share_ciphertext) ||
71
21
        !secret.CopyFrom(hints->key_share_secret)) {
72
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
73
0
      return false;
74
0
    }
75
491
  } else {
76
491
    ScopedCBB ciphertext;
77
491
    UniquePtr<SSLKeyShare> key_share = SSLKeyShare::Create(group_id);
78
491
    if (!key_share ||  //
79
491
        !CBB_init(ciphertext.get(), 32) ||
80
491
        !key_share->Encap(ciphertext.get(), &secret, &alert, peer_key) ||
81
491
        !CBBFinishArray(ciphertext.get(), &hs->key_share_ciphertext)) {
82
17
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
83
17
      return false;
84
17
    }
85
474
    if (hints && hs->hints_requested) {
86
0
      hints->key_share_group_id = group_id;
87
0
      if (!hints->key_share_ciphertext.CopyFrom(hs->key_share_ciphertext) ||
88
0
          !hints->key_share_secret.CopyFrom(secret)) {
89
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
90
0
        return false;
91
0
      }
92
0
    }
93
474
  }
94
95
495
  return tls13_advance_key_schedule(hs, secret);
96
512
}
97
98
static int ssl_ext_supported_versions_add_serverhello(SSL_HANDSHAKE *hs,
99
493
                                                      CBB *out) {
100
493
  CBB contents;
101
493
  if (!CBB_add_u16(out, TLSEXT_TYPE_supported_versions) ||
102
493
      !CBB_add_u16_length_prefixed(out, &contents) ||
103
493
      !CBB_add_u16(&contents, hs->ssl->version) ||
104
493
      !CBB_flush(out)) {
105
0
    return 0;
106
0
  }
107
108
493
  return 1;
109
493
}
110
111
static const SSL_CIPHER *choose_tls13_cipher(
112
844
    const SSL *ssl, const SSL_CLIENT_HELLO *client_hello, uint16_t group_id) {
113
844
  CBS cipher_suites;
114
844
  CBS_init(&cipher_suites, client_hello->cipher_suites,
115
844
           client_hello->cipher_suites_len);
116
117
844
  const uint16_t version = ssl_protocol_version(ssl);
118
119
844
  return ssl_choose_tls13_cipher(
120
844
      cipher_suites,
121
844
      ssl->config->aes_hw_override ? ssl->config->aes_hw_override_value
122
844
                                   : EVP_has_aes_hardware(),
123
844
      version, group_id, ssl->config->tls13_cipher_policy);
124
844
}
125
126
257
static bool add_new_session_tickets(SSL_HANDSHAKE *hs, bool *out_sent_tickets) {
127
257
  SSL *const ssl = hs->ssl;
128
257
  if (// If the client doesn't accept resumption with PSK_DHE_KE, don't send a
129
      // session ticket.
130
257
      !hs->accept_psk_mode ||
131
      // We only implement stateless resumption in TLS 1.3, so skip sending
132
      // tickets if disabled.
133
257
      (SSL_get_options(ssl) & SSL_OP_NO_TICKET)) {
134
53
    *out_sent_tickets = false;
135
53
    return true;
136
53
  }
137
138
  // Rebase the session timestamp so that it is measured from ticket
139
  // issuance.
140
204
  ssl_session_rebase_time(ssl, hs->new_session.get());
141
142
204
  assert(ssl->session_ctx->num_tickets <= kMaxTickets);
143
612
  for (size_t i = 0; i < ssl->session_ctx->num_tickets; i++) {
144
408
    UniquePtr<SSL_SESSION> session(
145
408
        SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_INCLUDE_NONAUTH));
146
408
    if (!session) {
147
0
      return false;
148
0
    }
149
150
408
    if (!RAND_bytes((uint8_t *)&session->ticket_age_add, 4)) {
151
0
      return false;
152
0
    }
153
408
    session->ticket_age_add_valid = true;
154
408
    bool enable_early_data =
155
408
        ssl->enable_early_data &&
156
408
        (!ssl->quic_method || !ssl->config->quic_early_data_context.empty());
157
408
    if (enable_early_data) {
158
      // QUIC does not use the max_early_data_size parameter and always sets it
159
      // to a fixed value. See RFC 9001, section 4.6.1.
160
408
      session->ticket_max_early_data =
161
408
          ssl->quic_method != nullptr ? 0xffffffff : kMaxEarlyDataAccepted;
162
408
    }
163
164
408
    static_assert(kMaxTickets < 256, "Too many tickets");
165
408
    assert(i < 256);
166
0
    uint8_t nonce[] = {static_cast<uint8_t>(i)};
167
168
408
    ScopedCBB cbb;
169
408
    CBB body, nonce_cbb, ticket, extensions;
170
408
    if (!ssl->method->init_message(ssl, cbb.get(), &body,
171
408
                                   SSL3_MT_NEW_SESSION_TICKET) ||
172
408
        !CBB_add_u32(&body, session->timeout) ||
173
408
        !CBB_add_u32(&body, session->ticket_age_add) ||
174
408
        !CBB_add_u8_length_prefixed(&body, &nonce_cbb) ||
175
408
        !CBB_add_bytes(&nonce_cbb, nonce, sizeof(nonce)) ||
176
408
        !CBB_add_u16_length_prefixed(&body, &ticket) ||
177
408
        !tls13_derive_session_psk(session.get(), nonce) ||
178
408
        !ssl_encrypt_ticket(hs, &ticket, session.get()) ||
179
408
        !CBB_add_u16_length_prefixed(&body, &extensions)) {
180
0
      return false;
181
0
    }
182
183
408
    if (enable_early_data) {
184
408
      CBB early_data;
185
408
      if (!CBB_add_u16(&extensions, TLSEXT_TYPE_early_data) ||
186
408
          !CBB_add_u16_length_prefixed(&extensions, &early_data) ||
187
408
          !CBB_add_u32(&early_data, session->ticket_max_early_data) ||
188
408
          !CBB_flush(&extensions)) {
189
0
        return false;
190
0
      }
191
408
    }
192
193
    // Add a fake extension. See RFC 8701.
194
408
    if (!CBB_add_u16(&extensions,
195
408
                     ssl_get_grease_value(hs, ssl_grease_ticket_extension)) ||
196
408
        !CBB_add_u16(&extensions, 0 /* empty */)) {
197
0
      return false;
198
0
    }
199
200
408
    if (!ssl_add_message_cbb(ssl, cbb.get())) {
201
0
      return false;
202
0
    }
203
408
  }
204
205
204
  *out_sent_tickets = true;
206
204
  return true;
207
204
}
208
209
850
static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
210
  // At this point, most ClientHello extensions have already been processed by
211
  // the common handshake logic. Resolve the remaining non-PSK parameters.
212
850
  SSL *const ssl = hs->ssl;
213
850
  SSLMessage msg;
214
850
  SSL_CLIENT_HELLO client_hello;
215
850
  if (!hs->GetClientHello(&msg, &client_hello)) {
216
0
    return ssl_hs_error;
217
0
  }
218
219
850
  if (ssl->quic_method != nullptr && client_hello.session_id_len > 0) {
220
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_COMPATIBILITY_MODE);
221
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
222
0
    return ssl_hs_error;
223
0
  }
224
850
  OPENSSL_memcpy(hs->session_id, client_hello.session_id,
225
850
                 client_hello.session_id_len);
226
850
  hs->session_id_len = client_hello.session_id_len;
227
228
850
  uint16_t group_id;
229
850
  if (!tls1_get_shared_group(hs, &group_id)) {
230
6
    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
231
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
232
6
    return ssl_hs_error;
233
6
  }
234
235
  // Negotiate the cipher suite.
236
844
  hs->new_cipher = choose_tls13_cipher(ssl, &client_hello, group_id);
237
844
  if (hs->new_cipher == NULL) {
238
11
    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
239
11
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
240
11
    return ssl_hs_error;
241
11
  }
242
243
  // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
244
  // deferred. Complete it now.
245
833
  uint8_t alert = SSL_AD_DECODE_ERROR;
246
833
  if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
247
6
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
248
6
    return ssl_hs_error;
249
6
  }
250
251
  // The PRF hash is now known.
252
827
  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
253
0
    return ssl_hs_error;
254
0
  }
255
256
827
  hs->tls13_state = state13_select_session;
257
827
  return ssl_hs_ok;
258
827
}
259
260
static enum ssl_ticket_aead_result_t select_session(
261
    SSL_HANDSHAKE *hs, uint8_t *out_alert, UniquePtr<SSL_SESSION> *out_session,
262
    int32_t *out_ticket_age_skew, bool *out_offered_ticket,
263
827
    const SSLMessage &msg, const SSL_CLIENT_HELLO *client_hello) {
264
827
  SSL *const ssl = hs->ssl;
265
827
  *out_session = nullptr;
266
267
827
  CBS pre_shared_key;
268
827
  *out_offered_ticket = ssl_client_hello_get_extension(
269
827
      client_hello, &pre_shared_key, TLSEXT_TYPE_pre_shared_key);
270
827
  if (!*out_offered_ticket) {
271
584
    return ssl_ticket_aead_ignore_ticket;
272
584
  }
273
274
  // Per RFC 8446, section 4.2.9, servers MUST abort the handshake if the client
275
  // sends pre_shared_key without psk_key_exchange_modes.
276
243
  CBS unused;
277
243
  if (!ssl_client_hello_get_extension(client_hello, &unused,
278
243
                                      TLSEXT_TYPE_psk_key_exchange_modes)) {
279
1
    *out_alert = SSL_AD_MISSING_EXTENSION;
280
1
    OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
281
1
    return ssl_ticket_aead_error;
282
1
  }
283
284
242
  CBS ticket, binders;
285
242
  uint32_t client_ticket_age;
286
242
  if (!ssl_ext_pre_shared_key_parse_clienthello(
287
242
          hs, &ticket, &binders, &client_ticket_age, out_alert, client_hello,
288
242
          &pre_shared_key)) {
289
27
    return ssl_ticket_aead_error;
290
27
  }
291
292
  // If the peer did not offer psk_dhe, ignore the resumption.
293
215
  if (!hs->accept_psk_mode) {
294
2
    return ssl_ticket_aead_ignore_ticket;
295
2
  }
296
297
  // TLS 1.3 session tickets are renewed separately as part of the
298
  // NewSessionTicket.
299
213
  bool unused_renew;
300
213
  UniquePtr<SSL_SESSION> session;
301
213
  enum ssl_ticket_aead_result_t ret =
302
213
      ssl_process_ticket(hs, &session, &unused_renew, ticket, {});
303
213
  switch (ret) {
304
194
    case ssl_ticket_aead_success:
305
194
      break;
306
0
    case ssl_ticket_aead_error:
307
0
      *out_alert = SSL_AD_INTERNAL_ERROR;
308
0
      return ret;
309
19
    default:
310
19
      return ret;
311
213
  }
312
313
194
  if (!ssl_session_is_resumable(hs, session.get()) ||
314
      // Historically, some TLS 1.3 tickets were missing ticket_age_add.
315
194
      !session->ticket_age_add_valid) {
316
16
    return ssl_ticket_aead_ignore_ticket;
317
16
  }
318
319
  // Recover the client ticket age and convert to seconds.
320
178
  client_ticket_age -= session->ticket_age_add;
321
178
  client_ticket_age /= 1000;
322
323
178
  struct OPENSSL_timeval now;
324
178
  ssl_get_current_time(ssl, &now);
325
326
  // Compute the server ticket age in seconds.
327
178
  assert(now.tv_sec >= session->time);
328
0
  uint64_t server_ticket_age = now.tv_sec - session->time;
329
330
  // To avoid overflowing |hs->ticket_age_skew|, we will not resume
331
  // 68-year-old sessions.
332
178
  if (server_ticket_age > INT32_MAX) {
333
0
    return ssl_ticket_aead_ignore_ticket;
334
0
  }
335
336
178
  *out_ticket_age_skew = static_cast<int32_t>(client_ticket_age) -
337
178
                         static_cast<int32_t>(server_ticket_age);
338
339
  // Check the PSK binder.
340
178
  if (!tls13_verify_psk_binder(hs, session.get(), msg, &binders)) {
341
0
    *out_alert = SSL_AD_DECRYPT_ERROR;
342
0
    return ssl_ticket_aead_error;
343
0
  }
344
345
178
  *out_session = std::move(session);
346
178
  return ssl_ticket_aead_success;
347
178
}
348
349
static bool quic_ticket_compatible(const SSL_SESSION *session,
350
60
                                   const SSL_CONFIG *config) {
351
60
  if (!session->is_quic) {
352
60
    return true;
353
60
  }
354
355
0
  if (session->quic_early_data_context.empty() ||
356
0
      config->quic_early_data_context.size() !=
357
0
          session->quic_early_data_context.size() ||
358
0
      CRYPTO_memcmp(config->quic_early_data_context.data(),
359
0
                    session->quic_early_data_context.data(),
360
0
                    session->quic_early_data_context.size()) != 0) {
361
0
    return false;
362
0
  }
363
0
  return true;
364
0
}
365
366
827
static enum ssl_hs_wait_t do_select_session(SSL_HANDSHAKE *hs) {
367
827
  SSL *const ssl = hs->ssl;
368
827
  SSLMessage msg;
369
827
  SSL_CLIENT_HELLO client_hello;
370
827
  if (!hs->GetClientHello(&msg, &client_hello)) {
371
0
    return ssl_hs_error;
372
0
  }
373
374
827
  uint8_t alert = SSL_AD_DECODE_ERROR;
375
827
  UniquePtr<SSL_SESSION> session;
376
827
  bool offered_ticket = false;
377
827
  switch (select_session(hs, &alert, &session, &ssl->s3->ticket_age_skew,
378
827
                         &offered_ticket, msg, &client_hello)) {
379
621
    case ssl_ticket_aead_ignore_ticket:
380
621
      assert(!session);
381
621
      if (!ssl_get_new_session(hs)) {
382
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
383
0
        return ssl_hs_error;
384
0
      }
385
621
      break;
386
387
621
    case ssl_ticket_aead_success:
388
      // Carry over authentication information from the previous handshake into
389
      // a fresh session.
390
178
      hs->new_session =
391
178
          SSL_SESSION_dup(session.get(), SSL_SESSION_DUP_AUTH_ONLY);
392
178
      if (hs->new_session == nullptr) {
393
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
394
0
        return ssl_hs_error;
395
0
      }
396
397
178
      ssl->s3->session_reused = true;
398
178
      hs->can_release_private_key = true;
399
400
      // Resumption incorporates fresh key material, so refresh the timeout.
401
178
      ssl_session_renew_timeout(ssl, hs->new_session.get(),
402
178
                                ssl->session_ctx->session_psk_dhe_timeout);
403
178
      break;
404
405
28
    case ssl_ticket_aead_error:
406
28
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
407
28
      return ssl_hs_error;
408
409
0
    case ssl_ticket_aead_retry:
410
0
      hs->tls13_state = state13_select_session;
411
0
      return ssl_hs_pending_ticket;
412
827
  }
413
414
  // Negotiate ALPS now, after ALPN is negotiated and |hs->new_session| is
415
  // initialized.
416
799
  if (!ssl_negotiate_alps(hs, &alert, &client_hello)) {
417
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
418
0
    return ssl_hs_error;
419
0
  }
420
421
  // Record connection properties in the new session.
422
799
  hs->new_session->cipher = hs->new_cipher;
423
799
  if (!tls1_get_shared_group(hs, &hs->new_session->group_id)) {
424
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_GROUP);
425
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
426
0
    return ssl_hs_error;
427
0
  }
428
429
  // Determine if we need HelloRetryRequest.
430
799
  bool found_key_share;
431
799
  if (!ssl_ext_key_share_parse_clienthello(hs, &found_key_share,
432
799
                                           /*out_key_share=*/nullptr, &alert,
433
799
                                           &client_hello)) {
434
81
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
435
81
    return ssl_hs_error;
436
81
  }
437
438
  // Determine if we're negotiating 0-RTT.
439
718
  if (!ssl->enable_early_data) {
440
0
    ssl->s3->early_data_reason = ssl_early_data_disabled;
441
718
  } else if (!offered_ticket) {
442
547
    ssl->s3->early_data_reason = ssl_early_data_no_session_offered;
443
547
  } else if (!session) {
444
24
    ssl->s3->early_data_reason = ssl_early_data_session_not_resumed;
445
147
  } else if (session->ticket_max_early_data == 0) {
446
42
    ssl->s3->early_data_reason = ssl_early_data_unsupported_for_session;
447
105
  } else if (!hs->early_data_offered) {
448
5
    ssl->s3->early_data_reason = ssl_early_data_peer_declined;
449
100
  } else if (hs->channel_id_negotiated) {
450
    // Channel ID is incompatible with 0-RTT.
451
1
    ssl->s3->early_data_reason = ssl_early_data_channel_id;
452
99
  } else if (MakeConstSpan(ssl->s3->alpn_selected) != session->early_alpn) {
453
    // The negotiated ALPN must match the one in the ticket.
454
1
    ssl->s3->early_data_reason = ssl_early_data_alpn_mismatch;
455
98
  } else if (hs->new_session->has_application_settings !=
456
98
                 session->has_application_settings ||
457
98
             MakeConstSpan(hs->new_session->local_application_settings) !=
458
98
                 session->local_application_settings) {
459
0
    ssl->s3->early_data_reason = ssl_early_data_alps_mismatch;
460
98
  } else if (ssl->s3->ticket_age_skew < -kMaxTicketAgeSkewSeconds ||
461
98
             kMaxTicketAgeSkewSeconds < ssl->s3->ticket_age_skew) {
462
38
    ssl->s3->early_data_reason = ssl_early_data_ticket_age_skew;
463
60
  } else if (!quic_ticket_compatible(session.get(), hs->config)) {
464
0
    ssl->s3->early_data_reason = ssl_early_data_quic_parameter_mismatch;
465
60
  } else if (!found_key_share) {
466
5
    ssl->s3->early_data_reason = ssl_early_data_hello_retry_request;
467
55
  } else {
468
    // |ssl_session_is_resumable| forbids cross-cipher resumptions even if the
469
    // PRF hashes match.
470
55
    assert(hs->new_cipher == session->cipher);
471
472
0
    ssl->s3->early_data_reason = ssl_early_data_accepted;
473
55
    ssl->s3->early_data_accepted = true;
474
55
  }
475
476
  // Store the ALPN and ALPS values in the session for 0-RTT. Note the peer
477
  // applications settings are not generally known until client
478
  // EncryptedExtensions.
479
718
  if (!hs->new_session->early_alpn.CopyFrom(ssl->s3->alpn_selected)) {
480
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
481
0
    return ssl_hs_error;
482
0
  }
483
484
  // The peer applications settings are usually received later, in
485
  // EncryptedExtensions. But, in 0-RTT handshakes, we carry over the
486
  // values from |session|. Do this now, before |session| is discarded.
487
718
  if (ssl->s3->early_data_accepted &&
488
718
      hs->new_session->has_application_settings &&
489
718
      !hs->new_session->peer_application_settings.CopyFrom(
490
0
          session->peer_application_settings)) {
491
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
492
0
    return ssl_hs_error;
493
0
  }
494
495
  // Copy the QUIC early data context to the session.
496
718
  if (ssl->enable_early_data && ssl->quic_method) {
497
0
    if (!hs->new_session->quic_early_data_context.CopyFrom(
498
0
            hs->config->quic_early_data_context)) {
499
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
500
0
      return ssl_hs_error;
501
0
    }
502
0
  }
503
504
718
  if (ssl->ctx->dos_protection_cb != NULL &&
505
718
      ssl->ctx->dos_protection_cb(&client_hello) == 0) {
506
    // Connection rejected for DOS reasons.
507
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
508
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
509
0
    return ssl_hs_error;
510
0
  }
511
512
718
  size_t hash_len = EVP_MD_size(
513
718
      ssl_get_handshake_digest(ssl_protocol_version(ssl), hs->new_cipher));
514
515
  // Set up the key schedule and incorporate the PSK into the running secret.
516
718
  if (!tls13_init_key_schedule(
517
718
          hs, ssl->s3->session_reused
518
718
                  ? MakeConstSpan(hs->new_session->secret,
519
147
                                  hs->new_session->secret_length)
520
718
                  : MakeConstSpan(kZeroes, hash_len)) ||
521
718
      !ssl_hash_message(hs, msg)) {
522
0
    return ssl_hs_error;
523
0
  }
524
525
718
  if (ssl->s3->early_data_accepted) {
526
55
    if (!tls13_derive_early_secret(hs)) {
527
0
      return ssl_hs_error;
528
0
    }
529
663
  } else if (hs->early_data_offered) {
530
145
    ssl->s3->skip_early_data = true;
531
145
  }
532
533
718
  if (!found_key_share) {
534
234
    ssl->method->next_message(ssl);
535
234
    if (!hs->transcript.UpdateForHelloRetryRequest()) {
536
0
      return ssl_hs_error;
537
0
    }
538
234
    hs->tls13_state = state13_send_hello_retry_request;
539
234
    return ssl_hs_ok;
540
234
  }
541
542
484
  if (!resolve_ecdhe_secret(hs, &client_hello)) {
543
17
    return ssl_hs_error;
544
17
  }
545
546
467
  ssl->method->next_message(ssl);
547
467
  hs->ech_client_hello_buf.Reset();
548
467
  hs->tls13_state = state13_send_server_hello;
549
467
  return ssl_hs_ok;
550
484
}
551
552
234
static enum ssl_hs_wait_t do_send_hello_retry_request(SSL_HANDSHAKE *hs) {
553
234
  SSL *const ssl = hs->ssl;
554
234
  if (hs->hints_requested) {
555
0
    return ssl_hs_hints_ready;
556
0
  }
557
558
234
  ScopedCBB cbb;
559
234
  CBB body, session_id, extensions;
560
234
  uint16_t group_id;
561
234
  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
562
234
      !CBB_add_u16(&body, TLS1_2_VERSION) ||
563
234
      !CBB_add_bytes(&body, kHelloRetryRequest, SSL3_RANDOM_SIZE) ||
564
234
      !CBB_add_u8_length_prefixed(&body, &session_id) ||
565
234
      !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
566
234
      !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
567
234
      !CBB_add_u8(&body, 0 /* no compression */) ||
568
234
      !tls1_get_shared_group(hs, &group_id) ||
569
234
      !CBB_add_u16_length_prefixed(&body, &extensions) ||
570
234
      !CBB_add_u16(&extensions, TLSEXT_TYPE_supported_versions) ||
571
234
      !CBB_add_u16(&extensions, 2 /* length */) ||
572
234
      !CBB_add_u16(&extensions, ssl->version) ||
573
234
      !CBB_add_u16(&extensions, TLSEXT_TYPE_key_share) ||
574
234
      !CBB_add_u16(&extensions, 2 /* length */) ||
575
234
      !CBB_add_u16(&extensions, group_id)) {
576
0
    return ssl_hs_error;
577
0
  }
578
234
  if (hs->ech_is_inner) {
579
    // Fill a placeholder for the ECH confirmation value.
580
78
    if (!CBB_add_u16(&extensions, TLSEXT_TYPE_encrypted_client_hello) ||
581
78
        !CBB_add_u16(&extensions, ECH_CONFIRMATION_SIGNAL_LEN) ||
582
78
        !CBB_add_zeros(&extensions, ECH_CONFIRMATION_SIGNAL_LEN)) {
583
0
      return ssl_hs_error;
584
0
    }
585
78
  }
586
234
  Array<uint8_t> hrr;
587
234
  if (!ssl->method->finish_message(ssl, cbb.get(), &hrr)) {
588
0
    return ssl_hs_error;
589
0
  }
590
234
  if (hs->ech_is_inner) {
591
    // Now that the message is encoded, fill in the whole value.
592
78
    size_t offset = hrr.size() - ECH_CONFIRMATION_SIGNAL_LEN;
593
78
    if (!ssl_ech_accept_confirmation(
594
78
            hs, MakeSpan(hrr).last(ECH_CONFIRMATION_SIGNAL_LEN),
595
78
            ssl->s3->client_random, hs->transcript, /*is_hrr=*/true, hrr,
596
78
            offset)) {
597
0
      return ssl_hs_error;
598
0
    }
599
78
  }
600
601
234
  if (!ssl->method->add_message(ssl, std::move(hrr)) ||
602
234
      !ssl->method->add_change_cipher_spec(ssl)) {
603
0
    return ssl_hs_error;
604
0
  }
605
606
234
  ssl->s3->used_hello_retry_request = true;
607
234
  hs->tls13_state = state13_read_second_client_hello;
608
234
  return ssl_hs_flush;
609
234
}
610
611
1.01k
static enum ssl_hs_wait_t do_read_second_client_hello(SSL_HANDSHAKE *hs) {
612
1.01k
  SSL *const ssl = hs->ssl;
613
1.01k
  SSLMessage msg;
614
1.01k
  if (!ssl->method->get_message(ssl, &msg)) {
615
920
    return ssl_hs_read_message;
616
920
  }
617
91
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
618
1
    return ssl_hs_error;
619
1
  }
620
90
  SSL_CLIENT_HELLO client_hello;
621
90
  if (!ssl_client_hello_init(ssl, &client_hello, msg.body)) {
622
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
623
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
624
3
    return ssl_hs_error;
625
3
  }
626
627
87
  if (ssl->s3->ech_status == ssl_ech_accepted) {
628
    // If we previously accepted the ClientHelloInner, the second ClientHello
629
    // must contain an outer encrypted_client_hello extension.
630
57
    CBS ech_body;
631
57
    if (!ssl_client_hello_get_extension(&client_hello, &ech_body,
632
57
                                        TLSEXT_TYPE_encrypted_client_hello)) {
633
2
      OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
634
2
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
635
2
      return ssl_hs_error;
636
2
    }
637
55
    uint16_t kdf_id, aead_id;
638
55
    uint8_t type, config_id;
639
55
    CBS enc, payload;
640
55
    if (!CBS_get_u8(&ech_body, &type) ||     //
641
55
        type != ECH_CLIENT_OUTER ||          //
642
55
        !CBS_get_u16(&ech_body, &kdf_id) ||  //
643
55
        !CBS_get_u16(&ech_body, &aead_id) ||
644
55
        !CBS_get_u8(&ech_body, &config_id) ||
645
55
        !CBS_get_u16_length_prefixed(&ech_body, &enc) ||
646
55
        !CBS_get_u16_length_prefixed(&ech_body, &payload) ||
647
55
        CBS_len(&ech_body) != 0) {
648
10
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
649
10
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
650
10
      return ssl_hs_error;
651
10
    }
652
653
45
    if (kdf_id != EVP_HPKE_KDF_id(EVP_HPKE_CTX_kdf(hs->ech_hpke_ctx.get())) ||
654
45
        aead_id !=
655
24
            EVP_HPKE_AEAD_id(EVP_HPKE_CTX_aead(hs->ech_hpke_ctx.get())) ||
656
45
        config_id != hs->ech_config_id || CBS_len(&enc) > 0) {
657
34
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
658
34
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
659
34
      return ssl_hs_error;
660
34
    }
661
662
    // Decrypt the payload with the HPKE context from the first ClientHello.
663
11
    uint8_t alert = SSL_AD_DECODE_ERROR;
664
11
    bool unused;
665
11
    if (!ssl_client_hello_decrypt(hs, &alert, &unused,
666
11
                                  &hs->ech_client_hello_buf, &client_hello,
667
11
                                  payload)) {
668
      // Decryption failure is fatal in the second ClientHello.
669
6
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
670
6
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
671
6
      return ssl_hs_error;
672
6
    }
673
674
    // Reparse |client_hello| from the buffer owned by |hs|.
675
5
    if (!hs->GetClientHello(&msg, &client_hello)) {
676
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
677
0
      return ssl_hs_error;
678
0
    }
679
5
  }
680
681
  // We perform all our negotiation based on the first ClientHello (for
682
  // consistency with what |select_certificate_cb| observed), which is in the
683
  // transcript, so we can ignore most of this second one.
684
  //
685
  // We do, however, check the second PSK binder. This covers the client key
686
  // share, in case we ever send half-RTT data (we currently do not). It is also
687
  // a tricky computation, so we enforce the peer handled it correctly.
688
35
  if (ssl->s3->session_reused) {
689
14
    CBS pre_shared_key;
690
14
    if (!ssl_client_hello_get_extension(&client_hello, &pre_shared_key,
691
14
                                        TLSEXT_TYPE_pre_shared_key)) {
692
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_INCONSISTENT_CLIENT_HELLO);
693
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
694
1
      return ssl_hs_error;
695
1
    }
696
697
13
    CBS ticket, binders;
698
13
    uint32_t client_ticket_age;
699
13
    uint8_t alert = SSL_AD_DECODE_ERROR;
700
13
    if (!ssl_ext_pre_shared_key_parse_clienthello(
701
13
            hs, &ticket, &binders, &client_ticket_age, &alert, &client_hello,
702
13
            &pre_shared_key)) {
703
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
704
1
      return ssl_hs_error;
705
1
    }
706
707
    // Note it is important that we do not obtain a new |SSL_SESSION| from
708
    // |ticket|. We have already selected parameters based on the first
709
    // ClientHello (in the transcript) and must not switch partway through.
710
12
    if (!tls13_verify_psk_binder(hs, hs->new_session.get(), msg, &binders)) {
711
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
712
0
      return ssl_hs_error;
713
0
    }
714
12
  }
715
716
33
  if (!resolve_ecdhe_secret(hs, &client_hello)) {
717
5
    return ssl_hs_error;
718
5
  }
719
720
28
  if (!ssl_hash_message(hs, msg)) {
721
0
    return ssl_hs_error;
722
0
  }
723
724
  // ClientHello should be the end of the flight.
725
28
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
726
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
727
2
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
728
2
    return ssl_hs_error;
729
2
  }
730
731
26
  ssl->method->next_message(ssl);
732
26
  hs->ech_client_hello_buf.Reset();
733
26
  hs->tls13_state = state13_send_server_hello;
734
26
  return ssl_hs_ok;
735
28
}
736
737
493
static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
738
493
  SSL *const ssl = hs->ssl;
739
740
493
  Span<uint8_t> random(ssl->s3->server_random);
741
742
493
  SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
743
493
  if (hints && !hs->hints_requested &&
744
493
      hints->server_random_tls13.size() == random.size()) {
745
97
    OPENSSL_memcpy(random.data(), hints->server_random_tls13.data(),
746
97
                   random.size());
747
396
  } else {
748
396
    RAND_bytes(random.data(), random.size());
749
396
    if (hints && hs->hints_requested &&
750
396
        !hints->server_random_tls13.CopyFrom(random)) {
751
0
      return ssl_hs_error;
752
0
    }
753
396
  }
754
755
493
  Array<uint8_t> server_hello;
756
493
  ScopedCBB cbb;
757
493
  CBB body, extensions, session_id;
758
493
  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
759
493
      !CBB_add_u16(&body, TLS1_2_VERSION) ||
760
493
      !CBB_add_bytes(&body, ssl->s3->server_random,
761
493
                     sizeof(ssl->s3->server_random)) ||
762
493
      !CBB_add_u8_length_prefixed(&body, &session_id) ||
763
493
      !CBB_add_bytes(&session_id, hs->session_id, hs->session_id_len) ||
764
493
      !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
765
493
      !CBB_add_u8(&body, 0) ||
766
493
      !CBB_add_u16_length_prefixed(&body, &extensions) ||
767
493
      !ssl_ext_pre_shared_key_add_serverhello(hs, &extensions) ||
768
493
      !ssl_ext_key_share_add_serverhello(hs, &extensions) ||
769
493
      !ssl_ext_supported_versions_add_serverhello(hs, &extensions) ||
770
493
      !ssl->method->finish_message(ssl, cbb.get(), &server_hello)) {
771
0
    return ssl_hs_error;
772
0
  }
773
774
493
  assert(ssl->s3->ech_status != ssl_ech_accepted || hs->ech_is_inner);
775
493
  if (hs->ech_is_inner) {
776
    // Fill in the ECH confirmation signal.
777
21
    const size_t offset = ssl_ech_confirmation_signal_hello_offset(ssl);
778
21
    Span<uint8_t> random_suffix = random.last(ECH_CONFIRMATION_SIGNAL_LEN);
779
21
    if (!ssl_ech_accept_confirmation(hs, random_suffix, ssl->s3->client_random,
780
21
                                     hs->transcript,
781
21
                                     /*is_hrr=*/false, server_hello, offset)) {
782
0
      return ssl_hs_error;
783
0
    }
784
785
    // Update |server_hello|.
786
21
    Span<uint8_t> server_hello_out =
787
21
        MakeSpan(server_hello).subspan(offset, ECH_CONFIRMATION_SIGNAL_LEN);
788
21
    OPENSSL_memcpy(server_hello_out.data(), random_suffix.data(),
789
21
                   ECH_CONFIRMATION_SIGNAL_LEN);
790
21
  }
791
792
493
  if (!ssl->method->add_message(ssl, std::move(server_hello))) {
793
0
    return ssl_hs_error;
794
0
  }
795
796
493
  hs->key_share_ciphertext.Reset();  // No longer needed.
797
493
  if (!ssl->s3->used_hello_retry_request &&
798
493
      !ssl->method->add_change_cipher_spec(ssl)) {
799
0
    return ssl_hs_error;
800
0
  }
801
802
  // Derive and enable the handshake traffic secrets.
803
493
  if (!tls13_derive_handshake_secrets(hs) ||
804
493
      !tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_seal,
805
493
                             hs->new_session.get(),
806
493
                             hs->server_handshake_secret())) {
807
0
    return ssl_hs_error;
808
0
  }
809
810
  // Send EncryptedExtensions.
811
493
  if (!ssl->method->init_message(ssl, cbb.get(), &body,
812
493
                                 SSL3_MT_ENCRYPTED_EXTENSIONS) ||
813
493
      !ssl_add_serverhello_tlsext(hs, &body) ||
814
493
      !ssl_add_message_cbb(ssl, cbb.get())) {
815
0
    return ssl_hs_error;
816
0
  }
817
818
493
  if (!ssl->s3->session_reused) {
819
    // Determine whether to request a client certificate.
820
409
    hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
821
    // Only request a certificate if Channel ID isn't negotiated.
822
409
    if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
823
409
        hs->channel_id_negotiated) {
824
0
      hs->cert_request = false;
825
0
    }
826
409
  }
827
828
  // Send a CertificateRequest, if necessary.
829
493
  if (hs->cert_request) {
830
121
    CBB cert_request_extensions, sigalg_contents, sigalgs_cbb;
831
121
    if (!ssl->method->init_message(ssl, cbb.get(), &body,
832
121
                                   SSL3_MT_CERTIFICATE_REQUEST) ||
833
121
        !CBB_add_u8(&body, 0 /* no certificate_request_context. */) ||
834
121
        !CBB_add_u16_length_prefixed(&body, &cert_request_extensions) ||
835
121
        !CBB_add_u16(&cert_request_extensions,
836
121
                     TLSEXT_TYPE_signature_algorithms) ||
837
121
        !CBB_add_u16_length_prefixed(&cert_request_extensions,
838
121
                                     &sigalg_contents) ||
839
121
        !CBB_add_u16_length_prefixed(&sigalg_contents, &sigalgs_cbb) ||
840
121
        !tls12_add_verify_sigalgs(hs, &sigalgs_cbb)) {
841
0
      return ssl_hs_error;
842
0
    }
843
844
121
    if (ssl_has_client_CAs(hs->config)) {
845
0
      CBB ca_contents;
846
0
      if (!CBB_add_u16(&cert_request_extensions,
847
0
                       TLSEXT_TYPE_certificate_authorities) ||
848
0
          !CBB_add_u16_length_prefixed(&cert_request_extensions,
849
0
                                       &ca_contents) ||
850
0
          !ssl_add_client_CA_list(hs, &ca_contents) ||
851
0
          !CBB_flush(&cert_request_extensions)) {
852
0
        return ssl_hs_error;
853
0
      }
854
0
    }
855
856
121
    if (!ssl_add_message_cbb(ssl, cbb.get())) {
857
0
      return ssl_hs_error;
858
0
    }
859
121
  }
860
861
  // Send the server Certificate message, if necessary.
862
493
  if (!ssl->s3->session_reused) {
863
409
    if (!ssl_has_certificate(hs)) {
864
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
865
0
      return ssl_hs_error;
866
0
    }
867
868
409
    if (!tls13_add_certificate(hs)) {
869
0
      return ssl_hs_error;
870
0
    }
871
872
409
    hs->tls13_state = state13_send_server_certificate_verify;
873
409
    return ssl_hs_ok;
874
409
  }
875
876
84
  hs->tls13_state = state13_send_server_finished;
877
84
  return ssl_hs_ok;
878
493
}
879
880
409
static enum ssl_hs_wait_t do_send_server_certificate_verify(SSL_HANDSHAKE *hs) {
881
409
  switch (tls13_add_certificate_verify(hs)) {
882
388
    case ssl_private_key_success:
883
388
      hs->tls13_state = state13_send_server_finished;
884
388
      return ssl_hs_ok;
885
886
0
    case ssl_private_key_retry:
887
0
      hs->tls13_state = state13_send_server_certificate_verify;
888
0
      return ssl_hs_private_key_operation;
889
890
21
    case ssl_private_key_failure:
891
21
      return ssl_hs_error;
892
409
  }
893
894
0
  assert(0);
895
0
  return ssl_hs_error;
896
409
}
897
898
472
static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
899
472
  SSL *const ssl = hs->ssl;
900
472
  if (hs->hints_requested) {
901
0
    return ssl_hs_hints_ready;
902
0
  }
903
904
472
  hs->can_release_private_key = true;
905
472
  if (!tls13_add_finished(hs) ||
906
      // Update the secret to the master secret and derive traffic keys.
907
472
      !tls13_advance_key_schedule(
908
472
          hs, MakeConstSpan(kZeroes, hs->transcript.DigestLen())) ||
909
472
      !tls13_derive_application_secrets(hs) ||
910
472
      !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_seal,
911
472
                             hs->new_session.get(),
912
472
                             hs->server_traffic_secret_0())) {
913
0
    return ssl_hs_error;
914
0
  }
915
916
472
  hs->tls13_state = state13_send_half_rtt_ticket;
917
472
  return hs->handback ? ssl_hs_handback : ssl_hs_ok;
918
472
}
919
920
472
static enum ssl_hs_wait_t do_send_half_rtt_ticket(SSL_HANDSHAKE *hs) {
921
472
  SSL *const ssl = hs->ssl;
922
923
472
  if (ssl->s3->early_data_accepted) {
924
    // If accepting 0-RTT, we send tickets half-RTT. This gets the tickets on
925
    // the wire sooner and also avoids triggering a write on |SSL_read| when
926
    // processing the client Finished. This requires computing the client
927
    // Finished early. See RFC 8446, section 4.6.1.
928
48
    static const uint8_t kEndOfEarlyData[4] = {SSL3_MT_END_OF_EARLY_DATA, 0,
929
48
                                               0, 0};
930
48
    if (ssl->quic_method == nullptr &&
931
48
        !hs->transcript.Update(kEndOfEarlyData)) {
932
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
933
0
      return ssl_hs_error;
934
0
    }
935
936
48
    size_t finished_len;
937
48
    if (!tls13_finished_mac(hs, hs->expected_client_finished().data(),
938
48
                            &finished_len, false /* client */)) {
939
0
      return ssl_hs_error;
940
0
    }
941
942
48
    if (finished_len != hs->expected_client_finished().size()) {
943
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
944
0
      return ssl_hs_error;
945
0
    }
946
947
    // Feed the predicted Finished into the transcript. This allows us to derive
948
    // the resumption secret early and send half-RTT tickets.
949
    //
950
    // TODO(davidben): This will need to be updated for DTLS 1.3.
951
48
    assert(!SSL_is_dtls(hs->ssl));
952
0
    assert(hs->expected_client_finished().size() <= 0xff);
953
0
    uint8_t header[4] = {
954
48
        SSL3_MT_FINISHED, 0, 0,
955
48
        static_cast<uint8_t>(hs->expected_client_finished().size())};
956
48
    bool unused_sent_tickets;
957
48
    if (!hs->transcript.Update(header) ||
958
48
        !hs->transcript.Update(hs->expected_client_finished()) ||
959
48
        !tls13_derive_resumption_secret(hs) ||
960
48
        !add_new_session_tickets(hs, &unused_sent_tickets)) {
961
0
      return ssl_hs_error;
962
0
    }
963
48
  }
964
965
472
  hs->tls13_state = state13_read_second_client_flight;
966
472
  return ssl_hs_flush;
967
472
}
968
969
472
static enum ssl_hs_wait_t do_read_second_client_flight(SSL_HANDSHAKE *hs) {
970
472
  SSL *const ssl = hs->ssl;
971
472
  if (ssl->s3->early_data_accepted) {
972
48
    if (!tls13_set_traffic_key(ssl, ssl_encryption_early_data, evp_aead_open,
973
48
                               hs->new_session.get(),
974
48
                               hs->early_traffic_secret())) {
975
0
      return ssl_hs_error;
976
0
    }
977
48
    hs->can_early_write = true;
978
48
    hs->can_early_read = true;
979
48
    hs->in_early_data = true;
980
48
  }
981
982
  // QUIC doesn't use an EndOfEarlyData message (RFC 9001, section 8.3), so we
983
  // switch to client_handshake_secret before the early return.
984
472
  if (ssl->quic_method != nullptr) {
985
0
    if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
986
0
                               hs->new_session.get(),
987
0
                               hs->client_handshake_secret())) {
988
0
      return ssl_hs_error;
989
0
    }
990
0
    hs->tls13_state = state13_process_end_of_early_data;
991
0
    return ssl->s3->early_data_accepted ? ssl_hs_early_return : ssl_hs_ok;
992
0
  }
993
994
472
  hs->tls13_state = state13_process_end_of_early_data;
995
472
  return ssl->s3->early_data_accepted ? ssl_hs_read_end_of_early_data
996
472
                                      : ssl_hs_ok;
997
472
}
998
999
429
static enum ssl_hs_wait_t do_process_end_of_early_data(SSL_HANDSHAKE *hs) {
1000
429
  SSL *const ssl = hs->ssl;
1001
  // In protocols that use EndOfEarlyData, we must consume the extra message and
1002
  // switch to client_handshake_secret after the early return.
1003
429
  if (ssl->quic_method == nullptr) {
1004
    // If early data was not accepted, the EndOfEarlyData will be in the
1005
    // discarded early data.
1006
429
    if (hs->ssl->s3->early_data_accepted) {
1007
5
      SSLMessage msg;
1008
5
      if (!ssl->method->get_message(ssl, &msg)) {
1009
0
        return ssl_hs_read_message;
1010
0
      }
1011
5
      if (!ssl_check_message_type(ssl, msg, SSL3_MT_END_OF_EARLY_DATA)) {
1012
1
        return ssl_hs_error;
1013
1
      }
1014
4
      if (CBS_len(&msg.body) != 0) {
1015
1
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1016
1
        OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1017
1
        return ssl_hs_error;
1018
1
      }
1019
3
      ssl->method->next_message(ssl);
1020
3
    }
1021
427
    if (!tls13_set_traffic_key(ssl, ssl_encryption_handshake, evp_aead_open,
1022
427
                               hs->new_session.get(),
1023
427
                               hs->client_handshake_secret())) {
1024
1
      return ssl_hs_error;
1025
1
    }
1026
427
  }
1027
426
  hs->tls13_state = state13_read_client_encrypted_extensions;
1028
426
  return ssl_hs_ok;
1029
429
}
1030
1031
static enum ssl_hs_wait_t do_read_client_encrypted_extensions(
1032
426
    SSL_HANDSHAKE *hs) {
1033
426
  SSL *const ssl = hs->ssl;
1034
  // For now, only one extension uses client EncryptedExtensions. This function
1035
  // may be generalized if others use it in the future.
1036
426
  if (hs->new_session->has_application_settings &&
1037
426
      !ssl->s3->early_data_accepted) {
1038
0
    SSLMessage msg;
1039
0
    if (!ssl->method->get_message(ssl, &msg)) {
1040
0
      return ssl_hs_read_message;
1041
0
    }
1042
0
    if (!ssl_check_message_type(ssl, msg, SSL3_MT_ENCRYPTED_EXTENSIONS)) {
1043
0
      return ssl_hs_error;
1044
0
    }
1045
1046
0
    CBS body = msg.body, extensions;
1047
0
    if (!CBS_get_u16_length_prefixed(&body, &extensions) ||
1048
0
        CBS_len(&body) != 0) {
1049
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1050
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1051
0
      return ssl_hs_error;
1052
0
    }
1053
1054
0
    SSLExtension application_settings(TLSEXT_TYPE_application_settings);
1055
0
    uint8_t alert = SSL_AD_DECODE_ERROR;
1056
0
    if (!ssl_parse_extensions(&extensions, &alert, {&application_settings},
1057
0
                              /*ignore_unknown=*/false)) {
1058
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1059
0
      return ssl_hs_error;
1060
0
    }
1061
1062
0
    if (!application_settings.present) {
1063
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_EXTENSION);
1064
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_MISSING_EXTENSION);
1065
0
      return ssl_hs_error;
1066
0
    }
1067
1068
    // Note that, if 0-RTT was accepted, these values will already have been
1069
    // initialized earlier.
1070
0
    if (!hs->new_session->peer_application_settings.CopyFrom(
1071
0
            application_settings.data) ||
1072
0
        !ssl_hash_message(hs, msg)) {
1073
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1074
0
      return ssl_hs_error;
1075
0
    }
1076
1077
0
    ssl->method->next_message(ssl);
1078
0
  }
1079
1080
426
  hs->tls13_state = state13_read_client_certificate;
1081
426
  return ssl_hs_ok;
1082
426
}
1083
1084
1.68k
static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
1085
1.68k
  SSL *const ssl = hs->ssl;
1086
1.68k
  if (!hs->cert_request) {
1087
309
    if (!ssl->s3->session_reused) {
1088
      // OpenSSL returns X509_V_OK when no certificates are requested. This is
1089
      // classed by them as a bug, but it's assumed by at least NGINX. (Only do
1090
      // this in full handshakes as resumptions should carry over the previous
1091
      // |verify_result|, though this is a no-op because servers do not
1092
      // implement the client's odd soft-fail mode.)
1093
271
      hs->new_session->verify_result = X509_V_OK;
1094
271
    }
1095
1096
    // Skip this state.
1097
309
    hs->tls13_state = state13_read_channel_id;
1098
309
    return ssl_hs_ok;
1099
309
  }
1100
1101
1.37k
  const bool allow_anonymous =
1102
1.37k
      (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) == 0;
1103
1.37k
  SSLMessage msg;
1104
1.37k
  if (!ssl->method->get_message(ssl, &msg)) {
1105
1.27k
    return ssl_hs_read_message;
1106
1.27k
  }
1107
100
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
1108
100
      !tls13_process_certificate(hs, msg, allow_anonymous) ||
1109
100
      !ssl_hash_message(hs, msg)) {
1110
61
    return ssl_hs_error;
1111
61
  }
1112
1113
39
  ssl->method->next_message(ssl);
1114
39
  hs->tls13_state = state13_read_client_certificate_verify;
1115
39
  return ssl_hs_ok;
1116
100
}
1117
1118
254
static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1119
254
  SSL *const ssl = hs->ssl;
1120
254
  if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1121
    // Skip this state.
1122
1
    hs->tls13_state = state13_read_channel_id;
1123
1
    return ssl_hs_ok;
1124
1
  }
1125
1126
253
  SSLMessage msg;
1127
253
  if (!ssl->method->get_message(ssl, &msg)) {
1128
224
    return ssl_hs_read_message;
1129
224
  }
1130
1131
29
  switch (ssl_verify_peer_cert(hs)) {
1132
29
    case ssl_verify_ok:
1133
29
      break;
1134
0
    case ssl_verify_invalid:
1135
0
      return ssl_hs_error;
1136
0
    case ssl_verify_retry:
1137
0
      hs->tls13_state = state13_read_client_certificate_verify;
1138
0
      return ssl_hs_certificate_verify;
1139
29
  }
1140
1141
29
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY) ||
1142
29
      !tls13_process_certificate_verify(hs, msg) ||
1143
29
      !ssl_hash_message(hs, msg)) {
1144
10
    return ssl_hs_error;
1145
10
  }
1146
1147
19
  ssl->method->next_message(ssl);
1148
19
  hs->tls13_state = state13_read_channel_id;
1149
19
  return ssl_hs_ok;
1150
29
}
1151
1152
531
static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1153
531
  SSL *const ssl = hs->ssl;
1154
531
  if (!hs->channel_id_negotiated) {
1155
301
    hs->tls13_state = state13_read_client_finished;
1156
301
    return ssl_hs_ok;
1157
301
  }
1158
1159
230
  SSLMessage msg;
1160
230
  if (!ssl->method->get_message(ssl, &msg)) {
1161
214
    return ssl_hs_read_message;
1162
214
  }
1163
16
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1164
16
      !tls1_verify_channel_id(hs, msg) ||
1165
16
      !ssl_hash_message(hs, msg)) {
1166
3
    return ssl_hs_error;
1167
3
  }
1168
1169
13
  ssl->method->next_message(ssl);
1170
13
  hs->tls13_state = state13_read_client_finished;
1171
13
  return ssl_hs_ok;
1172
16
}
1173
1174
896
static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1175
896
  SSL *const ssl = hs->ssl;
1176
896
  SSLMessage msg;
1177
896
  if (!ssl->method->get_message(ssl, &msg)) {
1178
677
    return ssl_hs_read_message;
1179
677
  }
1180
219
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED) ||
1181
      // If early data was accepted, we've already computed the client Finished
1182
      // and derived the resumption secret.
1183
219
      !tls13_process_finished(hs, msg, ssl->s3->early_data_accepted) ||
1184
      // evp_aead_seal keys have already been switched.
1185
219
      !tls13_set_traffic_key(ssl, ssl_encryption_application, evp_aead_open,
1186
215
                             hs->new_session.get(),
1187
215
                             hs->client_traffic_secret_0())) {
1188
9
    return ssl_hs_error;
1189
9
  }
1190
1191
210
  if (!ssl->s3->early_data_accepted) {
1192
209
    if (!ssl_hash_message(hs, msg) ||
1193
209
        !tls13_derive_resumption_secret(hs)) {
1194
0
      return ssl_hs_error;
1195
0
    }
1196
1197
    // We send post-handshake tickets as part of the handshake in 1-RTT.
1198
209
    hs->tls13_state = state13_send_new_session_ticket;
1199
209
  } else {
1200
    // We already sent half-RTT tickets.
1201
1
    hs->tls13_state = state13_done;
1202
1
  }
1203
1204
210
  ssl->method->next_message(ssl);
1205
210
  return ssl_hs_ok;
1206
210
}
1207
1208
209
static enum ssl_hs_wait_t do_send_new_session_ticket(SSL_HANDSHAKE *hs) {
1209
209
  bool sent_tickets;
1210
209
  if (!add_new_session_tickets(hs, &sent_tickets)) {
1211
0
    return ssl_hs_error;
1212
0
  }
1213
1214
209
  hs->tls13_state = state13_done;
1215
  // In TLS 1.3, the NewSessionTicket isn't flushed until the server performs a
1216
  // write, to prevent a non-reading client from causing the server to hang in
1217
  // the case of a small server write buffer. Consumers which don't write data
1218
  // to the client will need to do a zero-byte write if they wish to flush the
1219
  // tickets.
1220
209
  if (hs->ssl->quic_method != nullptr && sent_tickets) {
1221
0
    return ssl_hs_flush;
1222
0
  }
1223
209
  return ssl_hs_ok;
1224
209
}
1225
1226
4.59k
enum ssl_hs_wait_t tls13_server_handshake(SSL_HANDSHAKE *hs) {
1227
9.87k
  while (hs->tls13_state != state13_done) {
1228
9.66k
    enum ssl_hs_wait_t ret = ssl_hs_error;
1229
9.66k
    enum tls13_server_hs_state_t state =
1230
9.66k
        static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1231
9.66k
    switch (state) {
1232
850
      case state13_select_parameters:
1233
850
        ret = do_select_parameters(hs);
1234
850
        break;
1235
827
      case state13_select_session:
1236
827
        ret = do_select_session(hs);
1237
827
        break;
1238
234
      case state13_send_hello_retry_request:
1239
234
        ret = do_send_hello_retry_request(hs);
1240
234
        break;
1241
1.01k
      case state13_read_second_client_hello:
1242
1.01k
        ret = do_read_second_client_hello(hs);
1243
1.01k
        break;
1244
493
      case state13_send_server_hello:
1245
493
        ret = do_send_server_hello(hs);
1246
493
        break;
1247
409
      case state13_send_server_certificate_verify:
1248
409
        ret = do_send_server_certificate_verify(hs);
1249
409
        break;
1250
472
      case state13_send_server_finished:
1251
472
        ret = do_send_server_finished(hs);
1252
472
        break;
1253
472
      case state13_send_half_rtt_ticket:
1254
472
        ret = do_send_half_rtt_ticket(hs);
1255
472
        break;
1256
472
      case state13_read_second_client_flight:
1257
472
        ret = do_read_second_client_flight(hs);
1258
472
        break;
1259
429
      case state13_process_end_of_early_data:
1260
429
        ret = do_process_end_of_early_data(hs);
1261
429
        break;
1262
426
      case state13_read_client_encrypted_extensions:
1263
426
        ret = do_read_client_encrypted_extensions(hs);
1264
426
        break;
1265
1.68k
      case state13_read_client_certificate:
1266
1.68k
        ret = do_read_client_certificate(hs);
1267
1.68k
        break;
1268
254
      case state13_read_client_certificate_verify:
1269
254
        ret = do_read_client_certificate_verify(hs);
1270
254
        break;
1271
531
      case state13_read_channel_id:
1272
531
        ret = do_read_channel_id(hs);
1273
531
        break;
1274
896
      case state13_read_client_finished:
1275
896
        ret = do_read_client_finished(hs);
1276
896
        break;
1277
209
      case state13_send_new_session_ticket:
1278
209
        ret = do_send_new_session_ticket(hs);
1279
209
        break;
1280
0
      case state13_done:
1281
0
        ret = ssl_hs_ok;
1282
0
        break;
1283
9.66k
    }
1284
1285
9.66k
    if (hs->tls13_state != state) {
1286
6.03k
      ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1287
6.03k
    }
1288
1289
9.66k
    if (ret != ssl_hs_ok) {
1290
4.38k
      return ret;
1291
4.38k
    }
1292
9.66k
  }
1293
1294
210
  return ssl_hs_ok;
1295
4.59k
}
1296
1297
0
const char *tls13_server_handshake_state(SSL_HANDSHAKE *hs) {
1298
0
  enum tls13_server_hs_state_t state =
1299
0
      static_cast<enum tls13_server_hs_state_t>(hs->tls13_state);
1300
0
  switch (state) {
1301
0
    case state13_select_parameters:
1302
0
      return "TLS 1.3 server select_parameters";
1303
0
    case state13_select_session:
1304
0
      return "TLS 1.3 server select_session";
1305
0
    case state13_send_hello_retry_request:
1306
0
      return "TLS 1.3 server send_hello_retry_request";
1307
0
    case state13_read_second_client_hello:
1308
0
      return "TLS 1.3 server read_second_client_hello";
1309
0
    case state13_send_server_hello:
1310
0
      return "TLS 1.3 server send_server_hello";
1311
0
    case state13_send_server_certificate_verify:
1312
0
      return "TLS 1.3 server send_server_certificate_verify";
1313
0
    case state13_send_half_rtt_ticket:
1314
0
      return "TLS 1.3 server send_half_rtt_ticket";
1315
0
    case state13_send_server_finished:
1316
0
      return "TLS 1.3 server send_server_finished";
1317
0
    case state13_read_second_client_flight:
1318
0
      return "TLS 1.3 server read_second_client_flight";
1319
0
    case state13_process_end_of_early_data:
1320
0
      return "TLS 1.3 server process_end_of_early_data";
1321
0
    case state13_read_client_encrypted_extensions:
1322
0
      return "TLS 1.3 server read_client_encrypted_extensions";
1323
0
    case state13_read_client_certificate:
1324
0
      return "TLS 1.3 server read_client_certificate";
1325
0
    case state13_read_client_certificate_verify:
1326
0
      return "TLS 1.3 server read_client_certificate_verify";
1327
0
    case state13_read_channel_id:
1328
0
      return "TLS 1.3 server read_channel_id";
1329
0
    case state13_read_client_finished:
1330
0
      return "TLS 1.3 server read_client_finished";
1331
0
    case state13_send_new_session_ticket:
1332
0
      return "TLS 1.3 server send_new_session_ticket";
1333
0
    case state13_done:
1334
0
      return "TLS 1.3 server done";
1335
0
  }
1336
1337
0
  return "TLS 1.3 server unknown";
1338
0
}
1339
1340
BSSL_NAMESPACE_END