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