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 <stdio.h>
    152 
    153 #include <openssl/buf.h>
    154 #include <openssl/bytestring.h>
    155 #include <openssl/rand.h>
    156 #include <openssl/obj.h>
    157 #include <openssl/evp.h>
    158 #include <openssl/mem.h>
    159 #include <openssl/md5.h>
    160 #include <openssl/dh.h>
    161 #include <openssl/bn.h>
    162 #include <openssl/engine.h>
    163 #include <openssl/x509.h>
    164 
    165 #include "ssl_locl.h"
    166 #include "../crypto/dh/internal.h"
    167 
    168 static const SSL_METHOD *ssl3_get_client_method(int ver);
    169 
    170 static const SSL_METHOD *ssl3_get_client_method(int ver)
    171 	{
    172 	if (ver == SSL3_VERSION)
    173 		return(SSLv3_client_method());
    174 	else
    175 		return(NULL);
    176 	}
    177 
    178 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
    179 			ssl_undefined_function,
    180 			ssl3_connect,
    181 			ssl3_get_client_method)
    182 
    183 int ssl3_connect(SSL *s)
    184 	{
    185 	BUF_MEM *buf=NULL;
    186 	void (*cb)(const SSL *ssl,int type,int val)=NULL;
    187 	int ret= -1;
    188 	int new_state,state,skip=0;
    189 
    190 	ERR_clear_error();
    191 	ERR_clear_system_error();
    192 
    193 	if (s->info_callback != NULL)
    194 		cb=s->info_callback;
    195 	else if (s->ctx->info_callback != NULL)
    196 		cb=s->ctx->info_callback;
    197 
    198 	s->in_handshake++;
    199 	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
    200 
    201 	for (;;)
    202 		{
    203 		state=s->state;
    204 
    205 		switch(s->state)
    206 			{
    207 		case SSL_ST_RENEGOTIATE:
    208 			s->renegotiate=1;
    209 			s->state=SSL_ST_CONNECT;
    210 			s->ctx->stats.sess_connect_renegotiate++;
    211 			/* break */
    212 		case SSL_ST_BEFORE:
    213 		case SSL_ST_CONNECT:
    214 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
    215 		case SSL_ST_OK|SSL_ST_CONNECT:
    216 
    217 			s->server=0;
    218 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
    219 
    220 			if ((s->version & 0xff00 ) != 0x0300)
    221 				{
    222 				OPENSSL_PUT_ERROR(SSL, ssl3_connect, ERR_R_INTERNAL_ERROR);
    223 				ret = -1;
    224 				goto end;
    225 				}
    226 
    227 			/* s->version=SSL3_VERSION; */
    228 			s->type=SSL_ST_CONNECT;
    229 
    230 			if (s->init_buf == NULL)
    231 				{
    232 				if ((buf=BUF_MEM_new()) == NULL)
    233 					{
    234 					ret= -1;
    235 					goto end;
    236 					}
    237 				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
    238 					{
    239 					ret= -1;
    240 					goto end;
    241 					}
    242 				s->init_buf=buf;
    243 				buf=NULL;
    244 				}
    245 
    246 			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
    247 
    248 			/* setup buffing BIO */
    249 			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
    250 
    251 			/* don't push the buffering BIO quite yet */
    252 
    253 			ssl3_init_finished_mac(s);
    254 
    255 			s->state=SSL3_ST_CW_CLNT_HELLO_A;
    256 			s->ctx->stats.sess_connect++;
    257 			s->init_num=0;
    258 			break;
    259 
    260 		case SSL3_ST_CW_CLNT_HELLO_A:
    261 		case SSL3_ST_CW_CLNT_HELLO_B:
    262 
    263 			s->shutdown=0;
    264 			ret=ssl3_send_client_hello(s);
    265 			if (ret <= 0) goto end;
    266 			s->state=SSL3_ST_CR_SRVR_HELLO_A;
    267 			s->init_num=0;
    268 
    269 			/* turn on buffering for the next lot of output */
    270 			if (s->bbio != s->wbio)
    271 				s->wbio=BIO_push(s->bbio,s->wbio);
    272 
    273 			break;
    274 
    275 		case SSL3_ST_CR_SRVR_HELLO_A:
    276 		case SSL3_ST_CR_SRVR_HELLO_B:
    277 			ret=ssl3_get_server_hello(s);
    278 			if (ret <= 0) goto end;
    279 
    280 			if (s->hit)
    281 				{
    282 				s->state=SSL3_ST_CR_CHANGE;
    283 				if (s->tlsext_ticket_expected)
    284 					{
    285 					/* receive renewed session ticket */
    286 					s->state=SSL3_ST_CR_SESSION_TICKET_A;
    287 					}
    288 				}
    289 			else
    290 				{
    291 				s->state=SSL3_ST_CR_CERT_A;
    292 				}
    293 			s->init_num=0;
    294 			break;
    295 
    296 		case SSL3_ST_CR_CERT_A:
    297 		case SSL3_ST_CR_CERT_B:
    298 			if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
    299 				{
    300 				ret=ssl3_get_server_certificate(s);
    301 				if (ret <= 0) goto end;
    302 				if (s->s3->tmp.certificate_status_expected)
    303 					s->state=SSL3_ST_CR_CERT_STATUS_A;
    304 				else
    305 					s->state=SSL3_ST_CR_KEY_EXCH_A;
    306 				}
    307 			else
    308 				{
    309 				skip = 1;
    310 				s->state=SSL3_ST_CR_KEY_EXCH_A;
    311 				}
    312 			s->init_num=0;
    313 			break;
    314 
    315 		case SSL3_ST_CR_KEY_EXCH_A:
    316 		case SSL3_ST_CR_KEY_EXCH_B:
    317 			ret=ssl3_get_server_key_exchange(s);
    318 			if (ret <= 0) goto end;
    319 			s->state=SSL3_ST_CR_CERT_REQ_A;
    320 			s->init_num=0;
    321 
    322 			/* at this point we check that we have the
    323 			 * required stuff from the server */
    324 			if (!ssl3_check_cert_and_algorithm(s))
    325 				{
    326 				ret= -1;
    327 				goto end;
    328 				}
    329 			break;
    330 
    331 		case SSL3_ST_CR_CERT_REQ_A:
    332 		case SSL3_ST_CR_CERT_REQ_B:
    333 			ret=ssl3_get_certificate_request(s);
    334 			if (ret <= 0) goto end;
    335 			s->state=SSL3_ST_CR_SRVR_DONE_A;
    336 			s->init_num=0;
    337 			break;
    338 
    339 		case SSL3_ST_CR_SRVR_DONE_A:
    340 		case SSL3_ST_CR_SRVR_DONE_B:
    341 			ret=ssl3_get_server_done(s);
    342 			if (ret <= 0) goto end;
    343 			if (s->s3->tmp.cert_req)
    344 				s->state=SSL3_ST_CW_CERT_A;
    345 			else
    346 				s->state=SSL3_ST_CW_KEY_EXCH_A;
    347 			s->init_num=0;
    348 
    349 			break;
    350 
    351 		case SSL3_ST_CW_CERT_A:
    352 		case SSL3_ST_CW_CERT_B:
    353 		case SSL3_ST_CW_CERT_C:
    354 		case SSL3_ST_CW_CERT_D:
    355 			ret=ssl3_send_client_certificate(s);
    356 			if (ret <= 0) goto end;
    357 			s->state=SSL3_ST_CW_KEY_EXCH_A;
    358 			s->init_num=0;
    359 			break;
    360 
    361 		case SSL3_ST_CW_KEY_EXCH_A:
    362 		case SSL3_ST_CW_KEY_EXCH_B:
    363 			ret=ssl3_send_client_key_exchange(s);
    364 			if (ret <= 0) goto end;
    365 			/* For TLS, cert_req is set to 2, so a cert chain
    366 			 * of nothing is sent, but no verify packet is sent */
    367 			if (s->s3->tmp.cert_req == 1)
    368 				{
    369 				s->state=SSL3_ST_CW_CERT_VRFY_A;
    370 				}
    371 			else
    372 				{
    373 				s->state=SSL3_ST_CW_CHANGE_A;
    374 				s->s3->change_cipher_spec=0;
    375 				}
    376 
    377 			s->init_num=0;
    378 			break;
    379 
    380 		case SSL3_ST_CW_CERT_VRFY_A:
    381 		case SSL3_ST_CW_CERT_VRFY_B:
    382 			ret=ssl3_send_cert_verify(s);
    383 			if (ret <= 0) goto end;
    384 			s->state=SSL3_ST_CW_CHANGE_A;
    385 			s->init_num=0;
    386 			s->s3->change_cipher_spec=0;
    387 			break;
    388 
    389 		case SSL3_ST_CW_CHANGE_A:
    390 		case SSL3_ST_CW_CHANGE_B:
    391 			ret=ssl3_send_change_cipher_spec(s,
    392 				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
    393 			if (ret <= 0) goto end;
    394 
    395  			s->state=SSL3_ST_CW_FINISHED_A;
    396 			if (s->s3->tlsext_channel_id_valid)
    397 				s->state=SSL3_ST_CW_CHANNEL_ID_A;
    398 			if (s->s3->next_proto_neg_seen)
    399 				s->state=SSL3_ST_CW_NEXT_PROTO_A;
    400 			s->init_num=0;
    401 
    402 			s->session->cipher=s->s3->tmp.new_cipher;
    403 			if (!s->method->ssl3_enc->setup_key_block(s))
    404 				{
    405 				ret= -1;
    406 				goto end;
    407 				}
    408 
    409 			if (!s->method->ssl3_enc->change_cipher_state(s,
    410 				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
    411 				{
    412 				ret= -1;
    413 				goto end;
    414 				}
    415 
    416 			break;
    417 
    418 		case SSL3_ST_CW_NEXT_PROTO_A:
    419 		case SSL3_ST_CW_NEXT_PROTO_B:
    420 			ret=ssl3_send_next_proto(s);
    421 			if (ret <= 0) goto end;
    422 			if (s->s3->tlsext_channel_id_valid)
    423 				s->state=SSL3_ST_CW_CHANNEL_ID_A;
    424 			else
    425 				s->state=SSL3_ST_CW_FINISHED_A;
    426 			break;
    427 
    428 		case SSL3_ST_CW_CHANNEL_ID_A:
    429 		case SSL3_ST_CW_CHANNEL_ID_B:
    430 			ret=ssl3_send_channel_id(s);
    431 			if (ret <= 0) goto end;
    432 			s->state=SSL3_ST_CW_FINISHED_A;
    433 			break;
    434 
    435 		case SSL3_ST_CW_FINISHED_A:
    436 		case SSL3_ST_CW_FINISHED_B:
    437 			ret=ssl3_send_finished(s,
    438 				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
    439 				s->method->ssl3_enc->client_finished_label,
    440 				s->method->ssl3_enc->client_finished_label_len);
    441 			if (ret <= 0) goto end;
    442 			s->state=SSL3_ST_CW_FLUSH;
    443 
    444 			/* clear flags */
    445 			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
    446 			if (s->hit)
    447 				{
    448 				s->s3->tmp.next_state=SSL_ST_OK;
    449 				}
    450 			else
    451 				{
    452 				/* This is a non-resumption handshake. If it
    453 				 * involves ChannelID, then record the
    454 				 * handshake hashes at this point in the
    455 				 * session so that any resumption of this
    456 				 * session with ChannelID can sign those
    457 				 * hashes. */
    458 				if (s->s3->tlsext_channel_id_new)
    459 					{
    460 					ret = tls1_record_handshake_hashes_for_channel_id(s);
    461 					if (ret <= 0)
    462 						goto end;
    463 					}
    464 				if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH)
    465 				    && ssl3_can_cutthrough(s)
    466 				    && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */
    467 				   )
    468 					{
    469 					s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE;
    470 					}
    471 				else
    472 					{
    473 					/* Allow NewSessionTicket if ticket expected */
    474 					if (s->tlsext_ticket_expected)
    475 						s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
    476 					else
    477 						s->s3->tmp.next_state=SSL3_ST_CR_CHANGE;
    478 					}
    479 				}
    480 			s->init_num=0;
    481 			break;
    482 
    483 		case SSL3_ST_CR_SESSION_TICKET_A:
    484 		case SSL3_ST_CR_SESSION_TICKET_B:
    485 			ret=ssl3_get_new_session_ticket(s);
    486 			if (ret <= 0) goto end;
    487 			s->state=SSL3_ST_CR_CHANGE;
    488 			s->init_num=0;
    489 		break;
    490 
    491 		case SSL3_ST_CR_CERT_STATUS_A:
    492 		case SSL3_ST_CR_CERT_STATUS_B:
    493 			ret=ssl3_get_cert_status(s);
    494 			if (ret <= 0) goto end;
    495 			s->state=SSL3_ST_CR_KEY_EXCH_A;
    496 			s->init_num=0;
    497 		break;
    498 
    499 		case SSL3_ST_CR_CHANGE:
    500 			/* At this point, the next message must be entirely
    501 			 * behind a ChangeCipherSpec. */
    502 			if (!ssl3_expect_change_cipher_spec(s))
    503 				{
    504 				ret = -1;
    505 				goto end;
    506 				}
    507 			s->state = SSL3_ST_CR_FINISHED_A;
    508 			break;
    509 
    510 		case SSL3_ST_CR_FINISHED_A:
    511 		case SSL3_ST_CR_FINISHED_B:
    512 			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
    513 				SSL3_ST_CR_FINISHED_B);
    514 			if (ret <= 0) goto end;
    515 
    516 			if (s->hit)
    517 				s->state=SSL3_ST_CW_CHANGE_A;
    518 			else
    519 				s->state=SSL_ST_OK;
    520 			s->init_num=0;
    521 			break;
    522 
    523 		case SSL3_ST_CW_FLUSH:
    524 			s->rwstate=SSL_WRITING;
    525 			if (BIO_flush(s->wbio) <= 0)
    526 				{
    527 				ret= -1;
    528 				goto end;
    529 				}
    530 			s->rwstate=SSL_NOTHING;
    531 			s->state=s->s3->tmp.next_state;
    532 			break;
    533 
    534 		case SSL3_ST_CUTTHROUGH_COMPLETE:
    535 			/* Allow NewSessionTicket if ticket expected */
    536 			if (s->tlsext_ticket_expected)
    537 				s->state=SSL3_ST_CR_SESSION_TICKET_A;
    538 			else
    539 				s->state=SSL3_ST_CR_CHANGE;
    540 
    541 			ssl_free_wbio_buffer(s);
    542 			ret = 1;
    543 			goto end;
    544 			/* break; */
    545 
    546 		case SSL_ST_OK:
    547 			/* clean a few things up */
    548 			ssl3_cleanup_key_block(s);
    549 
    550 			if (s->init_buf != NULL)
    551 				{
    552 				BUF_MEM_free(s->init_buf);
    553 				s->init_buf=NULL;
    554 				}
    555 
    556 			/* If we are not 'joining' the last two packets,
    557 			 * remove the buffering now */
    558 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
    559 				ssl_free_wbio_buffer(s);
    560 			/* else do it later in ssl3_write */
    561 
    562 			s->init_num=0;
    563 			s->renegotiate=0;
    564 			s->new_session=0;
    565 
    566 			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
    567 			if (s->hit) s->ctx->stats.sess_hit++;
    568 
    569 			ret=1;
    570 			/* s->server=0; */
    571 			s->handshake_func=ssl3_connect;
    572 			s->ctx->stats.sess_connect_good++;
    573 
    574 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
    575 
    576 			goto end;
    577 			/* break; */
    578 
    579 		default:
    580 			OPENSSL_PUT_ERROR(SSL, ssl3_connect, SSL_R_UNKNOWN_STATE);
    581 			ret= -1;
    582 			goto end;
    583 			/* break; */
    584 			}
    585 
    586 		/* did we do anything */
    587 		if (!s->s3->tmp.reuse_message && !skip)
    588 			{
    589 			if (s->debug)
    590 				{
    591 				if ((ret=BIO_flush(s->wbio)) <= 0)
    592 					goto end;
    593 				}
    594 
    595 			if ((cb != NULL) && (s->state != state))
    596 				{
    597 				new_state=s->state;
    598 				s->state=state;
    599 				cb(s,SSL_CB_CONNECT_LOOP,1);
    600 				s->state=new_state;
    601 				}
    602 			}
    603 		skip=0;
    604 		}
    605 end:
    606 	s->in_handshake--;
    607 	if (buf != NULL)
    608 		BUF_MEM_free(buf);
    609 	if (cb != NULL)
    610 		cb(s,SSL_CB_CONNECT_EXIT,ret);
    611 	return(ret);
    612 	}
    613 
    614 
    615 int ssl3_send_client_hello(SSL *s)
    616 	{
    617 	unsigned char *buf;
    618 	unsigned char *p,*d;
    619 	int i;
    620 	unsigned long l;
    621 
    622 	buf=(unsigned char *)s->init_buf->data;
    623 	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
    624 		{
    625 		SSL_SESSION *sess = s->session;
    626 		if (sess == NULL ||
    627 			sess->ssl_version != s->version ||
    628 			!sess->session_id_length ||
    629 			sess->not_resumable)
    630 			{
    631 			if (!ssl_get_new_session(s,0))
    632 				goto err;
    633 			}
    634 		if (s->method->version == DTLS_ANY_VERSION)
    635 			{
    636 			/* Determine which DTLS version to use */
    637 			int options = s->options;
    638 			/* If DTLS 1.2 disabled correct the version number */
    639 			if (options & SSL_OP_NO_DTLSv1_2)
    640 				{
    641 				/* Disabling all versions is silly: return an
    642 				 * error.
    643 				 */
    644 				if (options & SSL_OP_NO_DTLSv1)
    645 					{
    646 					OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_WRONG_SSL_VERSION);
    647 					goto err;
    648 					}
    649 				/* Update method so we don't use any DTLS 1.2
    650 				 * features.
    651 				 */
    652 				s->method = DTLSv1_client_method();
    653 				s->version = DTLS1_VERSION;
    654 				}
    655 			else
    656 				{
    657 				/* We only support one version: update method */
    658 				if (options & SSL_OP_NO_DTLSv1)
    659 					s->method = DTLSv1_2_client_method();
    660 				s->version = DTLS1_2_VERSION;
    661 				}
    662 			s->client_version = s->version;
    663 			}
    664 		/* else use the pre-loaded session */
    665 
    666 		p=s->s3->client_random;
    667 
    668 		/* If resending the ClientHello in DTLS after a
    669 		 * HelloVerifyRequest, don't renegerate the client_random. The
    670 		 * random must be reused. */
    671 		if (!SSL_IS_DTLS(s) || !s->d1->send_cookie)
    672 			{
    673 			ssl_fill_hello_random(s, 0, p,
    674 					      sizeof(s->s3->client_random));
    675 			}
    676 
    677 		/* Do the message type and length last.
    678 		 * Note: the final argument to ssl_add_clienthello_tlsext below
    679 		 * depends on the size of this prefix. */
    680 		d=p= ssl_handshake_start(s);
    681 
    682 		/* version indicates the negotiated version: for example from
    683 		 * an SSLv2/v3 compatible client hello). The client_version
    684 		 * field is the maximum version we permit and it is also
    685 		 * used in RSA encrypted premaster secrets. Some servers can
    686 		 * choke if we initially report a higher version then
    687 		 * renegotiate to a lower one in the premaster secret. This
    688 		 * didn't happen with TLS 1.0 as most servers supported it
    689 		 * but it can with TLS 1.1 or later if the server only supports
    690 		 * 1.0.
    691 		 *
    692 		 * Possible scenario with previous logic:
    693 		 * 	1. Client hello indicates TLS 1.2
    694 		 * 	2. Server hello says TLS 1.0
    695 		 *	3. RSA encrypted premaster secret uses 1.2.
    696 		 * 	4. Handhaked proceeds using TLS 1.0.
    697 		 *	5. Server sends hello request to renegotiate.
    698 		 *	6. Client hello indicates TLS v1.0 as we now
    699 		 *	   know that is maximum server supports.
    700 		 *	7. Server chokes on RSA encrypted premaster secret
    701 		 *	   containing version 1.0.
    702 		 *
    703 		 * For interoperability it should be OK to always use the
    704 		 * maximum version we support in client hello and then rely
    705 		 * on the checking of version to ensure the servers isn't
    706 		 * being inconsistent: for example initially negotiating with
    707 		 * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
    708 		 * client_version in client hello and not resetting it to
    709 		 * the negotiated version.
    710 		 */
    711 #if 0
    712 		*(p++)=s->version>>8;
    713 		*(p++)=s->version&0xff;
    714 		s->client_version=s->version;
    715 #else
    716 		*(p++)=s->client_version>>8;
    717 		*(p++)=s->client_version&0xff;
    718 #endif
    719 
    720 		/* Random stuff */
    721 		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
    722 		p+=SSL3_RANDOM_SIZE;
    723 
    724 		/* Session ID */
    725 		if (s->new_session)
    726 			i=0;
    727 		else
    728 			i=s->session->session_id_length;
    729 		*(p++)=i;
    730 		if (i != 0)
    731 			{
    732 			if (i > (int)sizeof(s->session->session_id))
    733 				{
    734 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    735 				goto err;
    736 				}
    737 			memcpy(p,s->session->session_id,i);
    738 			p+=i;
    739 			}
    740 
    741 		/* cookie stuff for DTLS */
    742 		if (SSL_IS_DTLS(s))
    743 			{
    744 			if ( s->d1->cookie_len > sizeof(s->d1->cookie))
    745 				{
    746 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    747 				goto err;
    748 				}
    749 			*(p++) = s->d1->cookie_len;
    750 			memcpy(p, s->d1->cookie, s->d1->cookie_len);
    751 			p += s->d1->cookie_len;
    752 			}
    753 
    754 		/* Ciphers supported */
    755 		i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &p[2]);
    756 		if (i == 0)
    757 			{
    758 			OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_NO_CIPHERS_AVAILABLE);
    759 			goto err;
    760 			}
    761 		s2n(i,p);
    762 		p+=i;
    763 
    764 		/* COMPRESSION */
    765 		*(p++)=1;
    766 		*(p++)=0; /* Add the NULL method */
    767 
    768 		/* TLS extensions*/
    769 		if (ssl_prepare_clienthello_tlsext(s) <= 0)
    770 			{
    771 			OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, SSL_R_CLIENTHELLO_TLSEXT);
    772 			goto err;
    773 			}
    774 		if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, p-buf)) == NULL)
    775 			{
    776 			OPENSSL_PUT_ERROR(SSL, ssl3_send_client_hello, ERR_R_INTERNAL_ERROR);
    777 			goto err;
    778 			}
    779 
    780 		l= p-d;
    781 		ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l);
    782 		s->state=SSL3_ST_CW_CLNT_HELLO_B;
    783 		}
    784 
    785 	/* SSL3_ST_CW_CLNT_HELLO_B */
    786 	return ssl_do_write(s);
    787 err:
    788 	return(-1);
    789 	}
    790 
    791 int ssl3_get_server_hello(SSL *s)
    792 	{
    793 	STACK_OF(SSL_CIPHER) *sk;
    794 	const SSL_CIPHER *c;
    795 	CERT *ct = s->cert;
    796 	int al=SSL_AD_INTERNAL_ERROR,ok;
    797 	long n;
    798 	CBS server_hello, server_random, session_id;
    799 	uint16_t server_version, cipher_suite;
    800 	uint8_t compression_method;
    801 	unsigned long mask_ssl;
    802 
    803 	n=s->method->ssl_get_message(s,
    804 		SSL3_ST_CR_SRVR_HELLO_A,
    805 		SSL3_ST_CR_SRVR_HELLO_B,
    806 		SSL3_MT_SERVER_HELLO,
    807 		20000, /* ?? */
    808 		SSL_GET_MESSAGE_HASH_MESSAGE,
    809 		&ok);
    810 
    811 	if (!ok) return((int)n);
    812 
    813 	CBS_init(&server_hello, s->init_msg, n);
    814 
    815 	if (!CBS_get_u16(&server_hello, &server_version) ||
    816 		!CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
    817 		!CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
    818 		CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
    819 		!CBS_get_u16(&server_hello, &cipher_suite) ||
    820 		!CBS_get_u8(&server_hello, &compression_method))
    821 		{
    822 		al = SSL_AD_DECODE_ERROR;
    823 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_DECODE_ERROR);
    824 		goto f_err;
    825 		}
    826 
    827 	if (s->method->version == DTLS_ANY_VERSION)
    828 		{
    829 		/* Work out correct protocol version to use */
    830 		int options = s->options;
    831 		if (server_version == DTLS1_2_VERSION
    832 			&& !(options & SSL_OP_NO_DTLSv1_2))
    833 			s->method = DTLSv1_2_client_method();
    834 		else if (server_version == DTLS1_VERSION
    835 			&& !(options & SSL_OP_NO_DTLSv1))
    836 			s->method = DTLSv1_client_method();
    837 		else
    838 			{
    839 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
    840 			s->version = server_version;
    841 			al = SSL_AD_PROTOCOL_VERSION;
    842 			goto f_err;
    843 			}
    844 		s->version = s->client_version = s->method->version;
    845 		}
    846 
    847 	if (server_version != s->version)
    848 		{
    849 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_SSL_VERSION);
    850 		s->version = (s->version & 0xff00) | (server_version & 0xff);
    851 		al = SSL_AD_PROTOCOL_VERSION;
    852 		goto f_err;
    853 		}
    854 
    855 	/* Copy over the server random. */
    856 	memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
    857 
    858 	s->hit = 0;
    859 
    860 	/* check if we want to resume the session based on external pre-shared secret */
    861 	if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
    862 		{
    863 		const SSL_CIPHER *pref_cipher=NULL;
    864 		s->session->master_key_length=sizeof(s->session->master_key);
    865 		if (s->tls_session_secret_cb(s, s->session->master_key,
    866 					     &s->session->master_key_length,
    867 					     NULL, &pref_cipher,
    868 					     s->tls_session_secret_cb_arg))
    869 			{
    870 			s->session->cipher = pref_cipher ?
    871 				pref_cipher :
    872 				ssl3_get_cipher_by_value(cipher_suite);
    873 			s->hit = 1;
    874 			}
    875 		}
    876 
    877 	if (!s->hit && CBS_len(&session_id) != 0 &&
    878 		CBS_mem_equal(&session_id,
    879 			s->session->session_id, s->session->session_id_length))
    880 		{
    881 		if(s->sid_ctx_length != s->session->sid_ctx_length
    882 			|| memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length))
    883 			{
    884 			/* actually a client application bug */
    885 			al = SSL_AD_ILLEGAL_PARAMETER;
    886 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
    887 			goto f_err;
    888 			}
    889 		s->hit = 1;
    890 		}
    891 
    892 	/* a miss or crap from the other end */
    893 	if (!s->hit)
    894 		{
    895 		/* If we were trying for session-id reuse, make a new
    896 		 * SSL_SESSION so we don't stuff up other people */
    897 		if (s->session->session_id_length > 0)
    898 			{
    899 			if (!ssl_get_new_session(s,0))
    900 				{
    901 				goto f_err;
    902 				}
    903 			}
    904 		/* Note: session_id could be empty. */
    905 		s->session->session_id_length = CBS_len(&session_id);
    906 		memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
    907 		}
    908 
    909 	c = ssl3_get_cipher_by_value(cipher_suite);
    910 	if (c == NULL)
    911 		{
    912 		/* unknown cipher */
    913 		al = SSL_AD_ILLEGAL_PARAMETER;
    914 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNKNOWN_CIPHER_RETURNED);
    915 		goto f_err;
    916 		}
    917 	/* ct->mask_ssl was computed from client capabilities. Now
    918 	 * that the final version is known, compute a new mask_ssl. */
    919 	if (!SSL_USE_TLS1_2_CIPHERS(s))
    920 		mask_ssl = SSL_TLSV1_2;
    921 	else
    922 		mask_ssl = 0;
    923 	/* If it is a disabled cipher we didn't send it in client hello,
    924 	 * so return an error.
    925 	 */
    926 	if (c->algorithm_ssl & mask_ssl ||
    927 		c->algorithm_mkey & ct->mask_k ||
    928 		c->algorithm_auth & ct->mask_a)
    929 		{
    930 		al=SSL_AD_ILLEGAL_PARAMETER;
    931 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
    932 		goto f_err;
    933 		}
    934 
    935 	sk=ssl_get_ciphers_by_id(s);
    936 	if (!sk_SSL_CIPHER_find(sk, NULL, c))
    937 		{
    938 		/* we did not say we would use this cipher */
    939 		al=SSL_AD_ILLEGAL_PARAMETER;
    940 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_WRONG_CIPHER_RETURNED);
    941 		goto f_err;
    942 		}
    943 
    944 	/* Depending on the session caching (internal/external), the cipher
    945 	   and/or cipher_id values may not be set. Make sure that
    946 	   cipher_id is set and use it for comparison. */
    947 	if (s->session->cipher)
    948 		s->session->cipher_id = s->session->cipher->id;
    949 	if (s->hit && (s->session->cipher_id != c->id))
    950 		{
    951 		al = SSL_AD_ILLEGAL_PARAMETER;
    952 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
    953 		goto f_err;
    954 		}
    955 	s->s3->tmp.new_cipher=c;
    956 	/* Don't digest cached records if no sigalgs: we may need them for
    957 	 * client authentication.
    958 	 */
    959 	if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s))
    960 		goto f_err;
    961 
    962 	/* Only the NULL compression algorithm is supported. */
    963 	if (compression_method != 0)
    964 		{
    965 		al = SSL_AD_ILLEGAL_PARAMETER;
    966 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
    967 		goto f_err;
    968 		}
    969 
    970 	/* TLS extensions */
    971 	if (!ssl_parse_serverhello_tlsext(s, &server_hello))
    972 		{
    973 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_PARSE_TLSEXT);
    974 		goto err;
    975 		}
    976 
    977         /* There should be nothing left over in the record. */
    978 	if (CBS_len(&server_hello) != 0)
    979 		{
    980 		/* wrong packet length */
    981 		al=SSL_AD_DECODE_ERROR;
    982 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_hello, SSL_R_BAD_PACKET_LENGTH);
    983 		goto f_err;
    984 		}
    985 
    986 	return(1);
    987 f_err:
    988 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
    989 err:
    990 	return(-1);
    991 	}
    992 
    993 int ssl3_get_server_certificate(SSL *s)
    994 	{
    995 	int al,i,ok,ret= -1;
    996 	unsigned long n;
    997 	X509 *x=NULL;
    998 	STACK_OF(X509) *sk=NULL;
    999 	SESS_CERT *sc;
   1000 	EVP_PKEY *pkey=NULL;
   1001 	CBS cbs, certificate_list;
   1002 	const uint8_t* data;
   1003 
   1004 	n=s->method->ssl_get_message(s,
   1005 		SSL3_ST_CR_CERT_A,
   1006 		SSL3_ST_CR_CERT_B,
   1007 		SSL3_MT_CERTIFICATE,
   1008 		s->max_cert_list,
   1009 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1010 		&ok);
   1011 
   1012 	if (!ok) return((int)n);
   1013 
   1014 	CBS_init(&cbs, s->init_msg, n);
   1015 
   1016 	if ((sk=sk_X509_new_null()) == NULL)
   1017 		{
   1018 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
   1019 		goto err;
   1020 		}
   1021 
   1022 	if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
   1023 		CBS_len(&cbs) != 0)
   1024 		{
   1025 		al = SSL_AD_DECODE_ERROR;
   1026 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_LENGTH_MISMATCH);
   1027 		goto f_err;
   1028 		}
   1029 
   1030 	while (CBS_len(&certificate_list) > 0)
   1031 		{
   1032 		CBS certificate;
   1033 		if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
   1034 			{
   1035 			al = SSL_AD_DECODE_ERROR;
   1036 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
   1037 			goto f_err;
   1038 			}
   1039 		data = CBS_data(&certificate);
   1040 		x = d2i_X509(NULL, &data, CBS_len(&certificate));
   1041 		if (x == NULL)
   1042 			{
   1043 			al=SSL_AD_BAD_CERTIFICATE;
   1044 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_ASN1_LIB);
   1045 			goto f_err;
   1046 			}
   1047 		if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
   1048 			{
   1049 			al = SSL_AD_INTERNAL_ERROR;
   1050 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
   1051 			goto f_err;
   1052 			}
   1053 		if (CBS_len(&certificate) != 0)
   1054 			{
   1055 			al = SSL_AD_DECODE_ERROR;
   1056 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERT_LENGTH_MISMATCH);
   1057 			goto f_err;
   1058 			}
   1059 		if (!sk_X509_push(sk,x))
   1060 			{
   1061 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_MALLOC_FAILURE);
   1062 			goto err;
   1063 			}
   1064 		x=NULL;
   1065 		}
   1066 
   1067 	i=ssl_verify_cert_chain(s,sk);
   1068 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
   1069 		)
   1070 		{
   1071 		al=ssl_verify_alarm_type(s->verify_result);
   1072 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
   1073 		goto f_err;
   1074 		}
   1075 	ERR_clear_error(); /* but we keep s->verify_result */
   1076 
   1077 	sc=ssl_sess_cert_new();
   1078 	if (sc == NULL) goto err;
   1079 
   1080 	if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
   1081 	s->session->sess_cert=sc;
   1082 
   1083 	sc->cert_chain=sk;
   1084 	/* Inconsistency alert: cert_chain does include the peer's
   1085 	 * certificate, which we don't include in s3_srvr.c */
   1086 	x=sk_X509_value(sk,0);
   1087 	sk=NULL;
   1088  	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
   1089 
   1090 	pkey=X509_get_pubkey(x);
   1091 
   1092 	if ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))
   1093 		{
   1094 		x=NULL;
   1095 		al=SSL3_AL_FATAL;
   1096 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
   1097 		goto f_err;
   1098 		}
   1099 
   1100 	i=ssl_cert_type(x,pkey);
   1101 	if (i < 0)
   1102 		{
   1103 		x=NULL;
   1104 		al=SSL3_AL_FATAL;
   1105 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
   1106 		goto f_err;
   1107 		}
   1108 
   1109 	int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
   1110 	if (exp_idx >= 0 && i != exp_idx)
   1111 		{
   1112 		x=NULL;
   1113 		al=SSL_AD_ILLEGAL_PARAMETER;
   1114 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, SSL_R_WRONG_CERTIFICATE_TYPE);
   1115 		goto f_err;
   1116 		}
   1117 	sc->peer_cert_type=i;
   1118 	/* Why would the following ever happen?
   1119 	 * We just created sc a couple of lines ago. */
   1120 	if (sc->peer_pkeys[i].x509 != NULL)
   1121 		X509_free(sc->peer_pkeys[i].x509);
   1122 	sc->peer_pkeys[i].x509 = X509_up_ref(x);
   1123 	sc->peer_key = &(sc->peer_pkeys[i]);
   1124 
   1125 	if (s->session->peer != NULL)
   1126 		X509_free(s->session->peer);
   1127 	s->session->peer = X509_up_ref(x);
   1128 
   1129 	s->session->verify_result = s->verify_result;
   1130 
   1131 	x=NULL;
   1132 	ret=1;
   1133 	if (0)
   1134 		{
   1135 f_err:
   1136 		ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1137 		}
   1138 err:
   1139 	EVP_PKEY_free(pkey);
   1140 	X509_free(x);
   1141 	sk_X509_pop_free(sk,X509_free);
   1142 	return(ret);
   1143 	}
   1144 
   1145 int ssl3_get_server_key_exchange(SSL *s)
   1146 	{
   1147 	EVP_MD_CTX md_ctx;
   1148 	int al,ok;
   1149 	long n,alg_k,alg_a;
   1150 	EVP_PKEY *pkey=NULL;
   1151 	const EVP_MD *md = NULL;
   1152 	RSA *rsa=NULL;
   1153 	DH *dh=NULL;
   1154 	EC_KEY *ecdh = NULL;
   1155 	BN_CTX *bn_ctx = NULL;
   1156 	EC_POINT *srvr_ecpoint = NULL;
   1157 	CBS server_key_exchange, server_key_exchange_orig, parameter;
   1158 
   1159 	/* use same message size as in ssl3_get_certificate_request()
   1160 	 * as ServerKeyExchange message may be skipped */
   1161 	n=s->method->ssl_get_message(s,
   1162 		SSL3_ST_CR_KEY_EXCH_A,
   1163 		SSL3_ST_CR_KEY_EXCH_B,
   1164 		-1,
   1165 		s->max_cert_list,
   1166 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1167 		&ok);
   1168 	if (!ok) return((int)n);
   1169 
   1170 	if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
   1171 		{
   1172 		if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher))
   1173 			{
   1174 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
   1175 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
   1176 			return -1;
   1177 			}
   1178 
   1179 		/* In plain PSK ciphersuite, ServerKeyExchange can be
   1180 		   omitted if no identity hint is sent. Set
   1181 		   session->sess_cert anyway to avoid problems
   1182 		   later.*/
   1183 		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)
   1184 			{
   1185 			/* PSK ciphersuites that also send a
   1186 			 * Certificate would have already initialized
   1187 			 * |sess_cert|. */
   1188 			if (s->session->sess_cert == NULL)
   1189 				s->session->sess_cert = ssl_sess_cert_new();
   1190 			if (s->session->psk_identity_hint)
   1191 				{
   1192 				OPENSSL_free(s->session->psk_identity_hint);
   1193 				s->session->psk_identity_hint = NULL;
   1194 				}
   1195 			}
   1196 		s->s3->tmp.reuse_message=1;
   1197 		return(1);
   1198 		}
   1199 
   1200 	/* Retain a copy of the original CBS to compute the signature
   1201 	 * over. */
   1202 	CBS_init(&server_key_exchange, s->init_msg, n);
   1203 	server_key_exchange_orig = server_key_exchange;
   1204 
   1205 	if (s->session->sess_cert != NULL)
   1206 		{
   1207 		if (s->session->sess_cert->peer_rsa_tmp != NULL)
   1208 			{
   1209 			RSA_free(s->session->sess_cert->peer_rsa_tmp);
   1210 			s->session->sess_cert->peer_rsa_tmp=NULL;
   1211 			}
   1212 		if (s->session->sess_cert->peer_dh_tmp)
   1213 			{
   1214 			DH_free(s->session->sess_cert->peer_dh_tmp);
   1215 			s->session->sess_cert->peer_dh_tmp=NULL;
   1216 			}
   1217 		if (s->session->sess_cert->peer_ecdh_tmp)
   1218 			{
   1219 			EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
   1220 			s->session->sess_cert->peer_ecdh_tmp=NULL;
   1221 			}
   1222 		}
   1223 	else
   1224 		{
   1225 		s->session->sess_cert=ssl_sess_cert_new();
   1226 		}
   1227 
   1228 	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   1229 	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   1230 	EVP_MD_CTX_init(&md_ctx);
   1231 
   1232 	if (alg_a & SSL_aPSK)
   1233 		{
   1234 		CBS psk_identity_hint;
   1235 
   1236 		/* Each of the PSK key exchanges begins with a
   1237 		 * psk_identity_hint. */
   1238 		if (!CBS_get_u16_length_prefixed(&server_key_exchange, &psk_identity_hint))
   1239 			{
   1240 			al = SSL_AD_DECODE_ERROR;
   1241 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1242 			goto f_err;
   1243 			}
   1244 
   1245 		/* Store PSK identity hint for later use, hint is used in
   1246 		 * ssl3_send_client_key_exchange.  Assume that the maximum
   1247 		 * length of a PSK identity hint can be as long as the maximum
   1248 		 * length of a PSK identity. Also do not allow NULL
   1249 		 * characters; identities are saved as C strings.
   1250 		 *
   1251 		 * TODO(davidben): Should invalid hints be ignored? It's a hint
   1252 		 * rather than a specific identity. */
   1253 		if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
   1254 			CBS_contains_zero_byte(&psk_identity_hint))
   1255 			{
   1256 			al = SSL_AD_HANDSHAKE_FAILURE;
   1257 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
   1258 			goto f_err;
   1259 			}
   1260 
   1261 		/* Save the identity hint as a C string. */
   1262 		if (!CBS_strdup(&psk_identity_hint, &s->session->psk_identity_hint))
   1263 			{
   1264 			al = SSL_AD_HANDSHAKE_FAILURE;
   1265 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
   1266 			goto f_err;
   1267 			}
   1268 		}
   1269 
   1270 	if (alg_k & SSL_kRSA)
   1271 		{
   1272 		CBS rsa_modulus, rsa_exponent;
   1273 
   1274 		/* TODO(davidben): This was originally for export
   1275 		 * reasons. Do we still need to support it? */
   1276 
   1277 		if (!CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_modulus) ||
   1278 			CBS_len(&rsa_modulus) == 0 ||
   1279 			!CBS_get_u16_length_prefixed(&server_key_exchange, &rsa_exponent) ||
   1280 			CBS_len(&rsa_exponent) == 0)
   1281 			{
   1282 			al = SSL_AD_DECODE_ERROR;
   1283 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1284 			goto f_err;
   1285 			}
   1286 
   1287 		if ((rsa=RSA_new()) == NULL)
   1288 			{
   1289 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
   1290 			goto err;
   1291 			}
   1292 
   1293 		if (!(rsa->n = BN_bin2bn(CBS_data(&rsa_modulus),
   1294 					CBS_len(&rsa_modulus), rsa->n)))
   1295 			{
   1296 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1297 			goto err;
   1298 			}
   1299 
   1300 		if (!(rsa->e = BN_bin2bn(CBS_data(&rsa_exponent),
   1301 					CBS_len(&rsa_exponent), rsa->e)))
   1302 			{
   1303 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1304 			goto err;
   1305 			}
   1306 
   1307 		/* this should be because we are using an export cipher */
   1308 		if (alg_a & SSL_aRSA)
   1309 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1310 		else
   1311 			{
   1312 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
   1313 			goto err;
   1314 			}
   1315 		s->session->sess_cert->peer_rsa_tmp=rsa;
   1316 		rsa=NULL;
   1317 		}
   1318 	else if (alg_k & SSL_kEDH)
   1319 		{
   1320 		CBS dh_p, dh_g, dh_Ys;
   1321 
   1322 		if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
   1323 			CBS_len(&dh_p) == 0 ||
   1324 			!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
   1325 			CBS_len(&dh_g) == 0 ||
   1326 			!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
   1327 			CBS_len(&dh_Ys) == 0)
   1328 			{
   1329 			al = SSL_AD_DECODE_ERROR;
   1330 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1331 			goto f_err;
   1332 			}
   1333 
   1334 		if ((dh=DH_new()) == NULL)
   1335 			{
   1336 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_DH_LIB);
   1337 			goto err;
   1338 			}
   1339 
   1340 		if (!(dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)))
   1341 			{
   1342 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1343 			goto err;
   1344 			}
   1345 		if (!(dh->g=BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)))
   1346 			{
   1347 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1348 			goto err;
   1349 			}
   1350 		if (!(dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)))
   1351 			{
   1352 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_BN_LIB);
   1353 			goto err;
   1354 			}
   1355 
   1356 		if (DH_size(dh) < 512/8)
   1357 			{
   1358 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_DH_P_LENGTH);
   1359 			goto err;
   1360 			}
   1361 
   1362 		if (alg_a & SSL_aRSA)
   1363 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1364 		/* else anonymous DH, so no certificate or pkey. */
   1365 
   1366 		s->session->sess_cert->peer_dh_tmp=dh;
   1367 		dh=NULL;
   1368 		}
   1369 
   1370 	else if (alg_k & SSL_kEECDH)
   1371 		{
   1372 		uint16_t curve_id;
   1373 		int curve_nid = 0;
   1374 		EC_GROUP *ngroup;
   1375 		const EC_GROUP *group;
   1376 		CBS point;
   1377 
   1378 		/* Extract elliptic curve parameters and the server's
   1379 		 * ephemeral ECDH public key.  Check curve is one of
   1380 		 * our preferences, if not server has sent an invalid
   1381 		 * curve.
   1382 		 */
   1383 		if (!tls1_check_curve(s, &server_key_exchange, &curve_id))
   1384 			{
   1385 			al = SSL_AD_DECODE_ERROR;
   1386 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_WRONG_CURVE);
   1387 			goto f_err;
   1388 			}
   1389 
   1390 		if ((curve_nid = tls1_ec_curve_id2nid(curve_id)) == 0)
   1391 			{
   1392 			al=SSL_AD_INTERNAL_ERROR;
   1393 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
   1394 			goto f_err;
   1395 			}
   1396 
   1397 		if ((ecdh=EC_KEY_new()) == NULL)
   1398 			{
   1399 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
   1400 			goto err;
   1401 			}
   1402 		ngroup = EC_GROUP_new_by_curve_name(curve_nid);
   1403 		if (ngroup == NULL)
   1404 			{
   1405 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
   1406 			goto err;
   1407 			}
   1408 		if (EC_KEY_set_group(ecdh, ngroup) == 0)
   1409 			{
   1410 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_EC_LIB);
   1411 			goto err;
   1412 			}
   1413 		EC_GROUP_free(ngroup);
   1414 
   1415 		group = EC_KEY_get0_group(ecdh);
   1416 
   1417 		/* Next, get the encoded ECPoint */
   1418 		if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point))
   1419 			{
   1420 			al = SSL_AD_DECODE_ERROR;
   1421 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1422 			goto f_err;
   1423 			}
   1424 
   1425 		if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
   1426 		    ((bn_ctx = BN_CTX_new()) == NULL))
   1427 			{
   1428 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_MALLOC_FAILURE);
   1429 			goto err;
   1430 			}
   1431 
   1432 		if (!EC_POINT_oct2point(group, srvr_ecpoint,
   1433 				CBS_data(&point), CBS_len(&point), bn_ctx))
   1434 			{
   1435 			al = SSL_AD_DECODE_ERROR;
   1436 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_ECPOINT);
   1437 			goto f_err;
   1438 			}
   1439 
   1440 		/* The ECC/TLS specification does not mention
   1441 		 * the use of DSA to sign ECParameters in the server
   1442 		 * key exchange message. We do support RSA and ECDSA.
   1443 		 */
   1444 		if (0) ;
   1445 		else if (alg_a & SSL_aRSA)
   1446 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1447 		else if (alg_a & SSL_aECDSA)
   1448 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
   1449 		/* else anonymous ECDH, so no certificate or pkey. */
   1450 		EC_KEY_set_public_key(ecdh, srvr_ecpoint);
   1451 		s->session->sess_cert->peer_ecdh_tmp=ecdh;
   1452 		ecdh=NULL;
   1453 		BN_CTX_free(bn_ctx);
   1454 		bn_ctx = NULL;
   1455 		EC_POINT_free(srvr_ecpoint);
   1456 		srvr_ecpoint = NULL;
   1457 		}
   1458 
   1459 	else if (!(alg_k & SSL_kPSK))
   1460 		{
   1461 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1462 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
   1463 		goto f_err;
   1464 		}
   1465 
   1466 	/* At this point, |server_key_exchange| contains the
   1467 	 * signature, if any, while |server_key_exchange_orig|
   1468 	 * contains the entire message. From that, derive a CBS
   1469 	 * containing just the parameter. */
   1470 	CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
   1471 		CBS_len(&server_key_exchange_orig) -
   1472 		CBS_len(&server_key_exchange));
   1473 
   1474 	/* if it was signed, check the signature */
   1475 	if (pkey != NULL)
   1476 		{
   1477 		CBS signature;
   1478 
   1479 		if (SSL_USE_SIGALGS(s))
   1480 			{
   1481 			if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey))
   1482 				goto f_err;
   1483 			}
   1484 		else
   1485 			md = EVP_sha1();
   1486 
   1487 		/* The last field in |server_key_exchange| is the
   1488 		 * signature. */
   1489 		if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
   1490 			CBS_len(&server_key_exchange) != 0)
   1491 			{
   1492 			al = SSL_AD_DECODE_ERROR;
   1493 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_DECODE_ERROR);
   1494 			goto f_err;
   1495 			}
   1496 
   1497 		if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
   1498 			{
   1499 			int num;
   1500 			unsigned char *q, md_buf[EVP_MAX_MD_SIZE*2];
   1501 			size_t md_len = 0;
   1502 
   1503 			q=md_buf;
   1504 			for (num=2; num > 0; num--)
   1505 				{
   1506 				unsigned int digest_len;
   1507 				EVP_DigestInit_ex(&md_ctx,
   1508 					(num == 2) ? EVP_md5() : EVP_sha1(), NULL);
   1509 				EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
   1510 				EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
   1511 				EVP_DigestUpdate(&md_ctx, CBS_data(&parameter), CBS_len(&parameter));
   1512 				EVP_DigestFinal_ex(&md_ctx, q, &digest_len);
   1513 				q += digest_len;
   1514 				md_len += digest_len;
   1515 				}
   1516 			if (!RSA_verify(NID_md5_sha1, md_buf, md_len,
   1517 					CBS_data(&signature), CBS_len(&signature),
   1518 					pkey->pkey.rsa))
   1519 				{
   1520 				al = SSL_AD_DECRYPT_ERROR;
   1521 				OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
   1522 				goto f_err;
   1523 				}
   1524 			}
   1525 		else
   1526 			{
   1527 			EVP_VerifyInit_ex(&md_ctx, md, NULL);
   1528 			EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
   1529 			EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
   1530 			EVP_VerifyUpdate(&md_ctx, CBS_data(&parameter), CBS_len(&parameter));
   1531 			if (EVP_VerifyFinal(&md_ctx, CBS_data(&signature), CBS_len(&signature), pkey) <= 0)
   1532 				{
   1533 				/* bad signature */
   1534 				al=SSL_AD_DECRYPT_ERROR;
   1535 				OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_BAD_SIGNATURE);
   1536 				goto f_err;
   1537 				}
   1538 			}
   1539 		}
   1540 	else
   1541 		{
   1542 		if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
   1543 			{
   1544 			/* Might be wrong key type, check it */
   1545 			if (ssl3_check_cert_and_algorithm(s))
   1546 				/* Otherwise this shouldn't happen */
   1547 				OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, ERR_R_INTERNAL_ERROR);
   1548 			goto err;
   1549 			}
   1550 		/* still data left over */
   1551 		if (CBS_len(&server_key_exchange) > 0)
   1552 			{
   1553 			al=SSL_AD_DECODE_ERROR;
   1554 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_key_exchange, SSL_R_EXTRA_DATA_IN_MESSAGE);
   1555 			goto f_err;
   1556 			}
   1557 		}
   1558 	EVP_PKEY_free(pkey);
   1559 	EVP_MD_CTX_cleanup(&md_ctx);
   1560 	return(1);
   1561 f_err:
   1562 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1563 err:
   1564 	EVP_PKEY_free(pkey);
   1565 	if (rsa != NULL)
   1566 		RSA_free(rsa);
   1567 	if (dh != NULL)
   1568 		DH_free(dh);
   1569 	BN_CTX_free(bn_ctx);
   1570 	EC_POINT_free(srvr_ecpoint);
   1571 	if (ecdh != NULL)
   1572 		EC_KEY_free(ecdh);
   1573 	EVP_MD_CTX_cleanup(&md_ctx);
   1574 	return(-1);
   1575 	}
   1576 
   1577 static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b)
   1578 	{
   1579 	return(X509_NAME_cmp(*a,*b));
   1580 	}
   1581 
   1582 int ssl3_get_certificate_request(SSL *s)
   1583 	{
   1584 	int ok,ret=0;
   1585 	unsigned long n;
   1586 	unsigned int i;
   1587 	X509_NAME *xn=NULL;
   1588 	STACK_OF(X509_NAME) *ca_sk=NULL;
   1589 	CBS cbs;
   1590 	CBS certificate_types;
   1591 	CBS certificate_authorities;
   1592 	const uint8_t *data;
   1593 
   1594 	n=s->method->ssl_get_message(s,
   1595 		SSL3_ST_CR_CERT_REQ_A,
   1596 		SSL3_ST_CR_CERT_REQ_B,
   1597 		-1,
   1598 		s->max_cert_list,
   1599 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1600 		&ok);
   1601 
   1602 	if (!ok) return((int)n);
   1603 
   1604 	s->s3->tmp.cert_req=0;
   1605 
   1606 	if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
   1607 		{
   1608 		s->s3->tmp.reuse_message=1;
   1609 		/* If we get here we don't need any cached handshake records
   1610 		 * as we wont be doing client auth.
   1611 		 */
   1612 		if (s->s3->handshake_buffer)
   1613 			{
   1614 			if (!ssl3_digest_cached_records(s))
   1615 				goto err;
   1616 			}
   1617 		return(1);
   1618 		}
   1619 
   1620 	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
   1621 		{
   1622 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   1623 		OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_WRONG_MESSAGE_TYPE);
   1624 		goto err;
   1625 		}
   1626 
   1627 	/* TLS does not like anon-DH with client cert */
   1628 	if (s->version > SSL3_VERSION)
   1629 		{
   1630 		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
   1631 			{
   1632 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   1633 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
   1634 			goto err;
   1635 			}
   1636 		}
   1637 
   1638 	CBS_init(&cbs, s->init_msg, n);
   1639 
   1640 	ca_sk = sk_X509_NAME_new(ca_dn_cmp);
   1641 	if (ca_sk == NULL)
   1642 		{
   1643 		OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
   1644 		goto err;
   1645 		}
   1646 
   1647 	/* get the certificate types */
   1648 	if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types))
   1649 		{
   1650 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
   1651 		OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
   1652 		goto err;
   1653 		}
   1654 	if (!CBS_stow(&certificate_types,
   1655 			&s->s3->tmp.certificate_types,
   1656 			&s->s3->tmp.num_certificate_types))
   1657 		{
   1658 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
   1659 		goto err;
   1660 		}
   1661 	if (SSL_USE_SIGALGS(s))
   1662 		{
   1663 		CBS supported_signature_algorithms;
   1664 		if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms))
   1665 			{
   1666 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1667 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_DECODE_ERROR);
   1668 			goto err;
   1669 			}
   1670 		/* Clear certificate digests and validity flags */
   1671 		for (i = 0; i < SSL_PKEY_NUM; i++)
   1672 			{
   1673 			s->cert->pkeys[i].digest = NULL;
   1674 			s->cert->pkeys[i].valid_flags = 0;
   1675 			}
   1676 		if (!tls1_process_sigalgs(s, &supported_signature_algorithms))
   1677 			{
   1678 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1679 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
   1680 			goto err;
   1681 			}
   1682 		}
   1683 
   1684 	/* get the CA RDNs */
   1685 	if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities))
   1686 		{
   1687 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1688 		OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_LENGTH_MISMATCH);
   1689 		goto err;
   1690 		}
   1691 
   1692 	while (CBS_len(&certificate_authorities) > 0)
   1693 		{
   1694 		CBS distinguished_name;
   1695 		if (!CBS_get_u16_length_prefixed(&certificate_authorities, &distinguished_name))
   1696 			{
   1697 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1698 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_TOO_LONG);
   1699 			goto err;
   1700 			}
   1701 
   1702 		data = CBS_data(&distinguished_name);
   1703 		if ((xn=d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name))) == NULL)
   1704 			{
   1705 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1706 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_ASN1_LIB);
   1707 			goto err;
   1708 			}
   1709 
   1710 		if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name)))
   1711 			{
   1712 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1713 			OPENSSL_PUT_ERROR(SSL, ssl3_get_server_certificate, ERR_R_INTERNAL_ERROR);
   1714 			goto err;
   1715 			}
   1716 		if (CBS_len(&distinguished_name) != 0)
   1717 			{
   1718 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1719 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, SSL_R_CA_DN_LENGTH_MISMATCH);
   1720 			goto err;
   1721 			}
   1722 		if (!sk_X509_NAME_push(ca_sk,xn))
   1723 			{
   1724 			OPENSSL_PUT_ERROR(SSL, ssl3_get_certificate_request, ERR_R_MALLOC_FAILURE);
   1725 			goto err;
   1726 			}
   1727 		}
   1728 
   1729 	/* we should setup a certificate to return.... */
   1730 	s->s3->tmp.cert_req=1;
   1731 	if (s->s3->tmp.ca_names != NULL)
   1732 		sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
   1733 	s->s3->tmp.ca_names=ca_sk;
   1734 	ca_sk=NULL;
   1735 
   1736 	ret=1;
   1737 err:
   1738 	if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
   1739 	return(ret);
   1740 	}
   1741 
   1742 int ssl3_get_new_session_ticket(SSL *s)
   1743 	{
   1744 	int ok,al,ret=0;
   1745 	long n;
   1746 	CBS new_session_ticket, ticket;
   1747 
   1748 	n=s->method->ssl_get_message(s,
   1749 		SSL3_ST_CR_SESSION_TICKET_A,
   1750 		SSL3_ST_CR_SESSION_TICKET_B,
   1751 		SSL3_MT_NEWSESSION_TICKET,
   1752 		16384,
   1753 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1754 		&ok);
   1755 
   1756 	if (!ok)
   1757 		return((int)n);
   1758 
   1759 	CBS_init(&new_session_ticket, s->init_msg, n);
   1760 
   1761 	if (!CBS_get_u32(&new_session_ticket, &s->session->tlsext_tick_lifetime_hint) ||
   1762 		!CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
   1763 		CBS_len(&new_session_ticket) != 0)
   1764 		{
   1765 		al = SSL_AD_DECODE_ERROR;
   1766 		OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, SSL_R_DECODE_ERROR);
   1767 		goto f_err;
   1768 		}
   1769 
   1770 	if (!CBS_stow(&ticket, &s->session->tlsext_tick, &s->session->tlsext_ticklen))
   1771 		{
   1772 		OPENSSL_PUT_ERROR(SSL, ssl3_get_new_session_ticket, ERR_R_MALLOC_FAILURE);
   1773 		goto err;
   1774 		}
   1775 
   1776 	/* There are two ways to detect a resumed ticket sesion.
   1777 	 * One is to set an appropriate session ID and then the server
   1778 	 * must return a match in ServerHello. This allows the normal
   1779 	 * client session ID matching to work and we know much
   1780 	 * earlier that the ticket has been accepted.
   1781 	 *
   1782 	 * The other way is to set zero length session ID when the
   1783 	 * ticket is presented and rely on the handshake to determine
   1784 	 * session resumption.
   1785 	 *
   1786 	 * We choose the former approach because this fits in with
   1787 	 * assumptions elsewhere in OpenSSL. The session ID is set
   1788 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
   1789 	 * ticket.
   1790 	 */
   1791 	EVP_Digest(CBS_data(&ticket), CBS_len(&ticket),
   1792 			s->session->session_id, &s->session->session_id_length,
   1793 							EVP_sha256(), NULL);
   1794 	ret=1;
   1795 	return(ret);
   1796 f_err:
   1797 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1798 err:
   1799 	return(-1);
   1800 	}
   1801 
   1802 int ssl3_get_cert_status(SSL *s)
   1803 	{
   1804 	int ok, al;
   1805 	long n;
   1806 	CBS certificate_status, ocsp_response;
   1807 	uint8_t status_type;
   1808 
   1809 	n=s->method->ssl_get_message(s,
   1810 		SSL3_ST_CR_CERT_STATUS_A,
   1811 		SSL3_ST_CR_CERT_STATUS_B,
   1812 		SSL3_MT_CERTIFICATE_STATUS,
   1813 		16384,
   1814 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1815 		&ok);
   1816 
   1817 	if (!ok) return((int)n);
   1818 
   1819 	CBS_init(&certificate_status, s->init_msg, n);
   1820 	if (!CBS_get_u8(&certificate_status, &status_type) ||
   1821 		status_type != TLSEXT_STATUSTYPE_ocsp ||
   1822 		!CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
   1823 		CBS_len(&ocsp_response) == 0 ||
   1824 		CBS_len(&certificate_status) != 0)
   1825 		{
   1826 		al = SSL_AD_DECODE_ERROR;
   1827 		OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, SSL_R_DECODE_ERROR);
   1828 		goto f_err;
   1829 		}
   1830 
   1831 	if (!CBS_stow(&ocsp_response,
   1832 			&s->session->ocsp_response, &s->session->ocsp_response_length))
   1833 		{
   1834 		al = SSL_AD_INTERNAL_ERROR;
   1835 		OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_status, ERR_R_MALLOC_FAILURE);
   1836 		goto f_err;
   1837 		}
   1838 	return 1;
   1839 f_err:
   1840 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1841 	return(-1);
   1842 	}
   1843 
   1844 int ssl3_get_server_done(SSL *s)
   1845 	{
   1846 	int ok,ret=0;
   1847 	long n;
   1848 
   1849 	n=s->method->ssl_get_message(s,
   1850 		SSL3_ST_CR_SRVR_DONE_A,
   1851 		SSL3_ST_CR_SRVR_DONE_B,
   1852 		SSL3_MT_SERVER_DONE,
   1853 		30, /* should be very small, like 0 :-) */
   1854 		SSL_GET_MESSAGE_HASH_MESSAGE,
   1855 		&ok);
   1856 
   1857 	if (!ok) return((int)n);
   1858 	if (n > 0)
   1859 		{
   1860 		/* should contain no data */
   1861 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   1862 		OPENSSL_PUT_ERROR(SSL, ssl3_get_server_done, SSL_R_LENGTH_MISMATCH);
   1863 		return -1;
   1864 		}
   1865 	ret=1;
   1866 	return(ret);
   1867 	}
   1868 
   1869 
   1870 int ssl3_send_client_key_exchange(SSL *s)
   1871 	{
   1872 	unsigned char *p;
   1873 	int n = 0;
   1874 	unsigned long alg_k;
   1875 	unsigned long alg_a;
   1876 	unsigned char *q;
   1877 	EVP_PKEY *pkey=NULL;
   1878 	EC_KEY *clnt_ecdh = NULL;
   1879 	const EC_POINT *srvr_ecpoint = NULL;
   1880 	EVP_PKEY *srvr_pub_pkey = NULL;
   1881 	unsigned char *encodedPoint = NULL;
   1882 	int encoded_pt_len = 0;
   1883 	BN_CTX * bn_ctx = NULL;
   1884 	unsigned int psk_len = 0;
   1885 	unsigned char psk[PSK_MAX_PSK_LEN];
   1886 
   1887 	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
   1888 		{
   1889 		p = ssl_handshake_start(s);
   1890 
   1891 		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   1892 		alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   1893 
   1894 		if (alg_a & SSL_aPSK)
   1895 			{
   1896 			char identity[PSK_MAX_IDENTITY_LEN + 1];
   1897 			size_t identity_len;
   1898 			unsigned char *t = NULL;
   1899 			unsigned char pre_ms[PSK_MAX_PSK_LEN*2+4];
   1900 			unsigned int pre_ms_len = 0;
   1901 			int psk_err = 1;
   1902 
   1903 			n = 0;
   1904 			if (s->psk_client_callback == NULL)
   1905 				{
   1906 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_NO_CLIENT_CB);
   1907 				goto err;
   1908 				}
   1909 
   1910 			memset(identity, 0, sizeof(identity));
   1911 			psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
   1912 				identity, sizeof(identity), psk, sizeof(psk));
   1913 			if (psk_len > PSK_MAX_PSK_LEN)
   1914 				{
   1915 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   1916 				goto psk_err;
   1917 				}
   1918 			else if (psk_len == 0)
   1919 				{
   1920 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
   1921 				goto psk_err;
   1922 				}
   1923 			identity_len = OPENSSL_strnlen(identity, sizeof(identity));
   1924 			if (identity_len > PSK_MAX_IDENTITY_LEN)
   1925 				{
   1926 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   1927 				goto psk_err;
   1928 				}
   1929 
   1930 			if (!(alg_k & SSL_kEECDH))
   1931 				{
   1932 				/* Create the shared secret now if we're not using ECDHE-PSK.
   1933 				 * TODO(davidben): Refactor this logic similarly
   1934 				 * to ssl3_get_client_key_exchange. */
   1935 				pre_ms_len = 2+psk_len+2+psk_len;
   1936 				t = pre_ms;
   1937 				s2n(psk_len, t);
   1938 				memset(t, 0, psk_len);
   1939 				t+=psk_len;
   1940 				s2n(psk_len, t);
   1941 				memcpy(t, psk, psk_len);
   1942 
   1943 				s->session->master_key_length =
   1944 					s->method->ssl3_enc->generate_master_secret(s,
   1945 						s->session->master_key,
   1946 						pre_ms, pre_ms_len);
   1947 				s2n(identity_len, p);
   1948 				memcpy(p, identity, identity_len);
   1949 				n = 2 + identity_len;
   1950 				}
   1951 
   1952 			if (s->session->psk_identity != NULL)
   1953 				OPENSSL_free(s->session->psk_identity);
   1954 			s->session->psk_identity = BUF_strdup(identity);
   1955 			if (s->session->psk_identity == NULL)
   1956 				{
   1957 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
   1958 				goto psk_err;
   1959 				}
   1960 			psk_err = 0;
   1961 		psk_err:
   1962 			OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
   1963 			OPENSSL_cleanse(pre_ms, sizeof(pre_ms));
   1964 			if (psk_err != 0)
   1965 				{
   1966 				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1967 				goto err;
   1968 				}
   1969 			}
   1970 
   1971 		if (alg_k & SSL_kRSA)
   1972 			{
   1973 			RSA *rsa;
   1974 			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
   1975 
   1976 			if (s->session->sess_cert == NULL)
   1977 				{
   1978 				/* We should always have a server certificate with SSL_kRSA. */
   1979 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   1980 				goto err;
   1981 				}
   1982 
   1983 			if (s->session->sess_cert->peer_rsa_tmp != NULL)
   1984 				rsa=s->session->sess_cert->peer_rsa_tmp;
   1985 			else
   1986 				{
   1987 				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1988 				if ((pkey == NULL) ||
   1989 					(pkey->type != EVP_PKEY_RSA) ||
   1990 					(pkey->pkey.rsa == NULL))
   1991 					{
   1992 					OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   1993 					goto err;
   1994 					}
   1995 				rsa=pkey->pkey.rsa;
   1996 				EVP_PKEY_free(pkey);
   1997 				}
   1998 
   1999 			tmp_buf[0]=s->client_version>>8;
   2000 			tmp_buf[1]=s->client_version&0xff;
   2001 			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
   2002 					goto err;
   2003 
   2004 			s->session->master_key_length=sizeof tmp_buf;
   2005 
   2006 			q=p;
   2007 			/* Fix buf for TLS and beyond */
   2008 			if (s->version > SSL3_VERSION)
   2009 				p+=2;
   2010 			n=RSA_public_encrypt(sizeof tmp_buf,
   2011 				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
   2012 			if (n <= 0)
   2013 				{
   2014 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_BAD_RSA_ENCRYPT);
   2015 				goto err;
   2016 				}
   2017 
   2018 			/* Log the premaster secret, if logging is enabled. */
   2019 			if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx,
   2020 					p, n, tmp_buf, sizeof(tmp_buf)))
   2021 				{
   2022 				goto err;
   2023 				}
   2024 
   2025 			/* Fix buf for TLS and beyond */
   2026 			if (s->version > SSL3_VERSION)
   2027 				{
   2028 				s2n(n,q);
   2029 				n+=2;
   2030 				}
   2031 
   2032 			s->session->master_key_length=
   2033 				s->method->ssl3_enc->generate_master_secret(s,
   2034 					s->session->master_key,
   2035 					tmp_buf,sizeof tmp_buf);
   2036 			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
   2037 			}
   2038 		else if (alg_k & SSL_kEDH)
   2039 			{
   2040 			DH *dh_srvr,*dh_clnt;
   2041 			SESS_CERT *scert = s->session->sess_cert;
   2042 
   2043 			if (scert == NULL)
   2044 				{
   2045 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   2046 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
   2047 				goto err;
   2048 				}
   2049 
   2050 			if (scert->peer_dh_tmp == NULL)
   2051 				{
   2052 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   2053 				goto err;
   2054 				}
   2055 			dh_srvr=scert->peer_dh_tmp;
   2056 
   2057 			/* generate a new random key */
   2058 			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
   2059 				{
   2060 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   2061 				goto err;
   2062 				}
   2063 			if (!DH_generate_key(dh_clnt))
   2064 				{
   2065 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   2066 				DH_free(dh_clnt);
   2067 				goto err;
   2068 				}
   2069 
   2070 			/* use the 'p' output buffer for the DH key, but
   2071 			 * make sure to clear it out afterwards */
   2072 
   2073 			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
   2074 			if (n <= 0)
   2075 				{
   2076 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_DH_LIB);
   2077 				DH_free(dh_clnt);
   2078 				goto err;
   2079 				}
   2080 
   2081 			/* generate master key from the result */
   2082 			s->session->master_key_length=
   2083 				s->method->ssl3_enc->generate_master_secret(s,
   2084 					s->session->master_key,p,n);
   2085 			/* clean up */
   2086 			memset(p,0,n);
   2087 
   2088 			/* send off the data */
   2089 			n=BN_num_bytes(dh_clnt->pub_key);
   2090 			s2n(n,p);
   2091 			BN_bn2bin(dh_clnt->pub_key,p);
   2092 			n+=2;
   2093 
   2094 			DH_free(dh_clnt);
   2095 
   2096 			/* perhaps clean things up a bit EAY EAY EAY EAY*/
   2097 			}
   2098 
   2099 		else if (alg_k & SSL_kEECDH)
   2100 			{
   2101 			const EC_GROUP *srvr_group = NULL;
   2102 			EC_KEY *tkey;
   2103 			int field_size = 0;
   2104 			unsigned char *pre_ms;
   2105 			unsigned char *t;
   2106 			unsigned int pre_ms_len;
   2107 			unsigned int i;
   2108 
   2109 			if (s->session->sess_cert == NULL)
   2110 				{
   2111 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   2112 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, SSL_R_UNEXPECTED_MESSAGE);
   2113 				goto err;
   2114 				}
   2115 
   2116 			if (s->session->sess_cert->peer_ecdh_tmp == NULL)
   2117 				{
   2118 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   2119 				goto err;
   2120 				}
   2121 			tkey = s->session->sess_cert->peer_ecdh_tmp;
   2122 
   2123 			srvr_group   = EC_KEY_get0_group(tkey);
   2124 			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
   2125 
   2126 			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
   2127 				{
   2128 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   2129 				goto err;
   2130 				}
   2131 
   2132 			if ((clnt_ecdh=EC_KEY_new()) == NULL)
   2133 				{
   2134 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
   2135 				goto err;
   2136 				}
   2137 
   2138 			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
   2139 				{
   2140 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_EC_LIB);
   2141 				goto err;
   2142 				}
   2143 			/* Generate a new ECDH key pair */
   2144 			if (!(EC_KEY_generate_key(clnt_ecdh)))
   2145 				{
   2146 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   2147 				goto err;
   2148 				}
   2149 
   2150 			/* use the 'p' output buffer for the ECDH key, but
   2151 			 * make sure to clear it out afterwards
   2152 			 */
   2153 
   2154 			field_size = EC_GROUP_get_degree(srvr_group);
   2155 			if (field_size <= 0)
   2156 				{
   2157 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   2158 				goto err;
   2159 				}
   2160 			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
   2161 			if (n <= 0)
   2162 				{
   2163 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_ECDH_LIB);
   2164 				goto err;
   2165 				}
   2166 
   2167 			/* ECDHE PSK ciphersuites from RFC 5489 */
   2168 			if ((alg_a & SSL_aPSK) && psk_len != 0)
   2169 				{
   2170 				pre_ms_len = 2+psk_len+2+n;
   2171 				pre_ms = OPENSSL_malloc(pre_ms_len);
   2172 				if (pre_ms == NULL)
   2173 					{
   2174 					OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
   2175 					goto err;
   2176 					}
   2177 				memset(pre_ms, 0, pre_ms_len);
   2178 				t = pre_ms;
   2179 				s2n(psk_len, t);
   2180 				memcpy(t, psk, psk_len);
   2181 				t += psk_len;
   2182 				s2n(n, t);
   2183 				memcpy(t, p, n);
   2184 				s->session->master_key_length = s->method->ssl3_enc \
   2185 					-> generate_master_secret(s,
   2186 						s->session->master_key, pre_ms, pre_ms_len);
   2187 				OPENSSL_cleanse(pre_ms, pre_ms_len);
   2188 				OPENSSL_free(pre_ms);
   2189 				}
   2190 			if (!(alg_a & SSL_aPSK))
   2191 				{
   2192 				/* generate master key from the result */
   2193 				s->session->master_key_length = s->method->ssl3_enc \
   2194 					-> generate_master_secret(s,
   2195 						s->session->master_key, p, n);
   2196 				}
   2197 			memset(p, 0, n); /* clean up */
   2198 
   2199 			/* First check the size of encoding and
   2200 			 * allocate memory accordingly.
   2201 			 */
   2202 			encoded_pt_len =
   2203 				EC_POINT_point2oct(srvr_group,
   2204 					EC_KEY_get0_public_key(clnt_ecdh),
   2205 					POINT_CONVERSION_UNCOMPRESSED,
   2206 					NULL, 0, NULL);
   2207 
   2208 			encodedPoint = (unsigned char *)
   2209 				OPENSSL_malloc(encoded_pt_len *
   2210 					sizeof(unsigned char));
   2211 			bn_ctx = BN_CTX_new();
   2212 			if ((encodedPoint == NULL) ||
   2213 				(bn_ctx == NULL))
   2214 				{
   2215 				OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_MALLOC_FAILURE);
   2216 				goto err;
   2217 				}
   2218 
   2219 			/* Encode the public key */
   2220 			encoded_pt_len = EC_POINT_point2oct(srvr_group,
   2221 				EC_KEY_get0_public_key(clnt_ecdh),
   2222 				POINT_CONVERSION_UNCOMPRESSED,
   2223 				encodedPoint, encoded_pt_len, bn_ctx);
   2224 
   2225 			n = 0;
   2226 			if ((alg_a & SSL_aPSK) && psk_len != 0)
   2227 				{
   2228 				i = strlen(s->session->psk_identity);
   2229 				s2n(i, p);
   2230 				memcpy(p, s->session->psk_identity, i);
   2231 				p += i;
   2232 				n = i + 2;
   2233 				}
   2234 
   2235 			*p = encoded_pt_len; /* length of encoded point */
   2236 			/* Encoded point will be copied here */
   2237 			p += 1;
   2238 			n += 1;
   2239 			/* copy the point */
   2240 			memcpy((unsigned char *)p, encodedPoint, encoded_pt_len);
   2241 			/* increment n to account for length field */
   2242 			n += encoded_pt_len;
   2243 
   2244 			/* Free allocated memory */
   2245 			BN_CTX_free(bn_ctx);
   2246 			OPENSSL_free(encodedPoint);
   2247 			EC_KEY_free(clnt_ecdh);
   2248 			EVP_PKEY_free(srvr_pub_pkey);
   2249 			}
   2250 		else if (!(alg_k & SSL_kPSK) || ((alg_k & SSL_kPSK) && !(alg_a & SSL_aPSK)))
   2251 			{
   2252 			ssl3_send_alert(s, SSL3_AL_FATAL,
   2253 			    SSL_AD_HANDSHAKE_FAILURE);
   2254 			OPENSSL_PUT_ERROR(SSL, ssl3_send_client_key_exchange, ERR_R_INTERNAL_ERROR);
   2255 			goto err;
   2256 			}
   2257 
   2258 		ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n);
   2259 		s->state=SSL3_ST_CW_KEY_EXCH_B;
   2260 		}
   2261 
   2262 	/* SSL3_ST_CW_KEY_EXCH_B */
   2263 	return ssl_do_write(s);
   2264 err:
   2265 	BN_CTX_free(bn_ctx);
   2266 	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
   2267 	if (clnt_ecdh != NULL)
   2268 		EC_KEY_free(clnt_ecdh);
   2269 	EVP_PKEY_free(srvr_pub_pkey);
   2270 	return(-1);
   2271 	}
   2272 
   2273 int ssl3_send_cert_verify(SSL *s)
   2274 	{
   2275 	unsigned char *buf, *p;
   2276 	const EVP_MD *md = NULL;
   2277 	uint8_t digest[EVP_MAX_MD_SIZE];
   2278 	size_t digest_length;
   2279 	EVP_PKEY *pkey;
   2280 	EVP_PKEY_CTX *pctx = NULL;
   2281 	size_t signature_length = 0;
   2282 	unsigned long n = 0;
   2283 
   2284 	buf=(unsigned char *)s->init_buf->data;
   2285 
   2286 	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
   2287 		{
   2288 		p= ssl_handshake_start(s);
   2289 		pkey = s->cert->key->privatekey;
   2290 
   2291 		/* Write out the digest type if needbe. */
   2292 		if (SSL_USE_SIGALGS(s))
   2293 			{
   2294 			md = s->cert->key->digest;
   2295 			if (!tls12_get_sigandhash(p, pkey, md))
   2296 				{
   2297 				OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_INTERNAL_ERROR);
   2298 				goto err;
   2299 				}
   2300 			p += 2;
   2301 			n += 2;
   2302 			}
   2303 
   2304 		/* Compute the digest. */
   2305 		if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
   2306 			goto err;
   2307 
   2308 		/* The handshake buffer is no longer necessary. */
   2309 		if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
   2310 			goto err;
   2311 
   2312 		/* Sign the digest. */
   2313 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
   2314 		if (pctx == NULL)
   2315 			goto err;
   2316 
   2317 		/* Initialize the EVP_PKEY_CTX and determine the size of the signature. */
   2318 		if (!EVP_PKEY_sign_init(pctx) ||
   2319 			!EVP_PKEY_CTX_set_signature_md(pctx, md) ||
   2320 			!EVP_PKEY_sign(pctx, NULL, &signature_length,
   2321 				digest, digest_length))
   2322 			{
   2323 			OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
   2324 			goto err;
   2325 			}
   2326 
   2327 		if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH)
   2328 			{
   2329 			OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, SSL_R_DATA_LENGTH_TOO_LONG);
   2330 			goto err;
   2331 			}
   2332 
   2333 		if (!EVP_PKEY_sign(pctx, &p[2], &signature_length,
   2334 				digest, digest_length))
   2335 			{
   2336 			OPENSSL_PUT_ERROR(SSL, ssl3_send_cert_verify, ERR_R_EVP_LIB);
   2337 			goto err;
   2338 			}
   2339 
   2340 		s2n(signature_length, p);
   2341 		n += signature_length + 2;
   2342 
   2343 		ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n);
   2344 		s->state=SSL3_ST_CW_CERT_VRFY_B;
   2345 		}
   2346 	EVP_PKEY_CTX_free(pctx);
   2347 	return ssl_do_write(s);
   2348 err:
   2349 	EVP_PKEY_CTX_free(pctx);
   2350 	return(-1);
   2351 	}
   2352 
   2353 /* Check a certificate can be used for client authentication. Currently
   2354  * check the cert exists and if we have a suitable digest for TLS 1.2.
   2355  */
   2356 static int ssl3_check_client_certificate(SSL *s)
   2357 	{
   2358 	if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey)
   2359 		return 0;
   2360 	/* If no suitable signature algorithm can't use certificate */
   2361 	if (SSL_USE_SIGALGS(s) && !s->cert->key->digest)
   2362 		return 0;
   2363 	/* If strict mode check suitability of chain before using it.
   2364 	 */
   2365 	if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
   2366 		!tls1_check_chain(s, NULL, NULL, NULL, -2))
   2367 		return 0;
   2368 	return 1;
   2369 	}
   2370 
   2371 int ssl3_send_client_certificate(SSL *s)
   2372 	{
   2373 	X509 *x509=NULL;
   2374 	EVP_PKEY *pkey=NULL;
   2375 	int i;
   2376 
   2377 	if (s->state ==	SSL3_ST_CW_CERT_A)
   2378 		{
   2379 		/* Let cert callback update client certificates if required */
   2380 		if (s->cert->cert_cb)
   2381 			{
   2382 			i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
   2383 			if (i < 0)
   2384 				{
   2385 				s->rwstate=SSL_X509_LOOKUP;
   2386 				return -1;
   2387 				}
   2388 			if (i == 0)
   2389 				{
   2390 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
   2391 				return 0;
   2392 				}
   2393 			s->rwstate=SSL_NOTHING;
   2394 			}
   2395 		if (ssl3_check_client_certificate(s))
   2396 			s->state=SSL3_ST_CW_CERT_C;
   2397 		else
   2398 			s->state=SSL3_ST_CW_CERT_B;
   2399 		}
   2400 
   2401 	/* We need to get a client cert */
   2402 	if (s->state == SSL3_ST_CW_CERT_B)
   2403 		{
   2404 		/* If we get an error, we need to
   2405 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
   2406 		 * We then get retried later */
   2407 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
   2408 		if (i < 0)
   2409 			{
   2410 			s->rwstate=SSL_X509_LOOKUP;
   2411 			return(-1);
   2412 			}
   2413 		s->rwstate=SSL_NOTHING;
   2414 		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
   2415 			{
   2416 			s->state=SSL3_ST_CW_CERT_B;
   2417 			if (	!SSL_use_certificate(s,x509) ||
   2418 				!SSL_use_PrivateKey(s,pkey))
   2419 				i=0;
   2420 			}
   2421 		else if (i == 1)
   2422 			{
   2423 			i=0;
   2424 			OPENSSL_PUT_ERROR(SSL, ssl3_send_client_certificate, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
   2425 			}
   2426 
   2427 		if (x509 != NULL) X509_free(x509);
   2428 		if (pkey != NULL) EVP_PKEY_free(pkey);
   2429 		if (i && !ssl3_check_client_certificate(s))
   2430 			i = 0;
   2431 		if (i == 0)
   2432 			{
   2433 			if (s->version == SSL3_VERSION)
   2434 				{
   2435 				s->s3->tmp.cert_req=0;
   2436 				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
   2437 				return(1);
   2438 				}
   2439 			else
   2440 				{
   2441 				s->s3->tmp.cert_req=2;
   2442 				}
   2443 			}
   2444 
   2445 		/* Ok, we have a cert */
   2446 		s->state=SSL3_ST_CW_CERT_C;
   2447 		}
   2448 
   2449 	if (s->state == SSL3_ST_CW_CERT_C)
   2450 		{
   2451 		s->state=SSL3_ST_CW_CERT_D;
   2452 		ssl3_output_cert_chain(s,
   2453 			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key);
   2454 		}
   2455 	/* SSL3_ST_CW_CERT_D */
   2456 	return ssl_do_write(s);
   2457 	}
   2458 
   2459 #define has_bits(i,m)	(((i)&(m)) == (m))
   2460 
   2461 int ssl3_check_cert_and_algorithm(SSL *s)
   2462 	{
   2463 	int i,idx;
   2464 	long alg_k,alg_a;
   2465 	EVP_PKEY *pkey=NULL;
   2466 	SESS_CERT *sc;
   2467 	RSA *rsa;
   2468 	DH *dh;
   2469 
   2470 	/* we don't have a certificate */
   2471 	if (!ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
   2472 		return 1;
   2473 
   2474 	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   2475 	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   2476 
   2477 	sc=s->session->sess_cert;
   2478 	if (sc == NULL)
   2479 		{
   2480 		OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, ERR_R_INTERNAL_ERROR);
   2481 		goto err;
   2482 		}
   2483 
   2484 	rsa=s->session->sess_cert->peer_rsa_tmp;
   2485 	dh=s->session->sess_cert->peer_dh_tmp;
   2486 
   2487 	/* This is the passed certificate */
   2488 
   2489 	idx=sc->peer_cert_type;
   2490 	if (idx == SSL_PKEY_ECC)
   2491 		{
   2492 		if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
   2493 		    						s) == 0)
   2494 			{ /* check failed */
   2495 			OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_BAD_ECC_CERT);
   2496 			goto f_err;
   2497 			}
   2498 		else
   2499 			{
   2500 			return 1;
   2501 			}
   2502 		}
   2503 	else if (alg_a & SSL_aECDSA)
   2504 		{
   2505 		OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_ECDSA_SIGNING_CERT);
   2506 		goto f_err;
   2507 		}
   2508 	pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
   2509 	i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
   2510 	EVP_PKEY_free(pkey);
   2511 
   2512 
   2513 	/* Check that we have a certificate if we require one */
   2514 	if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
   2515 		{
   2516 		OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_SIGNING_CERT);
   2517 		goto f_err;
   2518 		}
   2519 	if ((alg_k & SSL_kRSA) &&
   2520 		!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
   2521 		{
   2522 		OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
   2523 		goto f_err;
   2524 		}
   2525 	if ((alg_k & SSL_kEDH) &&
   2526 		!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
   2527 		{
   2528 		OPENSSL_PUT_ERROR(SSL, ssl3_check_cert_and_algorithm, SSL_R_MISSING_DH_KEY);
   2529 		goto f_err;
   2530 		}
   2531 
   2532 	return(1);
   2533 f_err:
   2534 	ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   2535 err:
   2536 	return(0);
   2537 	}
   2538 
   2539 int ssl3_send_next_proto(SSL *s)
   2540 	{
   2541 	unsigned int len, padding_len;
   2542 	unsigned char *d;
   2543 
   2544 	if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
   2545 		{
   2546 		len = s->next_proto_negotiated_len;
   2547 		padding_len = 32 - ((len + 2) % 32);
   2548 		d = (unsigned char *)s->init_buf->data;
   2549 		d[4] = len;
   2550 		memcpy(d + 5, s->next_proto_negotiated, len);
   2551 		d[5 + len] = padding_len;
   2552 		memset(d + 6 + len, 0, padding_len);
   2553 		*(d++)=SSL3_MT_NEXT_PROTO;
   2554 		l2n3(2 + len + padding_len, d);
   2555 		s->state = SSL3_ST_CW_NEXT_PROTO_B;
   2556 		s->init_num = 4 + 2 + len + padding_len;
   2557 		s->init_off = 0;
   2558 		}
   2559 
   2560 	return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   2561 }
   2562 
   2563 
   2564 int ssl3_send_channel_id(SSL *s)
   2565 	{
   2566 	unsigned char *d;
   2567 	int ret = -1, public_key_len;
   2568 	EVP_MD_CTX md_ctx;
   2569 	size_t sig_len;
   2570 	ECDSA_SIG *sig = NULL;
   2571 	unsigned char *public_key = NULL, *derp, *der_sig = NULL;
   2572 
   2573 	if (s->state != SSL3_ST_CW_CHANNEL_ID_A)
   2574 		return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   2575 
   2576 	if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb)
   2577 		{
   2578 		EVP_PKEY *key = NULL;
   2579 		s->ctx->channel_id_cb(s, &key);
   2580 		if (key != NULL)
   2581 			{
   2582 			s->tlsext_channel_id_private = key;
   2583 			}
   2584 		}
   2585 	if (!s->tlsext_channel_id_private)
   2586 		{
   2587 		s->rwstate=SSL_CHANNEL_ID_LOOKUP;
   2588 		return (-1);
   2589 		}
   2590 	s->rwstate=SSL_NOTHING;
   2591 
   2592 	d = (unsigned char *)s->init_buf->data;
   2593 	*(d++)=SSL3_MT_ENCRYPTED_EXTENSIONS;
   2594 	l2n3(2 + 2 + TLSEXT_CHANNEL_ID_SIZE, d);
   2595 	if (s->s3->tlsext_channel_id_new)
   2596 		s2n(TLSEXT_TYPE_channel_id_new, d);
   2597 	else
   2598 		s2n(TLSEXT_TYPE_channel_id, d);
   2599 	s2n(TLSEXT_CHANNEL_ID_SIZE, d);
   2600 
   2601 	EVP_MD_CTX_init(&md_ctx);
   2602 
   2603 	public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
   2604 	if (public_key_len <= 0)
   2605 		{
   2606 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
   2607 		goto err;
   2608 		}
   2609 	/* i2d_PublicKey will produce an ANSI X9.62 public key which, for a
   2610 	 * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
   2611 	 * field elements as 32-byte, big-endian numbers. */
   2612 	if (public_key_len != 65)
   2613 		{
   2614 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_CHANNEL_ID_NOT_P256);
   2615 		goto err;
   2616 		}
   2617 	public_key = OPENSSL_malloc(public_key_len);
   2618 	if (!public_key)
   2619 		{
   2620 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
   2621 		goto err;
   2622 		}
   2623 
   2624 	derp = public_key;
   2625 	i2d_PublicKey(s->tlsext_channel_id_private, &derp);
   2626 
   2627 	if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
   2628 			       s->tlsext_channel_id_private) != 1)
   2629 		{
   2630 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNINIT_FAILED);
   2631 		goto err;
   2632 		}
   2633 
   2634 	if (!tls1_channel_id_hash(&md_ctx, s))
   2635 		goto err;
   2636 
   2637 	if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len))
   2638 		{
   2639 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   2640 		goto err;
   2641 		}
   2642 
   2643 	der_sig = OPENSSL_malloc(sig_len);
   2644 	if (!der_sig)
   2645 		{
   2646 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, ERR_R_MALLOC_FAILURE);
   2647 		goto err;
   2648 		}
   2649 
   2650 	if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len))
   2651 		{
   2652 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   2653 		goto err;
   2654 		}
   2655 
   2656 	derp = der_sig;
   2657 	sig = d2i_ECDSA_SIG(NULL, (const unsigned char**) &derp, sig_len);
   2658 	if (sig == NULL)
   2659 		{
   2660 		OPENSSL_PUT_ERROR(SSL, ssl3_send_channel_id, SSL_R_D2I_ECDSA_SIG);
   2661 		goto err;
   2662 		}
   2663 
   2664 	/* The first byte of public_key will be 0x4, denoting an uncompressed key. */
   2665 	memcpy(d, public_key + 1, 64);
   2666 	d += 64;
   2667 	memset(d, 0, 2 * 32);
   2668 	BN_bn2bin(sig->r, d + 32 - BN_num_bytes(sig->r));
   2669 	d += 32;
   2670 	BN_bn2bin(sig->s, d + 32 - BN_num_bytes(sig->s));
   2671 	d += 32;
   2672 
   2673 	s->state = SSL3_ST_CW_CHANNEL_ID_B;
   2674 	s->init_num = 4 + 2 + 2 + TLSEXT_CHANNEL_ID_SIZE;
   2675 	s->init_off = 0;
   2676 
   2677 	ret = ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   2678 
   2679 err:
   2680 	EVP_MD_CTX_cleanup(&md_ctx);
   2681 	if (public_key)
   2682 		OPENSSL_free(public_key);
   2683 	if (der_sig)
   2684 		OPENSSL_free(der_sig);
   2685 	if (sig)
   2686 		ECDSA_SIG_free(sig);
   2687 
   2688 	return ret;
   2689 	}
   2690 
   2691 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
   2692 	{
   2693 	int i = 0;
   2694 	if (s->ctx->client_cert_cb)
   2695 		i = s->ctx->client_cert_cb(s,px509,ppkey);
   2696 	return i;
   2697 	}
   2698