Coverage Report

Created: 2025-06-11 06:40

/src/boringssl/ssl/handshake_server.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 <string.h>
21
22
#include <openssl/bn.h>
23
#include <openssl/bytestring.h>
24
#include <openssl/cipher.h>
25
#include <openssl/curve25519.h>
26
#include <openssl/digest.h>
27
#include <openssl/ec.h>
28
#include <openssl/ecdsa.h>
29
#include <openssl/err.h>
30
#include <openssl/evp.h>
31
#include <openssl/hmac.h>
32
#include <openssl/md5.h>
33
#include <openssl/mem.h>
34
#include <openssl/nid.h>
35
#include <openssl/rand.h>
36
#include <openssl/x509.h>
37
38
#include "../crypto/internal.h"
39
#include "internal.h"
40
41
42
BSSL_NAMESPACE_BEGIN
43
44
bool ssl_client_cipher_list_contains_cipher(
45
6.43k
    const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
46
6.43k
  CBS cipher_suites;
47
6.43k
  CBS_init(&cipher_suites, client_hello->cipher_suites,
48
6.43k
           client_hello->cipher_suites_len);
49
50
83.9k
  while (CBS_len(&cipher_suites) > 0) {
51
77.8k
    uint16_t got_id;
52
77.8k
    if (!CBS_get_u16(&cipher_suites, &got_id)) {
53
0
      return false;
54
0
    }
55
56
77.8k
    if (got_id == id) {
57
379
      return true;
58
379
    }
59
77.8k
  }
60
61
6.05k
  return false;
62
6.43k
}
63
64
static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
65
4.09k
                              const SSL_CLIENT_HELLO *client_hello) {
66
4.09k
  SSL *const ssl = hs->ssl;
67
4.09k
  assert(ssl->s3->version == 0);
68
4.09k
  CBS supported_versions, versions;
69
4.09k
  if (ssl_client_hello_get_extension(client_hello, &supported_versions,
70
4.09k
                                     TLSEXT_TYPE_supported_versions)) {
71
1.01k
    if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||  //
72
1.01k
        CBS_len(&supported_versions) != 0 ||                            //
73
1.01k
        CBS_len(&versions) == 0) {
74
12
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
75
12
      *out_alert = SSL_AD_DECODE_ERROR;
76
12
      return false;
77
12
    }
78
3.07k
  } else {
79
    // Convert the ClientHello version to an equivalent supported_versions
80
    // extension.
81
3.07k
    static const uint8_t kTLSVersions[] = {
82
3.07k
        0x03, 0x03,  // TLS 1.2
83
3.07k
        0x03, 0x02,  // TLS 1.1
84
3.07k
        0x03, 0x01,  // TLS 1
85
3.07k
    };
86
87
3.07k
    static const uint8_t kDTLSVersions[] = {
88
3.07k
        0xfe, 0xfd,  // DTLS 1.2
89
3.07k
        0xfe, 0xff,  // DTLS 1.0
90
3.07k
    };
91
92
3.07k
    size_t versions_len = 0;
93
3.07k
    if (SSL_is_dtls(ssl)) {
94
0
      if (client_hello->version <= DTLS1_2_VERSION) {
95
0
        versions_len = 4;
96
0
      } else if (client_hello->version <= DTLS1_VERSION) {
97
0
        versions_len = 2;
98
0
      }
99
0
      versions = Span(kDTLSVersions).last(versions_len);
100
3.07k
    } else {
101
3.07k
      if (client_hello->version >= TLS1_2_VERSION) {
102
2.26k
        versions_len = 6;
103
2.26k
      } else if (client_hello->version >= TLS1_1_VERSION) {
104
372
        versions_len = 4;
105
442
      } else if (client_hello->version >= TLS1_VERSION) {
106
429
        versions_len = 2;
107
429
      }
108
3.07k
      versions = Span(kTLSVersions).last(versions_len);
109
3.07k
    }
110
3.07k
  }
111
112
4.08k
  if (!ssl_negotiate_version(hs, out_alert, &ssl->s3->version, &versions)) {
113
20
    return false;
114
20
  }
115
116
  // Handle FALLBACK_SCSV.
117
4.06k
  if (ssl_client_cipher_list_contains_cipher(client_hello,
118
4.06k
                                             SSL3_CK_FALLBACK_SCSV & 0xffff) &&
119
4.06k
      ssl_protocol_version(ssl) < hs->max_version) {
120
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
121
3
    *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
122
3
    return false;
123
3
  }
124
125
4.06k
  return true;
126
4.06k
}
127
128
static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
129
2.84k
    const SSL_CLIENT_HELLO *client_hello) {
130
2.84k
  CBS cipher_suites;
131
2.84k
  CBS_init(&cipher_suites, client_hello->cipher_suites,
132
2.84k
           client_hello->cipher_suites_len);
133
134
2.84k
  UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
135
2.84k
  if (!sk) {
136
0
    return nullptr;
137
0
  }
138
139
39.8k
  while (CBS_len(&cipher_suites) > 0) {
140
36.9k
    uint16_t cipher_suite;
141
142
36.9k
    if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
143
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
144
0
      return nullptr;
145
0
    }
146
147
36.9k
    const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
148
36.9k
    if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
149
0
      return nullptr;
150
0
    }
151
36.9k
  }
152
153
2.84k
  return sk;
154
2.84k
}
155
156
static const SSL_CIPHER *choose_cipher(SSL_HANDSHAKE *hs,
157
                                       const STACK_OF(SSL_CIPHER) *client_pref,
158
2.84k
                                       uint32_t mask_k, uint32_t mask_a) {
159
2.84k
  SSL *const ssl = hs->ssl;
160
2.84k
  const STACK_OF(SSL_CIPHER) *prio, *allow;
161
  // in_group_flags will either be NULL, or will point to an array of bytes
162
  // which indicate equal-preference groups in the |prio| stack. See the
163
  // comment about |in_group_flags| in the |SSLCipherPreferenceList|
164
  // struct.
165
2.84k
  const bool *in_group_flags;
166
  // best_index contains the index of the best matching cipher suite found so
167
  // far, indexed into |allow|. If |best_index| is |SIZE_MAX|, no matching
168
  // cipher suite has been found yet.
169
2.84k
  size_t best_index = SIZE_MAX;
170
171
2.84k
  const SSLCipherPreferenceList *server_pref =
172
2.84k
      hs->config->cipher_list ? hs->config->cipher_list.get()
173
2.84k
                              : ssl->ctx->cipher_list.get();
174
2.84k
  if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
175
0
    prio = server_pref->ciphers.get();
176
0
    in_group_flags = server_pref->in_group_flags;
177
0
    allow = client_pref;
178
2.84k
  } else {
179
2.84k
    prio = client_pref;
180
2.84k
    in_group_flags = nullptr;
181
2.84k
    allow = server_pref->ciphers.get();
182
2.84k
  }
183
184
7.00k
  for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
185
6.83k
    const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
186
6.83k
    const bool in_group = in_group_flags != nullptr && in_group_flags[i];
187
188
6.83k
    size_t cipher_index;
189
6.83k
    if (  // Check if the cipher is supported for the current version.
190
6.83k
        SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) &&  //
191
6.83k
        ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) &&  //
192
        // Check the cipher is supported for the server configuration.
193
6.83k
        (c->algorithm_mkey & mask_k) &&  //
194
6.83k
        (c->algorithm_auth & mask_a) &&  //
195
        // Check the cipher is in the |allow| list.
196
6.83k
        sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
197
      // Within a group, |allow|'s preference order applies.
198
2.68k
      if (best_index == SIZE_MAX || best_index > cipher_index) {
199
2.68k
        best_index = cipher_index;
200
2.68k
      }
201
2.68k
    }
202
203
    // We are about to leave a (possibly singleton) group, but we found a match
204
    // in it, so that's our answer.
205
6.83k
    if (!in_group && best_index != SIZE_MAX) {
206
2.68k
      return sk_SSL_CIPHER_value(allow, best_index);
207
2.68k
    }
208
6.83k
  }
209
210
  // The final cipher suite must end a group, so, if we found a match, we must
211
  // have returned early above.
212
166
  assert(best_index == SIZE_MAX);
213
166
  OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
214
166
  return nullptr;
215
166
}
216
217
struct TLS12ServerParams {
218
5.69k
  bool ok() const { return cipher != nullptr; }
219
220
  const SSL_CIPHER *cipher = nullptr;
221
  uint16_t signature_algorithm = 0;
222
};
223
224
static TLS12ServerParams choose_params(SSL_HANDSHAKE *hs,
225
                                       const SSL_CREDENTIAL *cred,
226
                                       const STACK_OF(SSL_CIPHER) *client_pref,
227
2.84k
                                       bool has_ecdhe_group) {
228
  // Determine the usable cipher suites.
229
2.84k
  uint32_t mask_k = 0, mask_a = 0;
230
2.84k
  if (has_ecdhe_group) {
231
2.25k
    mask_k |= SSL_kECDHE;
232
2.25k
  }
233
2.84k
  if (hs->config->psk_server_callback != nullptr) {
234
0
    mask_k |= SSL_kPSK;
235
0
    mask_a |= SSL_aPSK;
236
0
  }
237
2.84k
  uint16_t sigalg = 0;
238
2.84k
  if (cred != nullptr && cred->type == SSLCredentialType::kX509) {
239
2.84k
    bool sign_ok = tls1_choose_signature_algorithm(hs, cred, &sigalg);
240
2.84k
    ERR_clear_error();
241
242
    // ECDSA keys must additionally be checked against the peer's supported
243
    // curve list.
244
2.84k
    int key_type = EVP_PKEY_id(cred->pubkey.get());
245
2.84k
    if (key_type == EVP_PKEY_EC) {
246
0
      EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(cred->pubkey.get());
247
0
      uint16_t group_id;
248
0
      if (!ssl_nid_to_group_id(
249
0
              &group_id, EC_GROUP_get_curve_name(EC_KEY_get0_group(ec_key))) ||
250
0
          std::find(hs->peer_supported_group_list.begin(),
251
0
                    hs->peer_supported_group_list.end(),
252
0
                    group_id) == hs->peer_supported_group_list.end()) {
253
0
        sign_ok = false;
254
255
        // If this would make us unable to pick any cipher, return an error.
256
        // This is not strictly necessary, but it gives us a more specific
257
        // error to help the caller diagnose issues.
258
0
        if (mask_a == 0) {
259
0
          OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
260
0
          return TLS12ServerParams();
261
0
        }
262
0
      }
263
0
    }
264
265
2.84k
    mask_a |= ssl_cipher_auth_mask_for_key(cred->pubkey.get(), sign_ok);
266
2.84k
    if (key_type == EVP_PKEY_RSA) {
267
2.84k
      mask_k |= SSL_kRSA;
268
2.84k
    }
269
2.84k
  }
270
271
2.84k
  TLS12ServerParams params;
272
2.84k
  params.cipher = choose_cipher(hs, client_pref, mask_k, mask_a);
273
2.84k
  if (params.cipher == nullptr ||
274
2.84k
      (cred != nullptr &&
275
2.68k
       !ssl_credential_matches_requested_issuers(hs, cred))) {
276
166
    return TLS12ServerParams();
277
166
  }
278
  // Only report the selected signature algorithm if it will be used.
279
2.68k
  if (ssl_cipher_requires_server_key_exchange(params.cipher) &&
280
2.68k
      ssl_cipher_uses_certificate_auth(params.cipher)) {
281
2.19k
    params.signature_algorithm = sigalg;
282
2.19k
  }
283
2.68k
  return params;
284
2.84k
}
285
286
4.82k
static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
287
4.82k
  ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
