Coverage Report

Created: 2023-06-29 07:25

/src/boringssl/ssl/handshake.cc
Line
Count
Source (jump to first uncovered line)
1
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2
 * All rights reserved.
3
 *
4
 * This package is an SSL implementation written
5
 * by Eric Young (eay@cryptsoft.com).
6
 * The implementation was written so as to conform with Netscapes SSL.
7
 *
8
 * This library is free for commercial and non-commercial use as long as
9
 * the following conditions are aheared to.  The following conditions
10
 * apply to all code found in this distribution, be it the RC4, RSA,
11
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12
 * included with this distribution is covered by the same copyright terms
13
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14
 *
15
 * Copyright remains Eric Young's, and as such any Copyright notices in
16
 * the code are not to be removed.
17
 * If this package is used in a product, Eric Young should be given attribution
18
 * as the author of the parts of the library used.
19
 * This can be in the form of a textual message at program startup or
20
 * in documentation (online or textual) provided with the package.
21
 *
22
 * Redistribution and use in source and binary forms, with or without
23
 * modification, are permitted provided that the following conditions
24
 * are met:
25
 * 1. Redistributions of source code must retain the copyright
26
 *    notice, this list of conditions and the following disclaimer.
27
 * 2. Redistributions in binary form must reproduce the above copyright
28
 *    notice, this list of conditions and the following disclaimer in the
29
 *    documentation and/or other materials provided with the distribution.
30
 * 3. All advertising materials mentioning features or use of this software
31
 *    must display the following acknowledgement:
32
 *    "This product includes cryptographic software written by
33
 *     Eric Young (eay@cryptsoft.com)"
34
 *    The word 'cryptographic' can be left out if the rouines from the library
35
 *    being used are not cryptographic related :-).
36
 * 4. If you include any Windows specific code (or a derivative thereof) from
37
 *    the apps directory (application code) you must include an acknowledgement:
38
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39
 *
40
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50
 * SUCH DAMAGE.
51
 *
52
 * The licence and distribution terms for any publically available version or
53
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54
 * copied and put under another distribution licence
55
 * [including the GNU Public Licence.]
56
 */
57
/* ====================================================================
58
 * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
59
 *
60
 * Redistribution and use in source and binary forms, with or without
61
 * modification, are permitted provided that the following conditions
62
 * are met:
63
 *
64
 * 1. Redistributions of source code must retain the above copyright
65
 *    notice, this list of conditions and the following disclaimer.
66
 *
67
 * 2. Redistributions in binary form must reproduce the above copyright
68
 *    notice, this list of conditions and the following disclaimer in
69
 *    the documentation and/or other materials provided with the
70
 *    distribution.
71
 *
72
 * 3. All advertising materials mentioning features or use of this
73
 *    software must display the following acknowledgment:
74
 *    "This product includes software developed by the OpenSSL Project
75
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76
 *
77
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78
 *    endorse or promote products derived from this software without
79
 *    prior written permission. For written permission, please contact
80
 *    openssl-core@openssl.org.
81
 *
82
 * 5. Products derived from this software may not be called "OpenSSL"
83
 *    nor may "OpenSSL" appear in their names without prior written
84
 *    permission of the OpenSSL Project.
85
 *
86
 * 6. Redistributions of any form whatsoever must retain the following
87
 *    acknowledgment:
88
 *    "This product includes software developed by the OpenSSL Project
89
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90
 *
91
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102
 * OF THE POSSIBILITY OF SUCH DAMAGE.
103
 * ====================================================================
104
 *
105
 * This product includes cryptographic software written by Eric Young
106
 * (eay@cryptsoft.com).  This product includes software written by Tim
107
 * Hudson (tjh@cryptsoft.com). */
108
/* ====================================================================
109
 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
110
 * ECC cipher suite support in OpenSSL originally developed by
111
 * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */
112
113
#include <openssl/ssl.h>
114
115
#include <assert.h>
116
117
#include <utility>
118
119
#include <openssl/rand.h>
120
121
#include "../crypto/internal.h"
122
#include "internal.h"
123
124
125
BSSL_NAMESPACE_BEGIN
126
127
SSL_HANDSHAKE::SSL_HANDSHAKE(SSL *ssl_arg)
128
    : ssl(ssl_arg),
