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