288
4.82k
  hs->state = state12_read_client_hello;
289
4.82k
  return ssl_hs_ok;
290
4.82k
}
291
292
// is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent
293
// from a JDK 11 client with both TLS 1.3 and a prior version enabled.
294
0
static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) {
295
  // JDK 11 ClientHellos contain a number of unusual properties which should
296
  // limit false positives.
297
298
  // JDK 11 does not support ChaCha20-Poly1305. This is unusual: many modern
299
  // clients implement ChaCha20-Poly1305.
300
0
  if (ssl_client_cipher_list_contains_cipher(
301
0
          client_hello, TLS1_3_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
302
0
    return false;
303
0
  }
304
305
  // JDK 11 always sends extensions in a particular order.
306
0
  constexpr uint16_t kMaxFragmentLength = 0x0001;
307
0
  constexpr uint16_t kStatusRequestV2 = 0x0011;
308
0
  static constexpr struct {
309
0
    uint16_t id;
310
0
    bool required;
311
0
  } kJavaExtensions[] = {
312
0
      {TLSEXT_TYPE_server_name, false},
313
0
      {kMaxFragmentLength, false},
314
0
      {TLSEXT_TYPE_status_request, false},
315
0
      {TLSEXT_TYPE_supported_groups, true},
316
0
      {TLSEXT_TYPE_ec_point_formats, false},
317
0
      {TLSEXT_TYPE_signature_algorithms, true},
318
      // Java always sends signature_algorithms_cert.
319
0
      {TLSEXT_TYPE_signature_algorithms_cert, true},
320
0
      {TLSEXT_TYPE_application_layer_protocol_negotiation, false},
321
0
      {kStatusRequestV2, false},
322
0
      {TLSEXT_TYPE_extended_master_secret, false},
323
0
      {TLSEXT_TYPE_supported_versions, true},
324
0
      {TLSEXT_TYPE_cookie, false},
325
0
      {TLSEXT_TYPE_psk_key_exchange_modes, true},
326
0
      {TLSEXT_TYPE_key_share, true},
327
0
      {TLSEXT_TYPE_renegotiate, false},
328
0
      {TLSEXT_TYPE_pre_shared_key, false},
329
0
  };
330
0
  Span<const uint8_t> sigalgs, sigalgs_cert;
331
0
  bool has_status_request = false, has_status_request_v2 = false;
332
0
  CBS extensions, supported_groups;
333
0
  CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
334
0
  for (const auto &java_extension : kJavaExtensions) {
335
0
    CBS copy = extensions;
336
0
    uint16_t id;
337
0
    if (CBS_get_u16(&copy, &id) && id == java_extension.id) {
338
      // The next extension is the one we expected.
339
0
      extensions = copy;
340
0
      CBS body;
341
0
      if (!CBS_get_u16_length_prefixed(&extensions, &body)) {
342
0
        return false;
343
0
      }
344
0
      switch (id) {
345
0
        case TLSEXT_TYPE_status_request:
346
0
          has_status_request = true;
347
0
          break;
348
0
        case kStatusRequestV2:
349
0
          has_status_request_v2 = true;
350
0
          break;
351
0
        case TLSEXT_TYPE_signature_algorithms:
352
0
          sigalgs = body;
353
0
          break;
354
0
        case TLSEXT_TYPE_signature_algorithms_cert:
355
0
          sigalgs_cert = body;
356
0
          break;
357
0
        case TLSEXT_TYPE_supported_groups:
358
0
          supported_groups = body;
359
0
          break;
360
0
      }
361
0
    } else if (java_extension.required) {
362
0
      return false;
363
0
    }
364
0
  }
365
0
  if (CBS_len(&extensions) != 0) {
366
0
    return false;
367
0
  }
368
369
  // JDK 11 never advertises X25519. It is not offered by default, and
370
  // -Djdk.tls.namedGroups=x25519 does not work. This is unusual: many modern
371
  // clients implement X25519.
372
0
  while (CBS_len(&supported_groups) > 0) {
373
0
    uint16_t group;
374
0
    if (!CBS_get_u16(&supported_groups, &group) ||  //
375
0
        group == SSL_GROUP_X25519) {
376
0
      return false;
377
0
    }
378
0
  }
379
380
0
  if (  // JDK 11 always sends the same contents in signature_algorithms and
381
        // signature_algorithms_cert. This is unusual:
382
        // signature_algorithms_cert, if omitted, is treated as if it were
383
        // signature_algorithms.
384
0
      sigalgs != sigalgs_cert ||
385
      // When TLS 1.2 or below is enabled, JDK 11 sends status_request_v2 iff it
386
      // sends status_request. This is unusual: status_request_v2 is not widely
387
      // implemented.
388
0
      has_status_request != has_status_request_v2) {
389
0
    return false;
390
0
  }
391
392
0
  return true;
393
0
}
394
395
static bool decrypt_ech(SSL_HANDSHAKE *hs, uint8_t *out_alert,
396
4.19k
                        const SSL_CLIENT_HELLO *client_hello) {
397
4.19k
  SSL *const ssl = hs->ssl;
398
4.19k
  CBS body;
399
4.19k
  if (!ssl_client_hello_get_extension(client_hello, &body,
400
4.19k
                                      TLSEXT_TYPE_encrypted_client_hello)) {
401
3.96k
    return true;
402
3.96k
  }
403
232
  uint8_t type;
404
232
  if (!CBS_get_u8(&body, &type)) {
405
1
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
406
1
    *out_alert = SSL_AD_DECODE_ERROR;
407
1
    return false;
408
1
  }
409
231
  if (type != ECH_CLIENT_OUTER) {
410
26
    return true;
411
26
  }
412
  // This is a ClientHelloOuter ECH extension. Attempt to decrypt it.
413
205
  uint8_t config_id;
414
205
  uint16_t kdf_id, aead_id;
415
205
  CBS enc, payload;
416
205
  if (!CBS_get_u16(&body, &kdf_id) ||   //
417
205
      !CBS_get_u16(&body, &aead_id) ||  //
418
205
      !CBS_get_u8(&body, &config_id) ||
419
205
      !CBS_get_u16_length_prefixed(&body, &enc) ||
420
205
      !CBS_get_u16_length_prefixed(&body, &payload) ||  //
421
205
      CBS_len(&body) != 0) {
422
6
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
423
6
    *out_alert = SSL_AD_DECODE_ERROR;
424
6
    return false;
425
6
  }
426
427
199
  {
428
199
    MutexReadLock lock(&ssl->ctx->lock);
429
199
    hs->ech_keys = UpRef(ssl->ctx->ech_keys);
430
199
  }
431
432
199
  if (!hs->ech_keys) {
433
0
    ssl->s3->ech_status = ssl_ech_rejected;
434
0
    return true;
435
0
  }
436
437
199
  for (const auto &config : hs->ech_keys->configs) {
438
199
    hs->ech_hpke_ctx.Reset();
439
199
    if (config_id != config->ech_config().config_id ||
440
199
        !config->SetupContext(hs->ech_hpke_ctx.get(), kdf_id, aead_id, enc)) {
441
      // Ignore the error and try another ECHConfig.
442
40
      ERR_clear_error();
443
40
      continue;
444
40
    }
445
159
    bool is_decrypt_error;
446
159
    if (!ssl_client_hello_decrypt(hs, out_alert, &is_decrypt_error,
447
159
                                  &hs->ech_client_hello_buf, client_hello,
448
159
                                  payload)) {
449
68
      if (is_decrypt_error) {
450
        // Ignore the error and try another ECHConfig.
451
2
        ERR_clear_error();
452
        // The |out_alert| calling convention currently relies on a default of
453
        // |SSL_AD_DECODE_ERROR|. https://crbug.com/boringssl/373 tracks
454
        // switching to sum types, which avoids this.
455
2
        *out_alert = SSL_AD_DECODE_ERROR;
456
2
        continue;
457
2
      }
458
66
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
459
66
      return false;
460
68
    }
461
91
    hs->ech_config_id = config_id;
462
91
    ssl->s3->ech_status = ssl_ech_accepted;
463
91
    return true;
464
159
  }
465
466
  // If we did not accept ECH, proceed with the ClientHelloOuter. Note this
467
  // could be key mismatch or ECH GREASE, so we must complete the handshake
468
  // as usual, except EncryptedExtensions will contain retry configs.
469
42
  ssl->s3->ech_status = ssl_ech_rejected;
470
42
  return true;
471
199
}
472
473
static bool extract_sni(SSL_HANDSHAKE *hs, uint8_t *out_alert,
474
4.12k
                        const SSL_CLIENT_HELLO *client_hello) {
475
4.12k
  SSL *const ssl = hs->ssl;
476
4.12k
  CBS sni;
477
4.12k
  if (!ssl_client_hello_get_extension(client_hello, &sni,
478
4.12k
                                      TLSEXT_TYPE_server_name)) {
479
    // No SNI extension to parse.
480
    //
481
    // Clear state in case we previously extracted SNI from ClientHelloOuter.
482
2.40k
    ssl->s3->hostname.reset();
483
2.40k
    return true;
484
2.40k
  }
485
486
1.71k
  CBS server_name_list, host_name;
487
1.71k
  uint8_t name_type;
488
1.71k
  if (!CBS_get_u16_length_prefixed(&sni, &server_name_list) ||  //
489
1.71k
      !CBS_get_u8(&server_name_list, &name_type) ||             //
490
      // Although the server_name extension was intended to be extensible to
491
      // new name types and multiple names, OpenSSL 1.0.x had a bug which meant
492
      // different name types will cause an error. Further, RFC 4366 originally
493
      // defined syntax inextensibly. RFC 6066 corrected this mistake, but
494
      // adding new name types is no longer feasible.
495
      //
496
      // Act as if the extensibility does not exist to simplify parsing.
497
1.71k
      !CBS_get_u16_length_prefixed(&server_name_list, &host_name) ||  //
498
1.71k
      CBS_len(&server_name_list) != 0 ||                              //
499
1.71k
      CBS_len(&sni) != 0) {
500
21
    *out_alert = SSL_AD_DECODE_ERROR;
501
21
    return false;
502
21
  }
503
504
1.69k
  if (name_type != TLSEXT_NAMETYPE_host_name ||         //
505
1.69k
      CBS_len(&host_name) == 0 ||                       //
506
1.69k
      CBS_len(&host_name) > TLSEXT_MAXLEN_host_name ||  //
507
1.69k
      CBS_contains_zero_byte(&host_name)) {
508
6
    *out_alert = SSL_AD_UNRECOGNIZED_NAME;
509
6
    return false;
510
6
  }
511
512
  // Copy the hostname as a string.
513
1.68k
  char *raw = nullptr;
514
1.68k
  if (!CBS_strdup(&host_name, &raw)) {
515
0
    *out_alert = SSL_AD_INTERNAL_ERROR;
516
0
    return false;
517
0
  }
518
1.68k
  ssl->s3->hostname.reset(raw);
519
1.68k
  return true;
520
1.68k
}
521
522
20.8k
static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
523
20.8k
  SSL *const ssl = hs->ssl;
524
525
20.8k
  SSLMessage msg;
526
20.8k
  if (!ssl->method->get_message(ssl, &msg)) {
527
16.5k
    return ssl_hs_read_message;
528
16.5k
  }
529
530
4.31k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
531
12
    return ssl_hs_error;
532
12
  }