129
      ech_is_inner(false),
130
      ech_authenticated_reject(false),
131
      scts_requested(false),
132
      handshake_finalized(false),
133
      accept_psk_mode(false),
134
      cert_request(false),
135
      certificate_status_expected(false),
136
      ocsp_stapling_requested(false),
137
      delegated_credential_requested(false),
138
      should_ack_sni(false),
139
      in_false_start(false),
140
      in_early_data(false),
141
      early_data_offered(false),
142
      can_early_read(false),
143
      can_early_write(false),
144
      next_proto_neg_seen(false),
145
      ticket_expected(false),
146
      extended_master_secret(false),
147
      pending_private_key_op(false),
148
      handback(false),
149
      hints_requested(false),
150
      cert_compression_negotiated(false),
151
      apply_jdk11_workaround(false),
152
      can_release_private_key(false),
153
133k
      channel_id_negotiated(false) {
154
133k
  assert(ssl);
155
156
  // Draw entropy for all GREASE values at once. This avoids calling
157
  // |RAND_bytes| repeatedly and makes the values consistent within a
158
  // connection. The latter is so the second ClientHello matches after
159
  // HelloRetryRequest and so supported_groups and key_shares are consistent.
160
0
  RAND_bytes(grease_seed, sizeof(grease_seed));
161
133k
}
162
163
133k
SSL_HANDSHAKE::~SSL_HANDSHAKE() {
164
133k
  ssl->ctx->x509_method->hs_flush_cached_ca_names(this);
165
133k
}
166
167
1.15k
void SSL_HANDSHAKE::ResizeSecrets(size_t hash_len) {
168
1.15k
  if (hash_len > SSL_MAX_MD_SIZE) {
169
0
    abort();
170
0
  }
171
1.15k
  hash_len_ = hash_len;
172
1.15k
}
173
174
bool SSL_HANDSHAKE::GetClientHello(SSLMessage *out_msg,
175
19.3k
                                   SSL_CLIENT_HELLO *out_client_hello) {
176
19.3k
  if (!ech_client_hello_buf.empty()) {
177
    // If the backing buffer is non-empty, the ClientHelloInner has been set.
178
282
    out_msg->is_v2_hello = false;
179
282
    out_msg->type = SSL3_MT_CLIENT_HELLO;
180
282
    out_msg->raw = CBS(ech_client_hello_buf);
181
282
    out_msg->body = MakeConstSpan(ech_client_hello_buf).subspan(4);
182
19.0k
  } else if (!ssl->method->get_message(ssl, out_msg)) {
183
    // The message has already been read, so this cannot fail.
184
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
185
0
    return false;
186
0
  }
187
188
19.3k
  if (!ssl_client_hello_init(ssl, out_client_hello, out_msg->body)) {
189
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
190
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
191
0
    return false;
192
0
  }
193
19.3k
  return true;
194
19.3k
}
195
196
133k
UniquePtr<SSL_HANDSHAKE> ssl_handshake_new(SSL *ssl) {
197
133k
  UniquePtr<SSL_HANDSHAKE> hs = MakeUnique<SSL_HANDSHAKE>(ssl);
198
133k
  if (!hs || !hs->transcript.Init()) {
199
0
    return nullptr;
200
0
  }
201
133k
  hs->config = ssl->config.get();
202
133k
  if (!hs->config) {
203
0
    assert(hs->config);
204
0
    return nullptr;
205
0
  }
206
133k
  return hs;
207
133k
}
208
209
306k
bool ssl_check_message_type(SSL *ssl, const SSLMessage &msg, int type) {
210
306k
  if (msg.type != type) {
211
120
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
212
120
    OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
213
120
    ERR_add_error_dataf("got type %d, wanted type %d", msg.type, type);
214
120
    return false;
215
120
  }
216
217
306k
  return true;
218
306k
}
219
220
222k
bool ssl_add_message_cbb(SSL *ssl, CBB *cbb) {
221
222k
  Array<uint8_t> msg;
222
222k
  if (!ssl->method->finish_message(ssl, cbb, &msg) ||
223
222k
      !ssl->method->add_message(ssl, std::move(msg))) {
224
0
    return false;
225
0
  }
226
227
222k
  return true;
228
222k
}
229
230
1.89M
size_t ssl_max_handshake_message_len(const SSL *ssl) {
231
  // kMaxMessageLen is the default maximum message size for handshakes which do
232
  // not accept peer certificate chains.
233
1.89M
  static const size_t kMaxMessageLen = 16384;
234
235
1.89M
  if (SSL_in_init(ssl)) {
236
1.63M
    SSL_CONFIG *config = ssl->config.get();  // SSL_in_init() implies not NULL.
237
1.63M
    if ((!ssl->server || (config->verify_mode & SSL_VERIFY_PEER)) &&
238
1.63M
        kMaxMessageLen < ssl->max_cert_list) {
239
1.60M
      return ssl->max_cert_list;
240
1.60M
    }
241
39.1k
    return kMaxMessageLen;
242
1.63M
  }
243
244
256k
  if (ssl_protocol_version(ssl) < TLS1_3_VERSION) {
245
    // In TLS 1.2 and below, the largest acceptable post-handshake message is
246
    // a HelloRequest.
247
214k
    return 0;
248
214k
  }
249
250
42.1k
  if (ssl->server) {
251
    // The largest acceptable post-handshake message for a server is a
252
    // KeyUpdate. We will never initiate post-handshake auth.
253
19.8k
    return 1;
254
19.8k
  }
255
256
  // Clients must accept NewSessionTicket, so allow the default size.
257
22.2k
  return kMaxMessageLen;
258
42.1k
}
259
260
438k
bool ssl_hash_message(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
261
  // V2ClientHello messages are pre-hashed.
262
438k
  if (msg.is_v2_hello) {
263
175
    return true;
264
175
  }
265
266
438k
  return hs->transcript.Update(msg.raw);
267
438k
}
268
269
bool ssl_parse_extensions(const CBS *cbs, uint8_t *out_alert,
270
                          std::initializer_list<SSLExtension *> extensions,
271
67.2k
                          bool ignore_unknown) {
272
  // Reset everything.
273
69.0k
  for (SSLExtension *ext : extensions) {
274
69.0k
    ext->present = false;
275
69.0k
    CBS_init(&ext->data, nullptr, 0);
276
69.0k
    if (!ext->allowed) {
277
739
      assert(!ignore_unknown);
278
739
    }
279
69.0k
  }
280
281
67.2k
  CBS copy = *cbs;
282
234k
  while (CBS_len(&copy) != 0) {
283
166k
    uint16_t type;
284
166k
    CBS data;
285
166k
    if (!CBS_get_u16(&copy, &type) ||
286
166k
        !CBS_get_u16_length_prefixed(&copy, &data)) {
287
42
      OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
288
42
      *out_alert = SSL_AD_DECODE_ERROR;
289
42
      return false;
290
42
    }
291
292
166k
    SSLExtension *found = nullptr;
293
169k
    for (SSLExtension *ext : extensions) {
294
169k
      if (type == ext->type && ext->allowed) {
295
3.77k
        found = ext;
296
3.77k
        break;
297
3.77k
      }
298
169k
    }
299
300
166k
    if (found == nullptr) {
301
163k
      if (ignore_unknown) {
302
163k
        continue;
303
163k
      }
304
20
      OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
305
20
      *out_alert = SSL_AD_UNSUPPORTED_EXTENSION;
306
20
      return false;
307
163k
    }
308
309
    // Duplicate ext_types are forbidden.
310
3.77k
    if (found->present) {
311
3
      OPENSSL_PUT_ERROR(SSL, SSL_R_DUPLICATE_EXTENSION);
312
3
      *out_alert = SSL_AD_ILLEGAL_PARAMETER;
313
3
      return false;
314
3
    }
315
316
3.77k
    found->present = true;
317
3.77k
    found->data = data;
318
3.77k
  }
319
320
67.2k
  return true;
321
67.2k
}
322
323
67.6k
enum ssl_verify_result_t ssl_verify_peer_cert(SSL_HANDSHAKE *hs) {
324
67.6k
  SSL *const ssl = hs->ssl;
325
67.6k
  const SSL_SESSION *prev_session = ssl->s3->established_session.get();
326
67.6k
  if (prev_session != NULL) {
327
    // If renegotiating, the server must not change the server certificate. See
328
    // https://mitls.org/pages/attacks/3SHAKE. We never resume on renegotiation,
329
    // so this check is sufficient to ensure the reported peer certificate never
330
    // changes on renegotiation.
331
61.4k
    assert(!ssl->server);
332
61.4k
    if (sk_CRYPTO_BUFFER_num(prev_session->certs.get()) !=
333
61.4k
        sk_CRYPTO_BUFFER_num(hs->new_session->certs.get())) {
334
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
335
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
336
1
      return ssl_verify_invalid;
337
1
    }
338
339
122k
    for (size_t i = 0; i < sk_CRYPTO_BUFFER_num(hs->new_session->certs.get());
340
61.4k
         i++) {
341
61.4k
      const CRYPTO_BUFFER *old_cert =
342
61.4k
          sk_CRYPTO_BUFFER_value(prev_session->certs.get(), i);
343
61.4k
      const CRYPTO_BUFFER *new_cert =
344
61.4k
          sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), i);
345
61.4k
      if (CRYPTO_BUFFER_len(old_cert) != CRYPTO_BUFFER_len(new_cert) ||
346
61.4k
          OPENSSL_memcmp(CRYPTO_BUFFER_data(old_cert),
347
61.4k
                         CRYPTO_BUFFER_data(new_cert),
348
61.4k
                         CRYPTO_BUFFER_len(old_cert)) != 0) {
349
146
        OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_CERT_CHANGED);
350
146
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
351
146
        return ssl_verify_invalid;
352
146
      }
