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