533
534
4.30k
  SSL_CLIENT_HELLO client_hello;
535
4.30k
  if (!SSL_parse_client_hello(ssl, &client_hello, CBS_data(&msg.body),
536
4.30k
                              CBS_len(&msg.body))) {
537
101
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
538
101
    return ssl_hs_error;
539
101
  }
540
541
  // ClientHello should be the end of the flight. We check this early to cover
542
  // all protocol versions.
543
4.20k
  if (ssl->method->has_unprocessed_handshake_data(ssl)) {
544
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
545
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
546
3
    return ssl_hs_error;
547
3
  }
548
549
4.19k
  if (hs->config->handoff) {
550
2
    return ssl_hs_handoff;
551
2
  }
552
553
4.19k
  uint8_t alert = SSL_AD_DECODE_ERROR;
554
  // We check for rejection status in case we've rewound the state machine after
555
  // determining `ClientHelloInner` is invalid.
556
4.19k
  if (ssl->s3->ech_status != ssl_ech_rejected &&
557
4.19k
      !decrypt_ech(hs, &alert, &client_hello)) {
558
73
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
559
73
    return ssl_hs_error;
560
73
  }
561
562
  // ECH may have changed which ClientHello we process. Update |msg| and
563
  // |client_hello| in case.
564
4.12k
  if (!hs->GetClientHello(&msg, &client_hello)) {
565
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
566
0
    return ssl_hs_error;
567
0
  }
568
569
4.12k
  if (!extract_sni(hs, &alert, &client_hello)) {
570
27
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
571
27
    return ssl_hs_error;
572
27
  }
573
574
4.09k
  hs->state = state12_read_client_hello_after_ech;
575
4.09k
  return ssl_hs_ok;
576
4.12k
}
577
578
4.09k
static enum ssl_hs_wait_t do_read_client_hello_after_ech(SSL_HANDSHAKE *hs) {
579
4.09k
  SSL *const ssl = hs->ssl;
580
581
4.09k
  SSLMessage msg_unused;
582
4.09k
  SSL_CLIENT_HELLO client_hello;
583
4.09k
  if (!hs->GetClientHello(&msg_unused, &client_hello)) {
584
0
    return ssl_hs_error;
585
0
  }
586
587
  // Run the early callback.
588
4.09k
  if (ssl->ctx->select_certificate_cb != NULL) {
589
0
    switch (ssl->ctx->select_certificate_cb(&client_hello)) {
590
0
      case ssl_select_cert_retry:
591
0
        return ssl_hs_certificate_selection_pending;
592
593
0
      case ssl_select_cert_disable_ech:
594
0
        hs->ech_client_hello_buf.Reset();
595
0
        hs->ech_keys = nullptr;
596
0
        hs->state = state12_read_client_hello;
597
0
        ssl->s3->ech_status = ssl_ech_rejected;
598
0
        return ssl_hs_ok;
599
600
0
      case ssl_select_cert_error:
601
        // Connection rejected.
602
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
603
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
604
0
        return ssl_hs_error;
605
606
0
      default:
607
0
          /* fallthrough */;
608
0
    }
609
0
  }
610
611
  // Freeze the version range after the early callback.
612
4.09k
  if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
613
0
    return ssl_hs_error;
614
0
  }
615
616
4.09k
  if (hs->config->jdk11_workaround &&
617
4.09k
      is_probably_jdk11_with_tls13(&client_hello)) {
618
0
    hs->apply_jdk11_workaround = true;
619
0
  }
620
621
4.09k
  uint8_t alert = SSL_AD_DECODE_ERROR;
622
4.09k
  if (!negotiate_version(hs, &alert, &client_hello)) {
623
35
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
624
35
    return ssl_hs_error;
625
35
  }
626
627
4.06k
  hs->client_version = client_hello.version;
628
4.06k
  if (client_hello.random_len != SSL3_RANDOM_SIZE) {
629
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
630
0
    return ssl_hs_error;
631
0
  }
632
4.06k
  OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
633
4.06k
                 client_hello.random_len);
634
635
  // Only null compression is supported. TLS 1.3 further requires the peer
636
  // advertise no other compression.
637
4.06k
  if (OPENSSL_memchr(client_hello.compression_methods, 0,
638
4.06k
                     client_hello.compression_methods_len) == NULL ||
639
4.06k
      (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
640
4.04k
       client_hello.compression_methods_len != 1)) {
641
19
    OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
642
19
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
643
19
    return ssl_hs_error;
644
19
  }
645
646
  // TLS extensions.
647
4.04k
  if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
648
241
    OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
649
241
    return ssl_hs_error;
650
241
  }
651
652
3.80k
  hs->state = state12_cert_callback;
653
3.80k
  return ssl_hs_ok;
654
4.04k
}
655
656
3.80k
static enum ssl_hs_wait_t do_cert_callback(SSL_HANDSHAKE *hs) {
657
3.80k
  SSL *const ssl = hs->ssl;
658
659
  // Call |cert_cb| to update server certificates if required.
660
3.80k
  if (hs->config->cert->cert_cb != NULL) {
661
0
    int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
662
0
    if (rv == 0) {
663
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
664
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
665
0
      return ssl_hs_error;
666
0
    }
667
0
    if (rv < 0) {
668
0
      return ssl_hs_x509_lookup;
669
0
    }
670
0
  }
671
672
3.80k
  if (hs->ocsp_stapling_requested &&
673
3.80k
      ssl->ctx->legacy_ocsp_callback != nullptr) {
674
0
    switch (ssl->ctx->legacy_ocsp_callback(
675
0
        ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
676
0
      case SSL_TLSEXT_ERR_OK:
677
0
        break;
678
0
      case SSL_TLSEXT_ERR_NOACK:
679
0
        hs->ocsp_stapling_requested = false;
680
0
        break;
681
0
      default:
682
0
        OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
683
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
684
0
        return ssl_hs_error;
685
0
    }
686
0
  }
687
688
3.80k
  if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
689
    // Jump to the TLS 1.3 state machine.
690
953
    hs->state = state12_tls13;
691
953
    return ssl_hs_ok;
692
953
  }
693
694
  // It should not be possible to negotiate TLS 1.2 with ECH. The
695
  // ClientHelloInner decoding function rejects ClientHellos which offer TLS 1.2
696
  // or below.
697
2.84k
  assert(ssl->s3->ech_status != ssl_ech_accepted);
698
699
2.84k
  ssl->s3->early_data_reason = ssl_early_data_protocol_version;
700
701
2.84k
  hs->state = state12_select_parameters;
702
2.84k
  return ssl_hs_ok;
703
2.84k
}
704
705
5.29k
static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
706
5.29k
  enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
707
5.29k
  if (wait == ssl_hs_ok) {
708
250
    hs->state = state12_finish_server_handshake;
709
250
    return ssl_hs_ok;
710
250
  }
711
712
5.04k
  return wait;
713
5.29k
}
714
715
2.84k
static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
716
2.84k
  SSL *const ssl = hs->ssl;
717
2.84k
  SSLMessage msg;
718
2.84k
  SSL_CLIENT_HELLO client_hello;