353
61.4k
    }
354
355
    // The certificate is identical, so we may skip re-verifying the
356
    // certificate. Since we only authenticated the previous one, copy other
357
    // authentication from the established session and ignore what was newly
358
    // received.
359
61.3k
    hs->new_session->ocsp_response = UpRef(prev_session->ocsp_response);
360
61.3k
    hs->new_session->signed_cert_timestamp_list =
361
61.3k
        UpRef(prev_session->signed_cert_timestamp_list);
362
61.3k
    hs->new_session->verify_result = prev_session->verify_result;
363
61.3k
    return ssl_verify_ok;
364
61.4k
  }
365
366
6.17k
  uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
367
6.17k
  enum ssl_verify_result_t ret;
368
6.17k
  if (hs->config->custom_verify_callback != nullptr) {
369
0
    ret = hs->config->custom_verify_callback(ssl, &alert);
370
0
    switch (ret) {
371
0
      case ssl_verify_ok:
372
0
        hs->new_session->verify_result = X509_V_OK;
373
0
        break;
374
0
      case ssl_verify_invalid:
375
        // If |SSL_VERIFY_NONE|, the error is non-fatal, but we keep the result.
376
0
        if (hs->config->verify_mode == SSL_VERIFY_NONE) {
377
0
          ERR_clear_error();
378
0
          ret = ssl_verify_ok;
379
0
        }
380
0
        hs->new_session->verify_result = X509_V_ERR_APPLICATION_VERIFICATION;
381
0
        break;
382
0
      case ssl_verify_retry:
383
0
        break;
384
0
    }
385
6.17k
  } else {
386
6.17k
    ret = ssl->ctx->x509_method->session_verify_cert_chain(
387
6.17k
              hs->new_session.get(), hs, &alert)
388
6.17k
              ? ssl_verify_ok
389
6.17k
              : ssl_verify_invalid;
390
6.17k
  }
