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 #include <openssl/ssl.h>
    150 
    151 #include <assert.h>
    152 #include <string.h>
    153 
    154 #include <openssl/bn.h>
    155 #include <openssl/buf.h>
    156 #include <openssl/bytestring.h>
    157 #include <openssl/cipher.h>
    158 #include <openssl/ec.h>
    159 #include <openssl/ecdsa.h>
    160 #include <openssl/err.h>
    161 #include <openssl/evp.h>
    162 #include <openssl/hmac.h>
    163 #include <openssl/md5.h>
    164 #include <openssl/mem.h>
    165 #include <openssl/nid.h>
    166 #include <openssl/rand.h>
    167 #include <openssl/x509.h>
    168 
    169 #include "internal.h"
    170 #include "../crypto/internal.h"
    171 
    172 
    173 BSSL_NAMESPACE_BEGIN
    174 
    175 bool ssl_client_cipher_list_contains_cipher(
    176     const SSL_CLIENT_HELLO *client_hello, uint16_t id) {
    177   CBS cipher_suites;
    178   CBS_init(&cipher_suites, client_hello->cipher_suites,
    179            client_hello->cipher_suites_len);
    180 
    181   while (CBS_len(&cipher_suites) > 0) {
    182     uint16_t got_id;
    183     if (!CBS_get_u16(&cipher_suites, &got_id)) {
    184       return false;
    185     }
    186 
    187     if (got_id == id) {
    188       return true;
    189     }
    190   }
    191 
    192   return false;
    193 }
    194 
    195 static bool negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
    196                               const SSL_CLIENT_HELLO *client_hello) {
    197   SSL *const ssl = hs->ssl;
    198   assert(!ssl->s3->have_version);
    199   CBS supported_versions, versions;
    200   if (ssl_client_hello_get_extension(client_hello, &supported_versions,
    201                                      TLSEXT_TYPE_supported_versions)) {
    202     if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
    203         CBS_len(&supported_versions) != 0 ||
    204         CBS_len(&versions) == 0) {
    205       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    206       *out_alert = SSL_AD_DECODE_ERROR;
    207       return false;
    208     }
    209   } else {
    210     // Convert the ClientHello version to an equivalent supported_versions
    211     // extension.
    212     static const uint8_t kTLSVersions[] = {
    213         0x03, 0x03,  // TLS 1.2
    214         0x03, 0x02,  // TLS 1.1
    215         0x03, 0x01,  // TLS 1
    216     };
    217 
    218     static const uint8_t kDTLSVersions[] = {
    219         0xfe, 0xfd,  // DTLS 1.2
    220         0xfe, 0xff,  // DTLS 1.0
    221     };
    222 
    223     size_t versions_len = 0;
    224     if (SSL_is_dtls(ssl)) {
    225       if (client_hello->version <= DTLS1_2_VERSION) {
    226         versions_len = 4;
    227       } else if (client_hello->version <= DTLS1_VERSION) {
    228         versions_len = 2;
    229       }
    230       CBS_init(&versions, kDTLSVersions + sizeof(kDTLSVersions) - versions_len,
    231                versions_len);
    232     } else {
    233       if (client_hello->version >= TLS1_2_VERSION) {
    234         versions_len = 6;
    235       } else if (client_hello->version >= TLS1_1_VERSION) {
    236         versions_len = 4;
    237       } else if (client_hello->version >= TLS1_VERSION) {
    238         versions_len = 2;
    239       }
    240       CBS_init(&versions, kTLSVersions + sizeof(kTLSVersions) - versions_len,
    241                versions_len);
    242     }
    243   }
    244 
    245   if (!ssl_negotiate_version(hs, out_alert, &ssl->version, &versions)) {
    246     return false;
    247   }
    248 
    249   // At this point, the connection's version is known and |ssl->version| is
    250   // fixed. Begin enforcing the record-layer version.
    251   ssl->s3->have_version = true;
    252   ssl->s3->aead_write_ctx->SetVersionIfNullCipher(ssl->version);
    253 
    254   // Handle FALLBACK_SCSV.
    255   if (ssl_client_cipher_list_contains_cipher(client_hello,
    256                                              SSL3_CK_FALLBACK_SCSV & 0xffff) &&
    257       ssl_protocol_version(ssl) < hs->max_version) {
    258     OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
    259     *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
    260     return false;
    261   }
    262 
    263   return true;
    264 }
    265 
    266 static UniquePtr<STACK_OF(SSL_CIPHER)> ssl_parse_client_cipher_list(
    267     const SSL_CLIENT_HELLO *client_hello) {
    268   CBS cipher_suites;
    269   CBS_init(&cipher_suites, client_hello->cipher_suites,
    270            client_hello->cipher_suites_len);
    271 
    272   UniquePtr<STACK_OF(SSL_CIPHER)> sk(sk_SSL_CIPHER_new_null());
    273   if (!sk) {
    274     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    275     return nullptr;
    276   }
    277 
    278   while (CBS_len(&cipher_suites) > 0) {
    279     uint16_t cipher_suite;
    280 
    281     if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
    282       OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
    283       return nullptr;
    284     }
    285 
    286     const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
    287     if (c != NULL && !sk_SSL_CIPHER_push(sk.get(), c)) {
    288       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    289       return nullptr;
    290     }
    291   }
    292 
    293   return sk;
    294 }
    295 
    296 // ssl_get_compatible_server_ciphers determines the key exchange and
    297 // authentication cipher suite masks compatible with the server configuration
    298 // and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
    299 // exchange mask and |*out_mask_a| to the authentication mask.
    300 static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
    301                                               uint32_t *out_mask_k,
    302                                               uint32_t *out_mask_a) {
    303   uint32_t mask_k = 0;
    304   uint32_t mask_a = 0;
    305 
    306   if (ssl_has_certificate(hs)) {
    307     mask_a |= ssl_cipher_auth_mask_for_key(hs->local_pubkey.get());
    308     if (EVP_PKEY_id(hs->local_pubkey.get()) == EVP_PKEY_RSA) {
    309       mask_k |= SSL_kRSA;
    310     }
    311   }
    312 
    313   // Check for a shared group to consider ECDHE ciphers.
    314   uint16_t unused;
    315   if (tls1_get_shared_group(hs, &unused)) {
    316     mask_k |= SSL_kECDHE;
    317   }
    318 
    319   // PSK requires a server callback.
    320   if (hs->config->psk_server_callback != NULL) {
    321     mask_k |= SSL_kPSK;
    322     mask_a |= SSL_aPSK;
    323   }
    324 
    325   *out_mask_k = mask_k;
    326   *out_mask_a = mask_a;
    327 }
    328 
    329 static const SSL_CIPHER *ssl3_choose_cipher(
    330     SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
    331     const SSLCipherPreferenceList *server_pref) {
    332   SSL *const ssl = hs->ssl;
    333   const STACK_OF(SSL_CIPHER) *prio, *allow;
    334   // in_group_flags will either be NULL, or will point to an array of bytes
    335   // which indicate equal-preference groups in the |prio| stack. See the
    336   // comment about |in_group_flags| in the |SSLCipherPreferenceList|
    337   // struct.
    338   const bool *in_group_flags;
    339   // group_min contains the minimal index so far found in a group, or -1 if no
    340   // such value exists yet.
    341   int group_min = -1;
    342 
    343   UniquePtr<STACK_OF(SSL_CIPHER)> client_pref =
    344       ssl_parse_client_cipher_list(client_hello);
    345   if (!client_pref) {
    346     return nullptr;
    347   }
    348 
    349   if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
    350     prio = server_pref->ciphers.get();
    351     in_group_flags = server_pref->in_group_flags;
    352     allow = client_pref.get();
    353   } else {
    354     prio = client_pref.get();
    355     in_group_flags = NULL;
    356     allow = server_pref->ciphers.get();
    357   }
    358 
    359   uint32_t mask_k, mask_a;
    360   ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
    361 
    362   for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
    363     const SSL_CIPHER *c = sk_SSL_CIPHER_value(prio, i);
    364 
    365     size_t cipher_index;
    366     if (// Check if the cipher is supported for the current version.
    367         SSL_CIPHER_get_min_version(c) <= ssl_protocol_version(ssl) &&
    368         ssl_protocol_version(ssl) <= SSL_CIPHER_get_max_version(c) &&
    369         // Check the cipher is supported for the server configuration.
    370         (c->algorithm_mkey & mask_k) &&
    371         (c->algorithm_auth & mask_a) &&
    372         // Check the cipher is in the |allow| list.
    373         sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
    374       if (in_group_flags != NULL && in_group_flags[i]) {
    375         // This element of |prio| is in a group. Update the minimum index found
    376         // so far and continue looking.
    377         if (group_min == -1 || (size_t)group_min > cipher_index) {
    378           group_min = cipher_index;
    379         }
    380       } else {
    381         if (group_min != -1 && (size_t)group_min < cipher_index) {
    382           cipher_index = group_min;
    383         }
    384         return sk_SSL_CIPHER_value(allow, cipher_index);
    385       }
    386     }
    387 
    388     if (in_group_flags != NULL && !in_group_flags[i] && group_min != -1) {
    389       // We are about to leave a group, but we found a match in it, so that's
    390       // our answer.
    391       return sk_SSL_CIPHER_value(allow, group_min);
    392     }
    393   }
    394 
    395   return nullptr;
    396 }
    397 
    398 static enum ssl_hs_wait_t do_start_accept(SSL_HANDSHAKE *hs) {
    399   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_START, 1);
    400   hs->state = state12_read_client_hello;
    401   return ssl_hs_ok;
    402 }
    403 
    404 // is_probably_jdk11_with_tls13 returns whether |client_hello| was probably sent
    405 // from a JDK 11 client with both TLS 1.3 and a prior version enabled.
    406 static bool is_probably_jdk11_with_tls13(const SSL_CLIENT_HELLO *client_hello) {
    407   // JDK 11 ClientHellos contain a number of unusual properties which should
    408   // limit false positives.
    409 
    410   // JDK 11 does not support ChaCha20-Poly1305. This is unusual: many modern
    411   // clients implement ChaCha20-Poly1305.
    412   if (ssl_client_cipher_list_contains_cipher(
    413           client_hello, TLS1_CK_CHACHA20_POLY1305_SHA256 & 0xffff)) {
    414     return false;
    415   }
    416 
    417   // JDK 11 always sends extensions in a particular order.
    418   constexpr uint16_t kMaxFragmentLength = 0x0001;
    419   constexpr uint16_t kStatusRequestV2 = 0x0011;
    420   static CONSTEXPR_ARRAY struct {
    421     uint16_t id;
    422     bool required;
    423   } kJavaExtensions[] = {
    424       {TLSEXT_TYPE_server_name, false},
    425       {kMaxFragmentLength, false},
    426       {TLSEXT_TYPE_status_request, false},
    427       {TLSEXT_TYPE_supported_groups, true},
    428       {TLSEXT_TYPE_ec_point_formats, false},
    429       {TLSEXT_TYPE_signature_algorithms, true},
    430       // Java always sends signature_algorithms_cert.
    431       {TLSEXT_TYPE_signature_algorithms_cert, true},
    432       {TLSEXT_TYPE_application_layer_protocol_negotiation, false},
    433       {kStatusRequestV2, false},
    434       {TLSEXT_TYPE_extended_master_secret, false},
    435       {TLSEXT_TYPE_supported_versions, true},
    436       {TLSEXT_TYPE_cookie, false},
    437       {TLSEXT_TYPE_psk_key_exchange_modes, true},
    438       {TLSEXT_TYPE_key_share, true},
    439       {TLSEXT_TYPE_renegotiate, false},
    440       {TLSEXT_TYPE_pre_shared_key, false},
    441   };
    442   Span<const uint8_t> sigalgs, sigalgs_cert;
    443   bool has_status_request = false, has_status_request_v2 = false;
    444   CBS extensions, supported_groups;
    445   CBS_init(&extensions, client_hello->extensions, client_hello->extensions_len);
    446   for (const auto &java_extension : kJavaExtensions) {
    447     CBS copy = extensions;
    448     uint16_t id;
    449     if (CBS_get_u16(&copy, &id) && id == java_extension.id) {
    450       // The next extension is the one we expected.
    451       extensions = copy;
    452       CBS body;
    453       if (!CBS_get_u16_length_prefixed(&extensions, &body)) {
    454         return false;
    455       }
    456       switch (id) {
    457         case TLSEXT_TYPE_status_request:
    458           has_status_request = true;
    459           break;
    460         case kStatusRequestV2:
    461           has_status_request_v2 = true;
    462           break;
    463         case TLSEXT_TYPE_signature_algorithms:
    464           sigalgs = body;
    465           break;
    466         case TLSEXT_TYPE_signature_algorithms_cert:
    467           sigalgs_cert = body;
    468           break;
    469         case TLSEXT_TYPE_supported_groups:
    470           supported_groups = body;
    471           break;
    472       }
    473     } else if (java_extension.required) {
    474       return false;
    475     }
    476   }
    477   if (CBS_len(&extensions) != 0) {
    478     return false;
    479   }
    480 
    481   // JDK 11 never advertises X25519. It is not offered by default, and
    482   // -Djdk.tls.namedGroups=x25519 does not work. This is unusual: many modern
    483   // clients implement X25519.
    484   while (CBS_len(&supported_groups) > 0) {
    485     uint16_t group;
    486     if (!CBS_get_u16(&supported_groups, &group) ||
    487         group == SSL_CURVE_X25519) {
    488       return false;
    489     }
    490   }
    491 
    492   if (// JDK 11 always sends the same contents in signature_algorithms and
    493       // signature_algorithms_cert. This is unusual: signature_algorithms_cert,
    494       // if omitted, is treated as if it were signature_algorithms.
    495       sigalgs != sigalgs_cert ||
    496       // When TLS 1.2 or below is enabled, JDK 11 sends status_request_v2 iff it
    497       // sends status_request. This is unusual: status_request_v2 is not widely
    498       // implemented.
    499       has_status_request != has_status_request_v2) {
    500     return false;
    501   }
    502 
    503   return true;
    504 }
    505 
    506 static enum ssl_hs_wait_t do_read_client_hello(SSL_HANDSHAKE *hs) {
    507   SSL *const ssl = hs->ssl;
    508 
    509   SSLMessage msg;
    510   if (!ssl->method->get_message(ssl, &msg)) {
    511     return ssl_hs_read_message;
    512   }
    513 
    514   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_HELLO)) {
    515     return ssl_hs_error;
    516   }
    517 
    518   if (hs->config->handoff) {
    519     return ssl_hs_handoff;
    520   }
    521 
    522   SSL_CLIENT_HELLO client_hello;
    523   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
    524     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    525     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
    526     return ssl_hs_error;
    527   }
    528 
    529   // Run the early callback.
    530   if (ssl->ctx->select_certificate_cb != NULL) {
    531     switch (ssl->ctx->select_certificate_cb(&client_hello)) {
    532       case ssl_select_cert_retry:
    533         return ssl_hs_certificate_selection_pending;
    534 
    535       case ssl_select_cert_error:
    536         // Connection rejected.
    537         OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
    538         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    539         return ssl_hs_error;
    540 
    541       default:
    542         /* fallthrough */;
    543     }
    544   }
    545 
    546   // Freeze the version range after the early callback.
    547   if (!ssl_get_version_range(hs, &hs->min_version, &hs->max_version)) {
    548     return ssl_hs_error;
    549   }
    550 
    551   if (hs->config->jdk11_workaround &&
    552       is_probably_jdk11_with_tls13(&client_hello)) {
    553     hs->apply_jdk11_workaround = true;
    554   }
    555 
    556   uint8_t alert = SSL_AD_DECODE_ERROR;
    557   if (!negotiate_version(hs, &alert, &client_hello)) {
    558     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
    559     return ssl_hs_error;
    560   }
    561 
    562   hs->client_version = client_hello.version;
    563   if (client_hello.random_len != SSL3_RANDOM_SIZE) {
    564     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    565     return ssl_hs_error;
    566   }
    567   OPENSSL_memcpy(ssl->s3->client_random, client_hello.random,
    568                  client_hello.random_len);
    569 
    570   // Only null compression is supported. TLS 1.3 further requires the peer
    571   // advertise no other compression.
    572   if (OPENSSL_memchr(client_hello.compression_methods, 0,
    573                      client_hello.compression_methods_len) == NULL ||
    574       (ssl_protocol_version(ssl) >= TLS1_3_VERSION &&
    575        client_hello.compression_methods_len != 1)) {
    576     OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_COMPRESSION_LIST);
    577     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
    578     return ssl_hs_error;
    579   }
    580 
    581   // TLS extensions.
    582   if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
    583     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
    584     return ssl_hs_error;
    585   }
    586 
    587   hs->state = state12_select_certificate;
    588   return ssl_hs_ok;
    589 }
    590 
    591 static enum ssl_hs_wait_t do_select_certificate(SSL_HANDSHAKE *hs) {
    592   SSL *const ssl = hs->ssl;
    593 
    594   SSLMessage msg;
    595   if (!ssl->method->get_message(ssl, &msg)) {
    596     return ssl_hs_read_message;
    597   }
    598 
    599   // Call |cert_cb| to update server certificates if required.
    600   if (hs->config->cert->cert_cb != NULL) {
    601     int rv = hs->config->cert->cert_cb(ssl, hs->config->cert->cert_cb_arg);
    602     if (rv == 0) {
    603       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
    604       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    605       return ssl_hs_error;
    606     }
    607     if (rv < 0) {
    608       return ssl_hs_x509_lookup;
    609     }
    610   }
    611 
    612   if (!ssl_on_certificate_selected(hs)) {
    613     return ssl_hs_error;
    614   }
    615 
    616   if (hs->ocsp_stapling_requested &&
    617       ssl->ctx->legacy_ocsp_callback != nullptr) {
    618     switch (ssl->ctx->legacy_ocsp_callback(
    619         ssl, ssl->ctx->legacy_ocsp_callback_arg)) {
    620       case SSL_TLSEXT_ERR_OK:
    621         break;
    622       case SSL_TLSEXT_ERR_NOACK:
    623         hs->ocsp_stapling_requested = false;
    624         break;
    625       default:
    626         OPENSSL_PUT_ERROR(SSL, SSL_R_OCSP_CB_ERROR);
    627         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    628         return ssl_hs_error;
    629     }
    630   }
    631 
    632   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    633     // Jump to the TLS 1.3 state machine.
    634     hs->state = state12_tls13;
    635     return ssl_hs_ok;
    636   }
    637 
    638   SSL_CLIENT_HELLO client_hello;
    639   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
    640     return ssl_hs_error;
    641   }
    642 
    643   // Negotiate the cipher suite. This must be done after |cert_cb| so the
    644   // certificate is finalized.
    645   SSLCipherPreferenceList *prefs = hs->config->cipher_list
    646                                        ? hs->config->cipher_list.get()
    647                                        : ssl->ctx->cipher_list.get();
    648   hs->new_cipher = ssl3_choose_cipher(hs, &client_hello, prefs);
    649   if (hs->new_cipher == NULL) {
    650     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
    651     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    652     return ssl_hs_error;
    653   }
    654 
    655   hs->state = state12_select_parameters;
    656   return ssl_hs_ok;
    657 }
    658 
    659 static enum ssl_hs_wait_t do_tls13(SSL_HANDSHAKE *hs) {
    660   enum ssl_hs_wait_t wait = tls13_server_handshake(hs);
    661   if (wait == ssl_hs_ok) {
    662     hs->state = state12_finish_server_handshake;
    663     return ssl_hs_ok;
    664   }
    665 
    666   return wait;
    667 }
    668 
    669 static enum ssl_hs_wait_t do_select_parameters(SSL_HANDSHAKE *hs) {
    670   SSL *const ssl = hs->ssl;
    671 
    672   SSLMessage msg;
    673   if (!ssl->method->get_message(ssl, &msg)) {
    674     return ssl_hs_read_message;
    675   }
    676 
    677   SSL_CLIENT_HELLO client_hello;
    678   if (!ssl_client_hello_init(ssl, &client_hello, msg)) {
    679     return ssl_hs_error;
    680   }
    681 
    682   // Determine whether we are doing session resumption.
    683   UniquePtr<SSL_SESSION> session;
    684   bool tickets_supported = false, renew_ticket = false;
    685   enum ssl_hs_wait_t wait = ssl_get_prev_session(
    686       hs, &session, &tickets_supported, &renew_ticket, &client_hello);
    687   if (wait != ssl_hs_ok) {
    688     return wait;
    689   }
    690 
    691   if (session) {
    692     if (session->extended_master_secret && !hs->extended_master_secret) {
    693       // A ClientHello without EMS that attempts to resume a session with EMS
    694       // is fatal to the connection.
    695       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
    696       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    697       return ssl_hs_error;
    698     }
    699 
    700     if (!ssl_session_is_resumable(hs, session.get()) ||
    701         // If the client offers the EMS extension, but the previous session
    702         // didn't use it, then negotiate a new session.
    703         hs->extended_master_secret != session->extended_master_secret) {
    704       session.reset();
    705     }
    706   }
    707 
    708   if (session) {
    709     // Use the old session.
    710     hs->ticket_expected = renew_ticket;
    711     ssl->session = std::move(session);
    712     ssl->s3->session_reused = true;
    713   } else {
    714     hs->ticket_expected = tickets_supported;
    715     ssl_set_session(ssl, NULL);
    716     if (!ssl_get_new_session(hs, 1 /* server */)) {
    717       return ssl_hs_error;
    718     }
    719 
    720     // Clear the session ID if we want the session to be single-use.
    721     if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
    722       hs->new_session->session_id_length = 0;
    723     }
    724   }
    725 
    726   if (ssl->ctx->dos_protection_cb != NULL &&
    727       ssl->ctx->dos_protection_cb(&client_hello) == 0) {
    728     // Connection rejected for DOS reasons.
    729     OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
    730     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    731     return ssl_hs_error;
    732   }
    733 
    734   if (ssl->session == NULL) {
    735     hs->new_session->cipher = hs->new_cipher;
    736 
    737     // Determine whether to request a client certificate.
    738     hs->cert_request = !!(hs->config->verify_mode & SSL_VERIFY_PEER);
    739     // Only request a certificate if Channel ID isn't negotiated.
    740     if ((hs->config->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
    741         ssl->s3->channel_id_valid) {
    742       hs->cert_request = false;
    743     }
    744     // CertificateRequest may only be sent in certificate-based ciphers.
    745     if (!ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    746       hs->cert_request = false;
    747     }
    748 
    749     if (!hs->cert_request) {
    750       // OpenSSL returns X509_V_OK when no certificates are requested. This is
    751       // classed by them as a bug, but it's assumed by at least NGINX.
    752       hs->new_session->verify_result = X509_V_OK;
    753     }
    754   }
    755 
    756   // HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
    757   // deferred. Complete it now.
    758   uint8_t alert = SSL_AD_DECODE_ERROR;
    759   if (!ssl_negotiate_alpn(hs, &alert, &client_hello)) {
    760     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
    761     return ssl_hs_error;
    762   }
    763 
    764   // Now that all parameters are known, initialize the handshake hash and hash
    765   // the ClientHello.
    766   if (!hs->transcript.InitHash(ssl_protocol_version(ssl), hs->new_cipher) ||
    767       !ssl_hash_message(hs, msg)) {
    768     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    769     return ssl_hs_error;
    770   }
    771 
    772   // Handback includes the whole handshake transcript, so we cannot free the
    773   // transcript buffer in the handback case.
    774   if (!hs->cert_request && !hs->handback) {
    775     hs->transcript.FreeBuffer();
    776   }
    777 
    778   ssl->method->next_message(ssl);
    779 
    780   hs->state = state12_send_server_hello;
    781   return ssl_hs_ok;
    782 }
    783 
    784 static void copy_suffix(Span<uint8_t> out, Span<const uint8_t> in) {
    785   out = out.subspan(out.size() - in.size());
    786   assert(out.size() == in.size());
    787   OPENSSL_memcpy(out.data(), in.data(), in.size());
    788 }
    789 
    790 static enum ssl_hs_wait_t do_send_server_hello(SSL_HANDSHAKE *hs) {
    791   SSL *const ssl = hs->ssl;
    792 
    793   // We only accept ChannelIDs on connections with ECDHE in order to avoid a
    794   // known attack while we fix ChannelID itself.
    795   if (ssl->s3->channel_id_valid &&
    796       (hs->new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
    797     ssl->s3->channel_id_valid = false;
    798   }
    799 
    800   // If this is a resumption and the original handshake didn't support
    801   // ChannelID then we didn't record the original handshake hashes in the
    802   // session and so cannot resume with ChannelIDs.
    803   if (ssl->session != NULL &&
    804       ssl->session->original_handshake_hash_len == 0) {
    805     ssl->s3->channel_id_valid = false;
    806   }
    807 
    808   struct OPENSSL_timeval now;
    809   ssl_get_current_time(ssl, &now);
    810   ssl->s3->server_random[0] = now.tv_sec >> 24;
    811   ssl->s3->server_random[1] = now.tv_sec >> 16;
    812   ssl->s3->server_random[2] = now.tv_sec >> 8;
    813   ssl->s3->server_random[3] = now.tv_sec;
    814   if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
    815     return ssl_hs_error;
    816   }
    817 
    818   // Implement the TLS 1.3 anti-downgrade feature.
    819   if (ssl_supports_version(hs, TLS1_3_VERSION)) {
    820     if (ssl_protocol_version(ssl) == TLS1_2_VERSION) {
    821       if (hs->apply_jdk11_workaround) {
    822         // JDK 11 implements the TLS 1.3 downgrade signal, so we cannot send it
    823         // here. However, the signal is only effective if all TLS 1.2
    824         // ServerHellos produced by the server are marked. Thus we send a
    825         // different non-standard signal for the time being, until JDK 11.0.2 is
    826         // released and clients have updated.
    827         copy_suffix(ssl->s3->server_random, kJDK11DowngradeRandom);
    828       } else {
    829         copy_suffix(ssl->s3->server_random, kTLS13DowngradeRandom);
    830       }
    831     } else {
    832       copy_suffix(ssl->s3->server_random, kTLS12DowngradeRandom);
    833     }
    834   }
    835 
    836   const SSL_SESSION *session = hs->new_session.get();
    837   if (ssl->session != nullptr) {
    838     session = ssl->session.get();
    839   }
    840 
    841   ScopedCBB cbb;
    842   CBB body, session_id;
    843   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_SERVER_HELLO) ||
    844       !CBB_add_u16(&body, ssl->version) ||
    845       !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
    846       !CBB_add_u8_length_prefixed(&body, &session_id) ||
    847       !CBB_add_bytes(&session_id, session->session_id,
    848                      session->session_id_length) ||
    849       !CBB_add_u16(&body, ssl_cipher_get_value(hs->new_cipher)) ||
    850       !CBB_add_u8(&body, 0 /* no compression */) ||
    851       !ssl_add_serverhello_tlsext(hs, &body) ||
    852       !ssl_add_message_cbb(ssl, cbb.get())) {
    853     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    854     return ssl_hs_error;
    855   }
    856 
    857   if (ssl->session != NULL) {
    858     hs->state = state12_send_server_finished;
    859   } else {
    860     hs->state = state12_send_server_certificate;
    861   }
    862   return ssl_hs_ok;
    863 }
    864 
    865 static enum ssl_hs_wait_t do_send_server_certificate(SSL_HANDSHAKE *hs) {
    866   SSL *const ssl = hs->ssl;
    867   ScopedCBB cbb;
    868 
    869   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    870     if (!ssl_has_certificate(hs)) {
    871       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
    872       return ssl_hs_error;
    873     }
    874 
    875     if (!ssl_output_cert_chain(hs)) {
    876       return ssl_hs_error;
    877     }
    878 
    879     if (hs->certificate_status_expected) {
    880       CBB body, ocsp_response;
    881       if (!ssl->method->init_message(ssl, cbb.get(), &body,
    882                                      SSL3_MT_CERTIFICATE_STATUS) ||
    883           !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
    884           !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
    885           !CBB_add_bytes(
    886               &ocsp_response,
    887               CRYPTO_BUFFER_data(hs->config->cert->ocsp_response.get()),
    888               CRYPTO_BUFFER_len(hs->config->cert->ocsp_response.get())) ||
    889           !ssl_add_message_cbb(ssl, cbb.get())) {
    890         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    891         return ssl_hs_error;
    892       }
    893     }
    894   }
    895 
    896   // Assemble ServerKeyExchange parameters if needed.
    897   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
    898   uint32_t alg_a = hs->new_cipher->algorithm_auth;
    899   if (ssl_cipher_requires_server_key_exchange(hs->new_cipher) ||
    900       ((alg_a & SSL_aPSK) && hs->config->psk_identity_hint)) {
    901     // Pre-allocate enough room to comfortably fit an ECDHE public key. Prepend
    902     // the client and server randoms for the signing transcript.
    903     CBB child;
    904     if (!CBB_init(cbb.get(), SSL3_RANDOM_SIZE * 2 + 128) ||
    905         !CBB_add_bytes(cbb.get(), ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
    906         !CBB_add_bytes(cbb.get(), ssl->s3->server_random, SSL3_RANDOM_SIZE)) {
    907       return ssl_hs_error;
    908     }
    909 
    910     // PSK ciphers begin with an identity hint.
    911     if (alg_a & SSL_aPSK) {
    912       size_t len = hs->config->psk_identity_hint == nullptr
    913                        ? 0
    914                        : strlen(hs->config->psk_identity_hint.get());
    915       if (!CBB_add_u16_length_prefixed(cbb.get(), &child) ||
    916           !CBB_add_bytes(&child,
    917                          (const uint8_t *)hs->config->psk_identity_hint.get(),
    918                          len)) {
    919         return ssl_hs_error;
    920       }
    921     }
    922 
    923     if (alg_k & SSL_kECDHE) {
    924       // Determine the group to use.
    925       uint16_t group_id;
    926       if (!tls1_get_shared_group(hs, &group_id)) {
    927         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    928         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    929         return ssl_hs_error;
    930        }
    931       hs->new_session->group_id = group_id;
    932 
    933       // Set up ECDH, generate a key, and emit the public half.
    934       hs->key_shares[0] = SSLKeyShare::Create(group_id);
    935       if (!hs->key_shares[0] ||
    936           !CBB_add_u8(cbb.get(), NAMED_CURVE_TYPE) ||
    937           !CBB_add_u16(cbb.get(), group_id) ||
    938           !CBB_add_u8_length_prefixed(cbb.get(), &child) ||
    939           !hs->key_shares[0]->Offer(&child)) {
    940         return ssl_hs_error;
    941       }
    942     } else {
    943       assert(alg_k & SSL_kPSK);
    944     }
    945 
    946     if (!CBBFinishArray(cbb.get(), &hs->server_params)) {
    947       return ssl_hs_error;
    948     }
    949   }
    950 
    951   hs->state = state12_send_server_key_exchange;
    952   return ssl_hs_ok;
    953 }
    954 
    955 static enum ssl_hs_wait_t do_send_server_key_exchange(SSL_HANDSHAKE *hs) {
    956   SSL *const ssl = hs->ssl;
    957 
    958   if (hs->server_params.size() == 0) {
    959     hs->state = state12_send_server_hello_done;
    960     return ssl_hs_ok;
    961   }
    962 
    963   ScopedCBB cbb;
    964   CBB body, child;
    965   if (!ssl->method->init_message(ssl, cbb.get(), &body,
    966                                  SSL3_MT_SERVER_KEY_EXCHANGE) ||
    967       // |hs->server_params| contains a prefix for signing.
    968       hs->server_params.size() < 2 * SSL3_RANDOM_SIZE ||
    969       !CBB_add_bytes(&body, hs->server_params.data() + 2 * SSL3_RANDOM_SIZE,
    970                      hs->server_params.size() - 2 * SSL3_RANDOM_SIZE)) {
    971     return ssl_hs_error;
    972   }
    973 
    974   // Add a signature.
    975   if (ssl_cipher_uses_certificate_auth(hs->new_cipher)) {
    976     if (!ssl_has_private_key(hs)) {
    977       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    978       return ssl_hs_error;
    979     }
    980 
    981     // Determine the signature algorithm.
    982     uint16_t signature_algorithm;
    983     if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
    984       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
    985       return ssl_hs_error;
    986     }
    987     if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
    988       if (!CBB_add_u16(&body, signature_algorithm)) {
    989         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    990         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
    991         return ssl_hs_error;
    992       }
    993     }
    994 
    995     // Add space for the signature.
    996     const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
    997     uint8_t *ptr;
    998     if (!CBB_add_u16_length_prefixed(&body, &child) ||
    999         !CBB_reserve(&child, &ptr, max_sig_len)) {
   1000       return ssl_hs_error;
   1001     }
   1002 
   1003     size_t sig_len;
   1004     switch (ssl_private_key_sign(hs, ptr, &sig_len, max_sig_len,
   1005                                  signature_algorithm, hs->server_params)) {
   1006       case ssl_private_key_success:
   1007         if (!CBB_did_write(&child, sig_len)) {
   1008           return ssl_hs_error;
   1009         }
   1010         break;
   1011       case ssl_private_key_failure:
   1012         return ssl_hs_error;
   1013       case ssl_private_key_retry:
   1014         return ssl_hs_private_key_operation;
   1015     }
   1016   }
   1017 
   1018   if (!ssl_add_message_cbb(ssl, cbb.get())) {
   1019     return ssl_hs_error;
   1020   }
   1021 
   1022   hs->server_params.Reset();
   1023 
   1024   hs->state = state12_send_server_hello_done;
   1025   return ssl_hs_ok;
   1026 }
   1027 
   1028 static enum ssl_hs_wait_t do_send_server_hello_done(SSL_HANDSHAKE *hs) {
   1029   SSL *const ssl = hs->ssl;
   1030 
   1031   ScopedCBB cbb;
   1032   CBB body;
   1033 
   1034   if (hs->cert_request) {
   1035     CBB cert_types, sigalgs_cbb;
   1036     if (!ssl->method->init_message(ssl, cbb.get(), &body,
   1037                                    SSL3_MT_CERTIFICATE_REQUEST) ||
   1038         !CBB_add_u8_length_prefixed(&body, &cert_types) ||
   1039         !CBB_add_u8(&cert_types, SSL3_CT_RSA_SIGN) ||
   1040         !CBB_add_u8(&cert_types, TLS_CT_ECDSA_SIGN) ||
   1041         // TLS 1.2 has no way to specify different signature algorithms for
   1042         // certificates and the online signature, so emit the more restrictive
   1043         // certificate list.
   1044         (ssl_protocol_version(ssl) >= TLS1_2_VERSION &&
   1045          (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb) ||
   1046           !tls12_add_verify_sigalgs(ssl, &sigalgs_cbb, true /* certs */))) ||
   1047         !ssl_add_client_CA_list(hs, &body) ||
   1048         !ssl_add_message_cbb(ssl, cbb.get())) {
   1049       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1050       return ssl_hs_error;
   1051     }
   1052   }
   1053 
   1054   if (!ssl->method->init_message(ssl, cbb.get(), &body,
   1055                                  SSL3_MT_SERVER_HELLO_DONE) ||
   1056       !ssl_add_message_cbb(ssl, cbb.get())) {
   1057     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1058     return ssl_hs_error;
   1059   }
   1060 
   1061   hs->state = state12_read_client_certificate;
   1062   return ssl_hs_flush;
   1063 }
   1064 
   1065 static enum ssl_hs_wait_t do_read_client_certificate(SSL_HANDSHAKE *hs) {
   1066   SSL *const ssl = hs->ssl;
   1067 
   1068   if (hs->handback && hs->new_cipher->algorithm_mkey == SSL_kECDHE) {
   1069     return ssl_hs_handback;
   1070   }
   1071   if (!hs->cert_request) {
   1072     hs->state = state12_verify_client_certificate;
   1073     return ssl_hs_ok;
   1074   }
   1075 
   1076   SSLMessage msg;
   1077   if (!ssl->method->get_message(ssl, &msg)) {
   1078     return ssl_hs_read_message;
   1079   }
   1080 
   1081   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE)) {
   1082     return ssl_hs_error;
   1083   }
   1084 
   1085   if (!ssl_hash_message(hs, msg)) {
   1086     return ssl_hs_error;
   1087   }
   1088 
   1089   CBS certificate_msg = msg.body;
   1090   uint8_t alert = SSL_AD_DECODE_ERROR;
   1091   if (!ssl_parse_cert_chain(&alert, &hs->new_session->certs, &hs->peer_pubkey,
   1092                             hs->config->retain_only_sha256_of_client_certs
   1093                                 ? hs->new_session->peer_sha256
   1094                                 : nullptr,
   1095                             &certificate_msg, ssl->ctx->pool)) {
   1096     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1097     return ssl_hs_error;
   1098   }
   1099 
   1100   if (CBS_len(&certificate_msg) != 0 ||
   1101       !ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
   1102     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1103     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1104     return ssl_hs_error;
   1105   }
   1106 
   1107   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
   1108     // No client certificate so the handshake buffer may be discarded.
   1109     hs->transcript.FreeBuffer();
   1110 
   1111     if (hs->config->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
   1112       // Fail for TLS only if we required a certificate
   1113       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
   1114       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1115       return ssl_hs_error;
   1116     }
   1117 
   1118     // OpenSSL returns X509_V_OK when no certificates are received. This is
   1119     // classed by them as a bug, but it's assumed by at least NGINX.
   1120     hs->new_session->verify_result = X509_V_OK;
   1121   } else if (hs->config->retain_only_sha256_of_client_certs) {
   1122     // The hash will have been filled in.
   1123     hs->new_session->peer_sha256_valid = 1;
   1124   }
   1125 
   1126   ssl->method->next_message(ssl);
   1127   hs->state = state12_verify_client_certificate;
   1128   return ssl_hs_ok;
   1129 }
   1130 
   1131 static enum ssl_hs_wait_t do_verify_client_certificate(SSL_HANDSHAKE *hs) {
   1132   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) > 0) {
   1133     switch (ssl_verify_peer_cert(hs)) {
   1134       case ssl_verify_ok:
   1135         break;
   1136       case ssl_verify_invalid:
   1137         return ssl_hs_error;
   1138       case ssl_verify_retry:
   1139         return ssl_hs_certificate_verify;
   1140     }
   1141   }
   1142 
   1143   hs->state = state12_read_client_key_exchange;
   1144   return ssl_hs_ok;
   1145 }
   1146 
   1147 static enum ssl_hs_wait_t do_read_client_key_exchange(SSL_HANDSHAKE *hs) {
   1148   SSL *const ssl = hs->ssl;
   1149   SSLMessage msg;
   1150   if (!ssl->method->get_message(ssl, &msg)) {
   1151     return ssl_hs_read_message;
   1152   }
   1153 
   1154   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CLIENT_KEY_EXCHANGE)) {
   1155     return ssl_hs_error;
   1156   }
   1157 
   1158   CBS client_key_exchange = msg.body;
   1159   uint32_t alg_k = hs->new_cipher->algorithm_mkey;
   1160   uint32_t alg_a = hs->new_cipher->algorithm_auth;
   1161 
   1162   // If using a PSK key exchange, parse the PSK identity.
   1163   if (alg_a & SSL_aPSK) {
   1164     CBS psk_identity;
   1165 
   1166     // If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
   1167     // then this is the only field in the message.
   1168     if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
   1169         ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
   1170       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1171       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1172       return ssl_hs_error;
   1173     }
   1174 
   1175     if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
   1176         CBS_contains_zero_byte(&psk_identity)) {
   1177       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
   1178       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
   1179       return ssl_hs_error;
   1180     }
   1181     char *raw = nullptr;
   1182     if (!CBS_strdup(&psk_identity, &raw)) {
   1183       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1184       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1185       return ssl_hs_error;
   1186     }
   1187     hs->new_session->psk_identity.reset(raw);
   1188   }
   1189 
   1190   // Depending on the key exchange method, compute |premaster_secret|.
   1191   Array<uint8_t> premaster_secret;
   1192   if (alg_k & SSL_kRSA) {
   1193     CBS encrypted_premaster_secret;
   1194     if (!CBS_get_u16_length_prefixed(&client_key_exchange,
   1195                                      &encrypted_premaster_secret) ||
   1196         CBS_len(&client_key_exchange) != 0) {
   1197       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1198       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1199       return ssl_hs_error;
   1200     }
   1201 
   1202     // Allocate a buffer large enough for an RSA decryption.
   1203     Array<uint8_t> decrypt_buf;
   1204     if (!decrypt_buf.Init(EVP_PKEY_size(hs->local_pubkey.get()))) {
   1205       return ssl_hs_error;
   1206     }
   1207 
   1208     // Decrypt with no padding. PKCS#1 padding will be removed as part of the
   1209     // timing-sensitive code below.
   1210     size_t decrypt_len;
   1211     switch (ssl_private_key_decrypt(hs, decrypt_buf.data(), &decrypt_len,
   1212                                     decrypt_buf.size(),
   1213                                     encrypted_premaster_secret)) {
   1214       case ssl_private_key_success:
   1215         break;
   1216       case ssl_private_key_failure:
   1217         return ssl_hs_error;
   1218       case ssl_private_key_retry:
   1219         return ssl_hs_private_key_operation;
   1220     }
   1221 
   1222     if (decrypt_len != decrypt_buf.size()) {
   1223       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
   1224       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
   1225       return ssl_hs_error;
   1226     }
   1227 
   1228     CONSTTIME_SECRET(decrypt_buf.data(), decrypt_len);
   1229 
   1230     // Prepare a random premaster, to be used on invalid padding. See RFC 5246,
   1231     // section 7.4.7.1.
   1232     if (!premaster_secret.Init(SSL_MAX_MASTER_KEY_LENGTH) ||
   1233         !RAND_bytes(premaster_secret.data(), premaster_secret.size())) {
   1234       return ssl_hs_error;
   1235     }
   1236 
   1237     // The smallest padded premaster is 11 bytes of overhead. Small keys are
   1238     // publicly invalid.
   1239     if (decrypt_len < 11 + premaster_secret.size()) {
   1240       OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
   1241       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
   1242       return ssl_hs_error;
   1243     }
   1244 
   1245     // Check the padding. See RFC 3447, section 7.2.2.
   1246     size_t padding_len = decrypt_len - premaster_secret.size();
   1247     uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
   1248                    constant_time_eq_int_8(decrypt_buf[1], 2);
   1249     for (size_t i = 2; i < padding_len - 1; i++) {
   1250       good &= ~constant_time_is_zero_8(decrypt_buf[i]);
   1251     }
   1252     good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
   1253 
   1254     // The premaster secret must begin with |client_version|. This too must be
   1255     // checked in constant time (http://eprint.iacr.org/2003/052/).
   1256     good &= constant_time_eq_8(decrypt_buf[padding_len],
   1257                                (unsigned)(hs->client_version >> 8));
   1258     good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
   1259                                (unsigned)(hs->client_version & 0xff));
   1260 
   1261     // Select, in constant time, either the decrypted premaster or the random
   1262     // premaster based on |good|.
   1263     for (size_t i = 0; i < premaster_secret.size(); i++) {
   1264       premaster_secret[i] = constant_time_select_8(
   1265           good, decrypt_buf[padding_len + i], premaster_secret[i]);
   1266     }
   1267   } else if (alg_k & SSL_kECDHE) {
   1268     // Parse the ClientKeyExchange.
   1269     CBS peer_key;
   1270     if (!CBS_get_u8_length_prefixed(&client_key_exchange, &peer_key) ||
   1271         CBS_len(&client_key_exchange) != 0) {
   1272       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1273       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1274       return ssl_hs_error;
   1275     }
   1276 
   1277     // Compute the premaster.
   1278     uint8_t alert = SSL_AD_DECODE_ERROR;
   1279     if (!hs->key_shares[0]->Finish(&premaster_secret, &alert, peer_key)) {
   1280       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1281       return ssl_hs_error;
   1282     }
   1283 
   1284     // The key exchange state may now be discarded.
   1285     hs->key_shares[0].reset();
   1286     hs->key_shares[1].reset();
   1287   } else if (!(alg_k & SSL_kPSK)) {
   1288     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1289     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1290     return ssl_hs_error;
   1291   }
   1292 
   1293   // For a PSK cipher suite, the actual pre-master secret is combined with the
   1294   // pre-shared key.
   1295   if (alg_a & SSL_aPSK) {
   1296     if (hs->config->psk_server_callback == NULL) {
   1297       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1298       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1299       return ssl_hs_error;
   1300     }
   1301 
   1302     // Look up the key for the identity.
   1303     uint8_t psk[PSK_MAX_PSK_LEN];
   1304     unsigned psk_len = hs->config->psk_server_callback(
   1305         ssl, hs->new_session->psk_identity.get(), psk, sizeof(psk));
   1306     if (psk_len > PSK_MAX_PSK_LEN) {
   1307       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1308       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1309       return ssl_hs_error;
   1310     } else if (psk_len == 0) {
   1311       // PSK related to the given identity not found.
   1312       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
   1313       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNKNOWN_PSK_IDENTITY);
   1314       return ssl_hs_error;
   1315     }
   1316 
   1317     if (alg_k & SSL_kPSK) {
   1318       // In plain PSK, other_secret is a block of 0s with the same length as the
   1319       // pre-shared key.
   1320       if (!premaster_secret.Init(psk_len)) {
   1321         return ssl_hs_error;
   1322       }
   1323       OPENSSL_memset(premaster_secret.data(), 0, premaster_secret.size());
   1324     }
   1325 
   1326     ScopedCBB new_premaster;
   1327     CBB child;
   1328     if (!CBB_init(new_premaster.get(),
   1329                   2 + psk_len + 2 + premaster_secret.size()) ||
   1330         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
   1331         !CBB_add_bytes(&child, premaster_secret.data(),
   1332                        premaster_secret.size()) ||
   1333         !CBB_add_u16_length_prefixed(new_premaster.get(), &child) ||
   1334         !CBB_add_bytes(&child, psk, psk_len) ||
   1335         !CBBFinishArray(new_premaster.get(), &premaster_secret)) {
   1336       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1337       return ssl_hs_error;
   1338     }
   1339   }
   1340 
   1341   if (!ssl_hash_message(hs, msg)) {
   1342     return ssl_hs_error;
   1343   }
   1344 
   1345   // Compute the master secret.
   1346   hs->new_session->master_key_length = tls1_generate_master_secret(
   1347       hs, hs->new_session->master_key, premaster_secret);
   1348   if (hs->new_session->master_key_length == 0) {
   1349     return ssl_hs_error;
   1350   }
   1351   hs->new_session->extended_master_secret = hs->extended_master_secret;
   1352   CONSTTIME_DECLASSIFY(hs->new_session->master_key,
   1353                        hs->new_session->master_key_length);
   1354 
   1355   ssl->method->next_message(ssl);
   1356   hs->state = state12_read_client_certificate_verify;
   1357   return ssl_hs_ok;
   1358 }
   1359 
   1360 static enum ssl_hs_wait_t do_read_client_certificate_verify(SSL_HANDSHAKE *hs) {
   1361   SSL *const ssl = hs->ssl;
   1362 
   1363   // Only RSA and ECDSA client certificates are supported, so a
   1364   // CertificateVerify is required if and only if there's a client certificate.
   1365   if (!hs->peer_pubkey) {
   1366     hs->transcript.FreeBuffer();
   1367     hs->state = state12_read_change_cipher_spec;
   1368     return ssl_hs_ok;
   1369   }
   1370 
   1371   SSLMessage msg;
   1372   if (!ssl->method->get_message(ssl, &msg)) {
   1373     return ssl_hs_read_message;
   1374   }
   1375 
   1376   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CERTIFICATE_VERIFY)) {
   1377     return ssl_hs_error;
   1378   }
   1379 
   1380   CBS certificate_verify = msg.body, signature;
   1381 
   1382   // Determine the signature algorithm.
   1383   uint16_t signature_algorithm = 0;
   1384   if (ssl_protocol_version(ssl) >= TLS1_2_VERSION) {
   1385     if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
   1386       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1387       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1388       return ssl_hs_error;
   1389     }
   1390     uint8_t alert = SSL_AD_DECODE_ERROR;
   1391     if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
   1392       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
   1393       return ssl_hs_error;
   1394     }
   1395     hs->new_session->peer_signature_algorithm = signature_algorithm;
   1396   } else if (!tls1_get_legacy_signature_algorithm(&signature_algorithm,
   1397                                                   hs->peer_pubkey.get())) {
   1398     OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
   1399     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_CERTIFICATE);
   1400     return ssl_hs_error;
   1401   }
   1402 
   1403   // Parse and verify the signature.
   1404   if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
   1405       CBS_len(&certificate_verify) != 0) {
   1406     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1407     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1408     return ssl_hs_error;
   1409   }
   1410 
   1411   bool sig_ok =
   1412       ssl_public_key_verify(ssl, signature, signature_algorithm,
   1413                             hs->peer_pubkey.get(), hs->transcript.buffer());
   1414 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
   1415   sig_ok = true;
   1416   ERR_clear_error();
   1417 #endif
   1418   if (!sig_ok) {
   1419     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
   1420     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
   1421     return ssl_hs_error;
   1422   }
   1423 
   1424   // The handshake buffer is no longer necessary, and we may hash the current
   1425   // message.
   1426   hs->transcript.FreeBuffer();
   1427   if (!ssl_hash_message(hs, msg)) {
   1428     return ssl_hs_error;
   1429   }
   1430 
   1431   ssl->method->next_message(ssl);
   1432   hs->state = state12_read_change_cipher_spec;
   1433   return ssl_hs_ok;
   1434 }
   1435 
   1436 static enum ssl_hs_wait_t do_read_change_cipher_spec(SSL_HANDSHAKE *hs) {
   1437   if (hs->handback && hs->ssl->session != NULL) {
   1438     return ssl_hs_handback;
   1439   }
   1440   hs->state = state12_process_change_cipher_spec;
   1441   return ssl_hs_read_change_cipher_spec;
   1442 }
   1443 
   1444 static enum ssl_hs_wait_t do_process_change_cipher_spec(SSL_HANDSHAKE *hs) {
   1445   if (!tls1_change_cipher_state(hs, evp_aead_open)) {
   1446     return ssl_hs_error;
   1447   }
   1448 
   1449   hs->state = state12_read_next_proto;
   1450   return ssl_hs_ok;
   1451 }
   1452 
   1453 static enum ssl_hs_wait_t do_read_next_proto(SSL_HANDSHAKE *hs) {
   1454   SSL *const ssl = hs->ssl;
   1455 
   1456   if (!hs->next_proto_neg_seen) {
   1457     hs->state = state12_read_channel_id;
   1458     return ssl_hs_ok;
   1459   }
   1460 
   1461   SSLMessage msg;
   1462   if (!ssl->method->get_message(ssl, &msg)) {
   1463     return ssl_hs_read_message;
   1464   }
   1465 
   1466   if (!ssl_check_message_type(ssl, msg, SSL3_MT_NEXT_PROTO) ||
   1467       !ssl_hash_message(hs, msg)) {
   1468     return ssl_hs_error;
   1469   }
   1470 
   1471   CBS next_protocol = msg.body, selected_protocol, padding;
   1472   if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
   1473       !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
   1474       CBS_len(&next_protocol) != 0) {
   1475     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1476     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1477     return ssl_hs_error;
   1478   }
   1479 
   1480   if (!ssl->s3->next_proto_negotiated.CopyFrom(selected_protocol)) {
   1481     return ssl_hs_error;
   1482   }
   1483 
   1484   ssl->method->next_message(ssl);
   1485   hs->state = state12_read_channel_id;
   1486   return ssl_hs_ok;
   1487 }
   1488 
   1489 static enum ssl_hs_wait_t do_read_channel_id(SSL_HANDSHAKE *hs) {
   1490   SSL *const ssl = hs->ssl;
   1491 
   1492   if (!ssl->s3->channel_id_valid) {
   1493     hs->state = state12_read_client_finished;
   1494     return ssl_hs_ok;
   1495   }
   1496 
   1497   SSLMessage msg;
   1498   if (!ssl->method->get_message(ssl, &msg)) {
   1499     return ssl_hs_read_message;
   1500   }
   1501 
   1502   if (!ssl_check_message_type(ssl, msg, SSL3_MT_CHANNEL_ID) ||
   1503       !tls1_verify_channel_id(hs, msg) ||
   1504       !ssl_hash_message(hs, msg)) {
   1505     return ssl_hs_error;
   1506   }
   1507 
   1508   ssl->method->next_message(ssl);
   1509   hs->state = state12_read_client_finished;
   1510   return ssl_hs_ok;
   1511 }
   1512 
   1513 static enum ssl_hs_wait_t do_read_client_finished(SSL_HANDSHAKE *hs) {
   1514   SSL *const ssl = hs->ssl;
   1515   enum ssl_hs_wait_t wait = ssl_get_finished(hs);
   1516   if (wait != ssl_hs_ok) {
   1517     return wait;
   1518   }
   1519 
   1520   if (ssl->session != NULL) {
   1521     hs->state = state12_finish_server_handshake;
   1522   } else {
   1523     hs->state = state12_send_server_finished;
   1524   }
   1525 
   1526   // If this is a full handshake with ChannelID then record the handshake
   1527   // hashes in |hs->new_session| in case we need them to verify a
   1528   // ChannelID signature on a resumption of this session in the future.
   1529   if (ssl->session == NULL && ssl->s3->channel_id_valid &&
   1530       !tls1_record_handshake_hashes_for_channel_id(hs)) {
   1531     return ssl_hs_error;
   1532   }
   1533 
   1534   return ssl_hs_ok;
   1535 }
   1536 
   1537 static enum ssl_hs_wait_t do_send_server_finished(SSL_HANDSHAKE *hs) {
   1538   SSL *const ssl = hs->ssl;
   1539 
   1540   if (hs->ticket_expected) {
   1541     const SSL_SESSION *session;
   1542     UniquePtr<SSL_SESSION> session_copy;
   1543     if (ssl->session == NULL) {
   1544       // Fix the timeout to measure from the ticket issuance time.
   1545       ssl_session_rebase_time(ssl, hs->new_session.get());
   1546       session = hs->new_session.get();
   1547     } else {
   1548       // We are renewing an existing session. Duplicate the session to adjust
   1549       // the timeout.
   1550       session_copy =
   1551           SSL_SESSION_dup(ssl->session.get(), SSL_SESSION_INCLUDE_NONAUTH);
   1552       if (!session_copy) {
   1553         return ssl_hs_error;
   1554       }
   1555 
   1556       ssl_session_rebase_time(ssl, session_copy.get());
   1557       session = session_copy.get();
   1558     }
   1559 
   1560     ScopedCBB cbb;
   1561     CBB body, ticket;
   1562     if (!ssl->method->init_message(ssl, cbb.get(), &body,
   1563                                    SSL3_MT_NEW_SESSION_TICKET) ||
   1564         !CBB_add_u32(&body, session->timeout) ||
   1565         !CBB_add_u16_length_prefixed(&body, &ticket) ||
   1566         !ssl_encrypt_ticket(hs, &ticket, session) ||
   1567         !ssl_add_message_cbb(ssl, cbb.get())) {
   1568       return ssl_hs_error;
   1569     }
   1570   }
   1571 
   1572   if (!ssl->method->add_change_cipher_spec(ssl) ||
   1573       !tls1_change_cipher_state(hs, evp_aead_seal) ||
   1574       !ssl_send_finished(hs)) {
   1575     return ssl_hs_error;
   1576   }
   1577 
   1578   if (ssl->session != NULL) {
   1579     hs->state = state12_read_change_cipher_spec;
   1580   } else {
   1581     hs->state = state12_finish_server_handshake;
   1582   }
   1583   return ssl_hs_flush;
   1584 }
   1585 
   1586 static enum ssl_hs_wait_t do_finish_server_handshake(SSL_HANDSHAKE *hs) {
   1587   SSL *const ssl = hs->ssl;
   1588 
   1589   if (hs->handback) {
   1590     return ssl_hs_handback;
   1591   }
   1592 
   1593   ssl->method->on_handshake_complete(ssl);
   1594 
   1595   // If we aren't retaining peer certificates then we can discard it now.
   1596   if (hs->new_session != NULL &&
   1597       hs->config->retain_only_sha256_of_client_certs) {
   1598     hs->new_session->certs.reset();
   1599     ssl->ctx->x509_method->session_clear(hs->new_session.get());
   1600   }
   1601 
   1602   if (ssl->session != NULL) {
   1603     ssl->s3->established_session = UpRef(ssl->session);
   1604   } else {
   1605     ssl->s3->established_session = std::move(hs->new_session);
   1606     ssl->s3->established_session->not_resumable = false;
   1607   }
   1608 
   1609   hs->handshake_finalized = true;
   1610   ssl->s3->initial_handshake_complete = true;
   1611   ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
   1612 
   1613   hs->state = state12_done;
   1614   return ssl_hs_ok;
   1615 }
   1616 
   1617 enum ssl_hs_wait_t ssl_server_handshake(SSL_HANDSHAKE *hs) {
   1618   while (hs->state != state12_done) {
   1619     enum ssl_hs_wait_t ret = ssl_hs_error;
   1620     enum tls12_server_hs_state_t state =
   1621         static_cast<enum tls12_server_hs_state_t>(hs->state);
   1622     switch (state) {
   1623       case state12_start_accept:
   1624         ret = do_start_accept(hs);
   1625         break;
   1626       case state12_read_client_hello:
   1627         ret = do_read_client_hello(hs);
   1628         break;
   1629       case state12_select_certificate:
   1630         ret = do_select_certificate(hs);
   1631         break;
   1632       case state12_tls13:
   1633         ret = do_tls13(hs);
   1634         break;
   1635       case state12_select_parameters:
   1636         ret = do_select_parameters(hs);
   1637         break;
   1638       case state12_send_server_hello:
   1639         ret = do_send_server_hello(hs);
   1640         break;
   1641       case state12_send_server_certificate:
   1642         ret = do_send_server_certificate(hs);
   1643         break;
   1644       case state12_send_server_key_exchange:
   1645         ret = do_send_server_key_exchange(hs);
   1646         break;
   1647       case state12_send_server_hello_done:
   1648         ret = do_send_server_hello_done(hs);
   1649         break;
   1650       case state12_read_client_certificate:
   1651         ret = do_read_client_certificate(hs);
   1652         break;
   1653       case state12_verify_client_certificate:
   1654         ret = do_verify_client_certificate(hs);
   1655         break;
   1656       case state12_read_client_key_exchange:
   1657         ret = do_read_client_key_exchange(hs);
   1658         break;
   1659       case state12_read_client_certificate_verify:
   1660         ret = do_read_client_certificate_verify(hs);
   1661         break;
   1662       case state12_read_change_cipher_spec:
   1663         ret = do_read_change_cipher_spec(hs);
   1664         break;
   1665       case state12_process_change_cipher_spec:
   1666         ret = do_process_change_cipher_spec(hs);
   1667         break;
   1668       case state12_read_next_proto:
   1669         ret = do_read_next_proto(hs);
   1670         break;
   1671       case state12_read_channel_id:
   1672         ret = do_read_channel_id(hs);
   1673         break;
   1674       case state12_read_client_finished:
   1675         ret = do_read_client_finished(hs);
   1676         break;
   1677       case state12_send_server_finished:
   1678         ret = do_send_server_finished(hs);
   1679         break;
   1680       case state12_finish_server_handshake:
   1681         ret = do_finish_server_handshake(hs);
   1682         break;
   1683       case state12_done:
   1684         ret = ssl_hs_ok;
   1685         break;
   1686     }
   1687 
   1688     if (hs->state != state) {
   1689       ssl_do_info_callback(hs->ssl, SSL_CB_ACCEPT_LOOP, 1);
   1690     }
   1691 
   1692     if (ret != ssl_hs_ok) {
   1693       return ret;
   1694     }
   1695   }
   1696 
   1697   ssl_do_info_callback(hs->ssl, SSL_CB_HANDSHAKE_DONE, 1);
   1698   return ssl_hs_ok;
   1699 }
   1700 
   1701 const char *ssl_server_handshake_state(SSL_HANDSHAKE *hs) {
   1702   enum tls12_server_hs_state_t state =
   1703       static_cast<enum tls12_server_hs_state_t>(hs->state);
   1704   switch (state) {
   1705     case state12_start_accept:
   1706       return "TLS server start_accept";
   1707     case state12_read_client_hello:
   1708       return "TLS server read_client_hello";
   1709     case state12_select_certificate:
   1710       return "TLS server select_certificate";
   1711     case state12_tls13:
   1712       return tls13_server_handshake_state(hs);
   1713     case state12_select_parameters:
   1714       return "TLS server select_parameters";
   1715     case state12_send_server_hello:
   1716       return "TLS server send_server_hello";
   1717     case state12_send_server_certificate:
   1718       return "TLS server send_server_certificate";
   1719     case state12_send_server_key_exchange:
   1720       return "TLS server send_server_key_exchange";
   1721     case state12_send_server_hello_done:
   1722       return "TLS server send_server_hello_done";
   1723     case state12_read_client_certificate:
   1724       return "TLS server read_client_certificate";
   1725     case state12_verify_client_certificate:
   1726       return "TLS server verify_client_certificate";
   1727     case state12_read_client_key_exchange:
   1728       return "TLS server read_client_key_exchange";
   1729     case state12_read_client_certificate_verify:
   1730       return "TLS server read_client_certificate_verify";
   1731     case state12_read_change_cipher_spec:
   1732       return "TLS server read_change_cipher_spec";
   1733     case state12_process_change_cipher_spec:
   1734       return "TLS server process_change_cipher_spec";
   1735     case state12_read_next_proto:
   1736       return "TLS server read_next_proto";
   1737     case state12_read_channel_id:
   1738       return "TLS server read_channel_id";
   1739     case state12_read_client_finished:
   1740       return "TLS server read_client_finished";
   1741     case state12_send_server_finished:
   1742       return "TLS server send_server_finished";
   1743     case state12_finish_server_handshake:
   1744       return "TLS server finish_server_handshake";
   1745     case state12_done:
   1746       return "TLS server done";
   1747   }
   1748 
   1749   return "TLS server unknown";
   1750 }
   1751 
   1752 BSSL_NAMESPACE_END
   1753