xref: /aosp_15_r20/external/boringssl/src/ssl/handshake_client.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
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                                    hs->peer_pubkey.get())) {
1174         ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1175         return ssl_hs_error;
1176       }
1177       hs->new_session->peer_signature_algorithm = signature_algorithm;
1178     } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
1179                                                     hs->peer_pubkey.get())) {
1180       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
1181       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
1182       return ssl_hs_error;
1183     }
1184 
1185     // The last field in |server_key_exchange| is the signature.
1186     CBS signature;
1187     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
1188         CBS_len(&server_key_exchange) != 0) {
1189       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1190       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1191       return ssl_hs_error;
1192     }
1193 
1194     ScopedCBB transcript;
1195     Array<uint8_t> transcript_data;
1196     if (!CBB_init(transcript.get(),
1197                   2 * SSL3_RANDOM_SIZE + CBS_len(&parameter)) ||
1198         !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
1199                        SSL3_RANDOM_SIZE) ||
1200         !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
1201                        SSL3_RANDOM_SIZE) ||
1202         !CBB_add_bytes(transcript.get(), CBS_data(&parameter),
1203                        CBS_len(&parameter)) ||
1204         !CBBFinishArray(transcript.get(), &transcript_data)) {
1205       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1206       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1207       return ssl_hs_error;
1208     }
1209 
1210     if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
1211                                hs->peer_pubkey.get(), transcript_data)) {
1212       // bad signature
1213       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
1214       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
1215       return ssl_hs_error;
1216     }
1217   } else {
1218     // PSK ciphers are the only supported certificate-less ciphers.
1219     assert(alg_a == SSL_aPSK);
1220 
1221     if (CBS_len(&server_key_exchange) > 0) {
1222       OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
1223       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1224       return ssl_hs_error;
1225     }
1226   }
1227 
1228   ssl->method->next_message(ssl);
1229   hs->state = state_read_certificate_request;
1230   return ssl_hs_ok;
1231 }
1232 
do_read_certificate_request(SSL_HANDSHAKE * hs)1233 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
1234   SSL *const ssl = hs->ssl;
1235 
1236   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1237     hs->state = state_read_server_hello_done;
1238     return ssl_hs_ok;
1239   }
1240 
1241   SSLMessage msg;
1242   if (!ssl->method->get_message(ssl, &msg)) {
1243     return ssl_hs_read_message;
1244   }
1245 
1246   if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
1247     // If we get here we don't need the handshake buffer as we won't be doing
1248     // client auth.
1249     hs->transcript.FreeBuffer();
1250     hs->state = state_read_server_hello_done;
1251     return ssl_hs_ok;
1252   }
1253 
1254   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
1255       !ssl_hash_message(hs, msg)) {
1256     return ssl_hs_error;
1257   }
1258 
1259   // Get the certificate types.
1260   CBS body = msg.body, certificate_types;
1261   if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
1262     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1263     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1264     return ssl_hs_error;
1265   }
1266 
1267   if (!hs->certificate_types.CopyFrom(certificate_types)) {
1268     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1269     return ssl_hs_error;
1270   }
1271 
1272   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1273     CBS supported_signature_algorithms;
1274     if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
1275         !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
1276       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1277       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1278       return ssl_hs_error;
1279     }
1280   }
1281 
1282   uint8_t alert = SSL_AD_DECODE_ERROR;
1283   UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
1284       ssl_parse_client_CA_list(ssl, &alert, &body);
1285   if (!ca_names) {
1286     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1287     return ssl_hs_error;
1288   }
1289 
1290   if (CBS_len(&body) != 0) {
1291     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1292     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1293     return ssl_hs_error;
1294   }
1295 
1296   hs->cert_request = true;
1297   hs->ca_names = std::move(ca_names);
1298   ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
1299 
1300   ssl->method->next_message(ssl);
1301   hs->state = state_read_server_hello_done;
1302   return ssl_hs_ok;
1303 }
1304 
do_read_server_hello_done(SSL_HANDSHAKE * hs)1305 static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
1306   SSL *const ssl = hs->ssl;
1307   SSLMessage msg;
1308   if (!ssl->method->get_message(ssl, &msg)) {
1309     return ssl_hs_read_message;
1310   }
1311 
1312   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
1313       !ssl_hash_message(hs, msg)) {
1314     return ssl_hs_error;
1315   }
1316 
1317   // ServerHelloDone is empty.
1318   if (CBS_len(&msg.body) != 0) {
1319     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1320     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1321     return ssl_hs_error;
1322   }
1323 
1324   // ServerHelloDone should be the end of the flight.
1325   if (ssl->method->has_unprocessed_handshake_data(ssl)) {
1326     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1327     OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESS_HANDSHAKE_DATA);
1328     return ssl_hs_error;
1329   }
1330 
1331   ssl->method->next_message(ssl);
1332   hs->state = state_send_client_certificate;
1333   return ssl_hs_ok;
1334 }
1335 
check_credential(SSL_HANDSHAKE * hs,const SSL_CREDENTIAL * cred,uint16_t * out_sigalg)1336 static bool check_credential(SSL_HANDSHAKE *hs, const SSL_CREDENTIAL *cred,
1337                              uint16_t *out_sigalg) {
1338   if (cred->type != SSLCredentialType::kX509) {
1339     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1340     return false;
1341   }
1342 
1343   if (hs->config->check_client_certificate_type) {
1344     // Check the certificate types advertised by the peer.
1345     uint8_t cert_type;
1346     switch (EVP_PKEY_id(cred->pubkey.get())) {
1347       case EVP_PKEY_RSA:
1348         cert_type = SSL3_CT_RSA_SIGN;
1349         break;
1350       case EVP_PKEY_EC:
1351       case EVP_PKEY_ED25519:
1352         cert_type = TLS_CT_ECDSA_SIGN;
1353         break;
1354       default:
1355         OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1356         return false;
1357     }
1358     if (std::find(hs->certificate_types.begin(), hs->certificate_types.end(),
1359                   cert_type) == hs->certificate_types.end()) {
1360       OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1361       return false;
1362     }
1363   }
1364 
1365   // All currently supported credentials require a signature. Note this does not
1366   // check the ECDSA curve. Prior to TLS 1.3, there is no way to determine which
1367   // ECDSA curves are supported by the peer, so we must assume all curves are
1368   // supported.
1369   return tls1_choose_signature_algorithm(hs, cred, out_sigalg);
1370 }
1371 
do_send_client_certificate(SSL_HANDSHAKE * hs)1372 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
1373   SSL *const ssl = hs->ssl;
1374 
1375   // The peer didn't request a certificate.
1376   if (!hs->cert_request) {
1377     hs->state = state_send_client_key_exchange;
1378     return ssl_hs_ok;
1379   }
1380 
1381   if (ssl->s3->ech_status == ssl_ech_rejected) {
1382     // Do not send client certificates on ECH reject. We have not authenticated
1383     // the server for the name that can learn the certificate.
1384     SSL_certs_clear(ssl);
1385   } else if (hs->config->cert->cert_cb != nullptr) {
1386     // Call cert_cb to update the certificate.
1387     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
1388     if (rv == 0) {
1389       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
1390       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
1391       return ssl_hs_error;
1392     }
1393     if (rv < 0) {
1394       hs->state = state_send_client_certificate;
1395       return ssl_hs_x509_lookup;
1396     }
1397   }
1398 
1399   Array<SSL_CREDENTIAL *> creds;
1400   if (!ssl_get_credential_list(hs, &creds)) {
1401     return ssl_hs_error;
1402   }
1403 
1404   if (creds.empty()) {
1405     // If there were no credentials, proceed without a client certificate. In
1406     // this case, the handshake buffer may be released early.
1407     hs->transcript.FreeBuffer();
1408   } else {
1409     // Select the credential to use.
1410     for (SSL_CREDENTIAL *cred : creds) {
1411       ERR_clear_error();
1412       uint16_t sigalg;
1413       if (check_credential(hs, cred, &sigalg)) {
1414         hs->credential = UpRef(cred);
1415         hs->signature_algorithm = sigalg;
1416         break;
1417       }
1418     }
1419     if (hs->credential == nullptr) {
1420       // The error from the last attempt is in the error queue.
1421       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1422       return ssl_hs_error;
1423     }
1424   }
1425 
1426   if (!ssl_send_tls12_certificate(hs)) {
1427     return ssl_hs_error;
1428   }
1429 
1430   hs->state = state_send_client_key_exchange;
1431   return ssl_hs_ok;
1432 }
1433 
1434 static_assert(sizeof(size_t) >= sizeof(unsigned),
1435               "size_t is smaller than unsigned");
1436 
do_send_client_key_exchange(SSL_HANDSHAKE * hs)1437 static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
1438   SSL *const ssl = hs->ssl;
1439   ScopedCBB cbb;
1440   CBB body;
1441   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1442                                  SSL3_MT_CLIENT_KEY_EXCHANGE)) {
1443     return ssl_hs_error;
1444   }
1445 
1446   Array<uint8_t> pms;
1447   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
1448   uint32_t alg_a = hs->new_cipher->algorithm_auth;
1449   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
1450     const CRYPTO_BUFFER *leaf =
1451         sk_CRYPTO_BUFFER_value(hs->new_session->certs.get(), 0);
1452     CBS leaf_cbs;
1453     CRYPTO_BUFFER_init_CBS(leaf, &leaf_cbs);
1454 
1455     // Check the key usage matches the cipher suite. We do this unconditionally
1456     // for non-RSA certificates. In particular, it's needed to distinguish ECDH
1457     // certificates, which we do not support, from ECDSA certificates.
1458     // Historically, we have not checked RSA key usages, so it is controlled by
1459     // a flag for now. See https://crbug.com/795089.
1460     ssl_key_usage_t intended_use = (alg_k & SSL_kRSA)
1461                                        ? key_usage_encipherment
1462                                        : key_usage_digital_signature;
1463     if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) {
1464       if (hs->config->enforce_rsa_key_usage ||
1465           EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) {
1466         return ssl_hs_error;
1467       }
1468       ERR_clear_error();
1469       ssl->s3->was_key_usage_invalid = true;
1470     }
1471   }
1472 
1473   // If using a PSK key exchange, prepare the pre-shared key.
1474   unsigned psk_len = 0;
1475   uint8_t psk[PSK_MAX_PSK_LEN];
1476   if (alg_a & SSL_aPSK) {
1477     if (hs->config->psk_client_callback == NULL) {
1478       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
1479       return ssl_hs_error;
1480     }
1481 
1482     char identity[PSK_MAX_IDENTITY_LEN + 1];
1483     OPENSSL_memset(identity, 0, sizeof(identity));
1484     psk_len = hs->config->psk_client_callback(
1485         ssl, hs->peer_psk_identity_hint.get(), identity, sizeof(identity), psk,
1486         sizeof(psk));
1487     if (psk_len == 0) {
1488       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
1489       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1490       return ssl_hs_error;
1491     }
1492     assert(psk_len <= PSK_MAX_PSK_LEN);
1493 
1494     hs->new_session->psk_identity.reset(OPENSSL_strdup(identity));
1495     if (hs->new_session->psk_identity == nullptr) {
1496       return ssl_hs_error;
1497     }
1498 
1499     // Write out psk_identity.
1500     CBB child;
1501     if (!CBB_add_u16_length_prefixed(&body, &child) ||
1502         !CBB_add_bytes(&child, (const uint8_t *)identity,
1503                        OPENSSL_strnlen(identity, sizeof(identity))) ||
1504         !CBB_flush(&body)) {
1505       return ssl_hs_error;
1506     }
1507   }
1508 
1509   // Depending on the key exchange method, compute |pms|.
1510   if (alg_k & SSL_kRSA) {
1511     if (!pms.Init(SSL_MAX_MASTER_KEY_LENGTH)) {
1512       return ssl_hs_error;
1513     }
1514 
1515     RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
1516     if (rsa == NULL) {
1517       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1518       return ssl_hs_error;
1519     }
1520 
1521     pms[0] = hs->client_version >> 8;
1522     pms[1] = hs->client_version & 0xff;
1523     if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
1524       return ssl_hs_error;
1525     }
1526 
1527     CBB enc_pms;
1528     uint8_t *ptr;
1529     size_t enc_pms_len;
1530     if (!CBB_add_u16_length_prefixed(&body, &enc_pms) ||
1531         !CBB_reserve(&enc_pms, &ptr, RSA_size(rsa)) ||
1532         !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
1533                      pms.size(), RSA_PKCS1_PADDING) ||
1534         !CBB_did_write(&enc_pms, enc_pms_len) ||
1535         !CBB_flush(&body)) {
1536       return ssl_hs_error;
1537     }
1538   } else if (alg_k & SSL_kECDHE) {
1539     CBB child;
1540     if (!CBB_add_u8_length_prefixed(&body, &child)) {
1541       return ssl_hs_error;
1542     }
1543 
1544     // Generate a premaster secret and encapsulate it.
1545     bssl::UniquePtr<SSLKeyShare> kem =
1546         SSLKeyShare::Create(hs->new_session->group_id);
1547     uint8_t alert = SSL_AD_DECODE_ERROR;
1548     if (!kem || !kem->Encap(&child, &pms, &alert, hs->peer_key)) {
1549       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
1550       return ssl_hs_error;
1551     }
1552     if (!CBB_flush(&body)) {
1553       return ssl_hs_error;
1554     }
1555 
1556     // The peer key can now be discarded.
1557     hs->peer_key.Reset();
1558   } else if (alg_k & SSL_kPSK) {
1559     // For plain PSK, other_secret is a block of 0s with the same length as
1560     // the pre-shared key.
1561     if (!pms.Init(psk_len)) {
1562       return ssl_hs_error;
1563     }
1564     OPENSSL_memset(pms.data(), 0, pms.size());
1565   } else {
1566     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1567     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1568     return ssl_hs_error;
1569   }
1570 
1571   // For a PSK cipher suite, other_secret is combined with the pre-shared
1572   // key.
1573   if (alg_a & SSL_aPSK) {
1574     ScopedCBB pms_cbb;
1575     CBB child;
1576     if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
1577         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1578         !CBB_add_bytes(&child, pms.data(), pms.size()) ||
1579         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
1580         !CBB_add_bytes(&child, psk, psk_len) ||
1581         !CBBFinishArray(pms_cbb.get(), &pms)) {
1582       return ssl_hs_error;
1583     }
1584   }
1585 
1586   // The message must be added to the finished hash before calculating the
1587   // master secret.
1588   if (!ssl_add_message_cbb(ssl, cbb.get())) {
1589     return ssl_hs_error;
1590   }
1591 
1592   hs->new_session->secret_length =
1593       tls1_generate_master_secret(hs, hs->new_session->secret, pms);
1594   if (hs->new_session->secret_length == 0) {
1595     return ssl_hs_error;
1596   }
1597   hs->new_session->extended_master_secret = hs->extended_master_secret;
1598 
1599   hs->state = state_send_client_certificate_verify;
1600   return ssl_hs_ok;
1601 }
1602 
do_send_client_certificate_verify(SSL_HANDSHAKE * hs)1603 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
1604   SSL *const ssl = hs->ssl;
1605 
1606   if (!hs->cert_request || hs->credential == nullptr) {
1607     hs->state = state_send_client_finished;
1608     return ssl_hs_ok;
1609   }
1610 
1611   ScopedCBB cbb;
1612   CBB body, child;
1613   if (!ssl->method->init_message(ssl, cbb.get(), &body,
1614                                  SSL3_MT_CERTIFICATE_VERIFY)) {
1615     return ssl_hs_error;
1616   }
1617 
1618   assert(hs->signature_algorithm != 0);
1619   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
1620     // Write out the digest type in TLS 1.2.
1621     if (!CBB_add_u16(&body, hs->signature_algorithm)) {
1622       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1623       return ssl_hs_error;
1624     }
1625   }
1626 
1627   // Set aside space for the signature.
1628   const size_t max_sig_len = EVP_PKEY_size(hs->credential->pubkey.get());
1629   uint8_t *ptr;
1630   if (!CBB_add_u16_length_prefixed(&body, &child) ||
1631       !CBB_reserve(&child, &ptr, max_sig_len)) {
1632     return ssl_hs_error;
1633   }
1634 
1635   size_t sig_len = max_sig_len;
1636   switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
1637                                hs->signature_algorithm,
1638                                hs->transcript.buffer())) {
1639     case ssl_private_key_success:
1640       break;
1641     case ssl_private_key_failure:
1642       return ssl_hs_error;
1643     case ssl_private_key_retry:
1644       hs->state = state_send_client_certificate_verify;
1645       return ssl_hs_private_key_operation;
1646   }
1647 
1648   if (!CBB_did_write(&child, sig_len) ||
1649       !ssl_add_message_cbb(ssl, cbb.get())) {
1650     return ssl_hs_error;
1651   }
1652 
1653   // The handshake buffer is no longer necessary.
1654   hs->transcript.FreeBuffer();
1655 
1656   hs->state = state_send_client_finished;
1657   return ssl_hs_ok;
1658 }
1659 
do_send_client_finished(SSL_HANDSHAKE * hs)1660 static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
1661   SSL *const ssl = hs->ssl;
1662   hs->can_release_private_key = true;
1663   if (!ssl->method->add_change_cipher_spec(ssl) ||
1664       !tls1_change_cipher_state(hs, evp_aead_seal)) {
1665     return ssl_hs_error;
1666   }
1667 
1668   if (hs->next_proto_neg_seen) {
1669     static const uint8_t kZero[32] = {0};
1670     size_t padding_len =
1671         32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
1672 
1673     ScopedCBB cbb;
1674     CBB body, child;
1675     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
1676         !CBB_add_u8_length_prefixed(&body, &child) ||
1677         !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
1678                        ssl->s3->next_proto_negotiated.size()) ||
1679         !CBB_add_u8_length_prefixed(&body, &child) ||
1680         !CBB_add_bytes(&child, kZero, padding_len) ||
1681         !ssl_add_message_cbb(ssl, cbb.get())) {
1682       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1683       return ssl_hs_error;
1684     }
1685   }
1686 
1687   if (hs->channel_id_negotiated) {
1688     ScopedCBB cbb;
1689     CBB body;
1690     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
1691         !tls1_write_channel_id(hs, &body) ||
1692         !ssl_add_message_cbb(ssl, cbb.get())) {
1693       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
1694       return ssl_hs_error;
1695     }
1696   }
1697 
1698   if (!ssl_send_finished(hs)) {
1699     return ssl_hs_error;
1700   }
1701 
1702   hs->state = state_finish_flight;
1703   return ssl_hs_flush;
1704 }
1705 
can_false_start(const SSL_HANDSHAKE * hs)1706 static bool can_false_start(const SSL_HANDSHAKE *hs) {
1707   const SSL *const ssl = hs->ssl;
1708 
1709   // False Start bypasses the Finished check's downgrade protection. This can
1710   // enable attacks where we send data under weaker settings than supported
1711   // (e.g. the Logjam attack). Thus we require TLS 1.2 with an ECDHE+AEAD
1712   // cipher, our strongest settings before TLS 1.3.
1713   //
1714   // Now that TLS 1.3 exists, we would like to avoid similar attacks between
1715   // TLS 1.2 and TLS 1.3, but there are too many TLS 1.2 deployments to
1716   // sacrifice False Start on them. Instead, we rely on the ServerHello.random
1717   // downgrade signal, which we unconditionally enforce.
1718   if (SSL_is_dtls(ssl) ||
1719       SSL_version(ssl) != TLS1_2_VERSION ||
1720       hs->new_cipher->algorithm_mkey != SSL_kECDHE ||
1721       hs->new_cipher->algorithm_mac != SSL_AEAD) {
1722     return false;
1723   }
1724 
1725   // If ECH was rejected, disable False Start. We run the handshake to
1726   // completion, including the Finished downgrade check, to authenticate the
1727   // recovery flow.
1728   if (ssl->s3->ech_status == ssl_ech_rejected) {
1729     return false;
1730   }
1731 
1732   // Additionally require ALPN or NPN by default.
1733   //
1734   // TODO(davidben): Can this constraint be relaxed globally now that cipher
1735   // suite requirements have been tightened?
1736   if (!ssl->ctx->false_start_allowed_without_alpn &&
1737       ssl->s3->alpn_selected.empty() &&
1738       ssl->s3->next_proto_negotiated.empty()) {
1739     return false;
1740   }
1741 
1742   return true;
1743 }
1744 
do_finish_flight(SSL_HANDSHAKE * hs)1745 static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
1746   SSL *const ssl = hs->ssl;
1747   if (ssl->session != NULL) {
1748     hs->state = state_finish_client_handshake;
1749     return ssl_hs_ok;
1750   }
1751 
1752   // This is a full handshake. If it involves ChannelID, then record the
1753   // handshake hashes at this point in the session so that any resumption of
1754   // this session with ChannelID can sign those hashes.
1755   if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
1756     return ssl_hs_error;
1757   }
1758 
1759   hs->state = state_read_session_ticket;
1760 
1761   if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
1762       can_false_start(hs) &&
1763       // No False Start on renegotiation (would complicate the state machine).
1764       !ssl->s3->initial_handshake_complete) {
1765     hs->in_false_start = true;
1766     hs->can_early_write = true;
1767     return ssl_hs_early_return;
1768   }
1769 
1770   return ssl_hs_ok;
1771 }
1772 
do_read_session_ticket(SSL_HANDSHAKE * hs)1773 static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
1774   SSL *const ssl = hs->ssl;
1775 
1776   if (!hs->ticket_expected) {
1777     hs->state = state_process_change_cipher_spec;
1778     return ssl_hs_read_change_cipher_spec;
1779   }
1780 
1781   SSLMessage msg;
1782   if (!ssl->method->get_message(ssl, &msg)) {
1783     return ssl_hs_read_message;
1784   }
1785 
1786   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
1787       !ssl_hash_message(hs, msg)) {
1788     return ssl_hs_error;
1789   }
1790 
1791   CBS new_session_ticket = msg.body, ticket;
1792   uint32_t ticket_lifetime_hint;
1793   if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
1794       !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
1795       CBS_len(&new_session_ticket) != 0) {
1796     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1797     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
1798     return ssl_hs_error;
1799   }
1800 
1801   if (CBS_len(&ticket) == 0) {
1802     // RFC 5077 allows a server to change its mind and send no ticket after
1803     // negotiating the extension. The value of |ticket_expected| is checked in
1804     // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
1805     hs->ticket_expected = false;
1806     ssl->method->next_message(ssl);
1807     hs->state = state_process_change_cipher_spec;
1808     return ssl_hs_read_change_cipher_spec;
1809   }
1810 
1811   if (ssl->session != nullptr) {
1812     // The server is sending a new ticket for an existing session. Sessions are
1813     // immutable once established, so duplicate all but the ticket of the
1814     // existing session.
1815     assert(!hs->new_session);
1816     hs->new_session =
1817         SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
1818     if (!hs->new_session) {
1819       return ssl_hs_error;
1820     }
1821   }
1822 
1823   // |ticket_lifetime_hint| is measured from when the ticket was issued.
1824   ssl_session_rebase_time(ssl, hs->new_session.get());
1825 
1826   if (!hs->new_session->ticket.CopyFrom(ticket)) {
1827     return ssl_hs_error;
1828   }
1829   hs->new_session->ticket_lifetime_hint = ticket_lifetime_hint;
1830 
1831   // Historically, OpenSSL filled in fake session IDs for ticket-based sessions.
1832   // TODO(davidben): Are external callers relying on this? Try removing this.
1833   SHA256(CBS_data(&ticket), CBS_len(&ticket), hs->new_session->session_id);
1834   hs->new_session->session_id_length = SHA256_DIGEST_LENGTH;
1835 
1836   ssl->method->next_message(ssl);
1837   hs->state = state_process_change_cipher_spec;
1838   return ssl_hs_read_change_cipher_spec;
1839 }
1840 
do_process_change_cipher_spec(SSL_HANDSHAKE * hs)1841 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
1842   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
1843     return ssl_hs_error;
1844   }
1845 
1846   hs->state = state_read_server_finished;
1847   return ssl_hs_ok;
1848 }
1849 
do_read_server_finished(SSL_HANDSHAKE * hs)1850 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
1851   SSL *const ssl = hs->ssl;
1852   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
1853   if (wait != ssl_hs_ok) {
1854     return wait;
1855   }
1856 
1857   if (ssl->session != NULL) {
1858     hs->state = state_send_client_finished;
1859     return ssl_hs_ok;
1860   }
1861 
1862   hs->state = state_finish_client_handshake;
1863   return ssl_hs_ok;
1864 }
1865 
do_finish_client_handshake(SSL_HANDSHAKE * hs)1866 static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
1867   SSL *const ssl = hs->ssl;
1868   if (ssl->s3->ech_status == ssl_ech_rejected) {
1869     // Release the retry configs.
1870     hs->ech_authenticated_reject = true;
1871     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ECH_REQUIRED);
1872     OPENSSL_PUT_ERROR(SSL, SSL_R_ECH_REJECTED);
1873     return ssl_hs_error;
1874   }
1875 
1876   ssl->method->on_handshake_complete(ssl);
1877 
1878   // Note TLS 1.2 resumptions with ticket renewal have both |ssl->session| (the
1879   // resumed session) and |hs->new_session| (the session with the new ticket).
1880   bool has_new_session = hs->new_session != nullptr;
1881   if (has_new_session) {
1882     // When False Start is enabled, the handshake reports completion early. The
1883     // caller may then have passed the (then unresuable) |hs->new_session| to
1884     // another thread via |SSL_get0_session| for resumption. To avoid potential
1885     // race conditions in such callers, we duplicate the session before
1886     // clearing |not_resumable|.
1887     ssl->s3->established_session =
1888         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
1889     if (!ssl->s3->established_session) {
1890       return ssl_hs_error;
1891     }
1892     // Renegotiations do not participate in session resumption.
1893     if (!ssl->s3->initial_handshake_complete) {
1894       ssl->s3->established_session->not_resumable = false;
1895     }
1896 
1897     hs->new_session.reset();
1898   } else {
1899     assert(ssl->session != nullptr);
1900     ssl->s3->established_session = UpRef(ssl->session);
1901   }
1902 
1903   hs->handshake_finalized = true;
1904   ssl->s3->initial_handshake_complete = true;
1905   if (has_new_session) {
1906     ssl_update_cache(ssl);
1907   }
1908 
1909   hs->state = state_done;
1910   return ssl_hs_ok;
1911 }
1912 
ssl_client_handshake(SSL_HANDSHAKE * hs)1913 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
1914   while (hs->state != state_done) {
1915     enum ssl_hs_wait_t ret = ssl_hs_error;
1916     enum ssl_client_hs_state_t state =
1917         static_cast<enum ssl_client_hs_state_t>(hs->state);
1918     switch (state) {
1919       case state_start_connect:
1920         ret = do_start_connect(hs);
1921         break;
1922       case state_enter_early_data:
1923         ret = do_enter_early_data(hs);
1924         break;
1925       case state_early_reverify_server_certificate:
1926         ret = do_early_reverify_server_certificate(hs);
1927         break;
1928       case state_read_hello_verify_request:
1929         ret = do_read_hello_verify_request(hs);
1930         break;
1931       case state_read_server_hello:
1932         ret = do_read_server_hello(hs);
1933         break;
1934       case state_tls13:
1935         ret = do_tls13(hs);
1936         break;
1937       case state_read_server_certificate:
1938         ret = do_read_server_certificate(hs);
1939         break;
1940       case state_read_certificate_status:
1941         ret = do_read_certificate_status(hs);
1942         break;
1943       case state_verify_server_certificate:
1944         ret = do_verify_server_certificate(hs);
1945         break;
1946       case state_reverify_server_certificate:
1947         ret = do_reverify_server_certificate(hs);
1948         break;
1949       case state_read_server_key_exchange:
1950         ret = do_read_server_key_exchange(hs);
1951         break;
1952       case state_read_certificate_request:
1953         ret = do_read_certificate_request(hs);
1954         break;
1955       case state_read_server_hello_done:
1956         ret = do_read_server_hello_done(hs);
1957         break;
1958       case state_send_client_certificate:
1959         ret = do_send_client_certificate(hs);
1960         break;
1961       case state_send_client_key_exchange:
1962         ret = do_send_client_key_exchange(hs);
1963         break;
1964       case state_send_client_certificate_verify:
1965         ret = do_send_client_certificate_verify(hs);
1966         break;
1967       case state_send_client_finished:
1968         ret = do_send_client_finished(hs);
1969         break;
1970       case state_finish_flight:
1971         ret = do_finish_flight(hs);
1972         break;
1973       case state_read_session_ticket:
1974         ret = do_read_session_ticket(hs);
1975         break;
1976       case state_process_change_cipher_spec:
1977         ret = do_process_change_cipher_spec(hs);
1978         break;
1979       case state_read_server_finished:
1980         ret = do_read_server_finished(hs);
1981         break;
1982       case state_finish_client_handshake:
1983         ret = do_finish_client_handshake(hs);
1984         break;
1985       case state_done:
1986         ret = ssl_hs_ok;
1987         break;
1988     }
1989 
1990     if (hs->state != state) {
1991       ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
1992     }
1993 
1994     if (ret != ssl_hs_ok) {
1995       return ret;
1996     }
1997   }
1998 
1999   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
2000   return ssl_hs_ok;
2001 }
2002 
ssl_client_handshake_state(SSL_HANDSHAKE * hs)2003 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
2004   enum ssl_client_hs_state_t state =
2005       static_cast<enum ssl_client_hs_state_t>(hs->state);
2006   switch (state) {
2007     case state_start_connect:
2008       return "TLS client start_connect";
2009     case state_enter_early_data:
2010       return "TLS client enter_early_data";
2011     case state_early_reverify_server_certificate:
2012       return "TLS client early_reverify_server_certificate";
2013     case state_read_hello_verify_request:
2014       return "TLS client read_hello_verify_request";
2015     case state_read_server_hello:
2016       return "TLS client read_server_hello";
2017     case state_tls13:
2018       return tls13_client_handshake_state(hs);
2019     case state_read_server_certificate:
2020       return "TLS client read_server_certificate";
2021     case state_read_certificate_status:
2022       return "TLS client read_certificate_status";
2023     case state_verify_server_certificate:
2024       return "TLS client verify_server_certificate";
2025     case state_reverify_server_certificate:
2026       return "TLS client reverify_server_certificate";
2027     case state_read_server_key_exchange:
2028       return "TLS client read_server_key_exchange";
2029     case state_read_certificate_request:
2030       return "TLS client read_certificate_request";
2031     case state_read_server_hello_done:
2032       return "TLS client read_server_hello_done";
2033     case state_send_client_certificate:
2034       return "TLS client send_client_certificate";
2035     case state_send_client_key_exchange:
2036       return "TLS client send_client_key_exchange";
2037     case state_send_client_certificate_verify:
2038       return "TLS client send_client_certificate_verify";
2039     case state_send_client_finished:
2040       return "TLS client send_client_finished";
2041     case state_finish_flight:
2042       return "TLS client finish_flight";
2043     case state_read_session_ticket:
2044       return "TLS client read_session_ticket";
2045     case state_process_change_cipher_spec:
2046       return "TLS client process_change_cipher_spec";
2047     case state_read_server_finished:
2048       return "TLS client read_server_finished";
2049     case state_finish_client_handshake:
2050       return "TLS client finish_client_handshake";
2051     case state_done:
2052       return "TLS client done";
2053   }
2054 
2055   return "TLS client unknown";
2056 }
2057 
2058 BSSL_NAMESPACE_END
2059