391
392
6.17k
  if (ret == ssl_verify_invalid) {
393
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
394
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
395
0
  }
396
397
  // Emulate OpenSSL's client OCSP callback. OpenSSL verifies certificates
398
  // before it receives the OCSP, so it needs a second callback for OCSP.
399
6.17k
  if (ret == ssl_verify_ok && !ssl->server &&
400
6.17k
      hs->config->ocsp_stapling_enabled &&
401
6.17k
      ssl->ctx->legacy_ocsp_callback != nullptr) {
402
0
    int cb_ret =
403
0
        ssl->ctx->legacy_ocsp_callback(ssl, ssl->ctx->legacy_ocsp_callback_arg);
404
0
    if (cb_ret <= 0) {
405
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
406
0
      ssl_send_alert(ssl, SSL3_AL_FATAL,
407
0
                     cb_ret == 0 ? SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
408
0
                                 : SSL_AD_INTERNAL_ERROR);
409
0
      ret = ssl_verify_invalid;
410
0
    }
411
0
  }
412
413
6.17k
  return ret;
414
6.17k
}
415
416
// Verifies a stored certificate when resuming a session. A few things are
417
// different from verify_peer_cert:
418
// 1. We can't be renegotiating if we're resuming a session.
419
// 2. The session is immutable, so we don't support verify_mode ==
420
// SSL_VERIFY_NONE
421
// 3. We don't call the OCSP callback.
422
// 4. We only support custom verify callbacks.
423
enum ssl_verify_result_t ssl_reverify_peer_cert(SSL_HANDSHAKE *hs,
424
0
                                                bool send_alert) {
425
0
  SSL *const ssl = hs->ssl;
426
0
  assert(ssl->s3->established_session == nullptr);
427
0
  assert(hs->config->verify_mode != SSL_VERIFY_NONE);
428
429
0
  uint8_t alert = SSL_AD_CERTIFICATE_UNKNOWN;
430
0
  enum ssl_verify_result_t ret = ssl_verify_invalid;
431
0
  if (hs->config->custom_verify_callback != nullptr) {
432
0
    ret = hs->config->custom_verify_callback(ssl, &alert);
433
0
  }
434
435
0
  if (ret == ssl_verify_invalid) {
436
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
437
0
    if (send_alert) {
438
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
439
0
    }
440
0
  }
441
442
0
  return ret;
443
0
}
444
445
static uint16_t grease_index_to_value(const SSL_HANDSHAKE *hs,
446
408
                                      enum ssl_grease_index_t index) {
447
  // This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16.
448
408
  uint16_t ret = hs->grease_seed[index];
449
408
  ret = (ret & 0xf0) | 0x0a;
450
408
  ret |= ret << 8;
451
408
  return ret;
452
408
}
453
454
uint16_t ssl_get_grease_value(const SSL_HANDSHAKE *hs,
455
408
                              enum ssl_grease_index_t index) {
456
408
  uint16_t ret = grease_index_to_value(hs, index);
457
408
  if (index == ssl_grease_extension2 &&
458
408
      ret == grease_index_to_value(hs, ssl_grease_extension1)) {
459
    // The two fake extensions must not have the same value. GREASE values are
460
    // of the form 0x1a1a, 0x2a2a, 0x3a3a, etc., so XOR to generate a different
461
    // one.
462
0
    ret ^= 0x1010;
463
0
  }
464
408
  return ret;
465
408
}
466
467
126k
enum ssl_hs_wait_t ssl_get_finished(SSL_HANDSHAKE *hs) {
468
126k
  SSL *const ssl = hs->ssl;
469
126k
  SSLMessage msg;
470
126k
  if (!ssl->method->get_message(ssl, &msg)) {
471
63.9k
    return ssl_hs_read_message;
472
63.9k
  }
473
474
62.7k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_FINISHED)) {
475
10
    return ssl_hs_error;
476
10
  }