719
2.84k
  if (!hs->GetClientHello(&msg, &client_hello)) {
720
0
    return ssl_hs_error;
721
0
  }
722
723
  // Determine the ECDHE group to use, if we are to use ECDHE.
724
2.84k
  uint16_t group_id = 0;
725
2.84k
  bool has_ecdhe_group = tls1_get_shared_group(hs, &group_id);
726
727
  // Select the credential and cipher suite. This must be done after |cert_cb|
728
  // runs, so the final credential list is known.
729
  //
730
  // TODO(davidben): In the course of picking these, we also pick the ECDHE
731
  // group and signature algorithm. It would be tidier if we saved that decision
732
  // and avoided redoing it later.
733
2.84k
  UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
734
2.84k
      ssl_parse_client_cipher_list(&client_hello);
735
2.84k
  if (client_pref == nullptr) {
736
0
    return ssl_hs_error;
737
0
  }
738
2.84k
  Array<SSL_CREDENTIAL *> creds;
739
2.84k
  if (!ssl_get_full_credential_list(hs, &creds)) {
740
0
    return ssl_hs_error;
741
0
  }
742
2.84k
  TLS12ServerParams params;
743
2.84k
  if (creds.empty()) {
744
    // The caller may have configured no credentials, but set a PSK callback.
745
0
    params =
746
0
        choose_params(hs, /*cred=*/nullptr, client_pref.get(), has_ecdhe_group);
747
2.84k
  } else {
748
    // Select the first credential which works.
749
2.84k
    for (SSL_CREDENTIAL *cred : creds) {
750
2.84k
      ERR_clear_error();
751
2.84k
      params = choose_params(hs, cred, client_pref.get(), has_ecdhe_group);
752
2.84k
      if (params.ok()) {
753
2.68k
        hs->credential = UpRef(cred);
754
2.68k
        break;
755
2.68k
      }
756
2.84k
    }
757
2.84k
  }
758
2.84k
  if (!params.ok()) {
759
    // The error from the last attempt is in the error queue.
760
166
    assert(ERR_peek_error() != 0);
761
166
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
762
166
    return ssl_hs_error;
763
166
  }
764
2.68k
  hs->new_cipher = params.cipher;
765
2.68k
  hs->signature_algorithm = params.signature_algorithm;
766
767
  // |SSL_parse_client_hello| checks that |client_hello.session_id| is not too
768
  // large.
769
2.68k
  hs->session_id.CopyFrom(
770
2.68k
      Span(client_hello.session_id, client_hello.session_id_len));
771
772
  // Determine whether we are doing session resumption.
773
2.68k
  UniquePtr<SSL_SESSION> session;
774
2.68k
  bool tickets_supported = false, renew_ticket = false;
775
2.68k
  enum ssl_hs_wait_t wait = ssl_get_prev_session(
776
2.68k
      hs, &session, &tickets_supported, &renew_ticket, &client_hello);
777
2.68k
  if (wait != ssl_hs_ok) {
778
0
    return wait;
779
0
  }
780
781
2.68k
  if (session) {
782
89
    if (session->extended_master_secret && !hs->extended_master_secret) {
783
      // A ClientHello without EMS that attempts to resume a session with EMS
784
      // is fatal to the connection.
785
1
      OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
786
1
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
787
1
      return ssl_hs_error;
788
1
    }
789
790
88
    if (!ssl_session_is_resumable(hs, session.get()) ||
791
        // If the client offers the EMS extension, but the previous session
792
        // didn't use it, then negotiate a new session.
793
88
        hs->extended_master_secret != session->extended_master_secret) {
794
42
      session.reset();
795
42
    }
796
88
  }
797
798
2.68k
  if (session) {
799
    // Use the old session.
800
46
    hs->ticket_expected = renew_ticket;
801
46
    ssl->session = std::move(session);
802
46
    ssl->s3->session_reused = true;
803
46
    hs->can_release_private_key = true;
804
2.63k
  } else {
805
2.63k
    hs->ticket_expected = tickets_supported;
806
2.63k
    ssl_set_session(ssl, nullptr);
807
2.63k
    if (!ssl_get_new_session(hs)) {
808
0
      return ssl_hs_error;
809
0
    }
810
811
    // Assign a session ID if not using session tickets.
812
2.63k
    if (!hs->ticket_expected &&
813
2.63k
        (ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
814
1.88k
      hs->new_session->session_id.ResizeForOverwrite(
815
1.88k
          SSL3_SSL_SESSION_ID_LENGTH);
816
1.88k
      RAND_bytes(hs->new_session->session_id.data(),
817
1.88k
                 hs->new_session->session_id.size());
818
1.88k
    }
819
2.63k
  }
820
821
2.68k
  if (ssl->ctx->dos_protection_cb != NULL &&
822
2.68k
      ssl->ctx->dos_protection_cb(&client_hello) == 0) {
823
    // Connection rejected for DOS reasons.
824
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
825
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
826
0
    return ssl_hs_error;
827
0
  }
828
829
2.68k
  if (ssl->session == NULL) {
830
2.63k
    hs->new_session->cipher = hs->new_cipher;
831
2.63k
    if (hs->new_session->cipher->algorithm_mkey & SSL_kECDHE) {
832
2.16k
      assert(has_ecdhe_group);
833
2.16k
      hs->new_session->group_id = group_id;
834
2.16k
    }
835
836
    // Determine whether to request a client certificate. CertificateRequest may
837
    // only be sent in certificate-based ciphers.
838
2.63k
    hs->cert_request = (hs->config->verify_mode & SSL_VERIFY_PEER) &&
839
2.63k
                       ssl_cipher_uses_certificate_auth(hs->new_cipher);
840
2.63k
    if (!hs->cert_request) {
841
      // OpenSSL returns X509_V_OK when no certificates are requested. This is
842
      // classed by them as a bug, but it's assumed by at least NGINX.
843
1.18k
      hs->new_session->verify_result = X509_V_OK;
844
1.18k
    }
845
2.63k
  }
846
847
  // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
848
  // deferred. Complete it now.
849
2.68k
  uint8_t alert = SSL_AD_DECODE_ERROR;
850
2.68k
  if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
851
12
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
852
12
    return ssl_hs_error;
853
12
  }
854
855
  // Now that all parameters are known, initialize the handshake hash and hash
856
  // the ClientHello.
857
2.66k
  if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher)) {
858
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
859
0
    return ssl_hs_error;
860
0
  }
861
862
  // Handback includes the whole handshake transcript, so we cannot free the
863
  // transcript buffer in the handback case.
864
2.66k
  if (!hs->cert_request && !hs->handback) {
865
1.22k
    hs->transcript.FreeBuffer();
866
1.22k
  }
867
868
2.66k
  if (!ssl_hash_message(hs, msg)) {
869
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
870
0
    return ssl_hs_error;
871
0
  }
872
873
2.66k
  ssl->method->next_message(ssl);
874
875
2.66k
  hs->state = state12_send_server_hello;
876
2.66k
  return ssl_hs_ok;
877
2.66k
}
878
879
2.66k
static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
880
2.66k
  out = out.last(in.size());
881
2.66k
  OPENSSL_memcpy(out.data(), in.data(), in.size());
882
2.66k
}
883
884
2.66k
static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
885
2.66k
  SSL *const ssl = hs->ssl;
886
887
  // We only accept ChannelIDs on connections with ECDHE in order to avoid a
888
  // known attack while we fix ChannelID itself.
889
2.66k
  if (hs->channel_id_negotiated &&
890
2.66k
      (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
891
1
    hs->channel_id_negotiated = false;
892
1
  }
893
894
  // If this is a resumption and the original handshake didn't support
895
  // ChannelID then we didn't record the original handshake hashes in the
896
  // session and so cannot resume with ChannelIDs.
897
2.66k
  if (ssl->session != nullptr &&
898
2.66k
      ssl->session->original_handshake_hash.empty()) {
899
40
    hs->channel_id_negotiated = false;
900
40
  }
901
902
2.66k
  SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
903
2.66k
  if (hints && !hs->hints_requested &&
904
2.66k
      hints->server_random_tls12.size() == SSL3_RANDOM_SIZE) {
905
142
    OPENSSL_memcpy(ssl->s3->server_random, hints->server_random_tls12.data(),
906
142
                   SSL3_RANDOM_SIZE);
907
2.52k
  } else {
908
2.52k
    OPENSSL_timeval now = ssl_ctx_get_current_time(ssl->ctx.get());
909
2.52k
    CRYPTO_store_u32_be(ssl->s3->server_random,
910
2.52k
                        static_cast<uint32_t>(now.tv_sec));
911
2.52k
    if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
912
0
      return ssl_hs_error;
913
0
    }
914
2.52k
    if (hints && hs->hints_requested &&
915
2.52k
        !hints->server_random_tls12.CopyFrom(ssl->s3->server_random)) {
916
0
      return ssl_hs_error;
917
0
    }
918
2.52k
  }
919
920
  // Implement the TLS 1.3 anti-downgrade feature.
921
2.66k
  if (hs->max_version >= TLS1_3_VERSION) {
922
2.66k
    if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
923
1.94k
      if (hs->apply_jdk11_workaround) {
924
        // JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
925
        // here. However, the signal is only effective if all TLS 1.2
926
        // ServerHellos produced by the server are marked. Thus we send a
927
        // different non-standard signal for the time being, until JDK 11.0.2 is
928
        // released and clients have updated.
929
0
        copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
930
1.94k
      } else {
931
1.94k
        copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
932
1.94k
      }
933
1.94k
    } else {
934
722
      copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
935
722
    }
936
2.66k
  }
937
938
2.66k
  Span<const uint8_t> session_id;
939
2.66k
  if (ssl->session != nullptr) {
940
    // Echo the session ID from the ClientHello to indicate resumption.
941
46
    session_id = hs->session_id;
942
2.62k
  } else {
943
2.62k
    session_id = hs->new_session->session_id;
944
2.62k
  }
945
946
2.66k
  ScopedCBB cbb;
947
2.66k
  CBB body, session_id_bytes;
948
2.66k
  if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
