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