477
478
  // Snapshot the finished hash before incorporating the new message.
479
62.7k
  uint8_t finished[EVP_MAX_MD_SIZE];
480
62.7k
  size_t finished_len;
481
62.7k
  if (!hs->transcript.GetFinishedMAC(finished, &finished_len,
482
62.7k
                                     ssl_handshake_session(hs), !ssl->server) ||
483
62.7k
      !ssl_hash_message(hs, msg)) {
484
0
    return ssl_hs_error;
485
0
  }
486
487
62.7k
  int finished_ok = CBS_mem_equal(&msg.body, finished, finished_len);
488
62.7k
#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
489
62.7k
  finished_ok = 1;
490
62.7k
#endif
491
62.7k
  if (!finished_ok) {
492
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
493
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
494
0
    return ssl_hs_error;
495
0
  }
496
497
  // Copy the Finished so we can use it for renegotiation checks.
498
62.7k
  if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
499
62.7k
      finished_len > sizeof(ssl->s3->previous_server_finished)) {
500
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
501
0
    return ssl_hs_error;
502
0
  }
503
504
62.7k
  if (ssl->server) {
505
409
    OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
506
409
    ssl->s3->previous_client_finished_len = finished_len;
507
62.3k
  } else {
508
62.3k
    OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
509
62.3k
    ssl->s3->previous_server_finished_len = finished_len;
510
62.3k
  }