949
2.66k
      !CBB_add_u16(&body, ssl->s3->version) ||
950
2.66k
      !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
951
2.66k
      !CBB_add_u8_length_prefixed(&body, &session_id_bytes) ||
952
2.66k
      !CBB_add_bytes(&session_id_bytes, session_id.data(), session_id.size()) ||
953
2.66k
      !CBB_add_u16(&body, SSL_CIPHER_get_protocol_id(hs->new_cipher)) ||
954
2.66k
      !CBB_add_u8(&body, 0 /* no compression */) ||
955
2.66k
      !ssl_add_serverhello_tlsext(hs, &body) ||
956
2.66k
      !ssl_add_message_cbb(ssl, cbb.get())) {
957
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
958
0
    return ssl_hs_error;
959
0
  }
960
961
2.66k
  if (ssl->session != nullptr) {
962
    // No additional hints to generate in resumption.
963
46
    if (hs->hints_requested) {
964
0
      return ssl_hs_hints_ready;
965
0
    }
966
46
    hs->state = state12_send_server_finished;
967
2.62k
  } else {
968
2.62k
    hs->state = state12_send_server_certificate;
969
2.62k
  }
970
2.66k
  return ssl_hs_ok;
971
2.66k
}
972
973
2.62k
static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
974
2.62k
  SSL *const ssl = hs->ssl;
975
2.62k
  ScopedCBB cbb;
976
977
2.62k
  if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
978
2.62k
    assert(hs->credential != nullptr);
979
2.62k
    if (!ssl_send_tls12_certificate(hs)) {
980
0
      return ssl_hs_error;
981
0
    }
982
983
2.62k
    if (hs->certificate_status_expected) {
984
773
      CBB body, ocsp_response;
985
773
      if (!ssl->method->init_message(ssl, cbb.get(), &body,
986
773
                                     SSL3_MT_CERTIFICATE_STATUS) ||
987
773
          !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
988
773
          !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
989
773
          !CBB_add_bytes(
990
773
              &ocsp_response,
991
773
              CRYPTO_BUFFER_data(hs->credential->ocsp_response.get()),
992
773
              CRYPTO_BUFFER_len(hs->credential->ocsp_response.get())) ||
993
773
          !ssl_add_message_cbb(ssl, cbb.get())) {
994
0
        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
995
0
        return ssl_hs_error;
996
0
      }
997
773
    }
998
2.62k
  }
999
1000
  // Assemble ServerKeyExchange parameters if needed.
1001
2.62k
  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1002
2.62k
  uint32_t alg_a = hs->new_cipher->algorithm_auth;
1003
2.62k
  if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
1004
2.62k
      ((alg_a & SSL_aPSK) && hs->config->psk_identity_hint)) {
1005
    // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
1006
    // the client and server randoms for the signing transcript.
1007
2.15k
    CBB child;
1008
2.15k
    if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
1009
2.15k
        !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
1010
2.15k
        !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
1011
0
      return ssl_hs_error;
1012
0
    }
1013
1014
    // PSK ciphers begin with an identity hint.
1015
2.15k
    if (alg_a & SSL_aPSK) {
1016
0
      size_t len = hs->config->psk_identity_hint == nullptr
1017
0
                       ? 0
1018
0
                       : strlen(hs->config->psk_identity_hint.get());
1019
0
      if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
1020
0
          !CBB_add_bytes(&child,
1021
0
                         (const uint8_t *)hs->config->psk_identity_hint.get(),
1022
0
                         len)) {
1023
0
        return ssl_hs_error;
1024
0
      }
1025
0
    }
1026
1027
2.15k
    if (alg_k & SSL_kECDHE) {
1028
2.15k
      assert(hs->new_session->group_id != 0);
1029
2.15k
      hs->key_shares[0] = SSLKeyShare::Create(hs->new_session->group_id);
1030
2.15k
      if (!hs->key_shares[0] ||                                  //
1031
2.15k
          !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||            //
1032
2.15k
          !CBB_add_u16(cbb.get(), hs->new_session->group_id) ||  //
1033
2.15k
          !CBB_add_u8_length_prefixed(cbb.get(), &child)) {
1034
0
        return ssl_hs_error;
1035
0
      }
1036
1037
2.15k
      SSL_HANDSHAKE_HINTS *const hints = hs->hints.get();
1038
2.15k
      bool hint_ok = false;
1039
2.15k
      if (hints && !hs->hints_requested &&
1040
2.15k
          hints->ecdhe_group_id == hs->new_session->group_id &&
1041
2.15k
          !hints->ecdhe_public_key.empty() &&
1042
2.15k
          !hints->ecdhe_private_key.empty()) {
1043
322
        CBS cbs = CBS(hints->ecdhe_private_key);
1044
322
        hint_ok = hs->key_shares[0]->DeserializePrivateKey(&cbs);
1045
322
      }
1046
2.15k
      if (hint_ok) {
1047
        // Reuse the ECDH key from handshake hints.
1048
309
        if (!CBB_add_bytes(&child, hints->ecdhe_public_key.data(),
1049
309
                           hints->ecdhe_public_key.size())) {
1050
0
          return ssl_hs_error;
1051
0
        }
1052
1.85k
      } else {
1053
        // Generate a key, and emit the public half.
1054
1.85k
        if (!hs->key_shares[0]->Generate(&child)) {
1055
0
          return ssl_hs_error;
1056
0
        }
1057
        // If generating hints, save the ECDHE key.
1058
1.85k
        if (hints && hs->hints_requested) {
1059
0
          bssl::ScopedCBB private_key_cbb;
1060
0
          if (!hints->ecdhe_public_key.CopyFrom(
1061
0
                  Span(CBB_data(&child), CBB_len(&child))) ||
1062
0
              !CBB_init(private_key_cbb.get(), 32) ||
1063
0
              !hs->key_shares[0]->SerializePrivateKey(private_key_cbb.get()) ||
1064
0
              !CBBFinishArray(private_key_cbb.get(),
1065
0
                              &hints->ecdhe_private_key)) {
1066
0
            return ssl_hs_error;
1067
0
          }
1068
0
          hints->ecdhe_group_id = hs->new_session->group_id;
1069
0
        }
1070
1.85k
      }
1071
2.15k
    } else {
1072
0
      assert(alg_k & SSL_kPSK);
1073
0
    }
1074
1075
2.15k
    if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
1076
0
      return ssl_hs_error;
1077
0
    }
1078
2.15k
  }
1079
1080
2.62k
  hs->state = state12_send_server_key_exchange;
1081
2.62k
  return ssl_hs_ok;
1082
2.62k
}
1083
1084
2.62k
static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
1085
2.62k
  SSL *const ssl = hs->ssl;
1086
1087
2.62k
  if (hs->server_params.size() == 0) {
1088
464
    hs->state = state12_send_server_hello_done;
1089
464
    return ssl_hs_ok;
1090
464
  }
1091
1092
2.15k
  ScopedCBB cbb;
1093
2.15k
  CBB body, child;
1094
2.15k
  if (!ssl->method->init_message(ssl, cbb.get(), &body,
1095
2.15k
                                 SSL3_MT_SERVER_KEY_EXCHANGE) ||
1096
      // |hs->server_params| contains a prefix for signing.
1097
2.15k
      hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
1098
2.15k
      !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
1099
2.15k
                     hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
1100
0
    return ssl_hs_error;
1101
0
  }
1102
1103
  // Add a signature.
1104
2.15k
  if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1105
    // Determine the signature algorithm.
1106
2.15k
    uint16_t signature_algorithm;
1107
2.15k
    if (!tls1_choose_signature_algorithm(hs, hs->credential.get(),
1108
2.15k
                                         &signature_algorithm)) {
1109
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1110
0
      return ssl_hs_error;
1111
0
    }
1112
2.15k
    if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1113
1.52k
      if (!CBB_add_u16(&body, signature_algorithm)) {
1114
0
        OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1115
0
        ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1116
0
        return ssl_hs_error;
1117
0
      }
1118
1.52k
    }
1119
1120
    // Add space for the signature.
1121
2.15k
    const size_t max_sig_len = EVP_PKEY_size(hs->credential->pubkey.get());
1122
2.15k
    uint8_t *ptr;
1123
2.15k
    if (!CBB_add_u16_length_prefixed(&body, &child) ||
1124
2.15k
        !CBB_reserve(&child, &ptr, max_sig_len)) {
1125
0
      return ssl_hs_error;
1126
0
    }
1127
1128
2.15k
    size_t sig_len;
1129
2.15k
    switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1130
2.15k
                                 signature_algorithm, hs->server_params)) {
1131
2.15k
      case ssl_private_key_success:
1132
2.15k
        if (!CBB_did_write(&child, sig_len)) {
1133
0
          return ssl_hs_error;
1134
0
        }
1135
2.15k
        break;
1136
2.15k
      case ssl_private_key_failure:
1137
0
        return ssl_hs_error;
1138
0
      case ssl_private_key_retry:
1139
0
        return ssl_hs_private_key_operation;
1140
2.15k
    }
1141
2.15k
  }
1142
1143
2.15k
  hs->can_release_private_key = true;
1144
2.15k
  if (!ssl_add_message_cbb(ssl, cbb.get())) {
1145
0
    return ssl_hs_error;
1146
0
  }
1147
1148
2.15k
  hs->server_params.Reset();
1149
1150
2.15k
  hs->state = state12_send_server_hello_done;
1151
2.15k
  return ssl_hs_ok;
1152
2.15k
}
1153
1154
2.62k
static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
1155
2.62k
  SSL *const ssl = hs->ssl;
1156
2.62k
  if (hs->hints_requested) {
1157
0
    return ssl_hs_hints_ready;
1158
0
  }
1159
1160
2.62k
  ScopedCBB cbb;
1161
2.62k
  CBB body;
