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 <stdio.h>
    154 #include <string.h>
    155 
    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/obj.h>
    167 #include <openssl/rand.h>
    168 #include <openssl/x509.h>
    169 #include <openssl/x509v3.h>
    170 
    171 #include "internal.h"
    172 #include "../crypto/dh/internal.h"
    173 
    174 
    175 int ssl3_connect(SSL *ssl) {
    176   BUF_MEM *buf = NULL;
    177   void (*cb)(const SSL *ssl, int type, int value) = NULL;
    178   int ret = -1;
    179   int new_state, state, skip = 0;
    180 
    181   assert(ssl->handshake_func == ssl3_connect);
    182   assert(!ssl->server);
    183   assert(!SSL_IS_DTLS(ssl));
    184 
    185   ERR_clear_error();
    186   ERR_clear_system_error();
    187 
    188   if (ssl->info_callback != NULL) {
    189     cb = ssl->info_callback;
    190   } else if (ssl->ctx->info_callback != NULL) {
    191     cb = ssl->ctx->info_callback;
    192   }
    193 
    194   ssl->in_handshake++;
    195 
    196   for (;;) {
    197     state = ssl->state;
    198 
    199     switch (ssl->state) {
    200       case SSL_ST_CONNECT:
    201         if (cb != NULL) {
    202           cb(ssl, SSL_CB_HANDSHAKE_START, 1);
    203         }
    204 
    205         if (ssl->init_buf == NULL) {
    206           buf = BUF_MEM_new();
    207           if (buf == NULL ||
    208               !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
    209             ret = -1;
    210             goto end;
    211           }
    212 
    213           ssl->init_buf = buf;
    214           buf = NULL;
    215         }
    216 
    217         if (!ssl_init_wbio_buffer(ssl, 0)) {
    218           ret = -1;
    219           goto end;
    220         }
    221 
    222         /* don't push the buffering BIO quite yet */
    223 
    224         if (!ssl3_init_handshake_buffer(ssl)) {
    225           OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    226           ret = -1;
    227           goto end;
    228         }
    229 
    230         ssl->state = SSL3_ST_CW_CLNT_HELLO_A;
    231         ssl->init_num = 0;
    232         break;
    233 
    234       case SSL3_ST_CW_CLNT_HELLO_A:
    235       case SSL3_ST_CW_CLNT_HELLO_B:
    236         ssl->shutdown = 0;
    237         ret = ssl3_send_client_hello(ssl);
    238         if (ret <= 0) {
    239           goto end;
    240         }
    241         ssl->state = SSL3_ST_CR_SRVR_HELLO_A;
    242         ssl->init_num = 0;
    243 
    244         /* turn on buffering for the next lot of output */
    245         if (ssl->bbio != ssl->wbio) {
    246           ssl->wbio = BIO_push(ssl->bbio, ssl->wbio);
    247         }
    248 
    249         break;
    250 
    251       case SSL3_ST_CR_SRVR_HELLO_A:
    252       case SSL3_ST_CR_SRVR_HELLO_B:
    253         ret = ssl3_get_server_hello(ssl);
    254         if (ret <= 0) {
    255           goto end;
    256         }
    257 
    258         if (ssl->hit) {
    259           ssl->state = SSL3_ST_CR_CHANGE;
    260           if (ssl->tlsext_ticket_expected) {
    261             /* receive renewed session ticket */
    262             ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
    263           }
    264         } else {
    265           ssl->state = SSL3_ST_CR_CERT_A;
    266         }
    267         ssl->init_num = 0;
    268         break;
    269 
    270       case SSL3_ST_CR_CERT_A:
    271       case SSL3_ST_CR_CERT_B:
    272         if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
    273           ret = ssl3_get_server_certificate(ssl);
    274           if (ret <= 0) {
    275             goto end;
    276           }
    277           if (ssl->s3->tmp.certificate_status_expected) {
    278             ssl->state = SSL3_ST_CR_CERT_STATUS_A;
    279           } else {
    280             ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
    281           }
    282         } else {
    283           skip = 1;
    284           ssl->state = SSL3_ST_CR_KEY_EXCH_A;
    285         }
    286         ssl->init_num = 0;
    287         break;
    288 
    289       case SSL3_ST_VERIFY_SERVER_CERT:
    290         ret = ssl3_verify_server_cert(ssl);
    291         if (ret <= 0) {
    292           goto end;
    293         }
    294 
    295         ssl->state = SSL3_ST_CR_KEY_EXCH_A;
    296         ssl->init_num = 0;
    297         break;
    298 
    299       case SSL3_ST_CR_KEY_EXCH_A:
    300       case SSL3_ST_CR_KEY_EXCH_B:
    301         ret = ssl3_get_server_key_exchange(ssl);
    302         if (ret <= 0) {
    303           goto end;
    304         }
    305         ssl->state = SSL3_ST_CR_CERT_REQ_A;
    306         ssl->init_num = 0;
    307         break;
    308 
    309       case SSL3_ST_CR_CERT_REQ_A:
    310       case SSL3_ST_CR_CERT_REQ_B:
    311         ret = ssl3_get_certificate_request(ssl);
    312         if (ret <= 0) {
    313           goto end;
    314         }
    315         ssl->state = SSL3_ST_CR_SRVR_DONE_A;
    316         ssl->init_num = 0;
    317         break;
    318 
    319       case SSL3_ST_CR_SRVR_DONE_A:
    320       case SSL3_ST_CR_SRVR_DONE_B:
    321         ret = ssl3_get_server_done(ssl);
    322         if (ret <= 0) {
    323           goto end;
    324         }
    325         if (ssl->s3->tmp.cert_req) {
    326           ssl->state = SSL3_ST_CW_CERT_A;
    327         } else {
    328           ssl->state = SSL3_ST_CW_KEY_EXCH_A;
    329         }
    330         ssl->init_num = 0;
    331 
    332         break;
    333 
    334       case SSL3_ST_CW_CERT_A:
    335       case SSL3_ST_CW_CERT_B:
    336       case SSL3_ST_CW_CERT_C:
    337       case SSL3_ST_CW_CERT_D:
    338         ret = ssl3_send_client_certificate(ssl);
    339         if (ret <= 0) {
    340           goto end;
    341         }
    342         ssl->state = SSL3_ST_CW_KEY_EXCH_A;
    343         ssl->init_num = 0;
    344         break;
    345 
    346       case SSL3_ST_CW_KEY_EXCH_A:
    347       case SSL3_ST_CW_KEY_EXCH_B:
    348         ret = ssl3_send_client_key_exchange(ssl);
    349         if (ret <= 0) {
    350           goto end;
    351         }
    352         /* For TLS, cert_req is set to 2, so a cert chain
    353          * of nothing is sent, but no verify packet is sent */
    354         if (ssl->s3->tmp.cert_req == 1) {
    355           ssl->state = SSL3_ST_CW_CERT_VRFY_A;
    356         } else {
    357           ssl->state = SSL3_ST_CW_CHANGE_A;
    358         }
    359 
    360         ssl->init_num = 0;
    361         break;
    362 
    363       case SSL3_ST_CW_CERT_VRFY_A:
    364       case SSL3_ST_CW_CERT_VRFY_B:
    365       case SSL3_ST_CW_CERT_VRFY_C:
    366         ret = ssl3_send_cert_verify(ssl);
    367         if (ret <= 0) {
    368           goto end;
    369         }
    370         ssl->state = SSL3_ST_CW_CHANGE_A;
    371         ssl->init_num = 0;
    372         break;
    373 
    374       case SSL3_ST_CW_CHANGE_A:
    375       case SSL3_ST_CW_CHANGE_B:
    376         ret = ssl3_send_change_cipher_spec(ssl, SSL3_ST_CW_CHANGE_A,
    377                                            SSL3_ST_CW_CHANGE_B);
    378         if (ret <= 0) {
    379           goto end;
    380         }
    381 
    382         ssl->state = SSL3_ST_CW_FINISHED_A;
    383         if (ssl->s3->tlsext_channel_id_valid) {
    384           ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
    385         }
    386         if (ssl->s3->next_proto_neg_seen) {
    387           ssl->state = SSL3_ST_CW_NEXT_PROTO_A;
    388         }
    389         ssl->init_num = 0;
    390 
    391         ssl->session->cipher = ssl->s3->tmp.new_cipher;
    392         if (!ssl->enc_method->setup_key_block(ssl) ||
    393             !ssl->enc_method->change_cipher_state(
    394                 ssl, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
    395           ret = -1;
    396           goto end;
    397         }
    398 
    399         break;
    400 
    401       case SSL3_ST_CW_NEXT_PROTO_A:
    402       case SSL3_ST_CW_NEXT_PROTO_B:
    403         ret = ssl3_send_next_proto(ssl);
    404         if (ret <= 0) {
    405           goto end;
    406         }
    407 
    408         if (ssl->s3->tlsext_channel_id_valid) {
    409           ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
    410         } else {
    411           ssl->state = SSL3_ST_CW_FINISHED_A;
    412         }
    413         break;
    414 
    415       case SSL3_ST_CW_CHANNEL_ID_A:
    416       case SSL3_ST_CW_CHANNEL_ID_B:
    417         ret = ssl3_send_channel_id(ssl);
    418         if (ret <= 0) {
    419           goto end;
    420         }
    421         ssl->state = SSL3_ST_CW_FINISHED_A;
    422         break;
    423 
    424       case SSL3_ST_CW_FINISHED_A:
    425       case SSL3_ST_CW_FINISHED_B:
    426         ret = ssl3_send_finished(ssl, SSL3_ST_CW_FINISHED_A,
    427                                  SSL3_ST_CW_FINISHED_B,
    428                                  ssl->enc_method->client_finished_label,
    429                                  ssl->enc_method->client_finished_label_len);
    430         if (ret <= 0) {
    431           goto end;
    432         }
    433         ssl->state = SSL3_ST_CW_FLUSH;
    434 
    435         if (ssl->hit) {
    436           ssl->s3->tmp.next_state = SSL_ST_OK;
    437         } else {
    438           /* This is a non-resumption handshake. If it involves ChannelID, then
    439            * record the handshake hashes at this point in the session so that
    440            * any resumption of this session with ChannelID can sign those
    441            * hashes. */
    442           ret = tls1_record_handshake_hashes_for_channel_id(ssl);
    443           if (ret <= 0) {
    444             goto end;
    445           }
    446           if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
    447               ssl3_can_false_start(ssl) &&
    448               /* No False Start on renegotiation (would complicate the state
    449                * machine). */
    450               !ssl->s3->initial_handshake_complete) {
    451             ssl->s3->tmp.next_state = SSL3_ST_FALSE_START;
    452           } else {
    453             /* Allow NewSessionTicket if ticket expected */
    454             if (ssl->tlsext_ticket_expected) {
    455               ssl->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
    456             } else {
    457               ssl->s3->tmp.next_state = SSL3_ST_CR_CHANGE;
    458             }
    459           }
    460         }
    461         ssl->init_num = 0;
    462         break;
    463 
    464       case SSL3_ST_CR_SESSION_TICKET_A:
    465       case SSL3_ST_CR_SESSION_TICKET_B:
    466         ret = ssl3_get_new_session_ticket(ssl);
    467         if (ret <= 0) {
    468           goto end;
    469         }
    470         ssl->state = SSL3_ST_CR_CHANGE;
    471         ssl->init_num = 0;
    472         break;
    473 
    474       case SSL3_ST_CR_CERT_STATUS_A:
    475       case SSL3_ST_CR_CERT_STATUS_B:
    476         ret = ssl3_get_cert_status(ssl);
    477         if (ret <= 0) {
    478           goto end;
    479         }
    480         ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
    481         ssl->init_num = 0;
    482         break;
    483 
    484       case SSL3_ST_CR_CHANGE:
    485         ret = ssl->method->ssl_read_change_cipher_spec(ssl);
    486         if (ret <= 0) {
    487           goto end;
    488         }
    489 
    490         if (!ssl3_do_change_cipher_spec(ssl)) {
    491           ret = -1;
    492           goto end;
    493         }
    494         ssl->state = SSL3_ST_CR_FINISHED_A;
    495         break;
    496 
    497       case SSL3_ST_CR_FINISHED_A:
    498       case SSL3_ST_CR_FINISHED_B:
    499         ret = ssl3_get_finished(ssl, SSL3_ST_CR_FINISHED_A,
    500                                 SSL3_ST_CR_FINISHED_B);
    501         if (ret <= 0) {
    502           goto end;
    503         }
    504 
    505         if (ssl->hit) {
    506           ssl->state = SSL3_ST_CW_CHANGE_A;
    507         } else {
    508           ssl->state = SSL_ST_OK;
    509         }
    510         ssl->init_num = 0;
    511         break;
    512 
    513       case SSL3_ST_CW_FLUSH:
    514         ssl->rwstate = SSL_WRITING;
    515         if (BIO_flush(ssl->wbio) <= 0) {
    516           ret = -1;
    517           goto end;
    518         }
    519         ssl->rwstate = SSL_NOTHING;
    520         ssl->state = ssl->s3->tmp.next_state;
    521         break;
    522 
    523       case SSL3_ST_FALSE_START:
    524         /* Allow NewSessionTicket if ticket expected */
    525         if (ssl->tlsext_ticket_expected) {
    526           ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
    527         } else {
    528           ssl->state = SSL3_ST_CR_CHANGE;
    529         }
    530         ssl->s3->tmp.in_false_start = 1;
    531 
    532         ssl_free_wbio_buffer(ssl);
    533         ret = 1;
    534         goto end;
    535 
    536       case SSL_ST_OK:
    537         /* clean a few things up */
    538         ssl3_cleanup_key_block(ssl);
    539 
    540         BUF_MEM_free(ssl->init_buf);
    541         ssl->init_buf = NULL;
    542 
    543         /* Remove write buffering now. */
    544         ssl_free_wbio_buffer(ssl);
    545 
    546         const int is_initial_handshake = !ssl->s3->initial_handshake_complete;
    547 
    548         ssl->init_num = 0;
    549         ssl->s3->tmp.in_false_start = 0;
    550         ssl->s3->initial_handshake_complete = 1;
    551 
    552         if (is_initial_handshake) {
    553           /* Renegotiations do not participate in session resumption. */
    554           ssl_update_cache(ssl, SSL_SESS_CACHE_CLIENT);
    555         }
    556 
    557         ret = 1;
    558         /* ssl->server=0; */
    559 
    560         if (cb != NULL) {
    561           cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
    562         }
    563 
    564         goto end;
    565 
    566       default:
    567         OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
    568         ret = -1;
    569         goto end;
    570     }
    571 
    572     if (!ssl->s3->tmp.reuse_message && !skip) {
    573       if (cb != NULL && ssl->state != state) {
    574         new_state = ssl->state;
    575         ssl->state = state;
    576         cb(ssl, SSL_CB_CONNECT_LOOP, 1);
    577         ssl->state = new_state;
    578       }
    579     }
    580     skip = 0;
    581   }
    582 
    583 end:
    584   ssl->in_handshake--;
    585   BUF_MEM_free(buf);
    586   if (cb != NULL) {
    587     cb(ssl, SSL_CB_CONNECT_EXIT, ret);
    588   }
    589   return ret;
    590 }
    591 
    592 static int ssl3_write_client_cipher_list(SSL *ssl, CBB *out) {
    593   /* Prepare disabled cipher masks. */
    594   ssl_set_client_disabled(ssl);
    595 
    596   CBB child;
    597   if (!CBB_add_u16_length_prefixed(out, &child)) {
    598     return 0;
    599   }
    600 
    601   STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
    602 
    603   int any_enabled = 0;
    604   size_t i;
    605   for (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 & ssl->cert->mask_k) ||
    609         (cipher->algorithm_auth & ssl->cert->mask_a)) {
    610       continue;
    611     }
    612     if (SSL_CIPHER_get_min_version(cipher) >
    613         ssl3_version_from_wire(ssl, ssl->client_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) {
    624     OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
    625     return 0;
    626   }
    627 
    628   /* For SSLv3, the SCSV is added. Otherwise the renegotiation extension is
    629    * added. */
    630   if (ssl->client_version == SSL3_VERSION &&
    631       !ssl->s3->initial_handshake_complete) {
    632     if (!CBB_add_u16(&child, SSL3_CK_SCSV & 0xffff)) {
    633       return 0;
    634     }
    635     /* The renegotiation extension is required to be at index zero. */
    636     ssl->s3->tmp.extensions.sent |= (1u << 0);
    637   }
    638 
    639   if ((ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) &&
    640       !CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
    641     return 0;
    642   }
    643 
    644   return CBB_flush(out);
    645 }
    646 
    647 int ssl3_send_client_hello(SSL *ssl) {
    648   if (ssl->state == SSL3_ST_CW_CLNT_HELLO_B) {
    649     return ssl_do_write(ssl);
    650   }
    651 
    652   /* In DTLS, reset the handshake buffer each time a new ClientHello is
    653    * assembled. We may send multiple if we receive HelloVerifyRequest. */
    654   if (SSL_IS_DTLS(ssl) && !ssl3_init_handshake_buffer(ssl)) {
    655     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    656     return -1;
    657   }
    658 
    659   CBB cbb;
    660   CBB_zero(&cbb);
    661 
    662   assert(ssl->state == SSL3_ST_CW_CLNT_HELLO_A);
    663   if (!ssl->s3->have_version) {
    664     uint16_t max_version = ssl3_get_max_client_version(ssl);
    665     /* Disabling all versions is silly: return an error. */
    666     if (max_version == 0) {
    667       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
    668       goto err;
    669     }
    670 
    671     ssl->version = max_version;
    672     /* Only set |ssl->client_version| on the initial handshake. Renegotiations,
    673      * although locked to a version, reuse the value. When using the plain RSA
    674      * key exchange, the ClientHello version is checked in the premaster secret.
    675      * Some servers fail when this value changes. */
    676     ssl->client_version = max_version;
    677   }
    678 
    679   /* If the configured session has expired or was created at a version higher
    680    * than our maximum version, drop it. */
    681   if (ssl->session != NULL &&
    682       (ssl->session->session_id_length == 0 || ssl->session->not_resumable ||
    683        ssl->session->timeout < (long)(time(NULL) - ssl->session->time) ||
    684        (!SSL_IS_DTLS(ssl) && ssl->session->ssl_version > ssl->version) ||
    685        (SSL_IS_DTLS(ssl) && ssl->session->ssl_version < ssl->version))) {
    686     SSL_set_session(ssl, NULL);
    687   }
    688 
    689   /* If resending the ClientHello in DTLS after a HelloVerifyRequest, don't
    690    * renegerate the client_random. The random must be reused. */
    691   if ((!SSL_IS_DTLS(ssl) || !ssl->d1->send_cookie) &&
    692       !ssl_fill_hello_random(ssl->s3->client_random,
    693                              sizeof(ssl->s3->client_random), 0 /* client */)) {
    694     goto err;
    695   }
    696 
    697   /* Renegotiations do not participate in session resumption. */
    698   int has_session = ssl->session != NULL &&
    699                     !ssl->s3->initial_handshake_complete;
    700 
    701   CBB child;
    702   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
    703                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
    704       !CBB_add_u16(&cbb, ssl->client_version) ||
    705       !CBB_add_bytes(&cbb, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
    706       !CBB_add_u8_length_prefixed(&cbb, &child) ||
    707       (has_session &&
    708        !CBB_add_bytes(&child, ssl->session->session_id,
    709                       ssl->session->session_id_length))) {
    710     goto err;
    711   }
    712 
    713   if (SSL_IS_DTLS(ssl)) {
    714     if (!CBB_add_u8_length_prefixed(&cbb, &child) ||
    715         !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
    716       goto err;
    717     }
    718   }
    719 
    720   size_t length;
    721   if (!ssl3_write_client_cipher_list(ssl, &cbb) ||
    722       !CBB_add_u8(&cbb, 1 /* one compression method */) ||
    723       !CBB_add_u8(&cbb, 0 /* null compression */) ||
    724       !ssl_add_clienthello_tlsext(ssl, &cbb,
    725                                   CBB_len(&cbb) + SSL_HM_HEADER_LENGTH(ssl)) ||
    726       !CBB_finish(&cbb, NULL, &length) ||
    727       !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_HELLO, length)) {
    728     goto err;
    729   }
    730 
    731   ssl->state = SSL3_ST_CW_CLNT_HELLO_B;
    732   return ssl_do_write(ssl);
    733 
    734 err:
    735   CBB_cleanup(&cbb);
    736   return -1;
    737 }
    738 
    739 int ssl3_get_server_hello(SSL *ssl) {
    740   STACK_OF(SSL_CIPHER) *sk;
    741   const SSL_CIPHER *c;
    742   CERT *ct = ssl->cert;
    743   int al = SSL_AD_INTERNAL_ERROR, ok;
    744   long n;
    745   CBS server_hello, server_random, session_id;
    746   uint16_t server_version, cipher_suite;
    747   uint8_t compression_method;
    748 
    749   n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_SRVR_HELLO_A,
    750                                  SSL3_ST_CR_SRVR_HELLO_B, SSL3_MT_SERVER_HELLO,
    751                                  20000, /* ?? */
    752                                  ssl_hash_message, &ok);
    753 
    754   if (!ok) {
    755     uint32_t err = ERR_peek_error();
    756     if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
    757         ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
    758       /* Add a dedicated error code to the queue for a handshake_failure alert
    759        * in response to ClientHello. This matches NSS's client behavior and
    760        * gives a better error on a (probable) failure to negotiate initial
    761        * parameters. Note: this error code comes after the original one.
    762        *
    763        * See https://crbug.com/446505. */
    764       OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
    765     }
    766     return n;
    767   }
    768 
    769   CBS_init(&server_hello, ssl->init_msg, n);
    770 
    771   if (!CBS_get_u16(&server_hello, &server_version) ||
    772       !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
    773       !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
    774       CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
    775       !CBS_get_u16(&server_hello, &cipher_suite) ||
    776       !CBS_get_u8(&server_hello, &compression_method)) {
    777     al = SSL_AD_DECODE_ERROR;
    778     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    779     goto f_err;
    780   }
    781 
    782   assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
    783   if (!ssl->s3->have_version) {
    784     if (!ssl3_is_version_enabled(ssl, server_version)) {
    785       OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
    786       ssl->version = server_version;
    787       /* Mark the version as fixed so the record-layer version is not clamped
    788        * to TLS 1.0. */
    789       ssl->s3->have_version = 1;
    790       al = SSL_AD_PROTOCOL_VERSION;
    791       goto f_err;
    792     }
    793     ssl->version = server_version;
    794     ssl->enc_method = ssl3_get_enc_method(server_version);
    795     assert(ssl->enc_method != NULL);
    796     /* At this point, the connection's version is known and ssl->version is
    797      * fixed. Begin enforcing the record-layer version. */
    798     ssl->s3->have_version = 1;
    799   } else if (server_version != ssl->version) {
    800     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
    801     al = SSL_AD_PROTOCOL_VERSION;
    802     goto f_err;
    803   }
    804 
    805   /* Copy over the server random. */
    806   memcpy(ssl->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
    807 
    808   assert(ssl->session == NULL || ssl->session->session_id_length > 0);
    809   if (!ssl->s3->initial_handshake_complete && ssl->session != NULL &&
    810       CBS_mem_equal(&session_id, ssl->session->session_id,
    811                     ssl->session->session_id_length)) {
    812     if (ssl->sid_ctx_length != ssl->session->sid_ctx_length ||
    813         memcmp(ssl->session->sid_ctx, ssl->sid_ctx, ssl->sid_ctx_length)) {
    814       /* actually a client application bug */
    815       al = SSL_AD_ILLEGAL_PARAMETER;
    816       OPENSSL_PUT_ERROR(SSL,
    817                         SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
    818       goto f_err;
    819     }
    820     ssl->hit = 1;
    821   } else {
    822     /* The session wasn't resumed. Create a fresh SSL_SESSION to
    823      * fill out. */
    824     ssl->hit = 0;
    825     if (!ssl_get_new_session(ssl, 0 /* client */)) {
    826       goto f_err;
    827     }
    828     /* Note: session_id could be empty. */
    829     ssl->session->session_id_length = CBS_len(&session_id);
    830     memcpy(ssl->session->session_id, CBS_data(&session_id),
    831            CBS_len(&session_id));
    832   }
    833 
    834   c = SSL_get_cipher_by_value(cipher_suite);
    835   if (c == NULL) {
    836     /* unknown cipher */
    837     al = SSL_AD_ILLEGAL_PARAMETER;
    838     OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
    839     goto f_err;
    840   }
    841   /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
    842    * the server selected it, it's an error. */
    843   if ((c->algorithm_mkey & ct->mask_k) || (c->algorithm_auth & ct->mask_a) ||
    844       SSL_CIPHER_get_min_version(c) >
    845           ssl3_version_from_wire(ssl, ssl->version)) {
    846     al = SSL_AD_ILLEGAL_PARAMETER;
    847     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
    848     goto f_err;
    849   }
    850 
    851   sk = ssl_get_ciphers_by_id(ssl);
    852   if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
    853     /* we did not say we would use this cipher */
    854     al = SSL_AD_ILLEGAL_PARAMETER;
    855     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
    856     goto f_err;
    857   }
    858 
    859   if (ssl->hit) {
    860     if (ssl->session->cipher != c) {
    861       al = SSL_AD_ILLEGAL_PARAMETER;
    862       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
    863       goto f_err;
    864     }
    865     if (ssl->session->ssl_version != ssl->version) {
    866       al = SSL_AD_ILLEGAL_PARAMETER;
    867       OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
    868       goto f_err;
    869     }
    870   }
    871   ssl->s3->tmp.new_cipher = c;
    872 
    873   /* Now that the cipher is known, initialize the handshake hash. */
    874   if (!ssl3_init_handshake_hash(ssl)) {
    875     goto f_err;
    876   }
    877 
    878   /* If doing a full handshake with TLS 1.2, the server may request a client
    879    * certificate which requires hashing the handshake transcript under a
    880    * different hash. Otherwise, the handshake buffer may be released. */
    881   if (!SSL_USE_SIGALGS(ssl) || ssl->hit) {
    882     ssl3_free_handshake_buffer(ssl);
    883   }
    884 
    885   /* Only the NULL compression algorithm is supported. */
    886   if (compression_method != 0) {
    887     al = SSL_AD_ILLEGAL_PARAMETER;
    888     OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
    889     goto f_err;
    890   }
    891 
    892   /* TLS extensions */
    893   if (!ssl_parse_serverhello_tlsext(ssl, &server_hello)) {
    894     OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
    895     goto err;
    896   }
    897 
    898   /* There should be nothing left over in the record. */
    899   if (CBS_len(&server_hello) != 0) {
    900     /* wrong packet length */
    901     al = SSL_AD_DECODE_ERROR;
    902     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
    903     goto f_err;
    904   }
    905 
    906   if (ssl->hit &&
    907       ssl->s3->tmp.extended_master_secret !=
    908           ssl->session->extended_master_secret) {
    909     al = SSL_AD_HANDSHAKE_FAILURE;
    910     if (ssl->session->extended_master_secret) {
    911       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
    912     } else {
    913       OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
    914     }
    915     goto f_err;
    916   }
    917 
    918   return 1;
    919 
    920 f_err:
    921   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
    922 err:
    923   return -1;
    924 }
    925 
    926 /* ssl3_check_leaf_certificate returns one if |leaf| is a suitable leaf server
    927  * certificate for |ssl|. Otherwise, it returns zero and pushes an error on the
    928  * error queue. */
    929 static int ssl3_check_leaf_certificate(SSL *ssl, X509 *leaf) {
    930   int ret = 0;
    931   EVP_PKEY *pkey = X509_get_pubkey(leaf);
    932   if (pkey == NULL) {
    933     goto err;
    934   }
    935 
    936   /* Check the certificate's type matches the cipher. */
    937   const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
    938   int expected_type = ssl_cipher_get_key_type(cipher);
    939   assert(expected_type != EVP_PKEY_NONE);
    940   if (pkey->type != expected_type) {
    941     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
    942     goto err;
    943   }
    944 
    945   if (cipher->algorithm_auth & SSL_aECDSA) {
    946     /* TODO(davidben): This behavior is preserved from upstream. Should key
    947      * usages be checked in other cases as well? */
    948     /* This call populates the ex_flags field correctly */
    949     X509_check_purpose(leaf, -1, 0);
    950     if ((leaf->ex_flags & EXFLAG_KUSAGE) &&
    951         !(leaf->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)) {
    952       OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
    953       goto err;
    954     }
    955 
    956     if (!tls1_check_ec_cert(ssl, leaf)) {
    957       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
    958       goto err;
    959     }
    960   }
    961 
    962   ret = 1;
    963 
    964 err:
    965   EVP_PKEY_free(pkey);
    966   return ret;
    967 }
    968 
    969 int ssl3_get_server_certificate(SSL *ssl) {
    970   int al, ok, ret = -1;
    971   unsigned long n;
    972   X509 *x = NULL;
    973   STACK_OF(X509) *sk = NULL;
    974   EVP_PKEY *pkey = NULL;
    975   CBS cbs, certificate_list;
    976   const uint8_t *data;
    977 
    978   n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B,
    979                                  SSL3_MT_CERTIFICATE, (long)ssl->max_cert_list,
    980                                  ssl_hash_message, &ok);
    981 
    982   if (!ok) {
    983     return n;
    984   }
    985 
    986   CBS_init(&cbs, ssl->init_msg, n);
    987 
    988   sk = sk_X509_new_null();
    989   if (sk == NULL) {
    990     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    991     goto err;
    992   }
    993 
    994   if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
    995       CBS_len(&certificate_list) == 0 ||
    996       CBS_len(&cbs) != 0) {
    997     al = SSL_AD_DECODE_ERROR;
    998     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
    999     goto f_err;
   1000   }
   1001 
   1002   while (CBS_len(&certificate_list) > 0) {
   1003     CBS certificate;
   1004     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
   1005       al = SSL_AD_DECODE_ERROR;
   1006       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
   1007       goto f_err;
   1008     }
   1009     /* A u24 length cannot overflow a long. */
   1010     data = CBS_data(&certificate);
   1011     x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
   1012     if (x == NULL) {
   1013       al = SSL_AD_BAD_CERTIFICATE;
   1014       OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
   1015       goto f_err;
   1016     }
   1017     if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
   1018       al = SSL_AD_DECODE_ERROR;
   1019       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
   1020       goto f_err;
   1021     }
   1022     if (!sk_X509_push(sk, x)) {
   1023       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1024       goto err;
   1025     }
   1026     x = NULL;
   1027   }
   1028 
   1029   X509 *leaf = sk_X509_value(sk, 0);
   1030   if (!ssl3_check_leaf_certificate(ssl, leaf)) {
   1031     al = SSL_AD_ILLEGAL_PARAMETER;
   1032     goto f_err;
   1033   }
   1034 
   1035   /* NOTE: Unlike the server half, the client's copy of |cert_chain| includes
   1036    * the leaf. */
   1037   sk_X509_pop_free(ssl->session->cert_chain, X509_free);
   1038   ssl->session->cert_chain = sk;
   1039   sk = NULL;
   1040 
   1041   X509_free(ssl->session->peer);
   1042   ssl->session->peer = X509_up_ref(leaf);
   1043 
   1044   ssl->session->verify_result = ssl->verify_result;
   1045 
   1046   ret = 1;
   1047 
   1048   if (0) {
   1049   f_err:
   1050     ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   1051   }
   1052 
   1053 err:
   1054   EVP_PKEY_free(pkey);
   1055   X509_free(x);
   1056   sk_X509_pop_free(sk, X509_free);
   1057   return ret;
   1058 }
   1059 
   1060 int ssl3_get_server_key_exchange(SSL *ssl) {
   1061   EVP_MD_CTX md_ctx;
   1062   int al, ok;
   1063   long n, alg_k, alg_a;
   1064   EVP_PKEY *pkey = NULL;
   1065   const EVP_MD *md = NULL;
   1066   DH *dh = NULL;
   1067   EC_KEY *ecdh = NULL;
   1068   EC_POINT *srvr_ecpoint = NULL;
   1069   CBS server_key_exchange, server_key_exchange_orig, parameter;
   1070 
   1071   /* use same message size as in ssl3_get_certificate_request() as
   1072    * ServerKeyExchange message may be skipped */
   1073   n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_KEY_EXCH_A,
   1074                                  SSL3_ST_CR_KEY_EXCH_B, -1, ssl->max_cert_list,
   1075                                  ssl_hash_message, &ok);
   1076   if (!ok) {
   1077     return n;
   1078   }
   1079 
   1080   if (ssl->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
   1081     if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher)) {
   1082       OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
   1083       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1084       return -1;
   1085     }
   1086 
   1087     /* In plain PSK ciphersuite, ServerKeyExchange may be omitted to send no
   1088      * identity hint. */
   1089     if (ssl->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
   1090       /* TODO(davidben): This should be reset in one place with the rest of the
   1091        * handshake state. */
   1092       OPENSSL_free(ssl->s3->tmp.peer_psk_identity_hint);
   1093       ssl->s3->tmp.peer_psk_identity_hint = NULL;
   1094     }
   1095     ssl->s3->tmp.reuse_message = 1;
   1096     return 1;
   1097   }
   1098 
   1099   /* Retain a copy of the original CBS to compute the signature over. */
   1100   CBS_init(&server_key_exchange, ssl->init_msg, n);
   1101   server_key_exchange_orig = server_key_exchange;
   1102 
   1103   alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
   1104   alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
   1105   EVP_MD_CTX_init(&md_ctx);
   1106 
   1107   if (alg_a & SSL_aPSK) {
   1108     CBS psk_identity_hint;
   1109 
   1110     /* Each of the PSK key exchanges begins with a psk_identity_hint. */
   1111     if (!CBS_get_u16_length_prefixed(&server_key_exchange,
   1112                                      &psk_identity_hint)) {
   1113       al = SSL_AD_DECODE_ERROR;
   1114       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1115       goto f_err;
   1116     }
   1117 
   1118     /* Store PSK identity hint for later use, hint is used in
   1119      * ssl3_send_client_key_exchange.  Assume that the maximum length of a PSK
   1120      * identity hint can be as long as the maximum length of a PSK identity.
   1121      * Also do not allow NULL characters; identities are saved as C strings.
   1122      *
   1123      * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
   1124      * a specific identity. */
   1125     if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
   1126         CBS_contains_zero_byte(&psk_identity_hint)) {
   1127       al = SSL_AD_HANDSHAKE_FAILURE;
   1128       OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
   1129       goto f_err;
   1130     }
   1131 
   1132     /* Save the identity hint as a C string. */
   1133     if (!CBS_strdup(&psk_identity_hint, &ssl->s3->tmp.peer_psk_identity_hint)) {
   1134       al = SSL_AD_INTERNAL_ERROR;
   1135       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1136       goto f_err;
   1137     }
   1138   }
   1139 
   1140   if (alg_k & SSL_kDHE) {
   1141     CBS dh_p, dh_g, dh_Ys;
   1142     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
   1143         CBS_len(&dh_p) == 0 ||
   1144         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
   1145         CBS_len(&dh_g) == 0 ||
   1146         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
   1147         CBS_len(&dh_Ys) == 0) {
   1148       al = SSL_AD_DECODE_ERROR;
   1149       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1150       goto f_err;
   1151     }
   1152 
   1153     dh = DH_new();
   1154     if (dh == NULL) {
   1155       goto err;
   1156     }
   1157 
   1158     dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL);
   1159     dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL);
   1160     if (dh->p == NULL || dh->g == NULL) {
   1161       goto err;
   1162     }
   1163 
   1164     ssl->session->key_exchange_info = DH_num_bits(dh);
   1165     if (ssl->session->key_exchange_info < 1024) {
   1166       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DH_P_LENGTH);
   1167       goto err;
   1168     } else if (ssl->session->key_exchange_info > 4096) {
   1169       /* Overly large DHE groups are prohibitively expensive, so enforce a limit
   1170        * to prevent a server from causing us to perform too expensive of a
   1171        * computation. */
   1172       OPENSSL_PUT_ERROR(SSL, SSL_R_DH_P_TOO_LONG);
   1173       goto err;
   1174     }
   1175 
   1176     SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
   1177     dh = NULL;
   1178 
   1179     /* Save the peer public key for later. */
   1180     size_t peer_key_len;
   1181     if (!CBS_stow(&dh_Ys, &ssl->s3->tmp.peer_key, &peer_key_len)) {
   1182       goto err;
   1183     }
   1184     /* |dh_Ys| has a u16 length prefix, so this fits in a |uint16_t|. */
   1185     assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
   1186     ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
   1187   } else if (alg_k & SSL_kECDHE) {
   1188     /* Parse the server parameters. */
   1189     uint8_t curve_type;
   1190     uint16_t curve_id;
   1191     CBS point;
   1192     if (!CBS_get_u8(&server_key_exchange, &curve_type) ||
   1193         curve_type != NAMED_CURVE_TYPE ||
   1194         !CBS_get_u16(&server_key_exchange, &curve_id) ||
   1195         !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
   1196       al = SSL_AD_DECODE_ERROR;
   1197       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1198       goto f_err;
   1199     }
   1200     ssl->session->key_exchange_info = curve_id;
   1201 
   1202     /* Ensure the curve is consistent with preferences. */
   1203     if (!tls1_check_curve_id(ssl, curve_id)) {
   1204       al = SSL_AD_ILLEGAL_PARAMETER;
   1205       OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
   1206       goto f_err;
   1207     }
   1208 
   1209     /* Initialize ECDH and save the peer public key for later. */
   1210     size_t peer_key_len;
   1211     if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, curve_id) ||
   1212         !CBS_stow(&point, &ssl->s3->tmp.peer_key, &peer_key_len)) {
   1213       goto err;
   1214     }
   1215     /* |point| has a u8 length prefix, so this fits in a |uint16_t|. */
   1216     assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
   1217     ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
   1218   } else if (!(alg_k & SSL_kPSK)) {
   1219     al = SSL_AD_UNEXPECTED_MESSAGE;
   1220     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
   1221     goto f_err;
   1222   }
   1223 
   1224   /* At this point, |server_key_exchange| contains the signature, if any, while
   1225    * |server_key_exchange_orig| contains the entire message. From that, derive
   1226    * a CBS containing just the parameter. */
   1227   CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
   1228            CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
   1229 
   1230   /* ServerKeyExchange should be signed by the server's public key. */
   1231   if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
   1232     pkey = X509_get_pubkey(ssl->session->peer);
   1233     if (pkey == NULL) {
   1234       goto err;
   1235     }
   1236 
   1237     if (SSL_USE_SIGALGS(ssl)) {
   1238       uint8_t hash, signature;
   1239       if (!CBS_get_u8(&server_key_exchange, &hash) ||
   1240           !CBS_get_u8(&server_key_exchange, &signature)) {
   1241         al = SSL_AD_DECODE_ERROR;
   1242         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1243         goto f_err;
   1244       }
   1245       if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature, pkey)) {
   1246         goto f_err;
   1247       }
   1248       ssl->s3->tmp.server_key_exchange_hash = hash;
   1249     } else if (pkey->type == EVP_PKEY_RSA) {
   1250       md = EVP_md5_sha1();
   1251     } else {
   1252       md = EVP_sha1();
   1253     }
   1254 
   1255     /* The last field in |server_key_exchange| is the signature. */
   1256     CBS signature;
   1257     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
   1258         CBS_len(&server_key_exchange) != 0) {
   1259       al = SSL_AD_DECODE_ERROR;
   1260       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1261       goto f_err;
   1262     }
   1263 
   1264     if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
   1265         !EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->client_random,
   1266                                 SSL3_RANDOM_SIZE) ||
   1267         !EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->server_random,
   1268                                 SSL3_RANDOM_SIZE) ||
   1269         !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
   1270                                 CBS_len(&parameter)) ||
   1271         !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
   1272                                CBS_len(&signature))) {
   1273       /* bad signature */
   1274       al = SSL_AD_DECRYPT_ERROR;
   1275       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
   1276       goto f_err;
   1277     }
   1278   } else {
   1279     /* PSK ciphers are the only supported certificate-less ciphers. */
   1280     assert(alg_a == SSL_aPSK);
   1281 
   1282     if (CBS_len(&server_key_exchange) > 0) {
   1283       al = SSL_AD_DECODE_ERROR;
   1284       OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
   1285       goto f_err;
   1286     }
   1287   }
   1288   EVP_PKEY_free(pkey);
   1289   EVP_MD_CTX_cleanup(&md_ctx);
   1290   return 1;
   1291 
   1292 f_err:
   1293   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   1294 err:
   1295   EVP_PKEY_free(pkey);
   1296   DH_free(dh);
   1297   EC_POINT_free(srvr_ecpoint);
   1298   EC_KEY_free(ecdh);
   1299   EVP_MD_CTX_cleanup(&md_ctx);
   1300   return -1;
   1301 }
   1302 
   1303 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
   1304   return X509_NAME_cmp(*a, *b);
   1305 }
   1306 
   1307 int ssl3_get_certificate_request(SSL *ssl) {
   1308   int ok, ret = 0;
   1309   unsigned long n;
   1310   X509_NAME *xn = NULL;
   1311   STACK_OF(X509_NAME) *ca_sk = NULL;
   1312   CBS cbs;
   1313   CBS certificate_types;
   1314   CBS certificate_authorities;
   1315   const uint8_t *data;
   1316 
   1317   n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_CERT_REQ_A,
   1318                                  SSL3_ST_CR_CERT_REQ_B, -1, ssl->max_cert_list,
   1319                                  ssl_hash_message, &ok);
   1320 
   1321   if (!ok) {
   1322     return n;
   1323   }
   1324 
   1325   ssl->s3->tmp.cert_req = 0;
   1326 
   1327   if (ssl->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
   1328     ssl->s3->tmp.reuse_message = 1;
   1329     /* If we get here we don't need the handshake buffer as we won't be doing
   1330      * client auth. */
   1331     ssl3_free_handshake_buffer(ssl);
   1332     return 1;
   1333   }
   1334 
   1335   if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
   1336     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1337     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_MESSAGE_TYPE);
   1338     goto err;
   1339   }
   1340 
   1341   CBS_init(&cbs, ssl->init_msg, n);
   1342 
   1343   ca_sk = sk_X509_NAME_new(ca_dn_cmp);
   1344   if (ca_sk == NULL) {
   1345     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1346     goto err;
   1347   }
   1348 
   1349   /* get the certificate types */
   1350   if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
   1351     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1352     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1353     goto err;
   1354   }
   1355 
   1356   if (!CBS_stow(&certificate_types, &ssl->s3->tmp.certificate_types,
   1357                 &ssl->s3->tmp.num_certificate_types)) {
   1358     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1359     goto err;
   1360   }
   1361 
   1362   if (SSL_USE_SIGALGS(ssl)) {
   1363     CBS supported_signature_algorithms;
   1364     if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms) ||
   1365         !tls1_parse_peer_sigalgs(ssl, &supported_signature_algorithms)) {
   1366       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1367       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1368       goto err;
   1369     }
   1370   }
   1371 
   1372   /* get the CA RDNs */
   1373   if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
   1374     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1375     OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
   1376     goto err;
   1377   }
   1378 
   1379   while (CBS_len(&certificate_authorities) > 0) {
   1380     CBS distinguished_name;
   1381     if (!CBS_get_u16_length_prefixed(&certificate_authorities,
   1382                                      &distinguished_name)) {
   1383       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1384       OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
   1385       goto err;
   1386     }
   1387 
   1388     data = CBS_data(&distinguished_name);
   1389 
   1390     /* A u16 length cannot overflow a long. */
   1391     xn = d2i_X509_NAME(NULL, &data, (long)CBS_len(&distinguished_name));
   1392     if (xn == NULL) {
   1393       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1394       OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
   1395       goto err;
   1396     }
   1397 
   1398     if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name))) {
   1399       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1400       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1401       goto err;
   1402     }
   1403 
   1404     if (CBS_len(&distinguished_name) != 0) {
   1405       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1406       OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_LENGTH_MISMATCH);
   1407       goto err;
   1408     }
   1409 
   1410     if (!sk_X509_NAME_push(ca_sk, xn)) {
   1411       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1412       goto err;
   1413     }
   1414   }
   1415 
   1416   /* we should setup a certificate to return.... */
   1417   ssl->s3->tmp.cert_req = 1;
   1418   sk_X509_NAME_pop_free(ssl->s3->tmp.ca_names, X509_NAME_free);
   1419   ssl->s3->tmp.ca_names = ca_sk;
   1420   ca_sk = NULL;
   1421 
   1422   ret = 1;
   1423 
   1424 err:
   1425   sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
   1426   return ret;
   1427 }
   1428 
   1429 int ssl3_get_new_session_ticket(SSL *ssl) {
   1430   int ok, al;
   1431   long n = ssl->method->ssl_get_message(
   1432       ssl, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B,
   1433       SSL3_MT_NEWSESSION_TICKET, 16384, ssl_hash_message, &ok);
   1434 
   1435   if (!ok) {
   1436     return n;
   1437   }
   1438 
   1439   CBS new_session_ticket, ticket;
   1440   uint32_t ticket_lifetime_hint;
   1441   CBS_init(&new_session_ticket, ssl->init_msg, n);
   1442   if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
   1443       !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
   1444       CBS_len(&new_session_ticket) != 0) {
   1445     al = SSL_AD_DECODE_ERROR;
   1446     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1447     goto f_err;
   1448   }
   1449 
   1450   if (CBS_len(&ticket) == 0) {
   1451     /* RFC 5077 allows a server to change its mind and send no ticket after
   1452      * negotiating the extension. The value of |tlsext_ticket_expected| is
   1453      * checked in |ssl_update_cache| so is cleared here to avoid an unnecessary
   1454      * update. */
   1455     ssl->tlsext_ticket_expected = 0;
   1456     return 1;
   1457   }
   1458 
   1459   if (ssl->hit) {
   1460     /* The server is sending a new ticket for an existing session. Sessions are
   1461      * immutable once established, so duplicate all but the ticket of the
   1462      * existing session. */
   1463     uint8_t *bytes;
   1464     size_t bytes_len;
   1465     if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &bytes, &bytes_len)) {
   1466       goto err;
   1467     }
   1468     SSL_SESSION *new_session = SSL_SESSION_from_bytes(bytes, bytes_len);
   1469     OPENSSL_free(bytes);
   1470     if (new_session == NULL) {
   1471       /* This should never happen. */
   1472       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1473       goto err;
   1474     }
   1475 
   1476     SSL_SESSION_free(ssl->session);
   1477     ssl->session = new_session;
   1478   }
   1479 
   1480   if (!CBS_stow(&ticket, &ssl->session->tlsext_tick,
   1481                 &ssl->session->tlsext_ticklen)) {
   1482     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1483     goto err;
   1484   }
   1485   ssl->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
   1486 
   1487   /* Generate a session ID for this session based on the session ticket. We use
   1488    * the session ID mechanism for detecting ticket resumption. This also fits in
   1489    * with assumptions elsewhere in OpenSSL.*/
   1490   if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), ssl->session->session_id,
   1491                   &ssl->session->session_id_length, EVP_sha256(), NULL)) {
   1492     goto err;
   1493   }
   1494 
   1495   return 1;
   1496 
   1497 f_err:
   1498   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   1499 err:
   1500   return -1;
   1501 }
   1502 
   1503 int ssl3_get_cert_status(SSL *ssl) {
   1504   int ok, al;
   1505   long n;
   1506   CBS certificate_status, ocsp_response;
   1507   uint8_t status_type;
   1508 
   1509   n = ssl->method->ssl_get_message(
   1510       ssl, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B,
   1511       -1, 16384, ssl_hash_message, &ok);
   1512 
   1513   if (!ok) {
   1514     return n;
   1515   }
   1516 
   1517   if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
   1518     /* A server may send status_request in ServerHello and then change
   1519      * its mind about sending CertificateStatus. */
   1520     ssl->s3->tmp.reuse_message = 1;
   1521     return 1;
   1522   }
   1523 
   1524   CBS_init(&certificate_status, ssl->init_msg, n);
   1525   if (!CBS_get_u8(&certificate_status, &status_type) ||
   1526       status_type != TLSEXT_STATUSTYPE_ocsp ||
   1527       !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
   1528       CBS_len(&ocsp_response) == 0 ||
   1529       CBS_len(&certificate_status) != 0) {
   1530     al = SSL_AD_DECODE_ERROR;
   1531     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
   1532     goto f_err;
   1533   }
   1534 
   1535   if (!CBS_stow(&ocsp_response, &ssl->session->ocsp_response,
   1536                 &ssl->session->ocsp_response_length)) {
   1537     al = SSL_AD_INTERNAL_ERROR;
   1538     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1539     goto f_err;
   1540   }
   1541   return 1;
   1542 
   1543 f_err:
   1544   ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   1545   return -1;
   1546 }
   1547 
   1548 int ssl3_get_server_done(SSL *ssl) {
   1549   int ok;
   1550   long n;
   1551 
   1552   n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_SRVR_DONE_A,
   1553                                  SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
   1554                                  30, /* should be very small, like 0 :-) */
   1555                                  ssl_hash_message, &ok);
   1556 
   1557   if (!ok) {
   1558     return n;
   1559   }
   1560 
   1561   if (n > 0) {
   1562     /* should contain no data */
   1563     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1564     OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
   1565     return -1;
   1566   }
   1567 
   1568   return 1;
   1569 }
   1570 
   1571 OPENSSL_COMPILE_ASSERT(sizeof(size_t) >= sizeof(unsigned),
   1572                        SIZE_T_IS_SMALLER_THAN_UNSIGNED);
   1573 
   1574 int ssl3_send_client_key_exchange(SSL *ssl) {
   1575   if (ssl->state == SSL3_ST_CW_KEY_EXCH_B) {
   1576     return ssl_do_write(ssl);
   1577   }
   1578   assert(ssl->state == SSL3_ST_CW_KEY_EXCH_A);
   1579 
   1580   uint8_t *pms = NULL;
   1581   size_t pms_len = 0;
   1582   CBB cbb;
   1583   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
   1584                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
   1585     goto err;
   1586   }
   1587 
   1588   uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
   1589   uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
   1590 
   1591   /* If using a PSK key exchange, prepare the pre-shared key. */
   1592   unsigned psk_len = 0;
   1593   uint8_t psk[PSK_MAX_PSK_LEN];
   1594   if (alg_a & SSL_aPSK) {
   1595     if (ssl->psk_client_callback == NULL) {
   1596       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
   1597       goto err;
   1598     }
   1599 
   1600     char identity[PSK_MAX_IDENTITY_LEN + 1];
   1601     memset(identity, 0, sizeof(identity));
   1602     psk_len = ssl->psk_client_callback(
   1603         ssl, ssl->s3->tmp.peer_psk_identity_hint, identity, sizeof(identity),
   1604         psk, sizeof(psk));
   1605     if (psk_len == 0) {
   1606       OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
   1607       ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1608       goto err;
   1609     }
   1610     assert(psk_len <= PSK_MAX_PSK_LEN);
   1611 
   1612     OPENSSL_free(ssl->session->psk_identity);
   1613     ssl->session->psk_identity = BUF_strdup(identity);
   1614     if (ssl->session->psk_identity == NULL) {
   1615       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1616       goto err;
   1617     }
   1618 
   1619     /* Write out psk_identity. */
   1620     CBB child;
   1621     if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
   1622         !CBB_add_bytes(&child, (const uint8_t *)identity,
   1623                        OPENSSL_strnlen(identity, sizeof(identity))) ||
   1624         !CBB_flush(&cbb)) {
   1625       goto err;
   1626     }
   1627   }
   1628 
   1629   /* Depending on the key exchange method, compute |pms| and |pms_len|. */
   1630   if (alg_k & SSL_kRSA) {
   1631     pms_len = SSL_MAX_MASTER_KEY_LENGTH;
   1632     pms = OPENSSL_malloc(pms_len);
   1633     if (pms == NULL) {
   1634       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1635       goto err;
   1636     }
   1637 
   1638     EVP_PKEY *pkey = X509_get_pubkey(ssl->session->peer);
   1639     if (pkey == NULL) {
   1640       goto err;
   1641     }
   1642 
   1643     RSA *rsa = EVP_PKEY_get0_RSA(pkey);
   1644     if (rsa == NULL) {
   1645       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1646       EVP_PKEY_free(pkey);
   1647       goto err;
   1648     }
   1649 
   1650     ssl->session->key_exchange_info = EVP_PKEY_bits(pkey);
   1651     EVP_PKEY_free(pkey);
   1652 
   1653     pms[0] = ssl->client_version >> 8;
   1654     pms[1] = ssl->client_version & 0xff;
   1655     if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
   1656       goto err;
   1657     }
   1658 
   1659     CBB child, *enc_pms = &cbb;
   1660     size_t enc_pms_len;
   1661     /* In TLS, there is a length prefix. */
   1662     if (ssl->version > SSL3_VERSION) {
   1663       if (!CBB_add_u16_length_prefixed(&cbb, &child)) {
   1664         goto err;
   1665       }
   1666       enc_pms = &child;
   1667     }
   1668 
   1669     uint8_t *ptr;
   1670     if (!CBB_reserve(enc_pms, &ptr, RSA_size(rsa)) ||
   1671         !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms, pms_len,
   1672                      RSA_PKCS1_PADDING) ||
   1673         /* Log the premaster secret, if logging is enabled. */
   1674         !ssl_log_rsa_client_key_exchange(ssl, ptr, enc_pms_len, pms, pms_len) ||
   1675         !CBB_did_write(enc_pms, enc_pms_len) ||
   1676         !CBB_flush(&cbb)) {
   1677       goto err;
   1678     }
   1679   } else if (alg_k & (SSL_kECDHE|SSL_kDHE)) {
   1680     /* Generate a keypair and serialize the public half. ECDHE uses a u8 length
   1681      * prefix while DHE uses u16. */
   1682     CBB child;
   1683     int child_ok;
   1684     if (alg_k & SSL_kECDHE) {
   1685       child_ok = CBB_add_u8_length_prefixed(&cbb, &child);
   1686     } else {
   1687       child_ok = CBB_add_u16_length_prefixed(&cbb, &child);
   1688     }
   1689 
   1690     if (!child_ok ||
   1691         !SSL_ECDH_CTX_generate_keypair(&ssl->s3->tmp.ecdh_ctx, &child) ||
   1692         !CBB_flush(&cbb)) {
   1693       goto err;
   1694     }
   1695 
   1696     /* Compute the premaster. */
   1697     uint8_t alert;
   1698     if (!SSL_ECDH_CTX_compute_secret(&ssl->s3->tmp.ecdh_ctx, &pms, &pms_len,
   1699                                      &alert, ssl->s3->tmp.peer_key,
   1700                                      ssl->s3->tmp.peer_key_len)) {
   1701       ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
   1702       goto err;
   1703     }
   1704 
   1705     /* The key exchange state may now be discarded. */
   1706     SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
   1707     OPENSSL_free(ssl->s3->tmp.peer_key);
   1708     ssl->s3->tmp.peer_key = NULL;
   1709   } else if (alg_k & SSL_kPSK) {
   1710     /* For plain PSK, other_secret is a block of 0s with the same length as
   1711      * the pre-shared key. */
   1712     pms_len = psk_len;
   1713     pms = OPENSSL_malloc(pms_len);
   1714     if (pms == NULL) {
   1715       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1716       goto err;
   1717     }
   1718     memset(pms, 0, pms_len);
   1719   } else {
   1720     ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1721     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1722     goto err;
   1723   }
   1724 
   1725   /* For a PSK cipher suite, other_secret is combined with the pre-shared
   1726    * key. */
   1727   if (alg_a & SSL_aPSK) {
   1728     CBB pms_cbb, child;
   1729     uint8_t *new_pms;
   1730     size_t new_pms_len;
   1731 
   1732     CBB_zero(&pms_cbb);
   1733     if (!CBB_init(&pms_cbb, 2 + psk_len + 2 + pms_len) ||
   1734         !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
   1735         !CBB_add_bytes(&child, pms, pms_len) ||
   1736         !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
   1737         !CBB_add_bytes(&child, psk, psk_len) ||
   1738         !CBB_finish(&pms_cbb, &new_pms, &new_pms_len)) {
   1739       CBB_cleanup(&pms_cbb);
   1740       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
   1741       goto err;
   1742     }
   1743     OPENSSL_cleanse(pms, pms_len);
   1744     OPENSSL_free(pms);
   1745     pms = new_pms;
   1746     pms_len = new_pms_len;
   1747   }
   1748 
   1749   /* The message must be added to the finished hash before calculating the
   1750    * master secret. */
   1751   size_t length;
   1752   if (!CBB_finish(&cbb, NULL, &length) ||
   1753       !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_KEY_EXCHANGE, length)) {
   1754     goto err;
   1755   }
   1756   ssl->state = SSL3_ST_CW_KEY_EXCH_B;
   1757 
   1758   ssl->session->master_key_length = ssl->enc_method->generate_master_secret(
   1759       ssl, ssl->session->master_key, pms, pms_len);
   1760   if (ssl->session->master_key_length == 0) {
   1761     goto err;
   1762   }
   1763   ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
   1764   OPENSSL_cleanse(pms, pms_len);
   1765   OPENSSL_free(pms);
   1766 
   1767   /* SSL3_ST_CW_KEY_EXCH_B */
   1768   return ssl_do_write(ssl);
   1769 
   1770 err:
   1771   if (pms != NULL) {
   1772     OPENSSL_cleanse(pms, pms_len);
   1773     OPENSSL_free(pms);
   1774   }
   1775   return -1;
   1776 }
   1777 
   1778 int ssl3_send_cert_verify(SSL *ssl) {
   1779   if (ssl->state == SSL3_ST_CW_CERT_VRFY_C) {
   1780     return ssl_do_write(ssl);
   1781   }
   1782 
   1783   CBB cbb, child;
   1784   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
   1785                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
   1786     goto err;
   1787   }
   1788 
   1789   assert(ssl_has_private_key(ssl));
   1790 
   1791   const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
   1792   size_t sig_len;
   1793   enum ssl_private_key_result_t sign_result;
   1794   if (ssl->state == SSL3_ST_CW_CERT_VRFY_A) {
   1795     /* Select and write out the digest type in TLS 1.2. */
   1796     const EVP_MD *md = NULL;
   1797     if (SSL_USE_SIGALGS(ssl)) {
   1798       md = tls1_choose_signing_digest(ssl);
   1799       if (!tls12_add_sigandhash(ssl, &cbb, md)) {
   1800         OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1801         goto err;
   1802       }
   1803     }
   1804 
   1805     /* Compute the digest. In TLS 1.1 and below, the digest type is also
   1806      * selected here. */
   1807     uint8_t digest[EVP_MAX_MD_SIZE];
   1808     size_t digest_len;
   1809     if (!ssl3_cert_verify_hash(ssl, digest, &digest_len, &md,
   1810                                ssl_private_key_type(ssl))) {
   1811       goto err;
   1812     }
   1813 
   1814     /* The handshake buffer is no longer necessary. */
   1815     ssl3_free_handshake_buffer(ssl);
   1816 
   1817     /* Sign the digest. */
   1818     uint8_t *ptr;
   1819     if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
   1820         !CBB_reserve(&child, &ptr, max_sig_len)) {
   1821       goto err;
   1822     }
   1823     sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
   1824                                        digest, digest_len);
   1825   } else {
   1826     assert(ssl->state == SSL3_ST_CW_CERT_VRFY_B);
   1827 
   1828     /* Skip over the already written signature algorithm and retry the
   1829      * signature. */
   1830     uint8_t *ptr;
   1831     if ((SSL_USE_SIGALGS(ssl) && !CBB_did_write(&cbb, 2)) ||
   1832         !CBB_add_u16_length_prefixed(&cbb, &child) ||
   1833         !CBB_reserve(&child, &ptr, max_sig_len)) {
   1834       goto err;
   1835     }
   1836     sign_result =
   1837         ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
   1838   }
   1839 
   1840   switch (sign_result) {
   1841     case ssl_private_key_success:
   1842       ssl->rwstate = SSL_NOTHING;
   1843       break;
   1844     case ssl_private_key_failure:
   1845       ssl->rwstate = SSL_NOTHING;
   1846       goto err;
   1847     case ssl_private_key_retry:
   1848       ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
   1849       ssl->state = SSL3_ST_CW_CERT_VRFY_B;
   1850       goto err;
   1851   }
   1852 
   1853   size_t length;
   1854   if (!CBB_did_write(&child, sig_len) ||
   1855       !CBB_finish(&cbb, NULL, &length) ||
   1856       !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_VERIFY, length)) {
   1857     goto err;
   1858   }
   1859 
   1860   ssl->state = SSL3_ST_CW_CERT_VRFY_C;
   1861   return ssl_do_write(ssl);
   1862 
   1863 err:
   1864   CBB_cleanup(&cbb);
   1865   return -1;
   1866 }
   1867 
   1868 /* ssl3_has_client_certificate returns true if a client certificate is
   1869  * configured. */
   1870 static int ssl3_has_client_certificate(SSL *ssl) {
   1871   return ssl->cert && ssl->cert->x509 && ssl_has_private_key(ssl);
   1872 }
   1873 
   1874 int ssl3_send_client_certificate(SSL *ssl) {
   1875   X509 *x509 = NULL;
   1876   EVP_PKEY *pkey = NULL;
   1877   int i;
   1878 
   1879   if (ssl->state == SSL3_ST_CW_CERT_A) {
   1880     /* Let cert callback update client certificates if required */
   1881     if (ssl->cert->cert_cb) {
   1882       i = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
   1883       if (i < 0) {
   1884         ssl->rwstate = SSL_X509_LOOKUP;
   1885         return -1;
   1886       }
   1887       if (i == 0) {
   1888         ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1889         return 0;
   1890       }
   1891       ssl->rwstate = SSL_NOTHING;
   1892     }
   1893 
   1894     if (ssl3_has_client_certificate(ssl)) {
   1895       ssl->state = SSL3_ST_CW_CERT_C;
   1896     } else {
   1897       ssl->state = SSL3_ST_CW_CERT_B;
   1898     }
   1899   }
   1900 
   1901   /* We need to get a client cert */
   1902   if (ssl->state == SSL3_ST_CW_CERT_B) {
   1903     /* If we get an error, we need to:
   1904      *   ssl->rwstate=SSL_X509_LOOKUP; return(-1);
   1905      * We then get retried later */
   1906     i = ssl_do_client_cert_cb(ssl, &x509, &pkey);
   1907     if (i < 0) {
   1908       ssl->rwstate = SSL_X509_LOOKUP;
   1909       return -1;
   1910     }
   1911     ssl->rwstate = SSL_NOTHING;
   1912     if (i == 1 && pkey != NULL && x509 != NULL) {
   1913       ssl->state = SSL3_ST_CW_CERT_B;
   1914       if (!SSL_use_certificate(ssl, x509) || !SSL_use_PrivateKey(ssl, pkey)) {
   1915         i = 0;
   1916       }
   1917     } else if (i == 1) {
   1918       i = 0;
   1919       OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
   1920     }
   1921 
   1922     X509_free(x509);
   1923     EVP_PKEY_free(pkey);
   1924     if (i && !ssl3_has_client_certificate(ssl)) {
   1925       i = 0;
   1926     }
   1927     if (i == 0) {
   1928       if (ssl->version == SSL3_VERSION) {
   1929         ssl->s3->tmp.cert_req = 0;
   1930         ssl3_send_alert(ssl, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
   1931         return 1;
   1932       } else {
   1933         ssl->s3->tmp.cert_req = 2;
   1934         /* There is no client certificate, so the handshake buffer may be
   1935          * released. */
   1936         ssl3_free_handshake_buffer(ssl);
   1937       }
   1938     }
   1939 
   1940     /* Ok, we have a cert */
   1941     ssl->state = SSL3_ST_CW_CERT_C;
   1942   }
   1943 
   1944   if (ssl->state == SSL3_ST_CW_CERT_C) {
   1945     if (ssl->s3->tmp.cert_req == 2) {
   1946       /* Send an empty Certificate message. */
   1947       uint8_t *p = ssl_handshake_start(ssl);
   1948       l2n3(0, p);
   1949       if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE, 3)) {
   1950         return -1;
   1951       }
   1952     } else if (!ssl3_output_cert_chain(ssl)) {
   1953       return -1;
   1954     }
   1955     ssl->state = SSL3_ST_CW_CERT_D;
   1956   }
   1957 
   1958   /* SSL3_ST_CW_CERT_D */
   1959   return ssl_do_write(ssl);
   1960 }
   1961 
   1962 int ssl3_send_next_proto(SSL *ssl) {
   1963   if (ssl->state == SSL3_ST_CW_NEXT_PROTO_B) {
   1964     return ssl_do_write(ssl);
   1965   }
   1966 
   1967   assert(ssl->state == SSL3_ST_CW_NEXT_PROTO_A);
   1968 
   1969   static const uint8_t kZero[32] = {0};
   1970   size_t padding_len = 32 - ((ssl->next_proto_negotiated_len + 2) % 32);
   1971 
   1972   CBB cbb, child;
   1973   size_t length;
   1974   CBB_zero(&cbb);
   1975   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
   1976                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
   1977       !CBB_add_u8_length_prefixed(&cbb, &child) ||
   1978       !CBB_add_bytes(&child, ssl->next_proto_negotiated,
   1979                      ssl->next_proto_negotiated_len) ||
   1980       !CBB_add_u8_length_prefixed(&cbb, &child) ||
   1981       !CBB_add_bytes(&child, kZero, padding_len) ||
   1982       !CBB_finish(&cbb, NULL, &length) ||
   1983       !ssl_set_handshake_header(ssl, SSL3_MT_NEXT_PROTO, length)) {
   1984     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   1985     CBB_cleanup(&cbb);
   1986     return -1;
   1987   }
   1988 
   1989   ssl->state = SSL3_ST_CW_NEXT_PROTO_B;
   1990   return ssl_do_write(ssl);
   1991 }
   1992 
   1993 int ssl3_send_channel_id(SSL *ssl) {
   1994   if (ssl->state == SSL3_ST_CW_CHANNEL_ID_B) {
   1995     return ssl_do_write(ssl);
   1996   }
   1997 
   1998   assert(ssl->state == SSL3_ST_CW_CHANNEL_ID_A);
   1999 
   2000   if (ssl->tlsext_channel_id_private == NULL &&
   2001       ssl->ctx->channel_id_cb != NULL) {
   2002     EVP_PKEY *key = NULL;
   2003     ssl->ctx->channel_id_cb(ssl, &key);
   2004     if (key != NULL &&
   2005         !SSL_set1_tls_channel_id(ssl, key)) {
   2006       EVP_PKEY_free(key);
   2007       return -1;
   2008     }
   2009     EVP_PKEY_free(key);
   2010   }
   2011 
   2012   if (ssl->tlsext_channel_id_private == NULL) {
   2013     ssl->rwstate = SSL_CHANNEL_ID_LOOKUP;
   2014     return -1;
   2015   }
   2016   ssl->rwstate = SSL_NOTHING;
   2017 
   2018   EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(ssl->tlsext_channel_id_private);
   2019   if (ec_key == NULL) {
   2020     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2021     return -1;
   2022   }
   2023 
   2024   int ret = -1;
   2025   BIGNUM *x = BN_new();
   2026   BIGNUM *y = BN_new();
   2027   ECDSA_SIG *sig = NULL;
   2028   if (x == NULL || y == NULL ||
   2029       !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
   2030                                            EC_KEY_get0_public_key(ec_key),
   2031                                            x, y, NULL)) {
   2032     goto err;
   2033   }
   2034 
   2035   uint8_t digest[EVP_MAX_MD_SIZE];
   2036   size_t digest_len;
   2037   if (!tls1_channel_id_hash(ssl, digest, &digest_len)) {
   2038     goto err;
   2039   }
   2040 
   2041   sig = ECDSA_do_sign(digest, digest_len, ec_key);
   2042   if (sig == NULL) {
   2043     goto err;
   2044   }
   2045 
   2046   CBB cbb, child;
   2047   size_t length;
   2048   CBB_zero(&cbb);
   2049   if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
   2050                       ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
   2051       !CBB_add_u16(&cbb, TLSEXT_TYPE_channel_id) ||
   2052       !CBB_add_u16_length_prefixed(&cbb, &child) ||
   2053       !BN_bn2cbb_padded(&child, 32, x) ||
   2054       !BN_bn2cbb_padded(&child, 32, y) ||
   2055       !BN_bn2cbb_padded(&child, 32, sig->r) ||
   2056       !BN_bn2cbb_padded(&child, 32, sig->s) ||
   2057       !CBB_finish(&cbb, NULL, &length) ||
   2058       !ssl_set_handshake_header(ssl, SSL3_MT_ENCRYPTED_EXTENSIONS, length)) {
   2059     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
   2060     CBB_cleanup(&cbb);
   2061     goto err;
   2062   }
   2063 
   2064   ssl->state = SSL3_ST_CW_CHANNEL_ID_B;
   2065   ret = ssl_do_write(ssl);
   2066 
   2067 err:
   2068   BN_free(x);
   2069   BN_free(y);
   2070   ECDSA_SIG_free(sig);
   2071   return ret;
   2072 }
   2073 
   2074 int ssl_do_client_cert_cb(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
   2075   if (ssl->ctx->client_cert_cb == NULL) {
   2076     return 0;
   2077   }
   2078   return ssl->ctx->client_cert_cb(ssl, out_x509, out_pkey);
   2079 }
   2080 
   2081 int ssl3_verify_server_cert(SSL *ssl) {
   2082   int ret = ssl_verify_cert_chain(ssl, ssl->session->cert_chain);
   2083   if (ssl->verify_mode != SSL_VERIFY_NONE && ret <= 0) {
   2084     int al = ssl_verify_alarm_type(ssl->verify_result);
   2085     ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
   2086     OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
   2087   } else {
   2088     ret = 1;
   2089     ERR_clear_error(); /* but we keep ssl->verify_result */
   2090   }
   2091 
   2092   return ret;
   2093 }
   2094