511
512
  // The Finished message should be the end of a flight.
513
62.7k
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
514
28
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
515
28
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
516
28
    return ssl_hs_error;
517
28
  }
518
519
62.7k
  ssl->method->next_message(ssl);
520
62.7k
  return ssl_hs_ok;
521
62.7k
}
522
523
64.2k
bool ssl_send_finished(SSL_HANDSHAKE *hs) {
524
64.2k
  SSL *const ssl = hs->ssl;
525
64.2k
  const SSL_SESSION *session = ssl_handshake_session(hs);
526
527
64.2k
  uint8_t finished[EVP_MAX_MD_SIZE];
528
64.2k
  size_t finished_len;
529
64.2k
  if (!hs->transcript.GetFinishedMAC(finished, &finished_len, session,
530
64.2k
                                     ssl->server)) {
531
0
    return false;
532
0
  }
533
534
  // Log the master secret, if logging is enabled.
535
64.2k
  if (!ssl_log_secret(ssl, "CLIENT_RANDOM",
536
64.2k
                      MakeConstSpan(session->secret, session->secret_length))) {
537
0
    return false;
538
0
  }
539
540
  // Copy the Finished so we can use it for renegotiation checks.
541
64.2k
  if (finished_len > sizeof(ssl->s3->previous_client_finished) ||
542
64.2k
      finished_len > sizeof(ssl->s3->previous_server_finished)) {
543
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
544
0
    return false;
545
0
  }
546
547
64.2k
  if (ssl->server) {
548
457
    OPENSSL_memcpy(ssl->s3->previous_server_finished, finished, finished_len);
549
457
    ssl->s3->previous_server_finished_len = finished_len;
550
63.7k
  } else {
551
63.7k
    OPENSSL_memcpy(ssl->s3->previous_client_finished, finished, finished_len);
552
63.7k
    ssl->s3->previous_client_finished_len = finished_len;
553
63.7k
  }
554
555
64.2k
  ScopedCBB cbb;
556
64.2k
  CBB body;
557
64.2k
  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
558
64.2k
      !CBB_add_bytes(&body, finished, finished_len) ||
559
64.2k
      !ssl_add_message_cbb(ssl, cbb.get())) {
560
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
561
0
    return false;
562
0
  }
563
564
64.2k
  return true;