1162
1163
2.62k
  if (hs->cert_request) {
1164
1.44k
    CBB cert_types, sigalgs_cbb;
1165
1.44k
    if (!ssl->method->init_message(ssl, cbb.get(), &body,
1166
1.44k
                                   SSL3_MT_CERTIFICATE_REQUEST) ||
1167
1.44k
        !CBB_add_u8_length_prefixed(&body, &cert_types) ||
1168
1.44k
        !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
1169
1.44k
        !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN) ||
1170
1.44k
        (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
1171
1.44k
         (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
1172
1.11k
          !tls12_add_verify_sigalgs(hs, &sigalgs_cbb))) ||
1173
1.44k
        !ssl_add_client_CA_list(hs, &body) ||
1174
1.44k
        !ssl_add_message_cbb(ssl, cbb.get())) {
1175
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1176
0
      return ssl_hs_error;
1177
0
    }
1178
1.44k
  }
1179
1180
2.62k
  if (!ssl->method->init_message(ssl, cbb.get(), &body,
1181
2.62k
                                 SSL3_MT_SERVER_HELLO_DONE) ||
1182
2.62k
      !ssl_add_message_cbb(ssl, cbb.get())) {
1183
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1184
0
    return ssl_hs_error;
1185
0
  }
1186
1187
2.62k
  hs->state = state12_read_client_certificate;
1188
2.62k
  return ssl_hs_flush;
1189
2.62k
}
1190
1191
4.96k
static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
1192
4.96k
  SSL *const ssl = hs->ssl;
1193
1194
4.96k
  if (hs->handback && hs->new_cipher->algorithm_mkey == SSL_kECDHE) {
1195
0
    return ssl_hs_handback;
1196
0
  }
1197
4.96k
  if (!hs->cert_request) {
1198
1.17k
    hs->state = state12_verify_client_certificate;
1199
1.17k
    return ssl_hs_ok;
1200
1.17k
  }
1201
1202
3.78k
  SSLMessage msg;
1203
3.78k
  if (!ssl->method->get_message(ssl, &msg)) {
1204
2.42k
    return ssl_hs_read_message;
1205
2.42k
  }
1206
1207
1.36k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
1208
2
    return ssl_hs_error;
1209
2
  }
1210
1211
1.36k
  if (!ssl_hash_message(hs, msg)) {
1212
0
    return ssl_hs_error;
1213
0
  }
1214
1215
1.36k
  CBS certificate_msg = msg.body;
1216
1.36k
  uint8_t alert = SSL_AD_DECODE_ERROR;
1217
1.36k
  if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
1218
1.36k
                            hs->config->retain_only_sha256_of_client_certs
1219
1.36k
                                ? hs->new_session->peer_sha256
1220
1.36k
                                : nullptr,
1221
1.36k
                            &certificate_msg, ssl->ctx->pool)) {
1222
373
    ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1223
373
    return ssl_hs_error;
1224
373
  }
1225
1226
988
  if (CBS_len(&certificate_msg) != 0 ||
1227
988
      !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
1228
182
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1229
182
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1230
182
    return ssl_hs_error;
1231
182
  }
1232
1233
806
  if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
1234
    // No client certificate so the handshake buffer may be discarded.
1235
12
    hs->transcript.FreeBuffer();
1236
1237
12
    if (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
1238
      // Fail for TLS only if we required a certificate
1239
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
1240
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1241
0
      return ssl_hs_error;
1242
0
    }
1243
1244
    // OpenSSL returns X509_V_OK when no certificates are received. This is
1245
    // classed by them as a bug, but it's assumed by at least NGINX.
1246
12
    hs->new_session->verify_result = X509_V_OK;
1247
794
  } else if (hs->config->retain_only_sha256_of_client_certs) {
1248
    // The hash will have been filled in.
1249
0
    hs->new_session->peer_sha256_valid = true;
1250
0
  }
1251
1252
806
  ssl->method->next_message(ssl);
1253
806
  hs->state = state12_verify_client_certificate;
1254
806
  return ssl_hs_ok;
1255
806
}
1256
1257
1.98k
static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
1258
1.98k
  if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) > 0) {
1259
794
    switch (ssl_verify_peer_cert(hs)) {
1260
794
      case ssl_verify_ok:
1261
794
        break;
1262
0
      case ssl_verify_invalid:
1263
0
        return ssl_hs_error;
1264
0
      case ssl_verify_retry:
1265
0
        return ssl_hs_certificate_verify;
1266
794
    }
1267
794
  }
1268
1269
1.98k
  hs->state = state12_read_client_key_exchange;
1270
1.98k
  return ssl_hs_ok;
1271
1.98k
}
1272
1273
4.53k
static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
1274
4.53k
  SSL *const ssl = hs->ssl;
1275
4.53k
  SSLMessage msg;
1276
4.53k
  if (!ssl->method->get_message(ssl, &msg)) {
1277
3.04k
    return ssl_hs_read_message;
1278
3.04k
  }
1279
1280
1.48k
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1281
4
    return ssl_hs_error;
1282
4
  }
1283
1284
1.48k
  CBS client_key_exchange = msg.body;
1285
1.48k
  uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1286
1.48k
  uint32_t alg_a = hs->new_cipher->algorithm_auth;
1287
1288
  // If using a PSK key exchange, parse the PSK identity.
1289
1.48k
  if (alg_a & SSL_aPSK) {
1290
0
    CBS psk_identity;
1291
1292
    // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
1293
    // then this is the only field in the message.
1294
0
    if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
1295
0
        ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
1296
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1297
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1298
0
      return ssl_hs_error;
1299
0
    }
1300
1301
0
    if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
1302
0
        CBS_contains_zero_byte(&psk_identity)) {
1303
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
1304
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1305
0
      return ssl_hs_error;
1306
0
    }
1307
0
    char *raw = nullptr;
1308
0
    if (!CBS_strdup(&psk_identity, &raw)) {
1309
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1310
0
      return ssl_hs_error;
1311
0
    }
1312
0
    hs->new_session->psk_identity.reset(raw);
1313
0
  }
1314
1315
  // Depending on the key exchange method, compute |premaster_secret|.
1316
1.48k
  Array<uint8_t> premaster_secret;
1317
1.48k
  if (alg_k & SSL_kRSA) {
1318
18
    CBS encrypted_premaster_secret;
1319
18
    if (!CBS_get_u16_length_prefixed(&client_key_exchange,
1320
18
                                     &encrypted_premaster_secret) ||
1321
18
        CBS_len(&client_key_exchange) != 0) {
1322
11
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1323
11
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1324
11
      return ssl_hs_error;
1325
11
    }
1326
1327
    // Allocate a buffer large enough for an RSA decryption.
1328
7
    Array<uint8_t> decrypt_buf;
1329
7
    if (!decrypt_buf.InitForOverwrite(
1330
7
            EVP_PKEY_size(hs->credential->pubkey.get()))) {
1331
0
      return ssl_hs_error;
1332
0
    }
1333
1334
    // Decrypt with no padding. PKCS#1 padding will be removed as part of the
1335
    // timing-sensitive code below.
1336
7
    size_t decrypt_len;
1337
7
    switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
1338
7
                                    decrypt_buf.size(),
1339
7
                                    encrypted_premaster_secret)) {
1340
3
      case ssl_private_key_success:
1341
3
        break;
1342
4
      case ssl_private_key_failure:
1343
4
        return ssl_hs_error;
1344
0
      case ssl_private_key_retry:
1345
0
        return ssl_hs_private_key_operation;
1346
7
    }
1347
1348
3
    if (decrypt_len != decrypt_buf.size()) {
1349
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1350
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1351
0
      return ssl_hs_error;
1352
0
    }
1353
1354
3
    CONSTTIME_SECRET(decrypt_buf.data(), decrypt_len);
1355
1356
    // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
1357
    // section 7.4.7.1.
1358
3
    if (!premaster_secret.InitForOverwrite(SSL_MAX_MASTER_KEY_LENGTH) ||
1359
3
        !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
1360
0
      return ssl_hs_error;
1361
0
    }
1362
1363
    // The smallest padded premaster is 11 bytes of overhead. Small keys are
1364
    // publicly invalid.
1365
3
    if (decrypt_len < 11 + premaster_secret.size()) {
1366
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
1367
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1368
0
      return ssl_hs_error;
1369
0
    }
1370
1371
    // Check the padding. See RFC 3447, section 7.2.2.
1372
3
    size_t padding_len = decrypt_len - premaster_secret.size();
1373
3
    uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
1374
3
                   constant_time_eq_int_8(decrypt_buf[1], 2);
1375
618
    for (size_t i = 2; i < padding_len - 1; i++) {
1376
615
      good &= ~constant_time_is_zero_8(decrypt_buf[i]);
1377
615
    }
1378
3
    good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
1379
1380
    // The premaster secret must begin with |client_version|. This too must be
1381
    // checked in constant time (http://eprint.iacr.org/2003/052/).
1382
3
    good &= constant_time_eq_8(decrypt_buf[padding_len],
1383
3
                               (unsigned)(hs->client_version >> 8));
1384
3
    good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
1385
3
                               (unsigned)(hs->client_version & 0xff));
1386
1387
    // Select, in constant time, either the decrypted premaster or the random
1388
    // premaster based on |good|.
1389
147
    for (size_t i = 0; i < premaster_secret.size(); i++) {
1390
144
      premaster_secret[i] = constant_time_select_8(
1391
144
          good, decrypt_buf[padding_len + i], premaster_secret[i]);
1392
144
    }
1393
1.46k
  } else if (alg_k & SSL_kECDHE) {
1394
    // Parse the ClientKeyExchange.
1395
1.46k
    CBS ciphertext;
1396
1.46k
    if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ciphertext) ||
1397
1.46k
        CBS_len(&client_key_exchange) != 0) {
1398
5
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1399
5
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1400
5
      return ssl_hs_error;
1401
5
    }
1402
1403
    // Decapsulate the premaster secret.
1404
1.46k
    uint8_t alert = SSL_AD_DECODE_ERROR;
1405
1.46k
    if (!hs->key_shares[0]->Decap(&premaster_secret, &alert, ciphertext)) {
1406
31
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1407
31
      return ssl_hs_error;
1408
31
    }
1409
1410
    // The key exchange state may now be discarded.
