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