Coverage Report

Created: 2025-06-11 06:40

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