1411
1.43k
    hs->key_shares[0].reset();
1412
1.43k
    hs->key_shares[1].reset();
1413
1.43k
  } else if (!(alg_k & SSL_kPSK)) {
1414
0
    OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1415
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1416
0
    return ssl_hs_error;
1417
0
  }
1418
1419
  // For a PSK cipher suite, the actual pre-master secret is combined with the
1420
  // pre-shared key.
1421
1.43k
  if (alg_a & SSL_aPSK) {
1422
0
    if (hs->config->psk_server_callback == NULL) {
1423
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1424
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1425
0
      return ssl_hs_error;
1426
0
    }
1427
1428
    // Look up the key for the identity.
1429
0
    uint8_t psk[PSK_MAX_PSK_LEN];
1430
0
    unsigned psk_len = hs->config->psk_server_callback(
1431
0
        ssl, hs->new_session->psk_identity.get(), psk, sizeof(psk));
1432
0
    if (psk_len > PSK_MAX_PSK_LEN) {
1433
0
      OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1434
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1435
0
      return ssl_hs_error;
1436
0
    } else if (psk_len == 0) {
1437
      // PSK related to the given identity not found.
1438
0
      OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1439
0
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
1440
0
      return ssl_hs_error;
1441
0
    }
1442
1443
0
    if (alg_k & SSL_kPSK) {
1444
      // In plain PSK, other_secret is a block of 0s with the same length as the
1445
      // pre-shared key.
1446
0
      if (!premaster_secret.Init(psk_len)) {
1447
0
        return ssl_hs_error;
1448
0
      }
1449
0
    }
1450
1451
0
    ScopedCBB new_premaster;
1452
0
    CBB child;
1453
0
    if (!CBB_init(new_premaster.get(),
1454
0
                  2 + psk_len + 2 + premaster_secret.size()) ||
1455
0
        !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1456
0
        !CBB_add_bytes(&child, premaster_secret.data(),
1457
0
                       premaster_secret.size()) ||
1458
0
        !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
1459
0
        !CBB_add_bytes(&child, psk, psk_len) ||
1460
0
        !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
1461
0
      return ssl_hs_error;
1462
0
    }
1463
0
  }
1464
1465
1.43k
  if (!ssl_hash_message(hs, msg)) {
1466
0
    return ssl_hs_error;
1467
0
  }
1468
1469
  // Compute the master secret.
1470
1.43k
  hs->new_session->secret.ResizeForOverwrite(SSL3_MASTER_SECRET_SIZE);
1471
1.43k
  if (!tls1_generate_master_secret(hs, Span(hs->new_session->secret),
1472
1.43k
                                   premaster_secret)) {
1473
0
    return ssl_hs_error;
1474
0
  }
1475
1.43k
  hs->new_session->extended_master_secret = hs->extended_master_secret;
1476
  // Declassify the secret to undo the RSA decryption validation above. We are
1477
  // not currently running most of the TLS library with constant-time
1478
  // validation.
1479
  // TODO(crbug.com/42290551): Remove this and cover the TLS library too.
1480
1.43k
  CONSTTIME_DECLASSIFY(hs->new_session->secret.data(),
1481
1.43k
                       hs->new_session->secret.size());
1482
1.43k
  hs->can_release_private_key = true;
1483
1484
1.43k
  ssl->method->next_message(ssl);
1485
1.43k
  hs->state = state12_read_client_certificate_verify;
1486
1.43k
  return ssl_hs_ok;
1487
1.43k
}
1488
1489
2.34k
static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
1490
2.34k
  SSL *const ssl = hs->ssl;
1491
1492
  // Only RSA and ECDSA client certificates are supported, so a
1493
  // CertificateVerify is required if and only if there's a client certificate.
1494
2.34k
  if (!hs->peer_pubkey) {
1495
685
    hs->transcript.FreeBuffer();
1496
685
    hs->state = state12_read_change_cipher_spec;
1497
685
    return ssl_hs_ok;
1498
685
  }
1499
1500
1.65k
  SSLMessage msg;
1501
1.65k
  if (!ssl->method->get_message(ssl, &msg)) {
1502
921
    return ssl_hs_read_message;
1503
921
  }
1504
1505
734
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
1506
1
    return ssl_hs_error;
1507
1
  }
1508
1509
  // The peer certificate must be valid for signing.
1510
733
  const CRYPTO_BUFFER *leaf =
1511
733
      sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1512
733
  CBS leaf_cbs;
1513
733
  CRYPTO_BUFFER_init_CBS(leaf, &leaf_cbs);
1514
733
  if (!ssl_cert_check_key_usage(&leaf_cbs, key_usage_digital_signature)) {
1515
13
    return ssl_hs_error;
1516
13
  }
1517
1518
720
  CBS certificate_verify = msg.body, signature;
1519
1520
  // Determine the signature algorithm.
1521
720
  uint16_t signature_algorithm = 0;
1522
720
  if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1523
493
    if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
1524
2
      OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1525
2
      ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1526
2
      return ssl_hs_error;
1527
2
    }
1528
491
    uint8_t alert = SSL_AD_DECODE_ERROR;
1529
491
    if (!tls12_check_peer_sigalg(hs, &alert, signature_algorithm,
1530
491
                                 hs->peer_pubkey.get())) {
1531
13
      ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1532
13
      return ssl_hs_error;
1533
13
    }
1534
478
    hs->new_session->peer_signature_algorithm = signature_algorithm;
1535
478
  } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1536
227
                                                  hs->peer_pubkey.get())) {
1537
2
    OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1538
2
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1539
2
    return ssl_hs_error;
1540
2
  }
1541
1542
  // Parse and verify the signature.
1543
703
  if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
1544
703
      CBS_len(&certificate_verify) != 0) {
1545
8
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1546
8
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1547
8
    return ssl_hs_error;
1548
8
  }
1549
1550
695
  if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1551
695
                             hs->peer_pubkey.get(), hs->transcript.buffer())) {
1552
0
    OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1553
0
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1554
0
    return ssl_hs_error;
1555
0
  }
1556
1557
  // The handshake buffer is no longer necessary, and we may hash the current
1558
  // message.
1559
695
  hs->transcript.FreeBuffer();
1560
695
  if (!ssl_hash_message(hs, msg)) {
1561
0
    return ssl_hs_error;
1562
0
  }
1563
1564
695
  ssl->method->next_message(ssl);
1565
695
  hs->state = state12_read_change_cipher_spec;
1566
695
  return ssl_hs_ok;
1567
695
}
1568
1569
1.42k
static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
1570
1.42k
  if (hs->handback && hs->ssl->session != NULL) {
1571
0
    return ssl_hs_handback;
1572
0
  }
1573
1.42k
  hs->state = state12_process_change_cipher_spec;
1574
1.42k
  return ssl_hs_read_change_cipher_spec;
1575
1.42k
}
1576
1577
401
static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1578
401
  if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1579
0
    return ssl_hs_error;
1580
0
  }
1581
1582
401
  hs->state = state12_read_next_proto;
1583
401
  return ssl_hs_ok;
1584
401
}
1585
1586
471
static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
1587
471
  SSL *const ssl = hs->ssl;
1588
1589
471
  if (!hs->next_proto_neg_seen) {
1590
388
    hs->state = state12_read_channel_id;
1591
388
    return ssl_hs_ok;
1592
388
  }
1593
1594
83
  SSLMessage msg;
1595
83
  if (!ssl->method->get_message(ssl, &msg)) {
1596
78
    return ssl_hs_read_message;
1597
78
  }
1598
1599
5
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
1600
5
      !ssl_hash_message(hs, msg)) {
1601
1
    return ssl_hs_error;
1602
1
  }
1603
1604
4
  CBS next_protocol = msg.body, selected_protocol, padding;
1605
4
  if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
1606
4
      !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
1607
4
      CBS_len(&next_protocol) != 0) {
1608
3
    OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1609
3
    ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1610
3
    return ssl_hs_error;
1611
3
  }
1612
1613
1
  if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
1614
0
    return ssl_hs_error;
1615
0
  }
1616
1617
1
  ssl->method->next_message(ssl);
1618
1
  hs->state = state12_read_channel_id;
1619
1
  return ssl_hs_ok;
1620
1
}
1621
1622
753
static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
1623
753
  SSL *const ssl = hs->ssl;
1624
1625
753
  if (!hs->channel_id_negotiated) {
1626
205
    hs->state = state12_read_client_finished;
1627
205
    return ssl_hs_ok;
1628
205
  }
1629
1630
548
  SSLMessage msg;
1631
548
  if (!ssl->method->get_message(ssl, &msg)) {
1632
381
    return ssl_hs_read_message;
1633
381
  }
1634
1635
167
  if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
1636
167
      !tls1_verify_channel_id(hs, msg) ||  //
1637
167
      !ssl_hash_message(hs, msg)) {
1638
31
    return ssl_hs_error;
1639
31
  }
1640
1641
136
  ssl->method->next_message(ssl);
1642
136
  hs->state = state12_read_client_finished;
1643
136
  return ssl_hs_ok;
1644
167
}
1645
1646
990
static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
1647
990
  SSL *const ssl = hs->ssl;
1648
990
  enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1649
990
  if (wait != ssl_hs_ok) {
1650
832
    return wait;
1651
832
  }
1652
1653
158
  if (ssl->session != NULL) {
1654
1
    hs->state = state12_finish_server_handshake;
1655
157
  } else {
1656
157
    hs->state = state12_send_server_finished;
1657
157
  }
1658
1659
  // If this is a full handshake with ChannelID then record the handshake
1660
  // hashes in |hs->new_session| in case we need them to verify a
1661
  // ChannelID signature on a resumption of this session in the future.
1662
158
  if (ssl->session == NULL && ssl->s3->channel_id_valid &&
1663
158
      !tls1_record_handshake_hashes_for_channel_id(hs)) {
1664
0
    return ssl_hs_error;
1665
0
  }
1666
1667
158
  return ssl_hs_ok;
1668
158
}
1669
1670
203
static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
1671
203
  SSL *const ssl = hs->ssl;