565
64.2k
}
566
567
39.4k
bool ssl_output_cert_chain(SSL_HANDSHAKE *hs) {
568
39.4k
  ScopedCBB cbb;
569
39.4k
  CBB body;
570
39.4k
  if (!hs->ssl->method->init_message(hs->ssl, cbb.get(), &body,
571
39.4k
                                     SSL3_MT_CERTIFICATE) ||
572
39.4k
      !ssl_add_cert_chain(hs, &body) ||
573
39.4k
      !ssl_add_message_cbb(hs->ssl, cbb.get())) {
574
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
575
0
    return false;
576
0
  }
577
578
39.4k
  return true;
579
39.4k
}
580
581
254k
const SSL_SESSION *ssl_handshake_session(const SSL_HANDSHAKE *hs) {
582
254k
  if (hs->new_session) {
583
253k
    return hs->new_session.get();
584
253k
  }
585
1.06k
  return hs->ssl->session.get();
586
254k
}
587
588
79.5k
int ssl_run_handshake(SSL_HANDSHAKE *hs, bool *out_early_return) {
589
79.5k
  SSL *const ssl = hs->ssl;
590
1.91M
  for (;;) {
591
    // Resolve the operation the handshake was waiting on. Each condition may
592
    // halt the handshake by returning, or continue executing if the handshake
593
    // may immediately proceed. Cases which halt the handshake can clear
594
    // |hs->wait| to re-enter the state machine on the next iteration, or leave
595
    // it set to keep the condition sticky.
596
1.91M
    switch (hs->wait) {
597
0
      case ssl_hs_error:
598
0
        ERR_restore_state(hs->error.get());
599
0
        return -1;
600
601
143k
      case ssl_hs_flush: {
602
143k
        int ret = ssl->method->flush_flight(ssl);
603
143k
        if (ret <= 0) {
604
0
          return ret;
605
0
        }
606
143k
        break;
607
143k
      }
608
609
242k
      case ssl_hs_read_server_hello:
610
1.49M
      case ssl_hs_read_message:
611
1.69M
      case ssl_hs_read_change_cipher_spec: {
612
1.69M
        if (ssl->quic_method) {
613
          // QUIC has no ChangeCipherSpec messages.
614
0
          assert(hs->wait != ssl_hs_read_change_cipher_spec);
615
          // The caller should call |SSL_provide_quic_data|. Clear |hs->wait| so
616
          // the handshake can check if there is sufficient data next iteration.
617
0
          ssl->s3->rwstate = SSL_ERROR_WANT_READ;
618
0
          hs->wait = ssl_hs_ok;
619
0
          return -1;
620
0
        }
621
622
1.69M
        uint8_t alert = SSL_AD_DECODE_ERROR;
623
1.69M
        size_t consumed = 0;
624
1.69M
        ssl_open_record_t ret;
625
1.69M
        if (hs->wait == ssl_hs_read_change_cipher_spec) {
626
193k
          ret = ssl_open_change_cipher_spec(ssl, &consumed, &alert,
627
193k
                                            ssl->s3->read_buffer.span());
628
1.49M
        } else {
629
1.49M
          ret = ssl_open_handshake(ssl, &consumed, &alert,
630
1.49M
                                   ssl->s3->read_buffer.span());
631
1.49M
        }
632
1.69M
        if (ret == ssl_open_record_error &&
633
1.69M
            hs->wait == ssl_hs_read_server_hello) {
634
251
          uint32_t err = ERR_peek_error();
635
251
          if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
636
251
              ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
637
            // Add a dedicated error code to the queue for a handshake_failure
638
            // alert in response to ClientHello. This matches NSS's client
639
            // behavior and gives a better error on a (probable) failure to
640
            // negotiate initial parameters. Note: this error code comes after
641
            // the original one.
642
            //
643
            // See https://crbug.com/446505.
644
3
            OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
645
3
          }
646
251
        }
647
1.69M
        bool retry;
648
1.69M
        int bio_ret = ssl_handle_open_record(ssl, &retry, ret, consumed, alert);
649
1.69M
        if (bio_ret <= 0) {
650
10.1k
          return bio_ret;
651
10.1k
        }
652
1.68M
        if (retry) {
653
1.11M
          continue;
654
1.11M
        }
655
563k
        ssl->s3->read_buffer.DiscardConsumed();
656
563k
        break;
657
1.68M
      }
658
659
53
      case ssl_hs_read_end_of_early_data: {
660
53
        if (ssl->s3->hs->can_early_read) {
661
          // While we are processing early data, the handshake returns early.
662
48
          *out_early_return = true;
663
48
          return 1;
664
48
        }
665
5
        hs->wait = ssl_hs_ok;
666
5
        break;
667
53
      }
668
669
0
      case ssl_hs_certificate_selection_pending:
670
0
        ssl->s3->rwstate = SSL_ERROR_PENDING_CERTIFICATE;
671
0
        hs->wait = ssl_hs_ok;
672
0
        return -1;
673
674
4
      case ssl_hs_handoff:
675
4
        ssl->s3->rwstate = SSL_ERROR_HANDOFF;
676
4
        hs->wait = ssl_hs_ok;
677
4
        return -1;
678
679
0
      case ssl_hs_handback: {
680
0
        int ret = ssl->method->flush_flight(ssl);
681
0
        if (ret <= 0) {
682
0
          return ret;
683
0
        }
684
0
        ssl->s3->rwstate = SSL_ERROR_HANDBACK;
685
0
        hs->wait = ssl_hs_handback;
686
0
        return -1;
687
0
      }
688
689
        // The following cases are associated with callback APIs which expect to
690
        // be called each time the state machine runs. Thus they set |hs->wait|
691
        // to |ssl_hs_ok| so that, next time, we re-enter the state machine and
692
        // call the callback again.
693
0
      case ssl_hs_x509_lookup:
694
0
        ssl->s3->rwstate = SSL_ERROR_WANT_X509_LOOKUP;
695
0
        hs->wait = ssl_hs_ok;
696
0
        return -1;
697
0
      case ssl_hs_private_key_operation:
698
0
        ssl->s3->rwstate = SSL_ERROR_WANT_PRIVATE_KEY_OPERATION;
699
0
        hs->wait = ssl_hs_ok;
700
0
        return -1;
701
0
      case ssl_hs_pending_session:
702
0
        ssl->s3->rwstate = SSL_ERROR_PENDING_SESSION;
703
0
        hs->wait = ssl_hs_ok;
704
0
        return -1;
705
0
      case ssl_hs_pending_ticket:
706
0
        ssl->s3->rwstate = SSL_ERROR_PENDING_TICKET;
707
0
        hs->wait = ssl_hs_ok;
708
0
        return -1;
709
0
      case ssl_hs_certificate_verify:
710
0
        ssl->s3->rwstate = SSL_ERROR_WANT_CERTIFICATE_VERIFY;
711
0
        hs->wait = ssl_hs_ok;
712
0
        return -1;
713
714
5
      case ssl_hs_early_data_rejected:
715
5
        assert(ssl->s3->early_data_reason != ssl_early_data_unknown);
716
0
        assert(!hs->can_early_write);
717
5
        ssl->s3->rwstate = SSL_ERROR_EARLY_DATA_REJECTED;
718
5
        return -1;
719
720
87
      case ssl_hs_early_return:
721
87
        if (!ssl->server) {
722
          // On ECH reject, the handshake should never complete.
723
87
          assert(ssl->s3->ech_status != ssl_ech_rejected);
724
87
        }
725
0
        *out_early_return = true;
726
87
        hs->wait = ssl_hs_ok;
727
87
        return 1;
728
729
0
      case ssl_hs_hints_ready:
730
0
        ssl->s3->rwstate = SSL_ERROR_HANDSHAKE_HINTS_READY;
731
0
        return -1;
732
733
79.5k
      case ssl_hs_ok:
734
79.5k
        break;
735
1.91M
    }
736
737
    // Run the state machine again.
738
786k
    hs->wait = ssl->do_handshake(hs);
739
786k
    if (hs->wait == ssl_hs_error) {
740
6.08k
      hs->error.reset(ERR_save_state());
741
6.08k
      return -1;
742
6.08k
    }
743
780k
    if (hs->wait == ssl_hs_ok) {
744
63.1k
      if (!ssl->server) {
745
        // On ECH reject, the handshake should never complete.
746
62.5k
        assert(ssl->s3->ech_status != ssl_ech_rejected);
747
62.5k
      }
748
      // The handshake has completed.
749
0
      *out_early_return = false;
750
63.1k
      return 1;
751
63.1k
    }
752
753
    // Otherwise, loop to the beginning and resolve what was blocking the
754
    // handshake.
755
780k
  }
756
79.5k
}
757
758
BSSL_NAMESPACE_END