Home | History | Annotate | Download | only in ssl
      1 /* ssl/s3_clnt.c */
      2 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      3  * All rights reserved.
      4  *
      5  * This package is an SSL implementation written
      6  * by Eric Young (eay (at) cryptsoft.com).
      7  * The implementation was written so as to conform with Netscapes SSL.
      8  *
      9  * This library is free for commercial and non-commercial use as long as
     10  * the following conditions are aheared to.  The following conditions
     11  * apply to all code found in this distribution, be it the RC4, RSA,
     12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     13  * included with this distribution is covered by the same copyright terms
     14  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     15  *
     16  * Copyright remains Eric Young's, and as such any Copyright notices in
     17  * the code are not to be removed.
     18  * If this package is used in a product, Eric Young should be given attribution
     19  * as the author of the parts of the library used.
     20  * This can be in the form of a textual message at program startup or
     21  * in documentation (online or textual) provided with the package.
     22  *
     23  * Redistribution and use in source and binary forms, with or without
     24  * modification, are permitted provided that the following conditions
     25  * are met:
     26  * 1. Redistributions of source code must retain the copyright
     27  *    notice, this list of conditions and the following disclaimer.
     28  * 2. Redistributions in binary form must reproduce the above copyright
     29  *    notice, this list of conditions and the following disclaimer in the
     30  *    documentation and/or other materials provided with the distribution.
     31  * 3. All advertising materials mentioning features or use of this software
     32  *    must display the following acknowledgement:
     33  *    "This product includes cryptographic software written by
     34  *     Eric Young (eay (at) cryptsoft.com)"
     35  *    The word 'cryptographic' can be left out if the rouines from the library
     36  *    being used are not cryptographic related :-).
     37  * 4. If you include any Windows specific code (or a derivative thereof) from
     38  *    the apps directory (application code) you must include an acknowledgement:
     39  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     40  *
     41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     51  * SUCH DAMAGE.
     52  *
     53  * The licence and distribution terms for any publically available version or
     54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
     55  * copied and put under another distribution licence
     56  * [including the GNU Public Licence.]
     57  */
     58 /* ====================================================================
     59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
     60  *
     61  * Redistribution and use in source and binary forms, with or without
     62  * modification, are permitted provided that the following conditions
     63  * are met:
     64  *
     65  * 1. Redistributions of source code must retain the above copyright
     66  *    notice, this list of conditions and the following disclaimer.
     67  *
     68  * 2. Redistributions in binary form must reproduce the above copyright
     69  *    notice, this list of conditions and the following disclaimer in
     70  *    the documentation and/or other materials provided with the
     71  *    distribution.
     72  *
     73  * 3. All advertising materials mentioning features or use of this
     74  *    software must display the following acknowledgment:
     75  *    "This product includes software developed by the OpenSSL Project
     76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
     77  *
     78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     79  *    endorse or promote products derived from this software without
     80  *    prior written permission. For written permission, please contact
     81  *    openssl-core (at) openssl.org.
     82  *
     83  * 5. Products derived from this software may not be called "OpenSSL"
     84  *    nor may "OpenSSL" appear in their names without prior written
     85  *    permission of the OpenSSL Project.
     86  *
     87  * 6. Redistributions of any form whatsoever must retain the following
     88  *    acknowledgment:
     89  *    "This product includes software developed by the OpenSSL Project
     90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
     91  *
     92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    103  * OF THE POSSIBILITY OF SUCH DAMAGE.
    104  * ====================================================================
    105  *
    106  * This product includes cryptographic software written by Eric Young
    107  * (eay (at) cryptsoft.com).  This product includes software written by Tim
    108  * Hudson (tjh (at) cryptsoft.com).
    109  *
    110  */
    111 /* ====================================================================
    112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
    113  *
    114  * Portions of the attached software ("Contribution") are developed by
    115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
    116  *
    117  * The Contribution is licensed pursuant to the OpenSSL open source
    118  * license provided above.
    119  *
    120  * ECC cipher suite support in OpenSSL originally written by
    121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
    122  *
    123  */
    124 /* ====================================================================
    125  * Copyright 2005 Nokia. All rights reserved.
    126  *
    127  * The portions of the attached software ("Contribution") is developed by
    128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
    129  * license.
    130  *
    131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
    132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
    133  * support (see RFC 4279) to OpenSSL.
    134  *
    135  * No patent licenses or other rights except those expressly stated in
    136  * the OpenSSL open source license shall be deemed granted or received
    137  * expressly, by implication, estoppel, or otherwise.
    138  *
    139  * No assurances are provided by Nokia that the Contribution does not
    140  * infringe the patent or other intellectual property rights of any third
    141  * party or that the license provides you with all the necessary rights
    142  * to make use of the Contribution.
    143  *
    144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
    145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
    146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
    147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
    148  * OTHERWISE.
    149  */
    150 
    151 #include <assert.h>
    152 #include <stdio.h>
    153 #include <string.h>
    154 
    155 #include <openssl/buf.h>
    156 #include <openssl/bytestring.h>
    157 #include <openssl/rand.h>
    158 #include <openssl/obj.h>
    159 #include <openssl/err.h>
    160 #include <openssl/evp.h>
    161 #include <openssl/mem.h>
    162 #include <openssl/md5.h>
    163 #include <openssl/dh.h>
    164 #include <openssl/bn.h>
    165 #include <openssl/x509.h>
    166 
    167 #include "internal.h"
    168 #include "../crypto/dh/internal.h"
    169 
    170 
    171 int ssl3_connect(SSL *s) {
    172   BUF_MEM *buf = NULL;
    173   void (*cb)(const SSL *ssl, int type, int val) = NULL;
    174   int ret = -1;
    175   int new_state, state, skip = 0;
    176 
    177   assert(s->handshake_func == ssl3_connect);
    178   assert(!s->server);
    179   assert(!SSL_IS_DTLS(s));
    180 
    181   ERR_clear_error();
    182   ERR_clear_system_error();
    183 
    184   if (s->info_callback != NULL) {
    185     cb = s->info_callback;
    186   } else if (s->ctx->info_callback != NULL) {
    187     cb = s->ctx->info_callback;
    188   }
    189 
    190   s->in_handshake++;
    191 
    192   for (;;) {
    193     state = s->state;
    194 
    195     switch (s->state) {
    196       case SSL_ST_CONNECT:
    197         if (cb != NULL) {
    198           cb(s, SSL_CB_HANDSHAKE_START, 1);
    199         }
    200 
    201         if (s->init_buf == NULL) {
    202           buf = BUF_MEM_new();
    203           if (buf == NULL ||
    204               !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
    205             ret = -1;
    206             goto end;
    207           }
    208 
    209           s->init_buf = buf;
    210           buf = NULL;
    211         }
    212 
    213         if (!ssl_init_wbio_buffer(s, 0)) {
    214           ret = -1;
    215           goto end;
    216         }
    217 
    218         /* don't push the buffering BIO quite yet */
    219 
    220         if (!ssl3_init_finished_mac(s)) {
    221           OPENSSL_PUT_ERROR(SSL, ssl3_connect, ERR_R_INTERNAL_ERROR);
    222           ret = -1;
    223           goto end;
    224         }
    225 
    226         s->state = SSL3_ST_CW_CLNT_HELLO_A;
    227         s->init_num = 0;
    228         break;
    229 
    230       case SSL3_ST_CW_CLNT_HELLO_A:
    231       case SSL3_ST_CW_CLNT_HELLO_B:
    232         s->shutdown = 0;
    233         ret = ssl3_send_client_hello(s);
    234         if (ret <= 0) {
    235           goto end;
    236         }
    237         s->state = SSL3_ST_CR_SRVR_HELLO_A;
    238         s->init_num = 0;
    239 
    240         /* turn on buffering for the next lot of output */
    241         if (s->bbio != s->wbio) {
    242           s->wbio = BIO_push(s->bbio, s->wbio);
    243         }
    244 
    245         break;
    246 
    247       case SSL3_ST_CR_SRVR_HELLO_A:
    248       case SSL3_ST_CR_SRVR_HELLO_B:
    249         ret = ssl3_get_server_hello(s);
    250         if (ret <= 0) {
    251           goto end;
    252         }
    253 
    254         if (s->hit) {
    255           s->state = SSL3_ST_CR_CHANGE;
    256           if (s->tlsext_ticket_expected) {
    257             /* receive renewed session ticket */
    258             s->state = SSL3_ST_CR_SESSION_TICKET_A;
    259           }
    260         } else {
    261           s->state = SSL3_ST_CR_CERT_A;
    262         }
    263         s->init_num = 0;
    264         break;
    265 
    266       case SSL3_ST_CR_CERT_A:
    267       case SSL3_ST_CR_CERT_B:
    268         if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
    269           ret = ssl3_get_server_certificate(s);
    270           if (ret <= 0) {
    271             goto end;
    272           }
    273           if (s->s3->tmp.certificate_status_expected) {
    274             s->state = SSL3_ST_CR_CERT_STATUS_A;
    275           } else {
    276             s->state = SSL3_ST_CR_KEY_EXCH_A;
    277           }
    278         } else {
    279           skip = 1;
    280           s->state = SSL3_ST_CR_KEY_EXCH_A;
    281         }
    282         s->init_num = 0;
    283         break;
    284 
    285       case SSL3_ST_CR_KEY_EXCH_A:
    286       case SSL3_ST_CR_KEY_EXCH_B:
    287         ret = ssl3_get_server_key_exchange(s);
    288         if (ret <= 0) {
    289           goto end;
    290         }
    291         s->state = SSL3_ST_CR_CERT_REQ_A;
    292         s->init_num = 0;
    293 
    294         /* at this point we check that we have the
    295          * required stuff from the server */
    296         if (!ssl3_check_cert_and_algorithm(s)) {
    297           ret = -1;
    298           goto end;
    299         }
    300         break;
    301 
    302       case SSL3_ST_CR_CERT_REQ_A:
    303       case SSL3_ST_CR_CERT_REQ_B:
    304         ret = ssl3_get_certificate_request(s);
    305         if (ret <= 0) {
    306           goto end;
    307         }
    308         s->state = SSL3_ST_CR_SRVR_DONE_A;
    309         s->init_num = 0;
    310         break;
    311 
    312       case SSL3_ST_CR_SRVR_DONE_A:
    313       case SSL3_ST_CR_SRVR_DONE_B:
    314         ret = ssl3_get_server_done(s);
    315         if (ret <= 0) {
    316           goto end;
    317         }
    318         if (s->s3->tmp.cert_req) {
    319           s->state = SSL3_ST_CW_CERT_A;
    320         } else {
    321           s->state = SSL3_ST_CW_KEY_EXCH_A;
    322         }
    323         s->init_num = 0;
    324 
    325         break;
    326 
    327       case SSL3_ST_CW_CERT_A:
    328       case SSL3_ST_CW_CERT_B:
    329       case SSL3_ST_CW_CERT_C:
    330       case SSL3_ST_CW_CERT_D:
    331         ret = ssl3_send_client_certificate(s);
    332         if (ret <= 0) {
    333           goto end;
    334         }
    335         s->state = SSL3_ST_CW_KEY_EXCH_A;
    336         s->init_num = 0;
    337         break;
    338 
    339       case SSL3_ST_CW_KEY_EXCH_A:
    340       case SSL3_ST_CW_KEY_EXCH_B:
    341         ret = ssl3_send_client_key_exchange(s);
    342         if (ret <= 0) {
    343           goto end;
    344         }
    345         /* For TLS, cert_req is set to 2, so a cert chain
    346          * of nothing is sent, but no verify packet is sent */
    347         if (s->s3->tmp.cert_req == 1) {
    348           s->state = SSL3_ST_CW_CERT_VRFY_A;
    349         } else {
    350           s->state = SSL3_ST_CW_CHANGE_A;
    351           s->s3->change_cipher_spec = 0;
    352         }
    353 
    354         s->init_num = 0;
    355         break;
    356 
    357       case SSL3_ST_CW_CERT_VRFY_A:
    358       case SSL3_ST_CW_CERT_VRFY_B:
    359         ret = ssl3_send_cert_verify(s);
    360         if (ret <= 0) {
    361           goto end;
    362         }
    363         s->state = SSL3_ST_CW_CHANGE_A;
    364         s->init_num = 0;
    365         s->s3->change_cipher_spec = 0;
    366         break;
    367 
    368       case SSL3_ST_CW_CHANGE_A:
    369       case SSL3_ST_CW_CHANGE_B:
    370         ret = ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,
    371                                            SSL3_ST_CW_CHANGE_B);
    372         if (ret <= 0) {
    373           goto end;
    374         }
    375 
    376         s->state = SSL3_ST_CW_FINISHED_A;
    377         if (s->s3->tlsext_channel_id_valid) {
    378           s->state = SSL3_ST_CW_CHANNEL_ID_A;
    379         }
    380         if (s->s3->next_proto_neg_seen) {
    381           s->state = SSL3_ST_CW_NEXT_PROTO_A;
    382         }
    383         s->init_num = 0;
    384 
    385         s->session->cipher = s->s3->tmp.new_cipher;
    386         if (!s->enc_method->setup_key_block(s) ||
    387             !s->enc_method->change_cipher_state(
    388                 s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
    389           ret = -1;
    390           goto end;
    391         }
    392 
    393         break;
    394 
    395       case SSL3_ST_CW_NEXT_PROTO_A:
    396       case SSL3_ST_CW_NEXT_PROTO_B:
    397         ret = ssl3_send_next_proto(s);
    398         if (ret <= 0) {
    399           goto end;
    400         }
    401 
    402         if (s->s3->tlsext_channel_id_valid) {
    403           s->state = SSL3_ST_CW_CHANNEL_ID_A;
    404         } else {
    405           s->state = SSL3_ST_CW_FINISHED_A;
    406         }
    407         break;
    408 
    409       case SSL3_ST_CW_CHANNEL_ID_A:
    410       case SSL3_ST_CW_CHANNEL_ID_B:
    411         ret = ssl3_send_channel_id(s);
    412         if (ret <= 0) {
    413           goto end;
    414         }
    415         s->state = SSL3_ST_CW_FINISHED_A;
    416         break;
    417 
    418       case SSL3_ST_CW_FINISHED_A:
    419       case SSL3_ST_CW_FINISHED_B:
    420         ret =
    421             ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A, SSL3_ST_CW_FINISHED_B,
    422                                s->enc_method->client_finished_label,
    423                                s->enc_method->client_finished_label_len);
    424         if (ret <= 0) {
    425           goto end;
    426         }
    427         s->state = SSL3_ST_CW_FLUSH;
    428 
    429         if (s->hit) {
    430           s->s3->tmp.next_state = SSL_ST_OK;
    431         } else {
    432           /* This is a non-resumption handshake. If it involves ChannelID, then
    433            * record the handshake hashes at this point in the session so that
    434            * any resumption of this session with ChannelID can sign those
    435            * hashes. */
    436           if (s->s3->tlsext_channel_id_new) {
    437             ret = tls1_record_handshake_hashes_for_channel_id(s);
    438             if (ret <= 0) {
    439               goto end;
    440             }
    441           }
    442           if ((SSL_get_mode(s) & SSL_MODE_ENABLE_FALSE_START) &&
    443               ssl3_can_false_start(s) &&
    444               /* No False Start on renegotiation (would complicate the state
    445                * machine). */
    446               !s->s3->initial_handshake_complete) {
    447             s->s3->tmp.next_state = SSL3_ST_FALSE_START;
    448           } else {
    449             /* Allow NewSessionTicket if ticket expected */
    450             if (s->tlsext_ticket_expected) {
    451               s->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
    452             } else {
    453               s->s3->tmp.next_state = SSL3_ST_CR_CHANGE;
    454             }
    455           }
    456         }
    457         s->init_num = 0;
    458         break;
    459 
    460       case SSL3_ST_CR_SESSION_TICKET_A:
    461       case SSL3_ST_CR_SESSION_TICKET_B:
    462         ret = ssl3_get_new_session_ticket(s);
    463         if (ret <= 0) {
    464           goto end;
    465         }
    466         s->state = SSL3_ST_CR_CHANGE;
    467         s->init_num = 0;
    468         break;
    469 
    470       case SSL3_ST_CR_CERT_STATUS_A:
    471       case SSL3_ST_CR_CERT_STATUS_B:
    472         ret = ssl3_get_cert_status(s);
    473         if (ret <= 0) {
    474           goto end;
    475         }
    476         s->state = SSL3_ST_CR_KEY_EXCH_A;
    477         s->init_num = 0;
    478         break;
    479 
    480       case SSL3_ST_CR_CHANGE:
    481         /* At this point, the next message must be entirely behind a
    482          * ChangeCipherSpec. */
    483         if (!ssl3_expect_change_cipher_spec(s)) {
    484           ret = -1;
    485           goto end;
    486         }
    487         s->state = SSL3_ST_CR_FINISHED_A;
    488         break;
    489 
    490       case SSL3_ST_CR_FINISHED_A:
    491       case SSL3_ST_CR_FINISHED_B:
    492         ret =
    493             ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B);
    494         if (ret <= 0) {
    495           goto end;
    496         }
    497 
    498         if (s->hit) {
    499           s->state = SSL3_ST_CW_CHANGE_A;
    500         } else {
    501           s->state = SSL_ST_OK;
    502         }
    503         s->init_num = 0;
    504         break;
    505 
    506       case SSL3_ST_CW_FLUSH:
    507         s->rwstate = SSL_WRITING;
    508         if (BIO_flush(s->wbio) <= 0) {
    509           ret = -1;
    510           goto end;
    511         }
    512         s->rwstate = SSL_NOTHING;
    513         s->state = s->s3->tmp.next_state;
    514         break;
    515 
    516       case SSL3_ST_FALSE_START:
    517         /* Allow NewSessionTicket if ticket expected */
    518         if (s->tlsext_ticket_expected) {
    519           s->state = SSL3_ST_CR_SESSION_TICKET_A;
    520         } else {
    521           s->state = SSL3_ST_CR_CHANGE;
    522         }
    523         s->s3->tmp.in_false_start = 1;
    524 
    525         ssl_free_wbio_buffer(s);
    526         ret = 1;
    527         goto end;
    528 
    529       case SSL_ST_OK:
    530         /* clean a few things up */
    531         ssl3_cleanup_key_block(s);
    532 
    533         BUF_MEM_free(s->init_buf);
    534         s->init_buf = NULL;
    535 
    536         /* Remove write buffering now. */
    537         ssl_free_wbio_buffer(s);
    538 
    539         s->init_num = 0;
    540         s->s3->tmp.in_false_start = 0;
    541         s->s3->initial_handshake_complete = 1;
    542 
    543         ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
    544 
    545         ret = 1;
    546         /* s->server=0; */
    547 
    548         if (cb != NULL) {
    549           cb(s, SSL_CB_HANDSHAKE_DONE, 1);
    550         }
    551 
    552         goto end;
    553 
    554       default:
    555         OPENSSL_PUT_ERROR(SSL, ssl3_connect, SSL_R_UNKNOWN_STATE);
    556         ret = -1;
    557         goto end;
    558     }
    559 
    560     if (!s->s3->tmp.reuse_message && !skip) {
    561       if (cb != NULL && s->state != state) {
    562         new_state = s->state;
    563         s->state = state;
    564         cb(s, SSL_CB_CONNECT_LOOP, 1);
    565         s->state = new_state;
    566       }
    567     }
    568     skip = 0;
    569   }
    570 
    571 end:
    572   s->in_handshake--;
    573   BUF_MEM_free(buf);
    574   if (cb != NULL) {
    575     cb(s, SSL_CB_CONNECT_EXIT, ret);
    576   }
    577   return ret;
    578 }
    579 
    580 int ssl3_send_client_hello(SSL *s) {
    581   uint8_t *buf, *p, *d;
    582   int i;
    583   unsigned long l;
    584 
    585   buf = (uint8_t *)s->init_buf->data;
    586   if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
    587     if (!s->s3->have_version) {
    588       uint16_t max_version = ssl3_get_max_client_version(s);
    589       /* Disabling all versions is silly: return an error. */
    590       if (max_version == 0) {
    591         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_WRONG_SSL_VERSION);
    592         goto err;
    593       }
    594       s->version = max_version;
    595       s->client_version = max_version;
    596     }
    597 
    598     /* If the configured session was created at a version higher than our
    599      * maximum version, drop it. */
    600     if (s->session &&
    601         (s->session->session_id_length == 0 || s->session->not_resumable ||
    602          (!SSL_IS_DTLS(s) && s->session->ssl_version > s->version) ||
    603          (SSL_IS_DTLS(s) && s->session->ssl_version < s->version))) {
    604       SSL_set_session(s, NULL);
    605     }
    606 
    607     /* else use the pre-loaded session */
    608     p = s->s3->client_random;
    609 
    610     /* If resending the ClientHello in DTLS after a HelloVerifyRequest, don't
    611      * renegerate the client_random. The random must be reused. */
    612     if ((!SSL_IS_DTLS(s) || !s->d1->send_cookie) &&
    613         !ssl_fill_hello_random(p, sizeof(s->s3->client_random),
    614                                0 /* client */)) {
    615       goto err;
    616     }
    617 
    618     /* Do the message type and length last. Note: the final argument to
    619      * ssl_add_clienthello_tlsext below depends on the size of this prefix. */
    620     d = p = ssl_handshake_start(s);
    621 
    622     /* version indicates the negotiated version: for example from an SSLv2/v3
    623      * compatible client hello). The client_version field is the maximum
    624      * version we permit and it is also used in RSA encrypted premaster
    625      * secrets. Some servers can choke if we initially report a higher version
    626      * then renegotiate to a lower one in the premaster secret. This didn't
    627      * happen with TLS 1.0 as most servers supported it but it can with TLS 1.1
    628      * or later if the server only supports 1.0.
    629      *
    630      * Possible scenario with previous logic:
    631      *   1. Client hello indicates TLS 1.2
    632      *   2. Server hello says TLS 1.0
    633      *   3. RSA encrypted premaster secret uses 1.2.
    634      *   4. Handhaked proceeds using TLS 1.0.
    635      *   5. Server sends hello request to renegotiate.
    636      *   6. Client hello indicates TLS v1.0 as we now
    637      *      know that is maximum server supports.
    638      *   7. Server chokes on RSA encrypted premaster secret
    639      *      containing version 1.0.
    640      *
    641      * For interoperability it should be OK to always use the maximum version
    642      * we support in client hello and then rely on the checking of version to
    643      * ensure the servers isn't being inconsistent: for example initially
    644      * negotiating with TLS 1.0 and renegotiating with TLS 1.2. We do this by
    645      * using client_version in client hello and not resetting it to the
    646      * negotiated version. */
    647     *(p++) = s->client_version >> 8;
    648     *(p++) = s->client_version & 0xff;
    649 
    650     /* Random stuff */
    651     memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
    652     p += SSL3_RANDOM_SIZE;
    653 
    654     /* Session ID */
    655     if (s->s3->initial_handshake_complete || s->session == NULL) {
    656       /* Renegotiations do not participate in session resumption. */
    657       i = 0;
    658     } else {
    659       i = s->session->session_id_length;
    660     }
    661     *(p++) = i;
    662     if (i != 0) {
    663       if (i > (int)sizeof(s->session->session_id)) {
    664         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    665         goto err;
    666       }
    667       memcpy(p, s->session->session_id, i);
    668       p += i;
    669     }
    670 
    671     /* cookie stuff for DTLS */
    672     if (SSL_IS_DTLS(s)) {
    673       if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
    674         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    675         goto err;
    676       }
    677       *(p++) = s->d1->cookie_len;
    678       memcpy(p, s->d1->cookie, s->d1->cookie_len);
    679       p += s->d1->cookie_len;
    680     }
    681 
    682     /* Ciphers supported */
    683     i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &p[2]);
    684     if (i == 0) {
    685       OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello,
    686                         SSL_R_NO_CIPHERS_AVAILABLE);
    687       goto err;
    688     }
    689     s2n(i, p);
    690     p += i;
    691 
    692     /* COMPRESSION */
    693     *(p++) = 1;
    694     *(p++) = 0; /* Add the NULL method */
    695 
    696     /* TLS extensions*/
    697     if (ssl_prepare_clienthello_tlsext(s) <= 0) {
    698       OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
    699       goto err;
    700     }
    701 
    702     p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
    703                                    p - buf);
    704     if (p == NULL) {
    705       OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    706       goto err;
    707     }
    708 
    709     l = p - d;
    710     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
    711       goto err;
    712     }
    713     s->state = SSL3_ST_CW_CLNT_HELLO_B;
    714   }
    715 
    716   /* SSL3_ST_CW_CLNT_HELLO_B */
    717   return ssl_do_write(s);
    718 
    719 err:
    720   return -1;
    721 }
    722 
    723 int ssl3_get_server_hello(SSL *s) {
    724   STACK_OF(SSL_CIPHER) *sk;
    725   const SSL_CIPHER *c;
    726   CERT *ct = s->cert;
    727   int al = SSL_AD_INTERNAL_ERROR, ok;
    728   long n;
    729   CBS server_hello, server_random, session_id;
    730   uint16_t server_version, cipher_suite;
    731   uint8_t compression_method;
    732   uint32_t mask_ssl;
    733 
    734   n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
    735                                  SSL3_ST_CR_SRVR_HELLO_B, SSL3_MT_SERVER_HELLO,
    736                                  20000, /* ?? */
    737                                  ssl_hash_message, &ok);
    738 
    739   if (!ok) {
    740     uint32_t err = ERR_peek_error();
    741     if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
    742         ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
    743       /* Add a dedicated error code to the queue for a handshake_failure alert
    744        * in response to ClientHello. This matches NSS's client behavior and
    745        * gives a better error on a (probable) failure to negotiate initial
    746        * parameters. Note: this error code comes after the original one.
    747        *
    748        * See https://crbug.com/446505. */
    749       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    750                         SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
    751     }
    752     return n;
    753   }
    754 
    755   CBS_init(&server_hello, s->init_msg, n);
    756 
    757   if (!CBS_get_u16(&server_hello, &server_version) ||
    758       !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
    759       !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
    760       CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
    761       !CBS_get_u16(&server_hello, &cipher_suite) ||
    762       !CBS_get_u8(&server_hello, &compression_method)) {
    763     al = SSL_AD_DECODE_ERROR;
    764     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_DECODE_ERROR);
    765     goto f_err;
    766   }
    767 
    768   assert(s->s3->have_version == s->s3->initial_handshake_complete);
    769   if (!s->s3->have_version) {
    770     if (!ssl3_is_version_enabled(s, server_version)) {
    771       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNSUPPORTED_PROTOCOL);
    772       s->version = server_version;
    773       /* Mark the version as fixed so the record-layer version is not clamped
    774        * to TLS 1.0. */
    775       s->s3->have_version = 1;
    776       al = SSL_AD_PROTOCOL_VERSION;
    777       goto f_err;
    778     }
    779     s->version = server_version;
    780     s->enc_method = ssl3_get_enc_method(server_version);
    781     assert(s->enc_method != NULL);
    782     /* At this point, the connection's version is known and s->version is
    783      * fixed. Begin enforcing the record-layer version. */
    784     s->s3->have_version = 1;
    785   } else if (server_version != s->version) {
    786     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
    787     al = SSL_AD_PROTOCOL_VERSION;
    788     goto f_err;
    789   }
    790 
    791   /* Copy over the server random. */
    792   memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
    793 
    794   assert(s->session == NULL || s->session->session_id_length > 0);
    795   if (!s->s3->initial_handshake_complete && s->session != NULL &&
    796       CBS_mem_equal(&session_id, s->session->session_id,
    797                     s->session->session_id_length)) {
    798     if (s->sid_ctx_length != s->session->sid_ctx_length ||
    799         memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
    800       /* actually a client application bug */
    801       al = SSL_AD_ILLEGAL_PARAMETER;
    802       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    803                         SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
    804       goto f_err;
    805     }
    806     s->hit = 1;
    807   } else {
    808     /* The session wasn't resumed. Create a fresh SSL_SESSION to
    809      * fill out. */
    810     s->hit = 0;
    811     if (!ssl_get_new_session(s, 0)) {
    812       goto f_err;
    813     }
    814     /* Note: session_id could be empty. */
    815     s->session->session_id_length = CBS_len(&session_id);
    816     memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
    817   }
    818 
    819   c = SSL_get_cipher_by_value(cipher_suite);
    820   if (c == NULL) {
    821     /* unknown cipher */
    822     al = SSL_AD_ILLEGAL_PARAMETER;
    823     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    824                       SSL_R_UNKNOWN_CIPHER_RETURNED);
    825     goto f_err;
    826   }
    827   /* ct->mask_ssl was computed from client capabilities. Now
    828    * that the final version is known, compute a new mask_ssl. */
    829   if (!SSL_USE_TLS1_2_CIPHERS(s)) {
    830     mask_ssl = SSL_TLSV1_2;
    831   } else {
    832     mask_ssl = 0;
    833   }
    834   /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
    835    * the server selected it, it's an error. */
    836   if ((c->algorithm_ssl & mask_ssl) ||
    837       (c->algorithm_mkey & ct->mask_k) ||
    838       (c->algorithm_auth & ct->mask_a)) {
    839     al = SSL_AD_ILLEGAL_PARAMETER;
    840     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
    841     goto f_err;
    842   }
    843 
    844   sk = ssl_get_ciphers_by_id(s);
    845   if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
    846     /* we did not say we would use this cipher */
    847     al = SSL_AD_ILLEGAL_PARAMETER;
    848     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
    849     goto f_err;
    850   }
    851 
    852   if (s->hit) {
    853     if (s->session->cipher != c) {
    854       al = SSL_AD_ILLEGAL_PARAMETER;
    855       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    856                         SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
    857       goto f_err;
    858     }
    859     if (s->session->ssl_version != s->version) {
    860       al = SSL_AD_ILLEGAL_PARAMETER;
    861       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    862                         SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
    863       goto f_err;
    864     }
    865   }
    866   s->s3->tmp.new_cipher = c;
    867 
    868   /* If doing a full handshake with TLS 1.2, the server may request a client
    869    * certificate which requires hashing the handshake transcript under a
    870    * different hash. Otherwise, release the handshake buffer. */
    871   if ((!SSL_USE_SIGALGS(s) || s->hit) &&
    872       !ssl3_digest_cached_records(s, free_handshake_buffer)) {
    873     goto f_err;
    874   }
    875 
    876   /* Only the NULL compression algorithm is supported. */
    877   if (compression_method != 0) {
    878     al = SSL_AD_ILLEGAL_PARAMETER;
    879     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    880                       SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
    881     goto f_err;
    882   }
    883 
    884   /* TLS extensions */
    885   if (!ssl_parse_serverhello_tlsext(s, &server_hello)) {
    886     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_PARSE_TLSEXT);
    887     goto err;
    888   }
    889 
    890   /* There should be nothing left over in the record. */
    891   if (CBS_len(&server_hello) != 0) {
    892     /* wrong packet length */
    893     al = SSL_AD_DECODE_ERROR;
    894     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_BAD_PACKET_LENGTH);
    895     goto f_err;
    896   }
    897 
    898   if (s->hit &&
    899       s->s3->tmp.extended_master_secret != s->session->extended_master_secret) {
    900     al = SSL_AD_HANDSHAKE_FAILURE;
    901     if (s->session->extended_master_secret) {
    902       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    903                         SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
    904     } else {
    905       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello,
    906                         SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
    907     }
    908     goto f_err;
    909   }
    910 
    911   return 1;
    912 
    913 f_err:
    914   ssl3_send_alert(s, SSL3_AL_FATAL, al);
    915 err:
    916   return -1;
    917 }
    918 
    919 int ssl3_get_server_certificate(SSL *s) {
    920   int al, i, ok, ret = -1;
    921   unsigned long n;
    922   X509 *x = NULL;
    923   STACK_OF(X509) *sk = NULL;
    924   SESS_CERT *sc;
    925   EVP_PKEY *pkey = NULL;
    926   CBS cbs, certificate_list;
    927   const uint8_t *data;
    928 
    929   n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B,
    930                                  SSL3_MT_CERTIFICATE, (long)s->max_cert_list,
    931                                  ssl_hash_message, &ok);
    932 
    933   if (!ok) {
    934     return n;
    935   }
    936 
    937   CBS_init(&cbs, s->init_msg, n);
    938 
    939   sk = sk_X509_new_null();
    940   if (sk == NULL) {
    941     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
    942     goto err;
    943   }
    944 
    945   if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
    946       CBS_len(&cbs) != 0) {
    947     al = SSL_AD_DECODE_ERROR;
    948     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_LENGTH_MISMATCH);
    949     goto f_err;
    950   }
    951 
    952   while (CBS_len(&certificate_list) > 0) {
    953     CBS certificate;
    954     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
    955       al = SSL_AD_DECODE_ERROR;
    956       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
    957                         SSL_R_CERT_LENGTH_MISMATCH);
    958       goto f_err;
    959     }
    960     data = CBS_data(&certificate);
    961     x = d2i_X509(NULL, &data, CBS_len(&certificate));
    962     if (x == NULL) {
    963       al = SSL_AD_BAD_CERTIFICATE;
    964       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_ASN1_LIB);
    965       goto f_err;
    966     }
    967     if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
    968       al = SSL_AD_DECODE_ERROR;
    969       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
    970                         SSL_R_CERT_LENGTH_MISMATCH);
    971       goto f_err;
    972     }
    973     if (!sk_X509_push(sk, x)) {
    974       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
    975       goto err;
    976     }
    977     x = NULL;
    978   }
    979 
    980   i = ssl_verify_cert_chain(s, sk);
    981   if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
    982     al = ssl_verify_alarm_type(s->verify_result);
    983     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
    984                       SSL_R_CERTIFICATE_VERIFY_FAILED);
    985     goto f_err;
    986   }
    987   ERR_clear_error(); /* but we keep s->verify_result */
    988 
    989   sc = ssl_sess_cert_new();
    990   if (sc == NULL) {
    991     goto err;
    992   }
    993 
    994   ssl_sess_cert_free(s->session->sess_cert);
    995   s->session->sess_cert = sc;
    996 
    997   sc->cert_chain = sk;
    998   /* Inconsistency alert: cert_chain does include the peer's certificate, which
    999    * we don't include in s3_srvr.c */
   1000   x = sk_X509_value(sk, 0);
   1001   sk = NULL;
   1002   /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
   1003 
   1004   pkey = X509_get_pubkey(x);
   1005 
   1006   if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
   1007     x = NULL;
   1008     al = SSL3_AL_FATAL;
   1009     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
   1010                       SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
   1011     goto f_err;
   1012   }
   1013 
   1014   i = ssl_cert_type(pkey);
   1015   if (i < 0) {
   1016     x = NULL;
   1017     al = SSL3_AL_FATAL;
   1018     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
   1019                       SSL_R_UNKNOWN_CERTIFICATE_TYPE);
   1020     goto f_err;
   1021   }
   1022 
   1023   int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
   1024   if (exp_idx >= 0 && i != exp_idx) {
   1025     x = NULL;
   1026     al = SSL_AD_ILLEGAL_PARAMETER;
   1027     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate,
   1028                       SSL_R_WRONG_CERTIFICATE_TYPE);
   1029     goto f_err;
   1030   }
   1031   sc->peer_cert_type = i;
   1032   X509_free(sc->peer_pkeys[i].x509);
   1033   sc->peer_pkeys[i].x509 = X509_up_ref(x);
   1034   sc->peer_key = &(sc->peer_pkeys[i]);
   1035 
   1036   X509_free(s->session->peer);
   1037   s->session->peer = X509_up_ref(x);
   1038 
   1039   s->session->verify_result = s->verify_result;
   1040 
   1041   x = NULL;
   1042   ret = 1;
   1043 
   1044   if (0) {
   1045   f_err:
   1046     ssl3_send_alert(s, SSL3_AL_FATAL, al);
   1047   }
   1048 
   1049 err:
   1050   EVP_PKEY_free(pkey);
   1051   X509_free(x);
   1052   sk_X509_pop_free(sk, X509_free);
   1053   return ret;
   1054 }
   1055 
   1056 int ssl3_get_server_key_exchange(SSL *s) {
   1057   EVP_MD_CTX md_ctx;
   1058   int al, ok;
   1059   long n, alg_k, alg_a;
   1060   EVP_PKEY *pkey = NULL;
   1061   const EVP_MD *md = NULL;
   1062   RSA *rsa = NULL;
   1063   DH *dh = NULL;
   1064   EC_KEY *ecdh = NULL;
   1065   BN_CTX *bn_ctx = NULL;
   1066   EC_POINT *srvr_ecpoint = NULL;
   1067   CBS server_key_exchange, server_key_exchange_orig, parameter;
   1068 
   1069   /* use same message size as in ssl3_get_certificate_request() as
   1070    * ServerKeyExchange message may be skipped */
   1071   n = s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
   1072                                  SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list,
   1073                                  ssl_hash_message, &ok);
   1074   if (!ok) {
   1075     return n;
   1076   }
   1077 
   1078   if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
   1079     if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher)) {
   1080       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1081                         SSL_R_UNEXPECTED_MESSAGE);
   1082       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1083       return -1;
   1084     }
   1085 
   1086     /* In plain PSK ciphersuite, ServerKeyExchange can be
   1087        omitted if no identity hint is sent. Set session->sess_cert anyway to
   1088        avoid problems later.*/
   1089     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
   1090       /* PSK ciphersuites that also send a Certificate would have already
   1091        * initialized |sess_cert|. */
   1092       if (s->session->sess_cert == NULL) {
   1093         s->session->sess_cert = ssl_sess_cert_new();
   1094         if (s->session->sess_cert == NULL) {
   1095           return -1;
   1096         }
   1097       }
   1098 
   1099       /* TODO(davidben): This should be reset in one place with the rest of the
   1100        * handshake state. */
   1101       OPENSSL_free(s->s3->tmp.peer_psk_identity_hint);
   1102       s->s3->tmp.peer_psk_identity_hint = NULL;
   1103     }
   1104     s->s3->tmp.reuse_message = 1;
   1105     return 1;
   1106   }
   1107 
   1108   /* Retain a copy of the original CBS to compute the signature over. */
   1109   CBS_init(&server_key_exchange, s->init_msg, n);
   1110   server_key_exchange_orig = server_key_exchange;
   1111 
   1112   if (s->session->sess_cert != NULL) {
   1113     DH_free(s->session->sess_cert->peer_dh_tmp);
   1114     s->session->sess_cert->peer_dh_tmp = NULL;
   1115     EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
   1116     s->session->sess_cert->peer_ecdh_tmp = NULL;
   1117   } else {
   1118     s->session->sess_cert = ssl_sess_cert_new();
   1119     if (s->session->sess_cert == NULL) {
   1120       return -1;
   1121     }
   1122   }
   1123 
   1124   alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
   1125   alg_a = s->s3->tmp.new_cipher->algorithm_auth;
   1126   EVP_MD_CTX_init(&md_ctx);
   1127 
   1128   if (alg_a & SSL_aPSK) {
   1129     CBS psk_identity_hint;
   1130 
   1131     /* Each of the PSK key exchanges begins with a psk_identity_hint. */
   1132     if (!CBS_get_u16_length_prefixed(&server_key_exchange,
   1133                                      &psk_identity_hint)) {
   1134       al = SSL_AD_DECODE_ERROR;
   1135       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1136       goto f_err;
   1137     }
   1138 
   1139     /* Store PSK identity hint for later use, hint is used in
   1140      * ssl3_send_client_key_exchange.  Assume that the maximum length of a PSK
   1141      * identity hint can be as long as the maximum length of a PSK identity.
   1142      * Also do not allow NULL characters; identities are saved as C strings.
   1143      *
   1144      * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
   1145      * a specific identity. */
   1146     if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
   1147         CBS_contains_zero_byte(&psk_identity_hint)) {
   1148       al = SSL_AD_HANDSHAKE_FAILURE;
   1149       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1150                         SSL_R_DATA_LENGTH_TOO_LONG);
   1151       goto f_err;
   1152     }
   1153 
   1154     /* Save the identity hint as a C string. */
   1155     if (!CBS_strdup(&psk_identity_hint, &s->s3->tmp.peer_psk_identity_hint)) {
   1156       al = SSL_AD_INTERNAL_ERROR;
   1157       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1158                         ERR_R_MALLOC_FAILURE);
   1159       goto f_err;
   1160     }
   1161   }
   1162 
   1163   if (alg_k & SSL_kDHE) {
   1164     CBS dh_p, dh_g, dh_Ys;
   1165 
   1166     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
   1167         CBS_len(&dh_p) == 0 ||
   1168         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
   1169         CBS_len(&dh_g) == 0 ||
   1170         !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
   1171         CBS_len(&dh_Ys) == 0) {
   1172       al = SSL_AD_DECODE_ERROR;
   1173       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1174       goto f_err;
   1175     }
   1176 
   1177     dh = DH_new();
   1178     if (dh == NULL) {
   1179       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_DH_LIB);
   1180       goto err;
   1181     }
   1182 
   1183     if ((dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)) == NULL ||
   1184         (dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)) == NULL ||
   1185         (dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)) ==
   1186             NULL) {
   1187       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1188       goto err;
   1189     }
   1190 
   1191     if (DH_num_bits(dh) < 1024) {
   1192       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1193                         SSL_R_BAD_DH_P_LENGTH);
   1194       goto err;
   1195     }
   1196 
   1197     if (alg_a & SSL_aRSA) {
   1198       pkey = X509_get_pubkey(
   1199           s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1200     }
   1201     /* else anonymous DH, so no certificate or pkey. */
   1202 
   1203     s->session->sess_cert->peer_dh_tmp = dh;
   1204     dh = NULL;
   1205   } else if (alg_k & SSL_kECDHE) {
   1206     uint16_t curve_id;
   1207     int curve_nid = 0;
   1208     const EC_GROUP *group;
   1209     CBS point;
   1210 
   1211     /* Extract elliptic curve parameters and the server's ephemeral ECDH public
   1212      * key.  Check curve is one of our preferences, if not server has sent an
   1213      * invalid curve. */
   1214     if (!tls1_check_curve(s, &server_key_exchange, &curve_id)) {
   1215       al = SSL_AD_DECODE_ERROR;
   1216       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_WRONG_CURVE);
   1217       goto f_err;
   1218     }
   1219 
   1220     curve_nid = tls1_ec_curve_id2nid(curve_id);
   1221     if (curve_nid == 0) {
   1222       al = SSL_AD_INTERNAL_ERROR;
   1223       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1224                         SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
   1225       goto f_err;
   1226     }
   1227 
   1228     ecdh = EC_KEY_new_by_curve_name(curve_nid);
   1229     if (ecdh == NULL) {
   1230       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1231                         ERR_R_EC_LIB);
   1232       goto err;
   1233     }
   1234 
   1235     group = EC_KEY_get0_group(ecdh);
   1236 
   1237     /* Next, get the encoded ECPoint */
   1238     if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
   1239       al = SSL_AD_DECODE_ERROR;
   1240       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1241       goto f_err;
   1242     }
   1243 
   1244     if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
   1245         ((bn_ctx = BN_CTX_new()) == NULL)) {
   1246       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1247                         ERR_R_MALLOC_FAILURE);
   1248       goto err;
   1249     }
   1250 
   1251     if (!EC_POINT_oct2point(group, srvr_ecpoint, CBS_data(&point),
   1252                             CBS_len(&point), bn_ctx)) {
   1253       al = SSL_AD_DECODE_ERROR;
   1254       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_ECPOINT);
   1255       goto f_err;
   1256     }
   1257 
   1258     /* The ECC/TLS specification does not mention the use of DSA to sign
   1259      * ECParameters in the server key exchange message. We do support RSA and
   1260      * ECDSA. */
   1261     if (alg_a & SSL_aRSA) {
   1262       pkey = X509_get_pubkey(
   1263           s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1264     } else if (alg_a & SSL_aECDSA) {
   1265       pkey =
   1266           X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
   1267     }
   1268     /* else anonymous ECDH, so no certificate or pkey. */
   1269     EC_KEY_set_public_key(ecdh, srvr_ecpoint);
   1270     s->session->sess_cert->peer_ecdh_tmp = ecdh;
   1271     ecdh = NULL;
   1272     BN_CTX_free(bn_ctx);
   1273     bn_ctx = NULL;
   1274     EC_POINT_free(srvr_ecpoint);
   1275     srvr_ecpoint = NULL;
   1276   } else if (!(alg_k & SSL_kPSK)) {
   1277     al = SSL_AD_UNEXPECTED_MESSAGE;
   1278     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1279                       SSL_R_UNEXPECTED_MESSAGE);
   1280     goto f_err;
   1281   }
   1282 
   1283   /* At this point, |server_key_exchange| contains the signature, if any, while
   1284    * |server_key_exchange_orig| contains the entire message. From that, derive
   1285    * a CBS containing just the parameter. */
   1286   CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
   1287            CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
   1288 
   1289   /* if it was signed, check the signature */
   1290   if (pkey != NULL) {
   1291     CBS signature;
   1292 
   1293     if (SSL_USE_SIGALGS(s)) {
   1294       if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey)) {
   1295         goto f_err;
   1296       }
   1297     } else if (pkey->type == EVP_PKEY_RSA) {
   1298       md = EVP_md5_sha1();
   1299     } else {
   1300       md = EVP_sha1();
   1301     }
   1302 
   1303     /* The last field in |server_key_exchange| is the signature. */
   1304     if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
   1305         CBS_len(&server_key_exchange) != 0) {
   1306       al = SSL_AD_DECODE_ERROR;
   1307       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1308       goto f_err;
   1309     }
   1310 
   1311     if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
   1312         !EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
   1313                                 SSL3_RANDOM_SIZE) ||
   1314         !EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
   1315                                 SSL3_RANDOM_SIZE) ||
   1316         !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
   1317                                 CBS_len(&parameter)) ||
   1318         !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
   1319                                CBS_len(&signature))) {
   1320       /* bad signature */
   1321       al = SSL_AD_DECRYPT_ERROR;
   1322       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
   1323       goto f_err;
   1324     }
   1325   } else {
   1326     if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
   1327       /* Might be wrong key type, check it */
   1328       if (ssl3_check_cert_and_algorithm(s)) {
   1329         /* Otherwise this shouldn't happen */
   1330         OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1331                           ERR_R_INTERNAL_ERROR);
   1332       }
   1333       goto err;
   1334     }
   1335     /* still data left over */
   1336     if (CBS_len(&server_key_exchange) > 0) {
   1337       al = SSL_AD_DECODE_ERROR;
   1338       OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange,
   1339                         SSL_R_EXTRA_DATA_IN_MESSAGE);
   1340       goto f_err;
   1341     }
   1342   }
   1343   EVP_PKEY_free(pkey);
   1344   EVP_MD_CTX_cleanup(&md_ctx);
   1345   return 1;
   1346 
   1347 f_err:
   1348   ssl3_send_alert(s, SSL3_AL_FATAL, al);
   1349 err:
   1350   EVP_PKEY_free(pkey);
   1351   RSA_free(rsa);
   1352   DH_free(dh);
   1353   BN_CTX_free(bn_ctx);
   1354   EC_POINT_free(srvr_ecpoint);
   1355   EC_KEY_free(ecdh);
   1356   EVP_MD_CTX_cleanup(&md_ctx);
   1357   return -1;
   1358 }
   1359 
   1360 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
   1361   return X509_NAME_cmp(*a, *b);
   1362 }
   1363 
   1364 int ssl3_get_certificate_request(SSL *s) {
   1365   int ok, ret = 0;
   1366   unsigned long n;
   1367   X509_NAME *xn = NULL;
   1368   STACK_OF(X509_NAME) *ca_sk = NULL;
   1369   CBS cbs;
   1370   CBS certificate_types;
   1371   CBS certificate_authorities;
   1372   const uint8_t *data;
   1373 
   1374   n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
   1375                                  SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list,
   1376                                  ssl_hash_message, &ok);
   1377 
   1378   if (!ok) {
   1379     return n;
   1380   }
   1381 
   1382   s->s3->tmp.cert_req = 0;
   1383 
   1384   if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
   1385     s->s3->tmp.reuse_message = 1;
   1386     /* If we get here we don't need any cached handshake records as we wont be
   1387      * doing client auth. */
   1388     if (s->s3->handshake_buffer &&
   1389         !ssl3_digest_cached_records(s, free_handshake_buffer)) {
   1390       goto err;
   1391     }
   1392     return 1;
   1393   }
   1394 
   1395   if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
   1396     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1397     OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request,
   1398                       SSL_R_WRONG_MESSAGE_TYPE);
   1399     goto err;
   1400   }
   1401 
   1402   CBS_init(&cbs, s->init_msg, n);
   1403 
   1404   ca_sk = sk_X509_NAME_new(ca_dn_cmp);
   1405   if (ca_sk == NULL) {
   1406     OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
   1407     goto err;
   1408   }
   1409 
   1410   /* get the certificate types */
   1411   if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
   1412     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1413     OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
   1414     goto err;
   1415   }
   1416 
   1417   if (!CBS_stow(&certificate_types, &s->s3->tmp.certificate_types,
   1418                 &s->s3->tmp.num_certificate_types)) {
   1419     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1420     goto err;
   1421   }
   1422 
   1423   if (SSL_USE_SIGALGS(s)) {
   1424     CBS supported_signature_algorithms;
   1425     if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms)) {
   1426       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1427       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
   1428       goto err;
   1429     }
   1430 
   1431     if (!tls1_process_sigalgs(s, &supported_signature_algorithms)) {
   1432       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1433       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request,
   1434                         SSL_R_SIGNATURE_ALGORITHMS_ERROR);
   1435       goto err;
   1436     }
   1437   }
   1438 
   1439   /* get the CA RDNs */
   1440   if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
   1441     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1442     OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_LENGTH_MISMATCH);
   1443     goto err;
   1444   }
   1445 
   1446   while (CBS_len(&certificate_authorities) > 0) {
   1447     CBS distinguished_name;
   1448     if (!CBS_get_u16_length_prefixed(&certificate_authorities,
   1449                                      &distinguished_name)) {
   1450       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1451       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request,
   1452                         SSL_R_CA_DN_TOO_LONG);
   1453       goto err;
   1454     }
   1455 
   1456     data = CBS_data(&distinguished_name);
   1457 
   1458     xn = d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name));
   1459     if (xn == NULL) {
   1460       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1461       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_ASN1_LIB);
   1462       goto err;
   1463     }
   1464 
   1465     if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name))) {
   1466       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1467       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_INTERNAL_ERROR);
   1468       goto err;
   1469     }
   1470 
   1471     if (CBS_len(&distinguished_name) != 0) {
   1472       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1473       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request,
   1474                         SSL_R_CA_DN_LENGTH_MISMATCH);
   1475       goto err;
   1476     }
   1477 
   1478     if (!sk_X509_NAME_push(ca_sk, xn)) {
   1479       OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request,
   1480                         ERR_R_MALLOC_FAILURE);
   1481       goto err;
   1482     }
   1483   }
   1484 
   1485   /* we should setup a certificate to return.... */
   1486   s->s3->tmp.cert_req = 1;
   1487   sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
   1488   s->s3->tmp.ca_names = ca_sk;
   1489   ca_sk = NULL;
   1490 
   1491   ret = 1;
   1492 
   1493 err:
   1494   sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
   1495   return ret;
   1496 }
   1497 
   1498 int ssl3_get_new_session_ticket(SSL *s) {
   1499   int ok, al;
   1500   long n;
   1501   CBS new_session_ticket, ticket;
   1502 
   1503   n = s->method->ssl_get_message(
   1504       s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B,
   1505       SSL3_MT_NEWSESSION_TICKET, 16384, ssl_hash_message, &ok);
   1506 
   1507   if (!ok) {
   1508     return n;
   1509   }
   1510 
   1511   CBS_init(&new_session_ticket, s->init_msg, n);
   1512 
   1513   if (!CBS_get_u32(&new_session_ticket,
   1514                    &s->session->tlsext_tick_lifetime_hint) ||
   1515       !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
   1516       CBS_len(&new_session_ticket) != 0) {
   1517     al = SSL_AD_DECODE_ERROR;
   1518     OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, SSL_R_DECODE_ERROR);
   1519     goto f_err;
   1520   }
   1521 
   1522   if (!CBS_stow(&ticket, &s->session->tlsext_tick,
   1523                 &s->session->tlsext_ticklen)) {
   1524     OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, ERR_R_MALLOC_FAILURE);
   1525     goto err;
   1526   }
   1527 
   1528   /* Generate a session ID for this session based on the session ticket. We use
   1529    * the session ID mechanism for detecting ticket resumption. This also fits in
   1530    * with assumptions elsewhere in OpenSSL.*/
   1531   if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), s->session->session_id,
   1532                   &s->session->session_id_length, EVP_sha256(), NULL)) {
   1533     goto err;
   1534   }
   1535 
   1536   return 1;
   1537 
   1538 f_err:
   1539   ssl3_send_alert(s, SSL3_AL_FATAL, al);
   1540 err:
   1541   return -1;
   1542 }
   1543 
   1544 int ssl3_get_cert_status(SSL *s) {
   1545   int ok, al;
   1546   long n;
   1547   CBS certificate_status, ocsp_response;
   1548   uint8_t status_type;
   1549 
   1550   n = s->method->ssl_get_message(
   1551       s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B,
   1552       -1, 16384, ssl_hash_message, &ok);
   1553 
   1554   if (!ok) {
   1555     return n;
   1556   }
   1557 
   1558   if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
   1559     /* A server may send status_request in ServerHello and then change
   1560      * its mind about sending CertificateStatus. */
   1561     s->s3->tmp.reuse_message = 1;
   1562     return 1;
   1563   }
   1564 
   1565   CBS_init(&certificate_status, s->init_msg, n);
   1566   if (!CBS_get_u8(&certificate_status, &status_type) ||
   1567       status_type != TLSEXT_STATUSTYPE_ocsp ||
   1568       !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
   1569       CBS_len(&ocsp_response) == 0 ||
   1570       CBS_len(&certificate_status) != 0) {
   1571     al = SSL_AD_DECODE_ERROR;
   1572     OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, SSL_R_DECODE_ERROR);
   1573     goto f_err;
   1574   }
   1575 
   1576   if (!CBS_stow(&ocsp_response, &s->session->ocsp_response,
   1577                 &s->session->ocsp_response_length)) {
   1578     al = SSL_AD_INTERNAL_ERROR;
   1579     OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, ERR_R_MALLOC_FAILURE);
   1580     goto f_err;
   1581   }
   1582   return 1;
   1583 
   1584 f_err:
   1585   ssl3_send_alert(s, SSL3_AL_FATAL, al);
   1586   return -1;
   1587 }
   1588 
   1589 int ssl3_get_server_done(SSL *s) {
   1590   int ok;
   1591   long n;
   1592 
   1593   n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
   1594                                  SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
   1595                                  30, /* should be very small, like 0 :-) */
   1596                                  ssl_hash_message, &ok);
   1597 
   1598   if (!ok) {
   1599     return n;
   1600   }
   1601 
   1602   if (n > 0) {
   1603     /* should contain no data */
   1604     ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1605     OPENSSL_PUT_ERROR(SSL, ssl3_get_server_done, SSL_R_LENGTH_MISMATCH);
   1606     return -1;
   1607   }
   1608 
   1609   return 1;
   1610 }
   1611 
   1612 
   1613 int ssl3_send_client_key_exchange(SSL *s) {
   1614   uint8_t *p;
   1615   int n = 0;
   1616   uint32_t alg_k;
   1617   uint32_t alg_a;
   1618   uint8_t *q;
   1619   EVP_PKEY *pkey = NULL;
   1620   EC_KEY *clnt_ecdh = NULL;
   1621   const EC_POINT *srvr_ecpoint = NULL;
   1622   EVP_PKEY *srvr_pub_pkey = NULL;
   1623   uint8_t *encodedPoint = NULL;
   1624   int encoded_pt_len = 0;
   1625   BN_CTX *bn_ctx = NULL;
   1626   unsigned int psk_len = 0;
   1627   uint8_t psk[PSK_MAX_PSK_LEN];
   1628   uint8_t *pms = NULL;
   1629   size_t pms_len = 0;
   1630 
   1631   if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
   1632     p = ssl_handshake_start(s);
   1633 
   1634     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
   1635     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
   1636 
   1637     /* If using a PSK key exchange, prepare the pre-shared key. */
   1638     if (alg_a & SSL_aPSK) {
   1639       char identity[PSK_MAX_IDENTITY_LEN + 1];
   1640       size_t identity_len;
   1641 
   1642       if (s->psk_client_callback == NULL) {
   1643         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1644                           SSL_R_PSK_NO_CLIENT_CB);
   1645         goto err;
   1646       }
   1647 
   1648       memset(identity, 0, sizeof(identity));
   1649       psk_len =
   1650           s->psk_client_callback(s, s->s3->tmp.peer_psk_identity_hint, identity,
   1651                                  sizeof(identity), psk, sizeof(psk));
   1652       if (psk_len > PSK_MAX_PSK_LEN) {
   1653         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1654                           ERR_R_INTERNAL_ERROR);
   1655         goto err;
   1656       } else if (psk_len == 0) {
   1657         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1658                           SSL_R_PSK_IDENTITY_NOT_FOUND);
   1659         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1660         goto err;
   1661       }
   1662 
   1663       identity_len = OPENSSL_strnlen(identity, sizeof(identity));
   1664       if (identity_len > PSK_MAX_IDENTITY_LEN) {
   1665         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1666                           ERR_R_INTERNAL_ERROR);
   1667         goto err;
   1668       }
   1669 
   1670       OPENSSL_free(s->session->psk_identity);
   1671       s->session->psk_identity = BUF_strdup(identity);
   1672       if (s->session->psk_identity == NULL) {
   1673         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1674                           ERR_R_MALLOC_FAILURE);
   1675         goto err;
   1676       }
   1677 
   1678       /* Write out psk_identity. */
   1679       s2n(identity_len, p);
   1680       memcpy(p, identity, identity_len);
   1681       p += identity_len;
   1682       n = 2 + identity_len;
   1683     }
   1684 
   1685     /* Depending on the key exchange method, compute |pms| and |pms_len|. */
   1686     if (alg_k & SSL_kRSA) {
   1687       RSA *rsa;
   1688       size_t enc_pms_len;
   1689 
   1690       pms_len = SSL_MAX_MASTER_KEY_LENGTH;
   1691       pms = OPENSSL_malloc(pms_len);
   1692       if (pms == NULL) {
   1693         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1694                           ERR_R_MALLOC_FAILURE);
   1695         goto err;
   1696       }
   1697 
   1698       if (s->session->sess_cert == NULL) {
   1699         /* We should always have a server certificate with SSL_kRSA. */
   1700         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1701                           ERR_R_INTERNAL_ERROR);
   1702         goto err;
   1703       }
   1704 
   1705       pkey = X509_get_pubkey(
   1706           s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1707       if (pkey == NULL ||
   1708           pkey->type != EVP_PKEY_RSA ||
   1709           pkey->pkey.rsa == NULL) {
   1710         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1711                           ERR_R_INTERNAL_ERROR);
   1712         EVP_PKEY_free(pkey);
   1713         goto err;
   1714       }
   1715 
   1716       rsa = pkey->pkey.rsa;
   1717       EVP_PKEY_free(pkey);
   1718 
   1719       pms[0] = s->client_version >> 8;
   1720       pms[1] = s->client_version & 0xff;
   1721       if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
   1722         goto err;
   1723       }
   1724 
   1725       s->session->master_key_length = SSL_MAX_MASTER_KEY_LENGTH;
   1726 
   1727       q = p;
   1728       /* In TLS and beyond, reserve space for the length prefix. */
   1729       if (s->version > SSL3_VERSION) {
   1730         p += 2;
   1731         n += 2;
   1732       }
   1733       if (!RSA_encrypt(rsa, &enc_pms_len, p, RSA_size(rsa), pms, pms_len,
   1734                        RSA_PKCS1_PADDING)) {
   1735         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1736                           SSL_R_BAD_RSA_ENCRYPT);
   1737         goto err;
   1738       }
   1739       n += enc_pms_len;
   1740 
   1741       /* Log the premaster secret, if logging is enabled. */
   1742       if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx, p, enc_pms_len, pms,
   1743                                                pms_len)) {
   1744         goto err;
   1745       }
   1746 
   1747       /* Fill in the length prefix. */
   1748       if (s->version > SSL3_VERSION) {
   1749         s2n(enc_pms_len, q);
   1750       }
   1751     } else if (alg_k & SSL_kDHE) {
   1752       DH *dh_srvr, *dh_clnt;
   1753       SESS_CERT *scert = s->session->sess_cert;
   1754       int dh_len;
   1755       size_t pub_len;
   1756 
   1757       if (scert == NULL) {
   1758         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1759         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1760                           SSL_R_UNEXPECTED_MESSAGE);
   1761         goto err;
   1762       }
   1763 
   1764       if (scert->peer_dh_tmp == NULL) {
   1765         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1766                           ERR_R_INTERNAL_ERROR);
   1767         goto err;
   1768       }
   1769       dh_srvr = scert->peer_dh_tmp;
   1770 
   1771       /* generate a new random key */
   1772       dh_clnt = DHparams_dup(dh_srvr);
   1773       if (dh_clnt == NULL) {
   1774         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   1775         goto err;
   1776       }
   1777       if (!DH_generate_key(dh_clnt)) {
   1778         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   1779         DH_free(dh_clnt);
   1780         goto err;
   1781       }
   1782 
   1783       pms_len = DH_size(dh_clnt);
   1784       pms = OPENSSL_malloc(pms_len);
   1785       if (pms == NULL) {
   1786         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1787                           ERR_R_MALLOC_FAILURE);
   1788         DH_free(dh_clnt);
   1789         goto err;
   1790       }
   1791 
   1792       dh_len = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
   1793       if (dh_len <= 0) {
   1794         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   1795         DH_free(dh_clnt);
   1796         goto err;
   1797       }
   1798       pms_len = dh_len;
   1799 
   1800       /* send off the data */
   1801       pub_len = BN_num_bytes(dh_clnt->pub_key);
   1802       s2n(pub_len, p);
   1803       BN_bn2bin(dh_clnt->pub_key, p);
   1804       n += 2 + pub_len;
   1805 
   1806       DH_free(dh_clnt);
   1807     } else if (alg_k & SSL_kECDHE) {
   1808       const EC_GROUP *srvr_group = NULL;
   1809       EC_KEY *tkey;
   1810       int field_size = 0, ecdh_len;
   1811 
   1812       if (s->session->sess_cert == NULL) {
   1813         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1814         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1815                           SSL_R_UNEXPECTED_MESSAGE);
   1816         goto err;
   1817       }
   1818 
   1819       if (s->session->sess_cert->peer_ecdh_tmp == NULL) {
   1820         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1821                           ERR_R_INTERNAL_ERROR);
   1822         goto err;
   1823       }
   1824 
   1825       tkey = s->session->sess_cert->peer_ecdh_tmp;
   1826 
   1827       srvr_group = EC_KEY_get0_group(tkey);
   1828       srvr_ecpoint = EC_KEY_get0_public_key(tkey);
   1829       if (srvr_group == NULL || srvr_ecpoint == NULL) {
   1830         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1831                           ERR_R_INTERNAL_ERROR);
   1832         goto err;
   1833       }
   1834 
   1835       clnt_ecdh = EC_KEY_new();
   1836       if (clnt_ecdh == NULL) {
   1837         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1838                           ERR_R_MALLOC_FAILURE);
   1839         goto err;
   1840       }
   1841 
   1842       if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
   1843         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_EC_LIB);
   1844         goto err;
   1845       }
   1846 
   1847       /* Generate a new ECDH key pair */
   1848       if (!EC_KEY_generate_key(clnt_ecdh)) {
   1849         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   1850         goto err;
   1851       }
   1852 
   1853       field_size = EC_GROUP_get_degree(srvr_group);
   1854       if (field_size <= 0) {
   1855         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   1856         goto err;
   1857       }
   1858 
   1859       pms_len = (field_size + 7) / 8;
   1860       pms = OPENSSL_malloc(pms_len);
   1861       if (pms == NULL) {
   1862         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1863                           ERR_R_MALLOC_FAILURE);
   1864         goto err;
   1865       }
   1866 
   1867       ecdh_len = ECDH_compute_key(pms, pms_len, srvr_ecpoint, clnt_ecdh, NULL);
   1868       if (ecdh_len <= 0) {
   1869         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   1870         goto err;
   1871       }
   1872       pms_len = ecdh_len;
   1873 
   1874       /* First check the size of encoding and allocate memory accordingly. */
   1875       encoded_pt_len =
   1876           EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
   1877                              POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
   1878 
   1879       encodedPoint =
   1880           (uint8_t *)OPENSSL_malloc(encoded_pt_len * sizeof(uint8_t));
   1881       bn_ctx = BN_CTX_new();
   1882       if (encodedPoint == NULL || bn_ctx == NULL) {
   1883         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1884                           ERR_R_MALLOC_FAILURE);
   1885         goto err;
   1886       }
   1887 
   1888       /* Encode the public key */
   1889       encoded_pt_len = EC_POINT_point2oct(
   1890           srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
   1891           POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx);
   1892 
   1893       *p = encoded_pt_len; /* length of encoded point */
   1894       /* Encoded point will be copied here */
   1895       p += 1;
   1896       n += 1;
   1897       /* copy the point */
   1898       memcpy(p, encodedPoint, encoded_pt_len);
   1899       /* increment n to account for length field */
   1900       n += encoded_pt_len;
   1901 
   1902       /* Free allocated memory */
   1903       BN_CTX_free(bn_ctx);
   1904       bn_ctx = NULL;
   1905       OPENSSL_free(encodedPoint);
   1906       encodedPoint = NULL;
   1907       EC_KEY_free(clnt_ecdh);
   1908       clnt_ecdh = NULL;
   1909       EVP_PKEY_free(srvr_pub_pkey);
   1910       srvr_pub_pkey = NULL;
   1911     } else if (alg_k & SSL_kPSK) {
   1912       /* For plain PSK, other_secret is a block of 0s with the same length as
   1913        * the pre-shared key. */
   1914       pms_len = psk_len;
   1915       pms = OPENSSL_malloc(pms_len);
   1916       if (pms == NULL) {
   1917         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1918                           ERR_R_MALLOC_FAILURE);
   1919         goto err;
   1920       }
   1921       memset(pms, 0, pms_len);
   1922     } else {
   1923       ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1924       OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1925                         ERR_R_INTERNAL_ERROR);
   1926       goto err;
   1927     }
   1928 
   1929     /* For a PSK cipher suite, other_secret is combined with the pre-shared
   1930      * key. */
   1931     if (alg_a & SSL_aPSK) {
   1932       CBB cbb, child;
   1933       uint8_t *new_pms;
   1934       size_t new_pms_len;
   1935 
   1936       if (!CBB_init(&cbb, 2 + psk_len + 2 + pms_len)) {
   1937         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1938                           ERR_R_MALLOC_FAILURE);
   1939         goto err;
   1940       }
   1941       if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
   1942           !CBB_add_bytes(&child, pms, pms_len) ||
   1943           !CBB_add_u16_length_prefixed(&cbb, &child) ||
   1944           !CBB_add_bytes(&child, psk, psk_len) ||
   1945           !CBB_finish(&cbb, &new_pms, &new_pms_len)) {
   1946         CBB_cleanup(&cbb);
   1947         OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange,
   1948                           ERR_R_INTERNAL_ERROR);
   1949         goto err;
   1950       }
   1951       OPENSSL_cleanse(pms, pms_len);
   1952       OPENSSL_free(pms);
   1953       pms = new_pms;
   1954       pms_len = new_pms_len;
   1955     }
   1956 
   1957     /* The message must be added to the finished hash before calculating the
   1958      * master secret. */
   1959     if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
   1960       goto err;
   1961     }
   1962     s->state = SSL3_ST_CW_KEY_EXCH_B;
   1963 
   1964     s->session->master_key_length = s->enc_method->generate_master_secret(
   1965         s, s->session->master_key, pms, pms_len);
   1966     if (s->session->master_key_length == 0) {
   1967       goto err;
   1968     }
   1969     s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
   1970     OPENSSL_cleanse(pms, pms_len);
   1971     OPENSSL_free(pms);
   1972   }
   1973 
   1974   /* SSL3_ST_CW_KEY_EXCH_B */
   1975   return s->method->do_write(s);
   1976 
   1977 err:
   1978   BN_CTX_free(bn_ctx);
   1979   OPENSSL_free(encodedPoint);
   1980   EC_KEY_free(clnt_ecdh);
   1981   EVP_PKEY_free(srvr_pub_pkey);
   1982   if (pms) {
   1983     OPENSSL_cleanse(pms, pms_len);
   1984     OPENSSL_free(pms);
   1985   }
   1986   return -1;
   1987 }
   1988 
   1989 int ssl3_send_cert_verify(SSL *s) {
   1990   uint8_t *buf, *p;
   1991   const EVP_MD *md = NULL;
   1992   uint8_t digest[EVP_MAX_MD_SIZE];
   1993   size_t digest_length;
   1994   EVP_PKEY *pkey;
   1995   EVP_PKEY_CTX *pctx = NULL;
   1996   size_t signature_length = 0;
   1997   unsigned long n = 0;
   1998 
   1999   buf = (uint8_t *)s->init_buf->data;
   2000 
   2001   if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
   2002     p = ssl_handshake_start(s);
   2003     pkey = s->cert->key->privatekey;
   2004 
   2005     /* Write out the digest type if needbe. */
   2006     if (SSL_USE_SIGALGS(s)) {
   2007       md = tls1_choose_signing_digest(s, pkey);
   2008       if (!tls12_get_sigandhash(p, pkey, md)) {
   2009         OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_INTERNAL_ERROR);
   2010         goto err;
   2011       }
   2012       p += 2;
   2013       n += 2;
   2014     }
   2015 
   2016     /* Compute the digest. */
   2017     if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey)) {
   2018       goto err;
   2019     }
   2020 
   2021     /* The handshake buffer is no longer necessary. */
   2022     if (s->s3->handshake_buffer &&
   2023         !ssl3_digest_cached_records(s, free_handshake_buffer)) {
   2024       goto err;
   2025     }
   2026 
   2027     /* Sign the digest. */
   2028     pctx = EVP_PKEY_CTX_new(pkey, NULL);
   2029     if (pctx == NULL) {
   2030       goto err;
   2031     }
   2032 
   2033     /* Initialize the EVP_PKEY_CTX and determine the size of the signature. */
   2034     if (!EVP_PKEY_sign_init(pctx) || !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
   2035         !EVP_PKEY_sign(pctx, NULL, &signature_length, digest, digest_length)) {
   2036       OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
   2037       goto err;
   2038     }
   2039 
   2040     if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH) {
   2041       OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, SSL_R_DATA_LENGTH_TOO_LONG);
   2042       goto err;
   2043     }
   2044 
   2045     if (!EVP_PKEY_sign(pctx, &p[2], &signature_length, digest, digest_length)) {
   2046       OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
   2047       goto err;
   2048     }
   2049 
   2050     s2n(signature_length, p);
   2051     n += signature_length + 2;
   2052 
   2053     if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
   2054       goto err;
   2055     }
   2056     s->state = SSL3_ST_CW_CERT_VRFY_B;
   2057   }
   2058 
   2059   EVP_PKEY_CTX_free(pctx);
   2060   return ssl_do_write(s);
   2061 
   2062 err:
   2063   EVP_PKEY_CTX_free(pctx);
   2064   return -1;
   2065 }
   2066 
   2067 /* ssl3_has_client_certificate returns true if a client certificate is
   2068  * configured. */
   2069 static int ssl3_has_client_certificate(SSL *s) {
   2070   return s->cert && s->cert->key->x509 && s->cert->key->privatekey;
   2071 }
   2072 
   2073 int ssl3_send_client_certificate(SSL *s) {
   2074   X509 *x509 = NULL;
   2075   EVP_PKEY *pkey = NULL;
   2076   int i;
   2077 
   2078   if (s->state == SSL3_ST_CW_CERT_A) {
   2079     /* Let cert callback update client certificates if required */
   2080     if (s->cert->cert_cb) {
   2081       i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
   2082       if (i < 0) {
   2083         s->rwstate = SSL_X509_LOOKUP;
   2084         return -1;
   2085       }
   2086       if (i == 0) {
   2087         ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   2088         return 0;
   2089       }
   2090       s->rwstate = SSL_NOTHING;
   2091     }
   2092 
   2093     if (ssl3_has_client_certificate(s)) {
   2094       s->state = SSL3_ST_CW_CERT_C;
   2095     } else {
   2096       s->state = SSL3_ST_CW_CERT_B;
   2097     }
   2098   }
   2099 
   2100   /* We need to get a client cert */
   2101   if (s->state == SSL3_ST_CW_CERT_B) {
   2102     /* If we get an error, we need to:
   2103      *   ssl->rwstate=SSL_X509_LOOKUP; return(-1);
   2104      * We then get retried later */
   2105     i = ssl_do_client_cert_cb(s, &x509, &pkey);
   2106     if (i < 0) {
   2107       s->rwstate = SSL_X509_LOOKUP;
   2108       return -1;
   2109     }
   2110     s->rwstate = SSL_NOTHING;
   2111     if (i == 1 && pkey != NULL && x509 != NULL) {
   2112       s->state = SSL3_ST_CW_CERT_B;
   2113       if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey)) {
   2114         i = 0;
   2115       }
   2116     } else if (i == 1) {
   2117       i = 0;
   2118       OPENSSL_PUT_ERROR(SSL, ssl3_send_client_certificate,
   2119                         SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
   2120     }
   2121 
   2122     X509_free(x509);
   2123     EVP_PKEY_free(pkey);
   2124     if (i && !ssl3_has_client_certificate(s)) {
   2125       i = 0;
   2126     }
   2127     if (i == 0) {
   2128       if (s->version == SSL3_VERSION) {
   2129         s->s3->tmp.cert_req = 0;
   2130         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
   2131         return 1;
   2132       } else {
   2133         s->s3->tmp.cert_req = 2;
   2134         /* There is no client certificate, so the handshake buffer may be
   2135          * released. */
   2136         if (s->s3->handshake_buffer &&
   2137             !ssl3_digest_cached_records(s, free_handshake_buffer)) {
   2138           ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   2139           return -1;
   2140         }
   2141       }
   2142     }
   2143 
   2144     /* Ok, we have a cert */
   2145     s->state = SSL3_ST_CW_CERT_C;
   2146   }
   2147 
   2148   if (s->state == SSL3_ST_CW_CERT_C) {
   2149     CERT_PKEY *cert_pkey = (s->s3->tmp.cert_req == 2) ? NULL : s->cert->key;
   2150     if (!ssl3_output_cert_chain(s, cert_pkey)) {
   2151       return -1;
   2152     }
   2153   }
   2154 
   2155   /* SSL3_ST_CW_CERT_D */
   2156   return ssl_do_write(s);
   2157 }
   2158 
   2159 #define has_bits(i, m) (((i) & (m)) == (m))
   2160 
   2161 int ssl3_check_cert_and_algorithm(SSL *s) {
   2162   int i, idx;
   2163   long alg_k, alg_a;
   2164   EVP_PKEY *pkey = NULL;
   2165   SESS_CERT *sc;
   2166   DH *dh;
   2167 
   2168   /* we don't have a certificate */
   2169   if (!ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
   2170     return 1;
   2171   }
   2172 
   2173   alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
   2174   alg_a = s->s3->tmp.new_cipher->algorithm_auth;
   2175 
   2176   sc = s->session->sess_cert;
   2177   if (sc == NULL) {
   2178     OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, ERR_R_INTERNAL_ERROR);
   2179     goto err;
   2180   }
   2181 
   2182   dh = s->session->sess_cert->peer_dh_tmp;
   2183 
   2184   /* This is the passed certificate */
   2185 
   2186   idx = sc->peer_cert_type;
   2187   if (idx == SSL_PKEY_ECC) {
   2188     if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) {
   2189       /* check failed */
   2190       OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_BAD_ECC_CERT);
   2191       goto f_err;
   2192     } else {
   2193       return 1;
   2194     }
   2195   } else if (alg_a & SSL_aECDSA) {
   2196     OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm,
   2197                       SSL_R_MISSING_ECDSA_SIGNING_CERT);
   2198     goto f_err;
   2199   }
   2200   pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
   2201   i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
   2202   EVP_PKEY_free(pkey);
   2203 
   2204   /* Check that we have a certificate if we require one */
   2205   if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) {
   2206     OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm,
   2207                       SSL_R_MISSING_RSA_SIGNING_CERT);
   2208     goto f_err;
   2209   }
   2210 
   2211   if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) {
   2212     OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm,
   2213                       SSL_R_MISSING_RSA_ENCRYPTING_CERT);
   2214     goto f_err;
   2215   }
   2216 
   2217   if ((alg_k & SSL_kDHE) &&
   2218       !(has_bits(i, EVP_PK_DH | EVP_PKT_EXCH) || dh != NULL)) {
   2219     OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_DH_KEY);
   2220     goto f_err;
   2221   }
   2222 
   2223   return 1;
   2224 
   2225 f_err:
   2226   ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   2227 err:
   2228   return 0;
   2229 }
   2230 
   2231 int ssl3_send_next_proto(SSL *s) {
   2232   unsigned int len, padding_len;
   2233   uint8_t *d, *p;
   2234 
   2235   if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
   2236     len = s->next_proto_negotiated_len;
   2237     padding_len = 32 - ((len + 2) % 32);
   2238 
   2239     d = p = ssl_handshake_start(s);
   2240     *(p++) = len;
   2241     memcpy(p, s->next_proto_negotiated, len);
   2242     p += len;
   2243     *(p++) = padding_len;
   2244     memset(p, 0, padding_len);
   2245     p += padding_len;
   2246 
   2247     if (!ssl_set_handshake_header(s, SSL3_MT_NEXT_PROTO, p - d)) {
   2248       return -1;
   2249     }
   2250     s->state = SSL3_ST_CW_NEXT_PROTO_B;
   2251   }
   2252 
   2253   return ssl_do_write(s);
   2254 }
   2255 
   2256 int ssl3_send_channel_id(SSL *s) {
   2257   uint8_t *d;
   2258   int ret = -1, public_key_len;
   2259   EVP_MD_CTX md_ctx;
   2260   size_t sig_len;
   2261   ECDSA_SIG *sig = NULL;
   2262   uint8_t *public_key = NULL, *derp, *der_sig = NULL;
   2263 
   2264   if (s->state != SSL3_ST_CW_CHANNEL_ID_A) {
   2265     return ssl_do_write(s);
   2266   }
   2267 
   2268   if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb) {
   2269     EVP_PKEY *key = NULL;
   2270     s->ctx->channel_id_cb(s, &key);
   2271     if (key != NULL) {
   2272       s->tlsext_channel_id_private = key;
   2273     }
   2274   }
   2275 
   2276   if (!s->tlsext_channel_id_private) {
   2277     s->rwstate = SSL_CHANNEL_ID_LOOKUP;
   2278     return -1;
   2279   }
   2280   s->rwstate = SSL_NOTHING;
   2281 
   2282   d = ssl_handshake_start(s);
   2283   if (s->s3->tlsext_channel_id_new) {
   2284     s2n(TLSEXT_TYPE_channel_id_new, d);
   2285   } else {
   2286     s2n(TLSEXT_TYPE_channel_id, d);
   2287   }
   2288   s2n(TLSEXT_CHANNEL_ID_SIZE, d);
   2289 
   2290   EVP_MD_CTX_init(&md_ctx);
   2291 
   2292   public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
   2293   if (public_key_len <= 0) {
   2294     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id,
   2295                       SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
   2296     goto err;
   2297   }
   2298 
   2299   /* i2d_PublicKey will produce an ANSI X9.62 public key which, for a
   2300    * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
   2301    * field elements as 32-byte, big-endian numbers. */
   2302   if (public_key_len != 65) {
   2303     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CHANNEL_ID_NOT_P256);
   2304     goto err;
   2305   }
   2306   public_key = OPENSSL_malloc(public_key_len);
   2307   if (!public_key) {
   2308     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
   2309     goto err;
   2310   }
   2311 
   2312   derp = public_key;
   2313   i2d_PublicKey(s->tlsext_channel_id_private, &derp);
   2314 
   2315   if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
   2316                          s->tlsext_channel_id_private) != 1) {
   2317     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id,
   2318                       SSL_R_EVP_DIGESTSIGNINIT_FAILED);
   2319     goto err;
   2320   }
   2321 
   2322   if (!tls1_channel_id_hash(&md_ctx, s)) {
   2323     goto err;
   2324   }
   2325 
   2326   if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len)) {
   2327     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id,
   2328                       SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   2329     goto err;
   2330   }
   2331 
   2332   der_sig = OPENSSL_malloc(sig_len);
   2333   if (!der_sig) {
   2334     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
   2335     goto err;
   2336   }
   2337 
   2338   if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len)) {
   2339     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id,
   2340                       SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   2341     goto err;
   2342   }
   2343 
   2344   derp = der_sig;
   2345   sig = d2i_ECDSA_SIG(NULL, (const uint8_t **)&derp, sig_len);
   2346   if (sig == NULL) {
   2347     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_D2I_ECDSA_SIG);
   2348     goto err;
   2349   }
   2350 
   2351   /* The first byte of public_key will be 0x4, denoting an uncompressed key. */
   2352   memcpy(d, public_key + 1, 64);
   2353   d += 64;
   2354   if (!BN_bn2bin_padded(d, 32, sig->r) ||
   2355       !BN_bn2bin_padded(d + 32, 32, sig->s)) {
   2356     OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_INTERNAL_ERROR);
   2357     goto err;
   2358   }
   2359 
   2360   if (!ssl_set_handshake_header(s, SSL3_MT_ENCRYPTED_EXTENSIONS,
   2361                                 2 + 2 + TLSEXT_CHANNEL_ID_SIZE)) {
   2362     goto err;
   2363   }
   2364   s->state = SSL3_ST_CW_CHANNEL_ID_B;
   2365 
   2366   ret = ssl_do_write(s);
   2367 
   2368 err:
   2369   EVP_MD_CTX_cleanup(&md_ctx);
   2370   OPENSSL_free(public_key);
   2371   OPENSSL_free(der_sig);
   2372   ECDSA_SIG_free(sig);
   2373 
   2374   return ret;
   2375 }
   2376 
   2377 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) {
   2378   int i = 0;
   2379   if (s->ctx->client_cert_cb) {
   2380     i = s->ctx->client_cert_cb(s, px509, ppkey);
   2381   }
   2382   return i;
   2383 }
   2384