1672
1673
203
  if (hs->ticket_expected) {
1674
77
    const SSL_SESSION *session;
1675
77
    UniquePtr<SSL_SESSION> session_copy;
1676
77
    if (ssl->session == NULL) {
1677
      // Fix the timeout to measure from the ticket issuance time.
1678
61
      ssl_session_rebase_time(ssl, hs->new_session.get());
1679
61
      session = hs->new_session.get();
1680
61
    } else {
1681
      // We are renewing an existing session. Duplicate the session to adjust
1682
      // the timeout.
1683
16
      session_copy =
1684
16
          SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1685
16
      if (!session_copy) {
1686
0
        return ssl_hs_error;
1687
0
      }
1688
1689
16
      ssl_session_rebase_time(ssl, session_copy.get());
1690
16
      session = session_copy.get();
1691
16
    }
1692
1693
77
    ScopedCBB cbb;
1694
77
    CBB body, ticket;
1695
77
    if (!ssl->method->init_message(ssl, cbb.get(), &body,
1696
77
                                   SSL3_MT_NEW_SESSION_TICKET) ||
1697
77
        !CBB_add_u32(&body, session->timeout) ||
1698
77
        !CBB_add_u16_length_prefixed(&body, &ticket) ||
1699
77
        !ssl_encrypt_ticket(hs, &ticket, session) ||
1700
        // |ticket| may be empty to skip sending a ticket. In TLS 1.2, servers
1701
        // skip sending tickets by sending empty NewSessionTicket, so no special
1702
        // handling is needed.
1703
77
        !ssl_add_message_cbb(ssl, cbb.get())) {
1704
0
      return ssl_hs_error;
1705
0
    }
1706
77
  }
1707
1708
203
  if (!ssl->method->add_change_cipher_spec(ssl) ||     //
1709
203
      !tls1_change_cipher_state(hs, evp_aead_seal) ||  //
1710
203
      !ssl_send_finished(hs)) {
1711
0
    return ssl_hs_error;
1712
0
  }
1713
1714
203
  if (ssl->session != NULL) {
1715
46
    hs->state = state12_read_change_cipher_spec;
1716
157
  } else {
1717
157
    hs->state = state12_finish_server_handshake;
1718
157
  }
1719
203
  return ssl_hs_flush;
1720
203
}
1721
1722
408
static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
1723
408
  SSL *const ssl = hs->ssl;
1724
1725
408
  if (hs->handback) {
1726
0
    return ssl_hs_handback;
1727
0
  }
1728
1729
408
  ssl->method->on_handshake_complete(ssl);
1730
1731
  // If we aren't retaining peer certificates then we can discard it now.
1732
408
  if (hs->new_session != NULL &&
1733
408
      hs->config->retain_only_sha256_of_client_certs) {
1734
0
    hs->new_session->certs.reset();
1735
0
    ssl->ctx->x509_method->session_clear(hs->new_session.get());
1736
0
  }
1737
1738
408
  bool has_new_session = hs->new_session != nullptr;
1739
408
  if (has_new_session) {
1740
407
    assert(ssl->session == nullptr);
1741
407
    ssl->s3->established_session = std::move(hs->new_session);
1742
407
    ssl->s3->established_session->not_resumable = false;
1743
407
  } else {
1744
1
    assert(ssl->session != nullptr);
1745
1
    ssl->s3->established_session = UpRef(ssl->session);
1746
1
  }
1747
1748
408
  hs->handshake_finalized = true;
1749
408
  ssl->s3->initial_handshake_complete = true;
1750
408
  if (has_new_session) {
1751
407
    ssl_update_cache(ssl);
1752
407
  }
1753
1754
408
  hs->state = state12_done;
1755
408
  return ssl_hs_ok;
1756
408
}
1757
1758
35.2k
enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
1759
71.1k
  while (hs->state != state12_done) {
1760
70.7k
    enum ssl_hs_wait_t ret = ssl_hs_error;
1761
70.7k
    enum tls12_server_hs_state_t state =
1762
70.7k
        static_cast<enum tls12_server_hs_state_t>(hs->state);
1763
70.7k
    switch (state) {
1764
4.82k
      case state12_start_accept:
1765
4.82k
        ret = do_start_accept(hs);
1766
4.82k
        break;
1767
20.8k
      case state12_read_client_hello:
1768
20.8k
        ret = do_read_client_hello(hs);
1769
20.8k
        break;
1770
4.09k
      case state12_read_client_hello_after_ech:
1771
4.09k
        ret = do_read_client_hello_after_ech(hs);
1772
4.09k
        break;
1773
3.80k
      case state12_cert_callback:
1774
3.80k
        ret = do_cert_callback(hs);
1775
3.80k
        break;
1776
5.29k
      case state12_tls13:
1777
5.29k
        ret = do_tls13(hs);
1778
5.29k
        break;
1779
2.84k
      case state12_select_parameters:
1780
2.84k
        ret = do_select_parameters(hs);
1781
2.84k
        break;
1782
2.66k
      case state12_send_server_hello:
1783
2.66k
        ret = do_send_server_hello(hs);
1784
2.66k
        break;
1785
2.62k
      case state12_send_server_certificate:
1786
2.62k
        ret = do_send_server_certificate(hs);
1787
2.62k
        break;
1788
2.62k
      case state12_send_server_key_exchange:
1789
2.62k
        ret = do_send_server_key_exchange(hs);
1790
2.62k
        break;
1791
2.62k
      case state12_send_server_hello_done:
1792
2.62k
        ret = do_send_server_hello_done(hs);
1793
2.62k
        break;
1794
4.96k
      case state12_read_client_certificate:
1795
4.96k
        ret = do_read_client_certificate(hs);
1796
4.96k
        break;
1797
1.98k
      case state12_verify_client_certificate:
1798
1.98k
        ret = do_verify_client_certificate(hs);
1799
1.98k
        break;
1800
4.53k
      case state12_read_client_key_exchange:
1801
4.53k
        ret = do_read_client_key_exchange(hs);
1802
4.53k
        break;
1803
2.34k
      case state12_read_client_certificate_verify:
1804
2.34k
        ret = do_read_client_certificate_verify(hs);
1805
2.34k
        break;
1806
1.42k
      case state12_read_change_cipher_spec:
1807
1.42k
        ret = do_read_change_cipher_spec(hs);
1808
1.42k
        break;
1809
401
      case state12_process_change_cipher_spec:
1810
401
        ret = do_process_change_cipher_spec(hs);
1811
401
        break;
1812
471
      case state12_read_next_proto:
1813
471
        ret = do_read_next_proto(hs);
1814
471
        break;
1815
753
      case state12_read_channel_id:
1816
753
        ret = do_read_channel_id(hs);
1817
753
        break;
1818
990
      case state12_read_client_finished:
1819
990
        ret = do_read_client_finished(hs);
1820
990
        break;
1821
203
      case state12_send_server_finished:
1822
203
        ret = do_send_server_finished(hs);
1823
203
        break;
1824
408
      case state12_finish_server_handshake:
1825
408
        ret = do_finish_server_handshake(hs);
1826
408
        break;
1827
0
      case state12_done:
1828
0
        ret = ssl_hs_ok;
1829
0
        break;
1830
70.7k
    }
1831
1832
70.7k
    if (hs->state != state) {
1833
40.0k
      ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
1834
40.0k
    }
1835
1836
70.7k
    if (ret != ssl_hs_ok) {
1837
34.8k
      return ret;
1838
34.8k
    }
1839
70.7k
  }
1840
1841
408
  ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
1842
408
  return ssl_hs_ok;
1843
35.2k
}
1844
1845
0
const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
1846
0
  enum tls12_server_hs_state_t state =
1847
0
      static_cast<enum tls12_server_hs_state_t>(hs->state);
1848
0
  switch (state) {
1849
0
    case state12_start_accept:
1850
0
      return "TLS server start_accept";
1851
0
    case state12_read_client_hello:
1852
0
      return "TLS server read_client_hello";
1853
0
    case state12_read_client_hello_after_ech:
1854
0
      return "TLS server read_client_hello_after_ech";
1855
0
    case state12_cert_callback:
1856
0
      return "TLS server cert_callback";
1857
0
    case state12_tls13:
1858
0
      return tls13_server_handshake_state(hs);
1859
0
    case state12_select_parameters:
1860
0
      return "TLS server select_parameters";
1861
0
    case state12_send_server_hello:
1862
0
      return "TLS server send_server_hello";
1863
0
    case state12_send_server_certificate:
1864
0
      return "TLS server send_server_certificate";
1865
0
    case state12_send_server_key_exchange:
1866
0
      return "TLS server send_server_key_exchange";
1867
0
    case state12_send_server_hello_done:
1868
0
      return "TLS server send_server_hello_done";
1869
0
    case state12_read_client_certificate:
1870
0
      return "TLS server read_client_certificate";
1871
0
    case state12_verify_client_certificate:
1872
0
      return "TLS server verify_client_certificate";
1873
0
    case state12_read_client_key_exchange:
1874
0
      return "TLS server read_client_key_exchange";
1875
0
    case state12_read_client_certificate_verify:
1876
0
      return "TLS server read_client_certificate_verify";
1877
0
    case state12_read_change_cipher_spec:
1878
0
      return "TLS server read_change_cipher_spec";
1879
0
    case state12_process_change_cipher_spec:
1880
0
      return "TLS server process_change_cipher_spec";
1881
0
    case state12_read_next_proto:
1882
0
      return "TLS server read_next_proto";
1883
0
    case state12_read_channel_id:
1884
0
      return "TLS server read_channel_id";
1885
0
    case state12_read_client_finished:
1886
0
      return "TLS server read_client_finished";
1887
0
    case state12_send_server_finished:
1888
0
      return "TLS server send_server_finished";
1889
0
    case state12_finish_server_handshake:
1890
0
      return "TLS server finish_server_handshake";
1891
0
    case state12_done:
1892
0
      return "TLS server done";
1893
0
  }
1894
1895
0
  return "TLS server unknown";
1896
0
}
1897
1898
BSSL_NAMESPACE_END