Home | History | Annotate | Download | only in ssl
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) 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 (at) 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 (at) 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 (at) 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 (at) 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 (at) cryptsoft.com).  This product includes software written by Tim
    107  * Hudson (tjh (at) 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/buf.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/md5.h>
    167 #include <openssl/mem.h>
    168 #include <openssl/rand.h>
    169 
    170 #include "../crypto/internal.h"
    171 #include "internal.h"
    172 
    173 
    174 namespace bssl {
    175 
    176 enum ssl_client_hs_state_t {
    177   state_start_connect = 0,
    178   state_enter_early_data,
    179   state_read_hello_verify_request,
    180   state_read_server_hello,
    181   state_tls13,
    182   state_read_server_certificate,
    183   state_read_certificate_status,
    184   state_verify_server_certificate,
    185   state_read_server_key_exchange,
    186   state_read_certificate_request,
    187   state_read_server_hello_done,
    188   state_send_client_certificate,
    189   state_send_client_key_exchange,
    190   state_send_client_certificate_verify,
    191   state_send_client_finished,
    192   state_finish_flight,
    193   state_read_session_ticket,
    194   state_process_change_cipher_spec,
    195   state_read_server_finished,
    196   state_finish_client_handshake,
    197   state_done,
    198 };
    199 
    200 // ssl_get_client_disabled sets |*out_mask_a| and |*out_mask_k| to masks of
    201 // disabled algorithms.
    202 static void ssl_get_client_disabled(SSL *ssl, uint32_t *out_mask_a,
    203                                     uint32_t *out_mask_k) {
    204   *out_mask_a = 0;
    205   *out_mask_k = 0;
    206 
    207   // PSK requires a client callback.
    208   if (ssl->psk_client_callback == NULL) {
    209     *out_mask_a |= SSL_aPSK;
    210     *out_mask_k |= SSL_kPSK;
    211   }
    212 }
    213 
    214 static int ssl_write_client_cipher_list(SSL_HANDSHAKE *hs, CBB *out) {
    215   SSL *const ssl = hs->ssl;
    216   uint32_t mask_a, mask_k;
    217   ssl_get_client_disabled(ssl, &mask_a, &mask_k);
    218 
    219   CBB child;
    220   if (!CBB_add_u16_length_prefixed(out, &child)) {
    221     return 0;
    222   }
    223 
    224   // Add a fake cipher suite. See draft-davidben-tls-grease-01.
    225   if (ssl->ctx->grease_enabled &&
    226       !CBB_add_u16(&child, ssl_get_grease_value(hs, ssl_grease_cipher))) {
    227     return 0;
    228   }
    229 
    230   // Add TLS 1.3 ciphers. Order ChaCha20-Poly1305 relative to AES-GCM based on
    231   // hardware support.
    232   if (hs->max_version >= TLS1_3_VERSION) {
    233     if (!EVP_has_aes_hardware() &&
    234         !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
    235       return 0;
    236     }
    237     if (!CBB_add_u16(&child, TLS1_CK_AES_128_GCM_SHA256 & 0xffff) ||
    238         !CBB_add_u16(&child, TLS1_CK_AES_256_GCM_SHA384 & 0xffff)) {
    239       return 0;
    240     }
    241     if (EVP_has_aes_hardware() &&
    242         !CBB_add_u16(&child, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
    243       return 0;
    244     }
    245   }
    246 
    247   if (hs->min_version < TLS1_3_VERSION) {
    248     int any_enabled = 0;
    249     for (const SSL_CIPHER *cipher : SSL_get_ciphers(ssl)) {
    250       // Skip disabled ciphers
    251       if ((cipher->algorithm_mkey & mask_k) ||
    252           (cipher->algorithm_auth & mask_a)) {
    253         continue;
    254       }
    255       if (SSL_CIPHER_get_min_version(cipher) > hs->max_version ||
    256           SSL_CIPHER_get_max_version(cipher) < hs->min_version) {
    257         continue;
    258       }
    259       any_enabled = 1;
    260       if (!CBB_add_u16(&child, ssl_cipher_get_value(cipher))) {
    261         return 0;
    262       }
    263     }
    264 
    265     // If all ciphers were disabled, return the error to the caller.
    266     if (!any_enabled && hs->max_version < TLS1_3_VERSION) {
    267       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
    268       return 0;
    269     }
    270   }
    271 
    272   // For SSLv3, the SCSV is added. Otherwise the renegotiation extension is
    273   // added.
    274   if (hs->max_version == SSL3_VERSION &&
    275       !ssl->s3->initial_handshake_complete) {
    276     if (!CBB_add_u16(&child, SSL3_CK_SCSV & 0xffff)) {
    277       return 0;
    278     }
    279   }
    280 
    281   if (ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
    282     if (!CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
    283       return 0;
    284     }
    285   }
    286 
    287   return CBB_flush(out);
    288 }
    289 
    290 int ssl_write_client_hello(SSL_HANDSHAKE *hs) {
    291   SSL *const ssl = hs->ssl;
    292   ScopedCBB cbb;
    293   CBB body;
    294   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CLIENT_HELLO)) {
    295     return 0;
    296   }
    297 
    298   CBB child;
    299   if (!CBB_add_u16(&body, hs->client_version) ||
    300       !CBB_add_bytes(&body, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
    301       !CBB_add_u8_length_prefixed(&body, &child)) {
    302     return 0;
    303   }
    304 
    305   // Do not send a session ID on renegotiation.
    306   if (!ssl->s3->initial_handshake_complete &&
    307       !CBB_add_bytes(&child, hs->session_id, hs->session_id_len)) {
    308     return 0;
    309   }
    310 
    311   if (SSL_is_dtls(ssl)) {
    312     if (!CBB_add_u8_length_prefixed(&body, &child) ||
    313         !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
    314       return 0;
    315     }
    316   }
    317 
    318   size_t header_len =
    319       SSL_is_dtls(ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
    320   if (!ssl_write_client_cipher_list(hs, &body) ||
    321       !CBB_add_u8(&body, 1 /* one compression method */) ||
    322       !CBB_add_u8(&body, 0 /* null compression */) ||
    323       !ssl_add_clienthello_tlsext(hs, &body, header_len + CBB_len(&body))) {
    324     return 0;
    325   }
    326 
    327   Array<uint8_t> msg;
    328   if (!ssl->method->finish_message(ssl, cbb.get(), &msg)) {
    329     return 0;
    330   }
    331 
    332   // Now that the length prefixes have been computed, fill in the placeholder
    333   // PSK binder.
    334   if (hs->needs_psk_binder &&
    335       !tls13_write_psk_binder(hs, msg.data(), msg.size())) {
    336     return 0;
    337   }
    338 
    339   return ssl->method->add_message(ssl, std::move(msg));
    340 }
    341 
    342 static int parse_server_version(SSL_HANDSHAKE *hs, uint16_t *out,
    343                                 const SSLMessage &msg) {
    344   SSL *const ssl = hs->ssl;
    345   if (msg.type != SSL3_MT_SERVER_HELLO &&
    346       msg.type != SSL3_MT_HELLO_RETRY_REQUEST) {
    347     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
    348     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
    349     return 0;
    350   }
    351 
    352   CBS server_hello = msg.body;
    353   if (!CBS_get_u16(&server_hello, out)) {
    354     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    355     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    356     return 0;
    357   }
    358 
    359   // The server version may also be in the supported_versions extension if
    360   // applicable.
    361   if (msg.type != SSL3_MT_SERVER_HELLO || *out != TLS1_2_VERSION) {
    362     return 1;
    363   }
    364 
    365   uint8_t sid_length;
    366   if (!CBS_skip(&server_hello, SSL3_RANDOM_SIZE) ||
    367       !CBS_get_u8(&server_hello, &sid_length) ||
    368       !CBS_skip(&server_hello, sid_length + 2 /* cipher_suite */ +
    369                 1 /* compression_method */)) {
    370     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    371     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    372     return 0;
    373   }
    374 
    375   // The extensions block may not be present.
    376   if (CBS_len(&server_hello) == 0) {
    377     return 1;
    378   }
    379 
    380   CBS extensions;
    381   if (!CBS_get_u16_length_prefixed(&server_hello, &extensions) ||
    382       CBS_len(&server_hello) != 0) {
    383     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    384     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    385     return 0;
    386   }
    387 
    388   bool have_supported_versions;
    389   CBS supported_versions;
    390   const SSL_EXTENSION_TYPE ext_types[] = {
    391     {TLSEXT_TYPE_supported_versions, &have_supported_versions,
    392      &supported_versions},
    393   };
    394 
    395   uint8_t alert = SSL_AD_DECODE_ERROR;
    396   if (!ssl_parse_extensions(&extensions, &alert, ext_types,
    397                             OPENSSL_ARRAY_SIZE(ext_types),
    398                             1 /* ignore unknown */)) {
    399     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
    400     return 0;
    401   }
    402 
    403   if (have_supported_versions &&
    404       (!CBS_get_u16(&supported_versions, out) ||
    405        CBS_len(&supported_versions) != 0)) {
    406     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    407     return 0;
    408   }
    409 
    410   return 1;
    411 }
    412 
    413 static enum ssl_hs_wait_t do_start_connect(SSL_HANDSHAKE *hs) {
    414   SSL *const ssl = hs->ssl;
    415 
    416   ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
    417   // |session_reused| must be reset in case this is a renegotiation.
    418   ssl->s3->session_reused = false;
    419 
    420   // Freeze the version range.
    421   if (!ssl_get_version_range(ssl, &hs->min_version, &hs->max_version)) {
    422     return ssl_hs_error;
    423   }
    424 
    425   // SSL 3.0 ClientHellos should use SSL 3.0 not TLS 1.0, for the record-layer
    426   // version.
    427   if (hs->max_version == SSL3_VERSION) {
    428     ssl->s3->aead_write_ctx->SetVersionIfNullCipher(SSL3_VERSION);
    429   }
    430 
    431   // Always advertise the ClientHello version from the original maximum version,
    432   // even on renegotiation. The static RSA key exchange uses this field, and
    433   // some servers fail when it changes across handshakes.
    434   if (SSL_is_dtls(hs->ssl)) {
    435     hs->client_version =
    436         hs->max_version >= TLS1_2_VERSION ? DTLS1_2_VERSION : DTLS1_VERSION;
    437   } else {
    438     hs->client_version =
    439         hs->max_version >= TLS1_2_VERSION ? TLS1_2_VERSION : hs->max_version;
    440   }
    441 
    442   // If the configured session has expired or was created at a disabled
    443   // version, drop it.
    444   if (ssl->session != NULL) {
    445     if (ssl->session->is_server ||
    446         !ssl_supports_version(hs, ssl->session->ssl_version) ||
    447         (ssl->session->session_id_length == 0 &&
    448          ssl->session->tlsext_ticklen == 0) ||
    449         ssl->session->not_resumable ||
    450         !ssl_session_is_time_valid(ssl, ssl->session)) {
    451       ssl_set_session(ssl, NULL);
    452     }
    453   }
    454 
    455   if (!RAND_bytes(ssl->s3->client_random, sizeof(ssl->s3->client_random))) {
    456     return ssl_hs_error;
    457   }
    458 
    459   // Initialize a random session ID for the experimental TLS 1.3 variant
    460   // requiring a session id.
    461   if (ssl->session != nullptr &&
    462       !ssl->s3->initial_handshake_complete &&
    463       ssl->session->session_id_length > 0) {
    464     hs->session_id_len = ssl->session->session_id_length;
    465     OPENSSL_memcpy(hs->session_id, ssl->session->session_id,
    466                    hs->session_id_len);
    467   } else if (hs->max_version >= TLS1_3_VERSION) {
    468     hs->session_id_len = sizeof(hs->session_id);
    469     if (!RAND_bytes(hs->session_id, hs->session_id_len)) {
    470       return ssl_hs_error;
    471     }
    472   }
    473 
    474   if (!ssl_write_client_hello(hs)) {
    475     return ssl_hs_error;
    476   }
    477 
    478   hs->state = state_enter_early_data;
    479   return ssl_hs_flush;
    480 }
    481 
    482 static enum ssl_hs_wait_t do_enter_early_data(SSL_HANDSHAKE *hs) {
    483   SSL *const ssl = hs->ssl;
    484 
    485   if (SSL_is_dtls(ssl)) {
    486     hs->state = state_read_hello_verify_request;
    487     return ssl_hs_ok;
    488   }
    489 
    490   if (!hs->early_data_offered) {
    491     hs->state = state_read_server_hello;
    492     return ssl_hs_ok;
    493   }
    494 
    495   ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->session->ssl_version);
    496   if (!ssl->method->add_change_cipher_spec(ssl)) {
    497     return ssl_hs_error;
    498   }
    499 
    500   if (!tls13_init_early_key_schedule(hs, ssl->session->master_key,
    501                                      ssl->session->master_key_length) ||
    502       !tls13_derive_early_secrets(hs) ||
    503       !tls13_set_traffic_key(ssl, evp_aead_seal, hs->early_traffic_secret,
    504                              hs->hash_len)) {
    505     return ssl_hs_error;
    506   }
    507 
    508   // Stash the early data session, so connection properties may be queried out
    509   // of it.
    510   hs->in_early_data = true;
    511   SSL_SESSION_up_ref(ssl->session);
    512   hs->early_session.reset(ssl->session);
    513   hs->can_early_write = true;
    514 
    515   hs->state = state_read_server_hello;
    516   return ssl_hs_early_return;
    517 }
    518 
    519 static enum ssl_hs_wait_t do_read_hello_verify_request(SSL_HANDSHAKE *hs) {
    520   SSL *const ssl = hs->ssl;
    521 
    522   assert(SSL_is_dtls(ssl));
    523 
    524   SSLMessage msg;
    525   if (!ssl->method->get_message(ssl, &msg)) {
    526     return ssl_hs_read_message;
    527   }
    528 
    529   if (msg.type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
    530     hs->state = state_read_server_hello;
    531     return ssl_hs_ok;
    532   }
    533 
    534   CBS hello_verify_request = msg.body, cookie;
    535   uint16_t server_version;
    536   if (!CBS_get_u16(&hello_verify_request, &server_version) ||
    537       !CBS_get_u8_length_prefixed(&hello_verify_request, &cookie) ||
    538       CBS_len(&cookie) > sizeof(ssl->d1->cookie) ||
    539       CBS_len(&hello_verify_request) != 0) {
    540     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    541     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    542     return ssl_hs_error;
    543   }
    544 
    545   OPENSSL_memcpy(ssl->d1->cookie, CBS_data(&cookie), CBS_len(&cookie));
    546   ssl->d1->cookie_len = CBS_len(&cookie);
    547 
    548   ssl->method->next_message(ssl);
    549 
    550   // DTLS resets the handshake buffer after HelloVerifyRequest.
    551   if (!hs->transcript.Init()) {
    552     return ssl_hs_error;
    553   }
    554 
    555   if (!ssl_write_client_hello(hs)) {
    556     return ssl_hs_error;
    557   }
    558 
    559   hs->state = state_read_server_hello;
    560   return ssl_hs_flush;
    561 }
    562 
    563 static enum ssl_hs_wait_t do_read_server_hello(SSL_HANDSHAKE *hs) {
    564   SSL *const ssl = hs->ssl;
    565   SSLMessage msg;
    566   if (!ssl->method->get_message(ssl, &msg)) {
    567     return ssl_hs_read_server_hello;
    568   }
    569 
    570   uint16_t server_version;
    571   if (!parse_server_version(hs, &server_version, msg)) {
    572     return ssl_hs_error;
    573   }
    574 
    575   if (!ssl_supports_version(hs, server_version)) {
    576     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
    577     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
    578     return ssl_hs_error;
    579   }
    580 
    581   assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
    582   if (!ssl->s3->have_version) {
    583     ssl->version = server_version;
    584     // At this point, the connection's version is known and ssl->version is
    585     // fixed. Begin enforcing the record-layer version.
    586     ssl->s3->have_version = true;
    587     ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
    588   } else if (server_version != ssl->version) {
    589     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
    590     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
    591     return ssl_hs_error;
    592   }
    593 
    594   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    595     hs->state = state_tls13;
    596     return ssl_hs_ok;
    597   }
    598 
    599   // Clear some TLS 1.3 state that no longer needs to be retained.
    600   hs->key_share.reset();
    601   hs->key_share_bytes.Reset();
    602 
    603   // A TLS 1.2 server would not know to skip the early data we offered. Report
    604   // an error code sooner. The caller may use this error code to implement the
    605   // fallback described in draft-ietf-tls-tls13-18 appendix C.3.
    606   if (hs->early_data_offered) {
    607     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_ON_EARLY_DATA);
    608     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_PROTOCOL_VERSION);
    609     return ssl_hs_error;
    610   }
    611 
    612   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO)) {
    613     return ssl_hs_error;
    614   }
    615 
    616   CBS server_hello = msg.body, server_random, session_id;
    617   uint16_t cipher_suite;
    618   uint8_t compression_method;
    619   if (!CBS_skip(&server_hello, 2 /* version */) ||
    620       !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
    621       !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
    622       CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
    623       !CBS_get_u16(&server_hello, &cipher_suite) ||
    624       !CBS_get_u8(&server_hello, &compression_method)) {
    625     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    626     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    627     return ssl_hs_error;
    628   }
    629 
    630   // Copy over the server random.
    631   OPENSSL_memcpy(ssl->s3->server_random, CBS_data(&server_random),
    632                  SSL3_RANDOM_SIZE);
    633 
    634   // Measure, but do not enforce, the TLS 1.3 anti-downgrade feature, with a
    635   // different value.
    636   //
    637   // For draft TLS 1.3 versions, it is not safe to deploy this feature. However,
    638   // some TLS terminators are non-compliant and copy the origin server's value,
    639   // so we wish to measure eventual compatibility impact.
    640   if (!ssl->s3->initial_handshake_complete &&
    641       hs->max_version >= TLS1_3_VERSION &&
    642       OPENSSL_memcmp(ssl->s3->server_random + SSL3_RANDOM_SIZE -
    643                          sizeof(kDraftDowngradeRandom),
    644                      kDraftDowngradeRandom,
    645                      sizeof(kDraftDowngradeRandom)) == 0) {
    646     ssl->s3->draft_downgrade = true;
    647   }
    648 
    649   if (!ssl->s3->initial_handshake_complete && ssl->session != NULL &&
    650       ssl->session->session_id_length != 0 &&
    651       CBS_mem_equal(&session_id, ssl->session->session_id,
    652                     ssl->session->session_id_length)) {
    653     ssl->s3->session_reused = true;
    654   } else {
    655     // The server may also have echoed back the TLS 1.3 compatibility mode
    656     // session ID. As we know this is not a session the server knows about, any
    657     // server resuming it is in error. Reject the first connection
    658     // deterministicly, rather than installing an invalid session into the
    659     // session cache. https://crbug.com/796910
    660     if (hs->session_id_len != 0 &&
    661         CBS_mem_equal(&session_id, hs->session_id, hs->session_id_len)) {
    662       OPENSSL_PUT_ERROR(SSL, SSL_R_SERVER_ECHOED_INVALID_SESSION_ID);
    663       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    664       return ssl_hs_error;
    665     }
    666 
    667     // The session wasn't resumed. Create a fresh SSL_SESSION to
    668     // fill out.
    669     ssl_set_session(ssl, NULL);
    670     if (!ssl_get_new_session(hs, 0 /* client */)) {
    671       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    672       return ssl_hs_error;
    673     }
    674     // Note: session_id could be empty.
    675     hs->new_session->session_id_length = CBS_len(&session_id);
    676     OPENSSL_memcpy(hs->new_session->session_id, CBS_data(&session_id),
    677                    CBS_len(&session_id));
    678   }
    679 
    680   const SSL_CIPHER *cipher = SSL_get_cipher_by_value(cipher_suite);
    681   if (cipher == NULL) {
    682     // unknown cipher
    683     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
    684     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    685     return ssl_hs_error;
    686   }
    687 
    688   // The cipher must be allowed in the selected version and enabled.
    689   uint32_t mask_a, mask_k;
    690   ssl_get_client_disabled(ssl, &mask_a, &mask_k);
    691   if ((cipher->algorithm_mkey & mask_k) || (cipher->algorithm_auth & mask_a) ||
    692       SSL_CIPHER_get_min_version(cipher) > ssl_protocol_version(ssl) ||
    693       SSL_CIPHER_get_max_version(cipher) < ssl_protocol_version(ssl) ||
    694       !sk_SSL_CIPHER_find(SSL_get_ciphers(ssl), NULL, cipher)) {
    695     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
    696     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    697     return ssl_hs_error;
    698   }
    699 
    700   if (ssl->session != NULL) {
    701     if (ssl->session->ssl_version != ssl->version) {
    702       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
    703       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    704       return ssl_hs_error;
    705     }
    706     if (ssl->session->cipher != cipher) {
    707       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
    708       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    709       return ssl_hs_error;
    710     }
    711     if (!ssl_session_is_context_valid(ssl, ssl->session)) {
    712       // This is actually a client application bug.
    713       OPENSSL_PUT_ERROR(SSL,
    714                         SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
    715       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    716       return ssl_hs_error;
    717     }
    718   } else {
    719     hs->new_session->cipher = cipher;
    720   }
    721   hs->new_cipher = cipher;
    722 
    723   // Now that the cipher is known, initialize the handshake hash and hash the
    724   // ServerHello.
    725   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
    726       !ssl_hash_message(hs, msg)) {
    727     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    728     return ssl_hs_error;
    729   }
    730 
    731   // If doing a full handshake, the server may request a client certificate
    732   // which requires hashing the handshake transcript. Otherwise, the handshake
    733   // buffer may be released.
    734   if (ssl->session != NULL ||
    735       !ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    736     hs->transcript.FreeBuffer();
    737   }
    738 
    739   // Only the NULL compression algorithm is supported.
    740   if (compression_method != 0) {
    741     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
    742     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    743     return ssl_hs_error;
    744   }
    745 
    746   // TLS extensions
    747   if (!ssl_parse_serverhello_tlsext(hs, &server_hello)) {
    748     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
    749     return ssl_hs_error;
    750   }
    751 
    752   // There should be nothing left over in the record.
    753   if (CBS_len(&server_hello) != 0) {
    754     // wrong packet length
    755     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    756     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    757     return ssl_hs_error;
    758   }
    759 
    760   if (ssl->session != NULL &&
    761       hs->extended_master_secret != ssl->session->extended_master_secret) {
    762     if (ssl->session->extended_master_secret) {
    763       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
    764     } else {
    765       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
    766     }
    767     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    768     return ssl_hs_error;
    769   }
    770 
    771   if (ssl->token_binding_negotiated &&
    772       (!hs->extended_master_secret || !ssl->s3->send_connection_binding)) {
    773     OPENSSL_PUT_ERROR(SSL, SSL_R_NEGOTIATED_TB_WITHOUT_EMS_OR_RI);
    774     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
    775     return ssl_hs_error;
    776   }
    777 
    778   ssl->method->next_message(ssl);
    779 
    780   if (ssl->session != NULL) {
    781     hs->state = state_read_session_ticket;
    782     return ssl_hs_ok;
    783   }
    784 
    785   hs->state = state_read_server_certificate;
    786   return ssl_hs_ok;
    787 }
    788 
    789 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
    790   enum ssl_hs_wait_t wait = tls13_client_handshake(hs);
    791   if (wait == ssl_hs_ok) {
    792     hs->state = state_finish_client_handshake;
    793     return ssl_hs_ok;
    794   }
    795 
    796   return wait;
    797 }
    798 
    799 static enum ssl_hs_wait_t do_read_server_certificate(SSL_HANDSHAKE *hs) {
    800   SSL *const ssl = hs->ssl;
    801 
    802   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    803     hs->state = state_read_certificate_status;
    804     return ssl_hs_ok;
    805   }
    806 
    807   SSLMessage msg;
    808   if (!ssl->method->get_message(ssl, &msg)) {
    809     return ssl_hs_read_message;
    810   }
    811 
    812   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE) ||
    813       !ssl_hash_message(hs, msg)) {
    814     return ssl_hs_error;
    815   }
    816 
    817   CBS body = msg.body;
    818   uint8_t alert = SSL_AD_DECODE_ERROR;
    819   UniquePtr<STACK_OF(CRYPTO_BUFFER)> chain;
    820   if (!ssl_parse_cert_chain(&alert, &chain, &hs->peer_pubkey, NULL, &body,
    821                             ssl->ctx->pool)) {
    822     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
    823     return ssl_hs_error;
    824   }
    825   sk_CRYPTO_BUFFER_pop_free(hs->new_session->certs, CRYPTO_BUFFER_free);
    826   hs->new_session->certs = chain.release();
    827 
    828   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs) == 0 ||
    829       CBS_len(&body) != 0 ||
    830       !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
    831     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    832     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    833     return ssl_hs_error;
    834   }
    835 
    836   if (!ssl_check_leaf_certificate(
    837           hs, hs->peer_pubkey.get(),
    838           sk_CRYPTO_BUFFER_value(hs->new_session->certs, 0))) {
    839     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    840     return ssl_hs_error;
    841   }
    842 
    843   ssl->method->next_message(ssl);
    844 
    845   hs->state = state_read_certificate_status;
    846   return ssl_hs_ok;
    847 }
    848 
    849 static enum ssl_hs_wait_t do_read_certificate_status(SSL_HANDSHAKE *hs) {
    850   SSL *const ssl = hs->ssl;
    851 
    852   if (!hs->certificate_status_expected) {
    853     hs->state = state_verify_server_certificate;
    854     return ssl_hs_ok;
    855   }
    856 
    857   SSLMessage msg;
    858   if (!ssl->method->get_message(ssl, &msg)) {
    859     return ssl_hs_read_message;
    860   }
    861 
    862   if (msg.type != SSL3_MT_CERTIFICATE_STATUS) {
    863     // A server may send status_request in ServerHello and then change its mind
    864     // about sending CertificateStatus.
    865     hs->state = state_verify_server_certificate;
    866     return ssl_hs_ok;
    867   }
    868 
    869   if (!ssl_hash_message(hs, msg)) {
    870     return ssl_hs_error;
    871   }
    872 
    873   CBS certificate_status = msg.body, ocsp_response;
    874   uint8_t status_type;
    875   if (!CBS_get_u8(&certificate_status, &status_type) ||
    876       status_type != TLSEXT_STATUSTYPE_ocsp ||
    877       !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
    878       CBS_len(&ocsp_response) == 0 ||
    879       CBS_len(&certificate_status) != 0) {
    880     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    881     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    882     return ssl_hs_error;
    883   }
    884 
    885   CRYPTO_BUFFER_free(hs->new_session->ocsp_response);
    886   hs->new_session->ocsp_response =
    887       CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool);
    888   if (hs->new_session->ocsp_response == nullptr) {
    889     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    890     return ssl_hs_error;
    891   }
    892 
    893   ssl->method->next_message(ssl);
    894 
    895   hs->state = state_verify_server_certificate;
    896   return ssl_hs_ok;
    897 }
    898 
    899 static enum ssl_hs_wait_t do_verify_server_certificate(SSL_HANDSHAKE *hs) {
    900   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    901     hs->state = state_read_server_key_exchange;
    902     return ssl_hs_ok;
    903   }
    904 
    905   switch (ssl_verify_peer_cert(hs)) {
    906     case ssl_verify_ok:
    907       break;
    908     case ssl_verify_invalid:
    909       return ssl_hs_error;
    910     case ssl_verify_retry:
    911       hs->state = state_verify_server_certificate;
    912       return ssl_hs_certificate_verify;
    913   }
    914 
    915   hs->state = state_read_server_key_exchange;
    916   return ssl_hs_ok;
    917 }
    918 
    919 static enum ssl_hs_wait_t do_read_server_key_exchange(SSL_HANDSHAKE *hs) {
    920   SSL *const ssl = hs->ssl;
    921   SSLMessage msg;
    922   if (!ssl->method->get_message(ssl, &msg)) {
    923     return ssl_hs_read_message;
    924   }
    925 
    926   if (msg.type != SSL3_MT_SERVER_KEY_EXCHANGE) {
    927     // Some ciphers (pure PSK) have an optional ServerKeyExchange message.
    928     if (ssl_cipher_requires_server_key_exchange(hs->new_cipher)) {
    929       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
    930       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
    931       return ssl_hs_error;
    932     }
    933 
    934     hs->state = state_read_certificate_request;
    935     return ssl_hs_ok;
    936   }
    937 
    938   if (!ssl_hash_message(hs, msg)) {
    939     return ssl_hs_error;
    940   }
    941 
    942   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
    943   uint32_t alg_a = hs->new_cipher->algorithm_auth;
    944   CBS server_key_exchange = msg.body;
    945   if (alg_a & SSL_aPSK) {
    946     CBS psk_identity_hint;
    947 
    948     // Each of the PSK key exchanges begins with a psk_identity_hint.
    949     if (!CBS_get_u16_length_prefixed(&server_key_exchange,
    950                                      &psk_identity_hint)) {
    951       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    952       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    953       return ssl_hs_error;
    954     }
    955 
    956     // Store the PSK identity hint for the ClientKeyExchange. Assume that the
    957     // maximum length of a PSK identity hint can be as long as the maximum
    958     // length of a PSK identity. Also do not allow NULL characters; identities
    959     // are saved as C strings.
    960     //
    961     // TODO(davidben): Should invalid hints be ignored? It's a hint rather than
    962     // a specific identity.
    963     if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
    964         CBS_contains_zero_byte(&psk_identity_hint)) {
    965       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
    966       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    967       return ssl_hs_error;
    968     }
    969 
    970     // Save non-empty identity hints as a C string. Empty identity hints we
    971     // treat as missing. Plain PSK makes it possible to send either no hint
    972     // (omit ServerKeyExchange) or an empty hint, while ECDHE_PSK can only spell
    973     // empty hint. Having different capabilities is odd, so we interpret empty
    974     // and missing as identical.
    975     char *raw = nullptr;
    976     if (CBS_len(&psk_identity_hint) != 0 &&
    977         !CBS_strdup(&psk_identity_hint, &raw)) {
    978       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    979       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    980       return ssl_hs_error;
    981     }
    982     hs->peer_psk_identity_hint.reset(raw);
    983   }
    984 
    985   if (alg_k & SSL_kECDHE) {
    986     // Parse the server parameters.
    987     uint8_t group_type;
    988     uint16_t group_id;
    989     CBS point;
    990     if (!CBS_get_u8(&server_key_exchange, &group_type) ||
    991         group_type != NAMED_CURVE_TYPE ||
    992         !CBS_get_u16(&server_key_exchange, &group_id) ||
    993         !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
    994       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    995       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    996       return ssl_hs_error;
    997     }
    998     hs->new_session->group_id = group_id;
    999 
   1000     // Ensure the group is consistent with preferences.
   1001     if (!tls1_check_group_id(ssl, group_id)) {
   1002       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
   1003       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
   1004       return ssl_hs_error;
   1005     }
   1006 
   1007     // Initialize ECDH and save the peer public key for later.
   1008     hs->key_share = SSLKeyShare::Create(group_id);
   1009     if (!hs->key_share ||
   1010         !hs->peer_key.CopyFrom(point)) {
   1011       return ssl_hs_error;
   1012     }
   1013   } else if (!(alg_k & SSL_kPSK)) {
   1014     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
   1015     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1016     return ssl_hs_error;
   1017   }
   1018 
   1019   // At this point, |server_key_exchange| contains the signature, if any, while
   1020   // |msg.body| contains the entire message. From that, derive a CBS containing
   1021   // just the parameter.
   1022   CBS parameter;
   1023   CBS_init(&parameter, CBS_data(&msg.body),
   1024            CBS_len(&msg.body) - CBS_len(&server_key_exchange));
   1025 
   1026   // ServerKeyExchange should be signed by the server's public key.
   1027   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
   1028     uint16_t signature_algorithm = 0;
   1029     if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
   1030       if (!CBS_get_u16(&server_key_exchange, &signature_algorithm)) {
   1031         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1032         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1033         return ssl_hs_error;
   1034       }
   1035       uint8_t alert = SSL_AD_DECODE_ERROR;
   1036       if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
   1037         ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1038         return ssl_hs_error;
   1039       }
   1040       hs->new_session->peer_signature_algorithm = signature_algorithm;
   1041     } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
   1042                                                     hs->peer_pubkey.get())) {
   1043       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
   1044       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
   1045       return ssl_hs_error;
   1046     }
   1047 
   1048     // The last field in |server_key_exchange| is the signature.
   1049     CBS signature;
   1050     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
   1051         CBS_len(&server_key_exchange) != 0) {
   1052       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1053       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1054       return ssl_hs_error;
   1055     }
   1056 
   1057     ScopedCBB transcript;
   1058     Array<uint8_t> transcript_data;
   1059     if (!CBB_init(transcript.get(),
   1060                   2 * SSL3_RANDOM_SIZE + CBS_len(&parameter)) ||
   1061         !CBB_add_bytes(transcript.get(), ssl->s3->client_random,
   1062                        SSL3_RANDOM_SIZE) ||
   1063         !CBB_add_bytes(transcript.get(), ssl->s3->server_random,
   1064                        SSL3_RANDOM_SIZE) ||
   1065         !CBB_add_bytes(transcript.get(), CBS_data(&parameter),
   1066                        CBS_len(&parameter)) ||
   1067         !CBBFinishArray(transcript.get(), &transcript_data)) {
   1068       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1069       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1070       return ssl_hs_error;
   1071     }
   1072 
   1073     bool sig_ok = ssl_public_key_verify(ssl, signature, signature_algorithm,
   1074                                         hs->peer_pubkey.get(), transcript_data);
   1075 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
   1076     sig_ok = true;
   1077     ERR_clear_error();
   1078 #endif
   1079     if (!sig_ok) {
   1080       // bad signature
   1081       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
   1082       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
   1083       return ssl_hs_error;
   1084     }
   1085   } else {
   1086     // PSK ciphers are the only supported certificate-less ciphers.
   1087     assert(alg_a == SSL_aPSK);
   1088 
   1089     if (CBS_len(&server_key_exchange) > 0) {
   1090       OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
   1091       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1092       return ssl_hs_error;
   1093     }
   1094   }
   1095 
   1096   ssl->method->next_message(ssl);
   1097   hs->state = state_read_certificate_request;
   1098   return ssl_hs_ok;
   1099 }
   1100 
   1101 static enum ssl_hs_wait_t do_read_certificate_request(SSL_HANDSHAKE *hs) {
   1102   SSL *const ssl = hs->ssl;
   1103 
   1104   if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
   1105     hs->state = state_read_server_hello_done;
   1106     return ssl_hs_ok;
   1107   }
   1108 
   1109   SSLMessage msg;
   1110   if (!ssl->method->get_message(ssl, &msg)) {
   1111     return ssl_hs_read_message;
   1112   }
   1113 
   1114   if (msg.type == SSL3_MT_SERVER_HELLO_DONE) {
   1115     // If we get here we don't need the handshake buffer as we won't be doing
   1116     // client auth.
   1117     hs->transcript.FreeBuffer();
   1118     hs->state = state_read_server_hello_done;
   1119     return ssl_hs_ok;
   1120   }
   1121 
   1122   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_REQUEST) ||
   1123       !ssl_hash_message(hs, msg)) {
   1124     return ssl_hs_error;
   1125   }
   1126 
   1127   // Get the certificate types.
   1128   CBS body = msg.body, certificate_types;
   1129   if (!CBS_get_u8_length_prefixed(&body, &certificate_types)) {
   1130     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1131     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1132     return ssl_hs_error;
   1133   }
   1134 
   1135   if (!hs->certificate_types.CopyFrom(certificate_types)) {
   1136     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1137     return ssl_hs_error;
   1138   }
   1139 
   1140   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
   1141     CBS supported_signature_algorithms;
   1142     if (!CBS_get_u16_length_prefixed(&body, &supported_signature_algorithms) ||
   1143         !tls1_parse_peer_sigalgs(hs, &supported_signature_algorithms)) {
   1144       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1145       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1146       return ssl_hs_error;
   1147     }
   1148   }
   1149 
   1150   uint8_t alert = SSL_AD_DECODE_ERROR;
   1151   UniquePtr<STACK_OF(CRYPTO_BUFFER)> ca_names =
   1152       ssl_parse_client_CA_list(ssl, &alert, &body);
   1153   if (!ca_names) {
   1154     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1155     return ssl_hs_error;
   1156   }
   1157 
   1158   if (CBS_len(&body) != 0) {
   1159     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1160     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1161     return ssl_hs_error;
   1162   }
   1163 
   1164   hs->cert_request = true;
   1165   hs->ca_names = std::move(ca_names);
   1166   ssl->ctx->x509_method->hs_flush_cached_ca_names(hs);
   1167 
   1168   ssl->method->next_message(ssl);
   1169   hs->state = state_read_server_hello_done;
   1170   return ssl_hs_ok;
   1171 }
   1172 
   1173 static enum ssl_hs_wait_t do_read_server_hello_done(SSL_HANDSHAKE *hs) {
   1174   SSL *const ssl = hs->ssl;
   1175   SSLMessage msg;
   1176   if (!ssl->method->get_message(ssl, &msg)) {
   1177     return ssl_hs_read_message;
   1178   }
   1179 
   1180   if (!ssl_check_message_type(ssl, msg, SSL3_MT_SERVER_HELLO_DONE) ||
   1181       !ssl_hash_message(hs, msg)) {
   1182     return ssl_hs_error;
   1183   }
   1184 
   1185   // ServerHelloDone is empty.
   1186   if (CBS_len(&msg.body) != 0) {
   1187     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1188     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1189     return ssl_hs_error;
   1190   }
   1191 
   1192   ssl->method->next_message(ssl);
   1193   hs->state = state_send_client_certificate;
   1194   return ssl_hs_ok;
   1195 }
   1196 
   1197 static enum ssl_hs_wait_t do_send_client_certificate(SSL_HANDSHAKE *hs) {
   1198   SSL *const ssl = hs->ssl;
   1199 
   1200   // The peer didn't request a certificate.
   1201   if (!hs->cert_request) {
   1202     hs->state = state_send_client_key_exchange;
   1203     return ssl_hs_ok;
   1204   }
   1205 
   1206   // Call cert_cb to update the certificate.
   1207   if (ssl->cert->cert_cb != NULL) {
   1208     int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
   1209     if (rv == 0) {
   1210       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1211       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
   1212       return ssl_hs_error;
   1213     }
   1214     if (rv < 0) {
   1215       hs->state = state_send_client_certificate;
   1216       return ssl_hs_x509_lookup;
   1217     }
   1218   }
   1219 
   1220   if (!ssl_has_certificate(ssl)) {
   1221     // Without a client certificate, the handshake buffer may be released.
   1222     hs->transcript.FreeBuffer();
   1223 
   1224     // In SSL 3.0, the Certificate message is replaced with a warning alert.
   1225     if (ssl->version == SSL3_VERSION) {
   1226       if (!ssl->method->add_alert(ssl, SSL3_AL_WARNING,
   1227                                   SSL_AD_NO_CERTIFICATE)) {
   1228         return ssl_hs_error;
   1229       }
   1230       hs->state = state_send_client_key_exchange;
   1231       return ssl_hs_ok;
   1232     }
   1233   }
   1234 
   1235   if (!ssl_on_certificate_selected(hs) ||
   1236       !ssl_output_cert_chain(ssl)) {
   1237     return ssl_hs_error;
   1238   }
   1239 
   1240 
   1241   hs->state = state_send_client_key_exchange;
   1242   return ssl_hs_ok;
   1243 }
   1244 
   1245 static_assert(sizeof(size_t) >= sizeof(unsigned),
   1246               "size_t is smaller than unsigned");
   1247 
   1248 static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) {
   1249   SSL *const ssl = hs->ssl;
   1250   ScopedCBB cbb;
   1251   CBB body;
   1252   if (!ssl->method->init_message(ssl, cbb.get(), &body,
   1253                                  SSL3_MT_CLIENT_KEY_EXCHANGE)) {
   1254     return ssl_hs_error;
   1255   }
   1256 
   1257   Array<uint8_t> pms;
   1258   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
   1259   uint32_t alg_a = hs->new_cipher->algorithm_auth;
   1260 
   1261   // If using a PSK key exchange, prepare the pre-shared key.
   1262   unsigned psk_len = 0;
   1263   uint8_t psk[PSK_MAX_PSK_LEN];
   1264   if (alg_a & SSL_aPSK) {
   1265     if (ssl->psk_client_callback == NULL) {
   1266       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
   1267       return ssl_hs_error;
   1268     }
   1269 
   1270     char identity[PSK_MAX_IDENTITY_LEN + 1];
   1271     OPENSSL_memset(identity, 0, sizeof(identity));
   1272     psk_len =
   1273         ssl->psk_client_callback(ssl, hs->peer_psk_identity_hint.get(),
   1274                                  identity, sizeof(identity), psk, sizeof(psk));
   1275     if (psk_len == 0) {
   1276       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
   1277       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1278       return ssl_hs_error;
   1279     }
   1280     assert(psk_len <= PSK_MAX_PSK_LEN);
   1281 
   1282     OPENSSL_free(hs->new_session->psk_identity);
   1283     hs->new_session->psk_identity = BUF_strdup(identity);
   1284     if (hs->new_session->psk_identity == NULL) {
   1285       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1286       return ssl_hs_error;
   1287     }
   1288 
   1289     // Write out psk_identity.
   1290     CBB child;
   1291     if (!CBB_add_u16_length_prefixed(&body, &child) ||
   1292         !CBB_add_bytes(&child, (const uint8_t *)identity,
   1293                        OPENSSL_strnlen(identity, sizeof(identity))) ||
   1294         !CBB_flush(&body)) {
   1295       return ssl_hs_error;
   1296     }
   1297   }
   1298 
   1299   // Depending on the key exchange method, compute |pms|.
   1300   if (alg_k & SSL_kRSA) {
   1301     if (!pms.Init(SSL_MAX_MASTER_KEY_LENGTH)) {
   1302       return ssl_hs_error;
   1303     }
   1304 
   1305     RSA *rsa = EVP_PKEY_get0_RSA(hs->peer_pubkey.get());
   1306     if (rsa == NULL) {
   1307       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1308       return ssl_hs_error;
   1309     }
   1310 
   1311     pms[0] = hs->client_version >> 8;
   1312     pms[1] = hs->client_version & 0xff;
   1313     if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
   1314       return ssl_hs_error;
   1315     }
   1316 
   1317     CBB child, *enc_pms = &body;
   1318     size_t enc_pms_len;
   1319     // In TLS, there is a length prefix.
   1320     if (ssl->version > SSL3_VERSION) {
   1321       if (!CBB_add_u16_length_prefixed(&body, &child)) {
   1322         return ssl_hs_error;
   1323       }
   1324       enc_pms = &child;
   1325     }
   1326 
   1327     uint8_t *ptr;
   1328     if (!CBB_reserve(enc_pms, &ptr, RSA_size(rsa)) ||
   1329         !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms.data(),
   1330                      pms.size(), RSA_PKCS1_PADDING) ||
   1331         !CBB_did_write(enc_pms, enc_pms_len) ||
   1332         !CBB_flush(&body)) {
   1333       return ssl_hs_error;
   1334     }
   1335   } else if (alg_k & SSL_kECDHE) {
   1336     // Generate a keypair and serialize the public half.
   1337     CBB child;
   1338     if (!CBB_add_u8_length_prefixed(&body, &child)) {
   1339       return ssl_hs_error;
   1340     }
   1341 
   1342     // Compute the premaster.
   1343     uint8_t alert = SSL_AD_DECODE_ERROR;
   1344     if (!hs->key_share->Accept(&child, &pms, &alert, hs->peer_key)) {
   1345       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1346       return ssl_hs_error;
   1347     }
   1348     if (!CBB_flush(&body)) {
   1349       return ssl_hs_error;
   1350     }
   1351 
   1352     // The key exchange state may now be discarded.
   1353     hs->key_share.reset();
   1354     hs->peer_key.Reset();
   1355   } else if (alg_k & SSL_kPSK) {
   1356     // For plain PSK, other_secret is a block of 0s with the same length as
   1357     // the pre-shared key.
   1358     if (!pms.Init(psk_len)) {
   1359       return ssl_hs_error;
   1360     }
   1361     OPENSSL_memset(pms.data(), 0, pms.size());
   1362   } else {
   1363     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1364     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1365     return ssl_hs_error;
   1366   }
   1367 
   1368   // For a PSK cipher suite, other_secret is combined with the pre-shared
   1369   // key.
   1370   if (alg_a & SSL_aPSK) {
   1371     ScopedCBB pms_cbb;
   1372     CBB child;
   1373     if (!CBB_init(pms_cbb.get(), 2 + psk_len + 2 + pms.size()) ||
   1374         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
   1375         !CBB_add_bytes(&child, pms.data(), pms.size()) ||
   1376         !CBB_add_u16_length_prefixed(pms_cbb.get(), &child) ||
   1377         !CBB_add_bytes(&child, psk, psk_len) ||
   1378         !CBBFinishArray(pms_cbb.get(), &pms)) {
   1379       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1380       return ssl_hs_error;
   1381     }
   1382   }
   1383 
   1384   // The message must be added to the finished hash before calculating the
   1385   // master secret.
   1386   if (!ssl_add_message_cbb(ssl, cbb.get())) {
   1387     return ssl_hs_error;
   1388   }
   1389 
   1390   hs->new_session->master_key_length =
   1391       tls1_generate_master_secret(hs, hs->new_session->master_key, pms);
   1392   if (hs->new_session->master_key_length == 0) {
   1393     return ssl_hs_error;
   1394   }
   1395   hs->new_session->extended_master_secret = hs->extended_master_secret;
   1396 
   1397   hs->state = state_send_client_certificate_verify;
   1398   return ssl_hs_ok;
   1399 }
   1400 
   1401 static enum ssl_hs_wait_t do_send_client_certificate_verify(SSL_HANDSHAKE *hs) {
   1402   SSL *const ssl = hs->ssl;
   1403 
   1404   if (!hs->cert_request || !ssl_has_certificate(ssl)) {
   1405     hs->state = state_send_client_finished;
   1406     return ssl_hs_ok;
   1407   }
   1408 
   1409   assert(ssl_has_private_key(ssl));
   1410   ScopedCBB cbb;
   1411   CBB body, child;
   1412   if (!ssl->method->init_message(ssl, cbb.get(), &body,
   1413                                  SSL3_MT_CERTIFICATE_VERIFY)) {
   1414     return ssl_hs_error;
   1415   }
   1416 
   1417   uint16_t signature_algorithm;
   1418   if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
   1419     return ssl_hs_error;
   1420   }
   1421   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
   1422     // Write out the digest type in TLS 1.2.
   1423     if (!CBB_add_u16(&body, signature_algorithm)) {
   1424       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1425       return ssl_hs_error;
   1426     }
   1427   }
   1428 
   1429   // Set aside space for the signature.
   1430   const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
   1431   uint8_t *ptr;
   1432   if (!CBB_add_u16_length_prefixed(&body, &child) ||
   1433       !CBB_reserve(&child, &ptr, max_sig_len)) {
   1434     return ssl_hs_error;
   1435   }
   1436 
   1437   size_t sig_len = max_sig_len;
   1438   // The SSL3 construction for CertificateVerify does not decompose into a
   1439   // single final digest and signature, and must be special-cased.
   1440   if (ssl_protocol_version(ssl) == SSL3_VERSION) {
   1441     if (ssl->cert->key_method != NULL) {
   1442       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL_FOR_CUSTOM_KEY);
   1443       return ssl_hs_error;
   1444     }
   1445 
   1446     uint8_t digest[EVP_MAX_MD_SIZE];
   1447     size_t digest_len;
   1448     if (!hs->transcript.GetSSL3CertVerifyHash(
   1449             digest, &digest_len, hs->new_session.get(), signature_algorithm)) {
   1450       return ssl_hs_error;
   1451     }
   1452 
   1453     UniquePtr<EVP_PKEY_CTX> pctx(EVP_PKEY_CTX_new(ssl->cert->privatekey, NULL));
   1454     if (!pctx ||
   1455         !EVP_PKEY_sign_init(pctx.get()) ||
   1456         !EVP_PKEY_sign(pctx.get(), ptr, &sig_len, digest, digest_len)) {
   1457       return ssl_hs_error;
   1458     }
   1459   } else {
   1460     switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
   1461                                  signature_algorithm,
   1462                                  hs->transcript.buffer())) {
   1463       case ssl_private_key_success:
   1464         break;
   1465       case ssl_private_key_failure:
   1466         return ssl_hs_error;
   1467       case ssl_private_key_retry:
   1468         hs->state = state_send_client_certificate_verify;
   1469         return ssl_hs_private_key_operation;
   1470     }
   1471   }
   1472 
   1473   if (!CBB_did_write(&child, sig_len) ||
   1474       !ssl_add_message_cbb(ssl, cbb.get())) {
   1475     return ssl_hs_error;
   1476   }
   1477 
   1478   // The handshake buffer is no longer necessary.
   1479   hs->transcript.FreeBuffer();
   1480 
   1481   hs->state = state_send_client_finished;
   1482   return ssl_hs_ok;
   1483 }
   1484 
   1485 static enum ssl_hs_wait_t do_send_client_finished(SSL_HANDSHAKE *hs) {
   1486   SSL *const ssl = hs->ssl;
   1487   // Resolve Channel ID first, before any non-idempotent operations.
   1488   if (ssl->s3->tlsext_channel_id_valid) {
   1489     if (!ssl_do_channel_id_callback(ssl)) {
   1490       return ssl_hs_error;
   1491     }
   1492 
   1493     if (ssl->tlsext_channel_id_private == NULL) {
   1494       hs->state = state_send_client_finished;
   1495       return ssl_hs_channel_id_lookup;
   1496     }
   1497   }
   1498 
   1499   if (!ssl->method->add_change_cipher_spec(ssl) ||
   1500       !tls1_change_cipher_state(hs, evp_aead_seal)) {
   1501     return ssl_hs_error;
   1502   }
   1503 
   1504   if (hs->next_proto_neg_seen) {
   1505     static const uint8_t kZero[32] = {0};
   1506     size_t padding_len =
   1507         32 - ((ssl->s3->next_proto_negotiated.size() + 2) % 32);
   1508 
   1509     ScopedCBB cbb;
   1510     CBB body, child;
   1511     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_NEXT_PROTO) ||
   1512         !CBB_add_u8_length_prefixed(&body, &child) ||
   1513         !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated.data(),
   1514                        ssl->s3->next_proto_negotiated.size()) ||
   1515         !CBB_add_u8_length_prefixed(&body, &child) ||
   1516         !CBB_add_bytes(&child, kZero, padding_len) ||
   1517         !ssl_add_message_cbb(ssl, cbb.get())) {
   1518       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1519       return ssl_hs_error;
   1520     }
   1521   }
   1522 
   1523   if (ssl->s3->tlsext_channel_id_valid) {
   1524     ScopedCBB cbb;
   1525     CBB body;
   1526     if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_CHANNEL_ID) ||
   1527         !tls1_write_channel_id(hs, &body) ||
   1528         !ssl_add_message_cbb(ssl, cbb.get())) {
   1529       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1530       return ssl_hs_error;
   1531     }
   1532   }
   1533 
   1534   if (!ssl_send_finished(hs)) {
   1535     return ssl_hs_error;
   1536   }
   1537 
   1538   hs->state = state_finish_flight;
   1539   return ssl_hs_flush;
   1540 }
   1541 
   1542 static bool can_false_start(const SSL_HANDSHAKE *hs) {
   1543   SSL *const ssl = hs->ssl;
   1544 
   1545   // False Start only for TLS 1.2 with an ECDHE+AEAD cipher.
   1546   if (SSL_is_dtls(ssl) ||
   1547       SSL_version(ssl) != TLS1_2_VERSION ||
   1548       hs->new_cipher->algorithm_mkey != SSL_kECDHE ||
   1549       hs->new_cipher->algorithm_mac != SSL_AEAD) {
   1550     return false;
   1551   }
   1552 
   1553   // Additionally require ALPN or NPN by default.
   1554   //
   1555   // TODO(davidben): Can this constraint be relaxed globally now that cipher
   1556   // suite requirements have been relaxed?
   1557   if (!ssl->ctx->false_start_allowed_without_alpn &&
   1558       ssl->s3->alpn_selected.empty() &&
   1559       ssl->s3->next_proto_negotiated.empty()) {
   1560     return false;
   1561   }
   1562 
   1563   return true;
   1564 }
   1565 
   1566 static enum ssl_hs_wait_t do_finish_flight(SSL_HANDSHAKE *hs) {
   1567   SSL *const ssl = hs->ssl;
   1568   if (ssl->session != NULL) {
   1569     hs->state = state_finish_client_handshake;
   1570     return ssl_hs_ok;
   1571   }
   1572 
   1573   // This is a full handshake. If it involves ChannelID, then record the
   1574   // handshake hashes at this point in the session so that any resumption of
   1575   // this session with ChannelID can sign those hashes.
   1576   if (!tls1_record_handshake_hashes_for_channel_id(hs)) {
   1577     return ssl_hs_error;
   1578   }
   1579 
   1580   hs->state = state_read_session_ticket;
   1581 
   1582   if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
   1583       can_false_start(hs) &&
   1584       // No False Start on renegotiation (would complicate the state machine).
   1585       !ssl->s3->initial_handshake_complete) {
   1586     hs->in_false_start = true;
   1587     hs->can_early_write = true;
   1588     return ssl_hs_early_return;
   1589   }
   1590 
   1591   return ssl_hs_ok;
   1592 }
   1593 
   1594 static enum ssl_hs_wait_t do_read_session_ticket(SSL_HANDSHAKE *hs) {
   1595   SSL *const ssl = hs->ssl;
   1596 
   1597   if (!hs->ticket_expected) {
   1598     hs->state = state_process_change_cipher_spec;
   1599     return ssl_hs_read_change_cipher_spec;
   1600   }
   1601 
   1602   SSLMessage msg;
   1603   if (!ssl->method->get_message(ssl, &msg)) {
   1604     return ssl_hs_read_message;
   1605   }
   1606 
   1607   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEW_SESSION_TICKET) ||
   1608       !ssl_hash_message(hs, msg)) {
   1609     return ssl_hs_error;
   1610   }
   1611 
   1612   CBS new_session_ticket = msg.body, ticket;
   1613   uint32_t tlsext_tick_lifetime_hint;
   1614   if (!CBS_get_u32(&new_session_ticket, &tlsext_tick_lifetime_hint) ||
   1615       !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
   1616       CBS_len(&new_session_ticket) != 0) {
   1617     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1618     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1619     return ssl_hs_error;
   1620   }
   1621 
   1622   if (CBS_len(&ticket) == 0) {
   1623     // RFC 5077 allows a server to change its mind and send no ticket after
   1624     // negotiating the extension. The value of |ticket_expected| is checked in
   1625     // |ssl_update_cache| so is cleared here to avoid an unnecessary update.
   1626     hs->ticket_expected = false;
   1627     ssl->method->next_message(ssl);
   1628     hs->state = state_process_change_cipher_spec;
   1629     return ssl_hs_read_change_cipher_spec;
   1630   }
   1631 
   1632   SSL_SESSION *session = hs->new_session.get();
   1633   UniquePtr<SSL_SESSION> renewed_session;
   1634   if (ssl->session != NULL) {
   1635     // The server is sending a new ticket for an existing session. Sessions are
   1636     // immutable once established, so duplicate all but the ticket of the
   1637     // existing session.
   1638     renewed_session =
   1639         SSL_SESSION_dup(ssl->session, SSL_SESSION_INCLUDE_NONAUTH);
   1640     if (!renewed_session) {
   1641       // This should never happen.
   1642       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1643       return ssl_hs_error;
   1644     }
   1645     session = renewed_session.get();
   1646   }
   1647 
   1648   // |tlsext_tick_lifetime_hint| is measured from when the ticket was issued.
   1649   ssl_session_rebase_time(ssl, session);
   1650 
   1651   if (!CBS_stow(&ticket, &session->tlsext_tick, &session->tlsext_ticklen)) {
   1652     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1653     return ssl_hs_error;
   1654   }
   1655   session->tlsext_tick_lifetime_hint = tlsext_tick_lifetime_hint;
   1656 
   1657   // Generate a session ID for this session based on the session ticket. We use
   1658   // the session ID mechanism for detecting ticket resumption. This also fits in
   1659   // with assumptions elsewhere in OpenSSL.
   1660   if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket),
   1661                   session->session_id, &session->session_id_length,
   1662                   EVP_sha256(), NULL)) {
   1663     return ssl_hs_error;
   1664   }
   1665 
   1666   if (renewed_session) {
   1667     session->not_resumable = 0;
   1668     SSL_SESSION_free(ssl->session);
   1669     ssl->session = renewed_session.release();
   1670   }
   1671 
   1672   ssl->method->next_message(ssl);
   1673   hs->state = state_process_change_cipher_spec;
   1674   return ssl_hs_read_change_cipher_spec;
   1675 }
   1676 
   1677 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
   1678   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
   1679     return ssl_hs_error;
   1680   }
   1681 
   1682   hs->state = state_read_server_finished;
   1683   return ssl_hs_ok;
   1684 }
   1685 
   1686 static enum ssl_hs_wait_t do_read_server_finished(SSL_HANDSHAKE *hs) {
   1687   SSL *const ssl = hs->ssl;
   1688   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
   1689   if (wait != ssl_hs_ok) {
   1690     return wait;
   1691   }
   1692 
   1693   if (ssl->session != NULL) {
   1694     hs->state = state_send_client_finished;
   1695     return ssl_hs_ok;
   1696   }
   1697 
   1698   hs->state = state_finish_client_handshake;
   1699   return ssl_hs_ok;
   1700 }
   1701 
   1702 static enum ssl_hs_wait_t do_finish_client_handshake(SSL_HANDSHAKE *hs) {
   1703   SSL *const ssl = hs->ssl;
   1704 
   1705   ssl->method->on_handshake_complete(ssl);
   1706 
   1707   if (ssl->session != NULL) {
   1708     SSL_SESSION_up_ref(ssl->session);
   1709     ssl->s3->established_session.reset(ssl->session);
   1710   } else {
   1711     // We make a copy of the session in order to maintain the immutability
   1712     // of the new established_session due to False Start. The caller may
   1713     // have taken a reference to the temporary session.
   1714     ssl->s3->established_session =
   1715         SSL_SESSION_dup(hs->new_session.get(), SSL_SESSION_DUP_ALL);
   1716     if (!ssl->s3->established_session) {
   1717       return ssl_hs_error;
   1718     }
   1719     // Renegotiations do not participate in session resumption.
   1720     if (!ssl->s3->initial_handshake_complete) {
   1721       ssl->s3->established_session->not_resumable = 0;
   1722     }
   1723 
   1724     hs->new_session.reset();
   1725   }
   1726 
   1727   hs->handshake_finalized = true;
   1728   ssl->s3->initial_handshake_complete = true;
   1729   ssl_update_cache(hs, SSL_SESS_CACHE_CLIENT);
   1730 
   1731   hs->state = state_done;
   1732   return ssl_hs_ok;
   1733 }
   1734 
   1735 enum ssl_hs_wait_t ssl_client_handshake(SSL_HANDSHAKE *hs) {
   1736   while (hs->state != state_done) {
   1737     enum ssl_hs_wait_t ret = ssl_hs_error;
   1738     enum ssl_client_hs_state_t state =
   1739         static_cast<enum ssl_client_hs_state_t>(hs->state);
   1740     switch (state) {
   1741       case state_start_connect:
   1742         ret = do_start_connect(hs);
   1743         break;
   1744       case state_enter_early_data:
   1745         ret = do_enter_early_data(hs);
   1746         break;
   1747       case state_read_hello_verify_request:
   1748         ret = do_read_hello_verify_request(hs);
   1749         break;
   1750       case state_read_server_hello:
   1751         ret = do_read_server_hello(hs);
   1752         break;
   1753       case state_tls13:
   1754         ret = do_tls13(hs);
   1755         break;
   1756       case state_read_server_certificate:
   1757         ret = do_read_server_certificate(hs);
   1758         break;
   1759       case state_read_certificate_status:
   1760         ret = do_read_certificate_status(hs);
   1761         break;
   1762       case state_verify_server_certificate:
   1763         ret = do_verify_server_certificate(hs);
   1764         break;
   1765       case state_read_server_key_exchange:
   1766         ret = do_read_server_key_exchange(hs);
   1767         break;
   1768       case state_read_certificate_request:
   1769         ret = do_read_certificate_request(hs);
   1770         break;
   1771       case state_read_server_hello_done:
   1772         ret = do_read_server_hello_done(hs);
   1773         break;
   1774       case state_send_client_certificate:
   1775         ret = do_send_client_certificate(hs);
   1776         break;
   1777       case state_send_client_key_exchange:
   1778         ret = do_send_client_key_exchange(hs);
   1779         break;
   1780       case state_send_client_certificate_verify:
   1781         ret = do_send_client_certificate_verify(hs);
   1782         break;
   1783       case state_send_client_finished:
   1784         ret = do_send_client_finished(hs);
   1785         break;
   1786       case state_finish_flight:
   1787         ret = do_finish_flight(hs);
   1788         break;
   1789       case state_read_session_ticket:
   1790         ret = do_read_session_ticket(hs);
   1791         break;
   1792       case state_process_change_cipher_spec:
   1793         ret = do_process_change_cipher_spec(hs);
   1794         break;
   1795       case state_read_server_finished:
   1796         ret = do_read_server_finished(hs);
   1797         break;
   1798       case state_finish_client_handshake:
   1799         ret = do_finish_client_handshake(hs);
   1800         break;
   1801       case state_done:
   1802         ret = ssl_hs_ok;
   1803         break;
   1804     }
   1805 
   1806     if (hs->state != state) {
   1807       ssl_do_info_callback(hs->ssl, SSL_CB_CONNECT_LOOP, 1);
   1808     }
   1809 
   1810     if (ret != ssl_hs_ok) {
   1811       return ret;
   1812     }
   1813   }
   1814 
   1815   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
   1816   return ssl_hs_ok;
   1817 }
   1818 
   1819 const char *ssl_client_handshake_state(SSL_HANDSHAKE *hs) {
   1820   enum ssl_client_hs_state_t state =
   1821       static_cast<enum ssl_client_hs_state_t>(hs->state);
   1822   switch (state) {
   1823     case state_start_connect:
   1824       return "TLS client start_connect";
   1825     case state_enter_early_data:
   1826       return "TLS client enter_early_data";
   1827     case state_read_hello_verify_request:
   1828       return "TLS client read_hello_verify_request";
   1829     case state_read_server_hello:
   1830       return "TLS client read_server_hello";
   1831     case state_tls13:
   1832       return tls13_client_handshake_state(hs);
   1833     case state_read_server_certificate:
   1834       return "TLS client read_server_certificate";
   1835     case state_read_certificate_status:
   1836       return "TLS client read_certificate_status";
   1837     case state_verify_server_certificate:
   1838       return "TLS client verify_server_certificate";
   1839     case state_read_server_key_exchange:
   1840       return "TLS client read_server_key_exchange";
   1841     case state_read_certificate_request:
   1842       return "TLS client read_certificate_request";
   1843     case state_read_server_hello_done:
   1844       return "TLS client read_server_hello_done";
   1845     case state_send_client_certificate:
   1846       return "TLS client send_client_certificate";
   1847     case state_send_client_key_exchange:
   1848       return "TLS client send_client_key_exchange";
   1849     case state_send_client_certificate_verify:
   1850       return "TLS client send_client_certificate_verify";
   1851     case state_send_client_finished:
   1852       return "TLS client send_client_finished";
   1853     case state_finish_flight:
   1854       return "TLS client finish_flight";
   1855     case state_read_session_ticket:
   1856       return "TLS client read_session_ticket";
   1857     case state_process_change_cipher_spec:
   1858       return "TLS client process_change_cipher_spec";
   1859     case state_read_server_finished:
   1860       return "TLS client read_server_finished";
   1861     case state_finish_client_handshake:
   1862       return "TLS client finish_client_handshake";
   1863     case state_done:
   1864       return "TLS client done";
   1865   }
   1866 
   1867   return "TLS client unknown";
   1868 }
   1869 
   1870 }
   1871