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 #include "ssl_locl.h"
    153 #include "kssl_lcl.h"
    154 #include <openssl/buffer.h>
    155 #include <openssl/rand.h>
    156 #include <openssl/objects.h>
    157 #include <openssl/evp.h>
    158 #include <openssl/md5.h>
    159 #ifdef OPENSSL_FIPS
    160 #include <openssl/fips.h>
    161 #endif
    162 #ifndef OPENSSL_NO_DH
    163 #include <openssl/dh.h>
    164 #endif
    165 #include <openssl/bn.h>
    166 #ifndef OPENSSL_NO_ENGINE
    167 #include <openssl/engine.h>
    168 #endif
    169 
    170 static const SSL_METHOD *ssl3_get_client_method(int ver);
    171 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
    172 
    173 static const SSL_METHOD *ssl3_get_client_method(int ver)
    174 	{
    175 	if (ver == SSL3_VERSION)
    176 		return(SSLv3_client_method());
    177 	else
    178 		return(NULL);
    179 	}
    180 
    181 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
    182 			ssl_undefined_function,
    183 			ssl3_connect,
    184 			ssl3_get_client_method)
    185 
    186 int ssl3_connect(SSL *s)
    187 	{
    188 	BUF_MEM *buf=NULL;
    189 	unsigned long Time=(unsigned long)time(NULL);
    190 	void (*cb)(const SSL *ssl,int type,int val)=NULL;
    191 	int ret= -1;
    192 	int new_state,state,skip=0;
    193 
    194 	RAND_add(&Time,sizeof(Time),0);
    195 	ERR_clear_error();
    196 	clear_sys_error();
    197 
    198 	if (s->info_callback != NULL)
    199 		cb=s->info_callback;
    200 	else if (s->ctx->info_callback != NULL)
    201 		cb=s->ctx->info_callback;
    202 
    203 	s->in_handshake++;
    204 	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
    205 
    206 #ifndef OPENSSL_NO_HEARTBEATS
    207 	/* If we're awaiting a HeartbeatResponse, pretend we
    208 	 * already got and don't await it anymore, because
    209 	 * Heartbeats don't make sense during handshakes anyway.
    210 	 */
    211 	if (s->tlsext_hb_pending)
    212 		{
    213 		s->tlsext_hb_pending = 0;
    214 		s->tlsext_hb_seq++;
    215 		}
    216 #endif
    217 
    218 	if (SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH)
    219 		{
    220 		/* Send app data along with CCS/Finished */
    221 		s->s3->flags |= SSL3_FLAGS_DELAY_CLIENT_FINISHED;
    222 		}
    223 
    224 	for (;;)
    225 		{
    226 		state=s->state;
    227 
    228 		switch(s->state)
    229 			{
    230 		case SSL_ST_RENEGOTIATE:
    231 			s->renegotiate=1;
    232 			s->state=SSL_ST_CONNECT;
    233 			s->ctx->stats.sess_connect_renegotiate++;
    234 			/* break */
    235 		case SSL_ST_BEFORE:
    236 		case SSL_ST_CONNECT:
    237 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
    238 		case SSL_ST_OK|SSL_ST_CONNECT:
    239 
    240 			s->server=0;
    241 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
    242 
    243 			if ((s->version & 0xff00 ) != 0x0300)
    244 				{
    245 				SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
    246 				ret = -1;
    247 				goto end;
    248 				}
    249 
    250 			/* s->version=SSL3_VERSION; */
    251 			s->type=SSL_ST_CONNECT;
    252 
    253 			if (s->init_buf == NULL)
    254 				{
    255 				if ((buf=BUF_MEM_new()) == NULL)
    256 					{
    257 					ret= -1;
    258 					goto end;
    259 					}
    260 				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
    261 					{
    262 					ret= -1;
    263 					goto end;
    264 					}
    265 				s->init_buf=buf;
    266 				buf=NULL;
    267 				}
    268 
    269 			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
    270 
    271 			/* setup buffing BIO */
    272 			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
    273 
    274 			/* don't push the buffering BIO quite yet */
    275 
    276 			ssl3_init_finished_mac(s);
    277 
    278 			s->state=SSL3_ST_CW_CLNT_HELLO_A;
    279 			s->ctx->stats.sess_connect++;
    280 			s->init_num=0;
    281 			break;
    282 
    283 		case SSL3_ST_CW_CLNT_HELLO_A:
    284 		case SSL3_ST_CW_CLNT_HELLO_B:
    285 
    286 			s->shutdown=0;
    287 			ret=ssl3_client_hello(s);
    288 			if (ret <= 0) goto end;
    289 			s->state=SSL3_ST_CR_SRVR_HELLO_A;
    290 			s->init_num=0;
    291 
    292 			/* turn on buffering for the next lot of output */
    293 			if (s->bbio != s->wbio)
    294 				s->wbio=BIO_push(s->bbio,s->wbio);
    295 
    296 			break;
    297 
    298 		case SSL3_ST_CR_SRVR_HELLO_A:
    299 		case SSL3_ST_CR_SRVR_HELLO_B:
    300 			ret=ssl3_get_server_hello(s);
    301 			if (ret <= 0) goto end;
    302 
    303 			if (s->hit)
    304 				{
    305 				s->state=SSL3_ST_CR_FINISHED_A;
    306 #ifndef OPENSSL_NO_TLSEXT
    307 				if (s->tlsext_ticket_expected)
    308 					{
    309 					/* receive renewed session ticket */
    310 					s->state=SSL3_ST_CR_SESSION_TICKET_A;
    311 					}
    312 #endif
    313 				}
    314 			else
    315 				s->state=SSL3_ST_CR_CERT_A;
    316 			s->init_num=0;
    317 			break;
    318 
    319 		case SSL3_ST_CR_CERT_A:
    320 		case SSL3_ST_CR_CERT_B:
    321 #ifndef OPENSSL_NO_TLSEXT
    322 			ret=ssl3_check_finished(s);
    323 			if (ret <= 0) goto end;
    324 			if (ret == 2)
    325 				{
    326 				s->hit = 1;
    327 				if (s->tlsext_ticket_expected)
    328 					s->state=SSL3_ST_CR_SESSION_TICKET_A;
    329 				else
    330 					s->state=SSL3_ST_CR_FINISHED_A;
    331 				s->init_num=0;
    332 				break;
    333 				}
    334 #endif
    335 			/* Check if it is anon DH/ECDH */
    336 			/* or non-RSA PSK */
    337 			if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
    338 			    !((s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) &&
    339 			      !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kRSA)))
    340 				{
    341 				ret=ssl3_get_server_certificate(s);
    342 				if (ret <= 0) goto end;
    343 #ifndef OPENSSL_NO_TLSEXT
    344 				if (s->tlsext_status_expected)
    345 					s->state=SSL3_ST_CR_CERT_STATUS_A;
    346 				else
    347 					s->state=SSL3_ST_CR_KEY_EXCH_A;
    348 				}
    349 			else
    350 				{
    351 				skip = 1;
    352 				s->state=SSL3_ST_CR_KEY_EXCH_A;
    353 				}
    354 #else
    355 				}
    356 			else
    357 				skip=1;
    358 
    359 			s->state=SSL3_ST_CR_KEY_EXCH_A;
    360 #endif
    361 			s->init_num=0;
    362 			break;
    363 
    364 		case SSL3_ST_CR_KEY_EXCH_A:
    365 		case SSL3_ST_CR_KEY_EXCH_B:
    366 			ret=ssl3_get_key_exchange(s);
    367 			if (ret <= 0) goto end;
    368 			s->state=SSL3_ST_CR_CERT_REQ_A;
    369 			s->init_num=0;
    370 
    371 			/* at this point we check that we have the
    372 			 * required stuff from the server */
    373 			if (!ssl3_check_cert_and_algorithm(s))
    374 				{
    375 				ret= -1;
    376 				goto end;
    377 				}
    378 			break;
    379 
    380 		case SSL3_ST_CR_CERT_REQ_A:
    381 		case SSL3_ST_CR_CERT_REQ_B:
    382 			ret=ssl3_get_certificate_request(s);
    383 			if (ret <= 0) goto end;
    384 			s->state=SSL3_ST_CR_SRVR_DONE_A;
    385 			s->init_num=0;
    386 			break;
    387 
    388 		case SSL3_ST_CR_SRVR_DONE_A:
    389 		case SSL3_ST_CR_SRVR_DONE_B:
    390 			ret=ssl3_get_server_done(s);
    391 			if (ret <= 0) goto end;
    392 #ifndef OPENSSL_NO_SRP
    393 			if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
    394 				{
    395 				if ((ret = SRP_Calc_A_param(s))<=0)
    396 					{
    397 					SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
    398 					ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
    399 					goto end;
    400 					}
    401 				}
    402 #endif
    403 			if (s->s3->tmp.cert_req)
    404 				s->state=SSL3_ST_CW_CERT_A;
    405 			else
    406 				s->state=SSL3_ST_CW_KEY_EXCH_A;
    407 			s->init_num=0;
    408 
    409 			break;
    410 
    411 		case SSL3_ST_CW_CERT_A:
    412 		case SSL3_ST_CW_CERT_B:
    413 		case SSL3_ST_CW_CERT_C:
    414 		case SSL3_ST_CW_CERT_D:
    415 			ret=ssl3_send_client_certificate(s);
    416 			if (ret <= 0) goto end;
    417 			s->state=SSL3_ST_CW_KEY_EXCH_A;
    418 			s->init_num=0;
    419 			break;
    420 
    421 		case SSL3_ST_CW_KEY_EXCH_A:
    422 		case SSL3_ST_CW_KEY_EXCH_B:
    423 			ret=ssl3_send_client_key_exchange(s);
    424 			if (ret <= 0) goto end;
    425 			/* EAY EAY EAY need to check for DH fix cert
    426 			 * sent back */
    427 			/* For TLS, cert_req is set to 2, so a cert chain
    428 			 * of nothing is sent, but no verify packet is sent */
    429 			/* XXX: For now, we do not support client
    430 			 * authentication in ECDH cipher suites with
    431 			 * ECDH (rather than ECDSA) certificates.
    432 			 * We need to skip the certificate verify
    433 			 * message when client's ECDH public key is sent
    434 			 * inside the client certificate.
    435 			 */
    436 			if (s->s3->tmp.cert_req == 1)
    437 				{
    438 				s->state=SSL3_ST_CW_CERT_VRFY_A;
    439 				}
    440 			else
    441 				{
    442 				s->state=SSL3_ST_CW_CHANGE_A;
    443 				s->s3->change_cipher_spec=0;
    444 				}
    445 			if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
    446 				{
    447 				s->state=SSL3_ST_CW_CHANGE_A;
    448 				s->s3->change_cipher_spec=0;
    449 				}
    450 
    451 			s->init_num=0;
    452 			break;
    453 
    454 		case SSL3_ST_CW_CERT_VRFY_A:
    455 		case SSL3_ST_CW_CERT_VRFY_B:
    456 			ret=ssl3_send_client_verify(s);
    457 			if (ret <= 0) goto end;
    458 			s->state=SSL3_ST_CW_CHANGE_A;
    459 			s->init_num=0;
    460 			s->s3->change_cipher_spec=0;
    461 			break;
    462 
    463 		case SSL3_ST_CW_CHANGE_A:
    464 		case SSL3_ST_CW_CHANGE_B:
    465 			ret=ssl3_send_change_cipher_spec(s,
    466 				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
    467 			if (ret <= 0) goto end;
    468 
    469 			s->state=SSL3_ST_CW_FINISHED_A;
    470 #if !defined(OPENSSL_NO_TLSEXT)
    471 			if (s->s3->tlsext_channel_id_valid)
    472 				s->state=SSL3_ST_CW_CHANNEL_ID_A;
    473 # if !defined(OPENSSL_NO_NEXTPROTONEG)
    474 			if (s->s3->next_proto_neg_seen)
    475 				s->state=SSL3_ST_CW_NEXT_PROTO_A;
    476 # endif
    477 #endif
    478 			s->init_num=0;
    479 
    480 			s->session->cipher=s->s3->tmp.new_cipher;
    481 #ifdef OPENSSL_NO_COMP
    482 			s->session->compress_meth=0;
    483 #else
    484 			if (s->s3->tmp.new_compression == NULL)
    485 				s->session->compress_meth=0;
    486 			else
    487 				s->session->compress_meth=
    488 					s->s3->tmp.new_compression->id;
    489 #endif
    490 			if (!s->method->ssl3_enc->setup_key_block(s))
    491 				{
    492 				ret= -1;
    493 				goto end;
    494 				}
    495 
    496 			if (!s->method->ssl3_enc->change_cipher_state(s,
    497 				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
    498 				{
    499 				ret= -1;
    500 				goto end;
    501 				}
    502 
    503 			break;
    504 
    505 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
    506 		case SSL3_ST_CW_NEXT_PROTO_A:
    507 		case SSL3_ST_CW_NEXT_PROTO_B:
    508 			ret=ssl3_send_next_proto(s);
    509 			if (ret <= 0) goto end;
    510 			if (s->s3->tlsext_channel_id_valid)
    511 				s->state=SSL3_ST_CW_CHANNEL_ID_A;
    512 			else
    513 				s->state=SSL3_ST_CW_FINISHED_A;
    514 			break;
    515 #endif
    516 
    517 #if !defined(OPENSSL_NO_TLSEXT)
    518 		case SSL3_ST_CW_CHANNEL_ID_A:
    519 		case SSL3_ST_CW_CHANNEL_ID_B:
    520 			ret=ssl3_send_channel_id(s);
    521 			if (ret <= 0) goto end;
    522 			s->state=SSL3_ST_CW_FINISHED_A;
    523 			break;
    524 #endif
    525 
    526 		case SSL3_ST_CW_FINISHED_A:
    527 		case SSL3_ST_CW_FINISHED_B:
    528 			ret=ssl3_send_finished(s,
    529 				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
    530 				s->method->ssl3_enc->client_finished_label,
    531 				s->method->ssl3_enc->client_finished_label_len);
    532 			if (ret <= 0) goto end;
    533 			s->state=SSL3_ST_CW_FLUSH;
    534 
    535 			/* clear flags */
    536 			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
    537 			if (s->hit)
    538 				{
    539 				s->s3->tmp.next_state=SSL_ST_OK;
    540 				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
    541 					{
    542 					s->state=SSL_ST_OK;
    543 					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
    544 					s->s3->delay_buf_pop_ret=0;
    545 					}
    546 				}
    547 			else
    548 				{
    549 				/* This is a non-resumption handshake. If it
    550 				 * involves ChannelID, then record the
    551 				 * handshake hashes at this point in the
    552 				 * session so that any resumption of this
    553 				 * session with ChannelID can sign those
    554 				 * hashes. */
    555 				if (s->s3->tlsext_channel_id_new)
    556 					{
    557 					ret = tls1_record_handshake_hashes_for_channel_id(s);
    558 					if (ret <= 0)
    559 						goto end;
    560 					}
    561 				if ((SSL_get_mode(s) & SSL_MODE_HANDSHAKE_CUTTHROUGH)
    562 				    && ssl3_can_cutthrough(s)
    563 				    && s->s3->previous_server_finished_len == 0 /* no cutthrough on renegotiation (would complicate the state machine) */
    564 				   )
    565 					{
    566 					if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
    567 						{
    568 						s->state=SSL3_ST_CUTTHROUGH_COMPLETE;
    569 						s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
    570 						s->s3->delay_buf_pop_ret=0;
    571 						}
    572 					else
    573 						{
    574 						s->s3->tmp.next_state=SSL3_ST_CUTTHROUGH_COMPLETE;
    575 						}
    576 					}
    577 				else
    578 					{
    579 #ifndef OPENSSL_NO_TLSEXT
    580 					/* Allow NewSessionTicket if ticket expected */
    581 					if (s->tlsext_ticket_expected)
    582 						s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
    583 					else
    584 #endif
    585 						s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
    586 					}
    587 				}
    588 			s->init_num=0;
    589 			break;
    590 
    591 #ifndef OPENSSL_NO_TLSEXT
    592 		case SSL3_ST_CR_SESSION_TICKET_A:
    593 		case SSL3_ST_CR_SESSION_TICKET_B:
    594 			ret=ssl3_get_new_session_ticket(s);
    595 			if (ret <= 0) goto end;
    596 			s->state=SSL3_ST_CR_FINISHED_A;
    597 			s->init_num=0;
    598 		break;
    599 
    600 		case SSL3_ST_CR_CERT_STATUS_A:
    601 		case SSL3_ST_CR_CERT_STATUS_B:
    602 			ret=ssl3_get_cert_status(s);
    603 			if (ret <= 0) goto end;
    604 			s->state=SSL3_ST_CR_KEY_EXCH_A;
    605 			s->init_num=0;
    606 		break;
    607 #endif
    608 
    609 		case SSL3_ST_CR_FINISHED_A:
    610 		case SSL3_ST_CR_FINISHED_B:
    611 
    612 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
    613 			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
    614 				SSL3_ST_CR_FINISHED_B);
    615 			if (ret <= 0) goto end;
    616 
    617 			if (s->hit)
    618 				s->state=SSL3_ST_CW_CHANGE_A;
    619 			else
    620 				s->state=SSL_ST_OK;
    621 			s->init_num=0;
    622 			break;
    623 
    624 		case SSL3_ST_CW_FLUSH:
    625 			s->rwstate=SSL_WRITING;
    626 			if (BIO_flush(s->wbio) <= 0)
    627 				{
    628 				ret= -1;
    629 				goto end;
    630 				}
    631 			s->rwstate=SSL_NOTHING;
    632 			s->state=s->s3->tmp.next_state;
    633 			break;
    634 
    635 		case SSL3_ST_CUTTHROUGH_COMPLETE:
    636 #ifndef OPENSSL_NO_TLSEXT
    637 			/* Allow NewSessionTicket if ticket expected */
    638 			if (s->tlsext_ticket_expected)
    639 				s->state=SSL3_ST_CR_SESSION_TICKET_A;
    640 			else
    641 #endif
    642 				s->state=SSL3_ST_CR_FINISHED_A;
    643 
    644 			/* SSL_write() will take care of flushing buffered data if
    645 			 * DELAY_CLIENT_FINISHED is set.
    646 			 */
    647 			if (!(s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED))
    648 				ssl_free_wbio_buffer(s);
    649 			ret = 1;
    650 			goto end;
    651 			/* break; */
    652 
    653 		case SSL_ST_OK:
    654 			/* clean a few things up */
    655 			ssl3_cleanup_key_block(s);
    656 
    657 			if (s->init_buf != NULL)
    658 				{
    659 				BUF_MEM_free(s->init_buf);
    660 				s->init_buf=NULL;
    661 				}
    662 
    663 			/* If we are not 'joining' the last two packets,
    664 			 * remove the buffering now */
    665 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
    666 				ssl_free_wbio_buffer(s);
    667 			/* else do it later in ssl3_write */
    668 
    669 			s->init_num=0;
    670 			s->renegotiate=0;
    671 			s->new_session=0;
    672 
    673 			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
    674 			if (s->hit) s->ctx->stats.sess_hit++;
    675 
    676 			ret=1;
    677 			/* s->server=0; */
    678 			s->handshake_func=ssl3_connect;
    679 			s->ctx->stats.sess_connect_good++;
    680 
    681 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
    682 
    683 			goto end;
    684 			/* break; */
    685 
    686 		default:
    687 			SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
    688 			ret= -1;
    689 			goto end;
    690 			/* break; */
    691 			}
    692 
    693 		/* did we do anything */
    694 		if (!s->s3->tmp.reuse_message && !skip)
    695 			{
    696 			if (s->debug)
    697 				{
    698 				if ((ret=BIO_flush(s->wbio)) <= 0)
    699 					goto end;
    700 				}
    701 
    702 			if ((cb != NULL) && (s->state != state))
    703 				{
    704 				new_state=s->state;
    705 				s->state=state;
    706 				cb(s,SSL_CB_CONNECT_LOOP,1);
    707 				s->state=new_state;
    708 				}
    709 			}
    710 		skip=0;
    711 		}
    712 end:
    713 	s->in_handshake--;
    714 	if (buf != NULL)
    715 		BUF_MEM_free(buf);
    716 	if (cb != NULL)
    717 		cb(s,SSL_CB_CONNECT_EXIT,ret);
    718 	return(ret);
    719 	}
    720 
    721 
    722 int ssl3_client_hello(SSL *s)
    723 	{
    724 	unsigned char *buf;
    725 	unsigned char *p,*d;
    726 	int i;
    727 	unsigned long l;
    728 #ifndef OPENSSL_NO_COMP
    729 	int j;
    730 	SSL_COMP *comp;
    731 #endif
    732 
    733 	buf=(unsigned char *)s->init_buf->data;
    734 	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
    735 		{
    736 		SSL_SESSION *sess = s->session;
    737 		if ((sess == NULL) ||
    738 			(sess->ssl_version != s->version) ||
    739 #ifdef OPENSSL_NO_TLSEXT
    740 			!sess->session_id_length ||
    741 #else
    742 			(!sess->session_id_length && !sess->tlsext_tick) ||
    743 #endif
    744 			(sess->not_resumable))
    745 			{
    746 		        if (!s->session_creation_enabled)
    747 				{
    748 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
    749 				SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
    750 				goto err;
    751 				}
    752 			if (!ssl_get_new_session(s,0))
    753 				goto err;
    754 			}
    755 		/* else use the pre-loaded session */
    756 
    757 		p=s->s3->client_random;
    758 
    759 		if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
    760 			goto err;
    761 
    762 		/* Do the message type and length last */
    763 		d=p= &(buf[4]);
    764 
    765 		/* version indicates the negotiated version: for example from
    766 		 * an SSLv2/v3 compatible client hello). The client_version
    767 		 * field is the maximum version we permit and it is also
    768 		 * used in RSA encrypted premaster secrets. Some servers can
    769 		 * choke if we initially report a higher version then
    770 		 * renegotiate to a lower one in the premaster secret. This
    771 		 * didn't happen with TLS 1.0 as most servers supported it
    772 		 * but it can with TLS 1.1 or later if the server only supports
    773 		 * 1.0.
    774 		 *
    775 		 * Possible scenario with previous logic:
    776 		 * 	1. Client hello indicates TLS 1.2
    777 		 * 	2. Server hello says TLS 1.0
    778 		 *	3. RSA encrypted premaster secret uses 1.2.
    779 		 * 	4. Handhaked proceeds using TLS 1.0.
    780 		 *	5. Server sends hello request to renegotiate.
    781 		 *	6. Client hello indicates TLS v1.0 as we now
    782 		 *	   know that is maximum server supports.
    783 		 *	7. Server chokes on RSA encrypted premaster secret
    784 		 *	   containing version 1.0.
    785 		 *
    786 		 * For interoperability it should be OK to always use the
    787 		 * maximum version we support in client hello and then rely
    788 		 * on the checking of version to ensure the servers isn't
    789 		 * being inconsistent: for example initially negotiating with
    790 		 * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
    791 		 * client_version in client hello and not resetting it to
    792 		 * the negotiated version.
    793 		 */
    794 #if 0
    795 		*(p++)=s->version>>8;
    796 		*(p++)=s->version&0xff;
    797 		s->client_version=s->version;
    798 #else
    799 		*(p++)=s->client_version>>8;
    800 		*(p++)=s->client_version&0xff;
    801 #endif
    802 
    803 		/* Random stuff */
    804 		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
    805 		p+=SSL3_RANDOM_SIZE;
    806 
    807 		/* Session ID */
    808 		if (s->new_session)
    809 			i=0;
    810 		else
    811 			i=s->session->session_id_length;
    812 		*(p++)=i;
    813 		if (i != 0)
    814 			{
    815 			if (i > (int)sizeof(s->session->session_id))
    816 				{
    817 				SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
    818 				goto err;
    819 				}
    820 			memcpy(p,s->session->session_id,i);
    821 			p+=i;
    822 			}
    823 
    824 		/* Ciphers supported */
    825 		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
    826 		if (i == 0)
    827 			{
    828 			SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
    829 			goto err;
    830 			}
    831 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
    832 			/* Some servers hang if client hello > 256 bytes
    833 			 * as hack workaround chop number of supported ciphers
    834 			 * to keep it well below this if we use TLS v1.2
    835 			 */
    836 			if (TLS1_get_version(s) >= TLS1_2_VERSION
    837 				&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
    838 				i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
    839 #endif
    840 		s2n(i,p);
    841 		p+=i;
    842 
    843 		/* COMPRESSION */
    844 #ifdef OPENSSL_NO_COMP
    845 		*(p++)=1;
    846 #else
    847 
    848 		if ((s->options & SSL_OP_NO_COMPRESSION)
    849 					|| !s->ctx->comp_methods)
    850 			j=0;
    851 		else
    852 			j=sk_SSL_COMP_num(s->ctx->comp_methods);
    853 		*(p++)=1+j;
    854 		for (i=0; i<j; i++)
    855 			{
    856 			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
    857 			*(p++)=comp->id;
    858 			}
    859 #endif
    860 		*(p++)=0; /* Add the NULL method */
    861 
    862 #ifndef OPENSSL_NO_TLSEXT
    863 		/* TLS extensions*/
    864 		if (ssl_prepare_clienthello_tlsext(s) <= 0)
    865 			{
    866 			SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
    867 			goto err;
    868 			}
    869 		if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
    870 			{
    871 			SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
    872 			goto err;
    873 			}
    874 #endif
    875 
    876 		l=(p-d);
    877 		d=buf;
    878 		*(d++)=SSL3_MT_CLIENT_HELLO;
    879 		l2n3(l,d);
    880 
    881 		s->state=SSL3_ST_CW_CLNT_HELLO_B;
    882 		/* number of bytes to write */
    883 		s->init_num=p-buf;
    884 		s->init_off=0;
    885 		}
    886 
    887 	/* SSL3_ST_CW_CLNT_HELLO_B */
    888 	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
    889 err:
    890 	return(-1);
    891 	}
    892 
    893 int ssl3_get_server_hello(SSL *s)
    894 	{
    895 	STACK_OF(SSL_CIPHER) *sk;
    896 	const SSL_CIPHER *c;
    897 	unsigned char *p,*d;
    898 	int i,al,ok;
    899 	unsigned int j;
    900 	long n;
    901 #ifndef OPENSSL_NO_COMP
    902 	SSL_COMP *comp;
    903 #endif
    904 
    905 	n=s->method->ssl_get_message(s,
    906 		SSL3_ST_CR_SRVR_HELLO_A,
    907 		SSL3_ST_CR_SRVR_HELLO_B,
    908 		-1,
    909 		20000, /* ?? */
    910 		&ok);
    911 
    912 	if (!ok) return((int)n);
    913 
    914 	if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
    915 		{
    916 		if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
    917 			{
    918 			if ( s->d1->send_cookie == 0)
    919 				{
    920 				s->s3->tmp.reuse_message = 1;
    921 				return 1;
    922 				}
    923 			else /* already sent a cookie */
    924 				{
    925 				al=SSL_AD_UNEXPECTED_MESSAGE;
    926 				SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
    927 				goto f_err;
    928 				}
    929 			}
    930 		}
    931 
    932 	if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
    933 		{
    934 		al=SSL_AD_UNEXPECTED_MESSAGE;
    935 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
    936 		goto f_err;
    937 		}
    938 
    939 	d=p=(unsigned char *)s->init_msg;
    940 
    941 	if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
    942 		{
    943 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
    944 		s->version=(s->version&0xff00)|p[1];
    945 		al=SSL_AD_PROTOCOL_VERSION;
    946 		goto f_err;
    947 		}
    948 	p+=2;
    949 
    950 	/* load the server hello data */
    951 	/* load the server random */
    952 	memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
    953 	p+=SSL3_RANDOM_SIZE;
    954 
    955 	/* get the session-id */
    956 	j= *(p++);
    957 
    958 	if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
    959 		{
    960 		al=SSL_AD_ILLEGAL_PARAMETER;
    961 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
    962 		goto f_err;
    963 		}
    964 
    965 #ifndef OPENSSL_NO_TLSEXT
    966 	/* check if we want to resume the session based on external pre-shared secret */
    967 	if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
    968 		{
    969 		SSL_CIPHER *pref_cipher=NULL;
    970 		s->session->master_key_length=sizeof(s->session->master_key);
    971 		if (s->tls_session_secret_cb(s, s->session->master_key,
    972 					     &s->session->master_key_length,
    973 					     NULL, &pref_cipher,
    974 					     s->tls_session_secret_cb_arg))
    975 			{
    976 			s->session->cipher = pref_cipher ?
    977 				pref_cipher : ssl_get_cipher_by_char(s, p+j);
    978 			}
    979 		}
    980 #endif /* OPENSSL_NO_TLSEXT */
    981 
    982 	if (j != 0 && j == s->session->session_id_length
    983 	    && memcmp(p,s->session->session_id,j) == 0)
    984 	    {
    985 	    if(s->sid_ctx_length != s->session->sid_ctx_length
    986 	       || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
    987 		{
    988 		/* actually a client application bug */
    989 		al=SSL_AD_ILLEGAL_PARAMETER;
    990 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
    991 		goto f_err;
    992 		}
    993 	    s->s3->flags |= SSL3_FLAGS_CCS_OK;
    994 	    s->hit=1;
    995 	    }
    996 	else	/* a miss or crap from the other end */
    997 		{
    998 		/* If we were trying for session-id reuse, make a new
    999 		 * SSL_SESSION so we don't stuff up other people */
   1000 		s->hit=0;
   1001 		if (s->session->session_id_length > 0)
   1002 			{
   1003 		        if (!s->session_creation_enabled)
   1004 				{
   1005 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   1006 				SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
   1007 				goto err;
   1008 				}
   1009 			if (!ssl_get_new_session(s,0))
   1010 				{
   1011 				al=SSL_AD_INTERNAL_ERROR;
   1012 				goto f_err;
   1013 				}
   1014 			}
   1015 		s->session->session_id_length=j;
   1016 		memcpy(s->session->session_id,p,j); /* j could be 0 */
   1017 		}
   1018 	p+=j;
   1019 	c=ssl_get_cipher_by_char(s,p);
   1020 	if (c == NULL)
   1021 		{
   1022 		/* unknown cipher */
   1023 		al=SSL_AD_ILLEGAL_PARAMETER;
   1024 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
   1025 		goto f_err;
   1026 		}
   1027 	/* TLS v1.2 only ciphersuites require v1.2 or later */
   1028 	if ((c->algorithm_ssl & SSL_TLSV1_2) &&
   1029 		(TLS1_get_version(s) < TLS1_2_VERSION))
   1030 		{
   1031 		al=SSL_AD_ILLEGAL_PARAMETER;
   1032 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
   1033 		goto f_err;
   1034 		}
   1035 	p+=ssl_put_cipher_by_char(s,NULL,NULL);
   1036 
   1037 	sk=ssl_get_ciphers_by_id(s);
   1038 	i=sk_SSL_CIPHER_find(sk,c);
   1039 	if (i < 0)
   1040 		{
   1041 		/* we did not say we would use this cipher */
   1042 		al=SSL_AD_ILLEGAL_PARAMETER;
   1043 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
   1044 		goto f_err;
   1045 		}
   1046 
   1047 	/* Depending on the session caching (internal/external), the cipher
   1048 	   and/or cipher_id values may not be set. Make sure that
   1049 	   cipher_id is set and use it for comparison. */
   1050 	if (s->session->cipher)
   1051 		s->session->cipher_id = s->session->cipher->id;
   1052 	if (s->hit && (s->session->cipher_id != c->id))
   1053 		{
   1054 /* Workaround is now obsolete */
   1055 #if 0
   1056 		if (!(s->options &
   1057 			SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
   1058 #endif
   1059 			{
   1060 			al=SSL_AD_ILLEGAL_PARAMETER;
   1061 			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
   1062 			goto f_err;
   1063 			}
   1064 		}
   1065 	s->s3->tmp.new_cipher=c;
   1066 	/* Don't digest cached records if TLS v1.2: we may need them for
   1067 	 * client authentication.
   1068 	 */
   1069 	if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s))
   1070 		{
   1071 		al = SSL_AD_INTERNAL_ERROR;
   1072 		goto f_err;
   1073 		}
   1074 	/* lets get the compression algorithm */
   1075 	/* COMPRESSION */
   1076 #ifdef OPENSSL_NO_COMP
   1077 	if (*(p++) != 0)
   1078 		{
   1079 		al=SSL_AD_ILLEGAL_PARAMETER;
   1080 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
   1081 		goto f_err;
   1082 		}
   1083 	/* If compression is disabled we'd better not try to resume a session
   1084 	 * using compression.
   1085 	 */
   1086 	if (s->session->compress_meth != 0)
   1087 		{
   1088 		al=SSL_AD_INTERNAL_ERROR;
   1089 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
   1090 		goto f_err;
   1091 		}
   1092 #else
   1093 	j= *(p++);
   1094 	if (s->hit && j != s->session->compress_meth)
   1095 		{
   1096 		al=SSL_AD_ILLEGAL_PARAMETER;
   1097 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
   1098 		goto f_err;
   1099 		}
   1100 	if (j == 0)
   1101 		comp=NULL;
   1102 	else if (s->options & SSL_OP_NO_COMPRESSION)
   1103 		{
   1104 		al=SSL_AD_ILLEGAL_PARAMETER;
   1105 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
   1106 		goto f_err;
   1107 		}
   1108 	else
   1109 		comp=ssl3_comp_find(s->ctx->comp_methods,j);
   1110 
   1111 	if ((j != 0) && (comp == NULL))
   1112 		{
   1113 		al=SSL_AD_ILLEGAL_PARAMETER;
   1114 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
   1115 		goto f_err;
   1116 		}
   1117 	else
   1118 		{
   1119 		s->s3->tmp.new_compression=comp;
   1120 		}
   1121 #endif
   1122 
   1123 #ifndef OPENSSL_NO_TLSEXT
   1124 	/* TLS extensions*/
   1125 	if (s->version >= SSL3_VERSION)
   1126 		{
   1127 		if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al))
   1128 			{
   1129 			/* 'al' set by ssl_parse_serverhello_tlsext */
   1130 			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
   1131 			goto f_err;
   1132 			}
   1133 		if (ssl_check_serverhello_tlsext(s) <= 0)
   1134 			{
   1135 			SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
   1136 				goto err;
   1137 			}
   1138 		}
   1139 #endif
   1140 
   1141 	if (p != (d+n))
   1142 		{
   1143 		/* wrong packet length */
   1144 		al=SSL_AD_DECODE_ERROR;
   1145 		SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
   1146 		goto f_err;
   1147 		}
   1148 
   1149 	return(1);
   1150 f_err:
   1151 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1152 err:
   1153 	return(-1);
   1154 	}
   1155 
   1156 int ssl3_get_server_certificate(SSL *s)
   1157 	{
   1158 	int al,i,ok,ret= -1;
   1159 	unsigned long n,nc,llen,l;
   1160 	X509 *x=NULL;
   1161 	const unsigned char *q,*p;
   1162 	unsigned char *d;
   1163 	STACK_OF(X509) *sk=NULL;
   1164 	SESS_CERT *sc;
   1165 	EVP_PKEY *pkey=NULL;
   1166 	int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
   1167 
   1168 	n=s->method->ssl_get_message(s,
   1169 		SSL3_ST_CR_CERT_A,
   1170 		SSL3_ST_CR_CERT_B,
   1171 		-1,
   1172 		s->max_cert_list,
   1173 		&ok);
   1174 
   1175 	if (!ok) return((int)n);
   1176 
   1177 	if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
   1178 		((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) &&
   1179 		(s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)))
   1180 		{
   1181 		s->s3->tmp.reuse_message=1;
   1182 		return(1);
   1183 		}
   1184 
   1185 	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
   1186 		{
   1187 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1188 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
   1189 		goto f_err;
   1190 		}
   1191 	p=d=(unsigned char *)s->init_msg;
   1192 
   1193 	if ((sk=sk_X509_new_null()) == NULL)
   1194 		{
   1195 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
   1196 		goto err;
   1197 		}
   1198 
   1199 	n2l3(p,llen);
   1200 	if (llen+3 != n)
   1201 		{
   1202 		al=SSL_AD_DECODE_ERROR;
   1203 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
   1204 		goto f_err;
   1205 		}
   1206 	for (nc=0; nc<llen; )
   1207 		{
   1208 		n2l3(p,l);
   1209 		if ((l+nc+3) > llen)
   1210 			{
   1211 			al=SSL_AD_DECODE_ERROR;
   1212 			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
   1213 			goto f_err;
   1214 			}
   1215 
   1216 		q=p;
   1217 		x=d2i_X509(NULL,&q,l);
   1218 		if (x == NULL)
   1219 			{
   1220 			al=SSL_AD_BAD_CERTIFICATE;
   1221 			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
   1222 			goto f_err;
   1223 			}
   1224 		if (q != (p+l))
   1225 			{
   1226 			al=SSL_AD_DECODE_ERROR;
   1227 			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
   1228 			goto f_err;
   1229 			}
   1230 		if (!sk_X509_push(sk,x))
   1231 			{
   1232 			SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
   1233 			goto err;
   1234 			}
   1235 		x=NULL;
   1236 		nc+=l+3;
   1237 		p=q;
   1238 		}
   1239 
   1240 	i=ssl_verify_cert_chain(s,sk);
   1241 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
   1242 #ifndef OPENSSL_NO_KRB5
   1243 	    && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
   1244 		 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
   1245 #endif /* OPENSSL_NO_KRB5 */
   1246 		)
   1247 		{
   1248 		al=ssl_verify_alarm_type(s->verify_result);
   1249 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
   1250 		goto f_err;
   1251 		}
   1252 	ERR_clear_error(); /* but we keep s->verify_result */
   1253 
   1254 	sc=ssl_sess_cert_new();
   1255 	if (sc == NULL) goto err;
   1256 
   1257 	if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
   1258 	s->session->sess_cert=sc;
   1259 
   1260 	sc->cert_chain=sk;
   1261 	/* Inconsistency alert: cert_chain does include the peer's
   1262 	 * certificate, which we don't include in s3_srvr.c */
   1263 	x=sk_X509_value(sk,0);
   1264 	sk=NULL;
   1265  	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
   1266 
   1267 	pkey=X509_get_pubkey(x);
   1268 
   1269 	/* VRS: allow null cert if auth == KRB5 */
   1270 	need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
   1271 	            (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
   1272 	            ? 0 : 1;
   1273 
   1274 #ifdef KSSL_DEBUG
   1275 	printf("pkey,x = %p, %p\n", pkey,x);
   1276 	printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
   1277 	printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
   1278 		s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
   1279 #endif    /* KSSL_DEBUG */
   1280 
   1281 	if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
   1282 		{
   1283 		x=NULL;
   1284 		al=SSL3_AL_FATAL;
   1285 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
   1286 			SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
   1287 		goto f_err;
   1288 		}
   1289 
   1290 	i=ssl_cert_type(x,pkey);
   1291 	if (need_cert && i < 0)
   1292 		{
   1293 		x=NULL;
   1294 		al=SSL3_AL_FATAL;
   1295 		SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
   1296 			SSL_R_UNKNOWN_CERTIFICATE_TYPE);
   1297 		goto f_err;
   1298 		}
   1299 
   1300 	if (need_cert)
   1301 		{
   1302 		sc->peer_cert_type=i;
   1303 		CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
   1304 		/* Why would the following ever happen?
   1305 		 * We just created sc a couple of lines ago. */
   1306 		if (sc->peer_pkeys[i].x509 != NULL)
   1307 			X509_free(sc->peer_pkeys[i].x509);
   1308 		sc->peer_pkeys[i].x509=x;
   1309 		sc->peer_key= &(sc->peer_pkeys[i]);
   1310 
   1311 		if (s->session->peer != NULL)
   1312 			X509_free(s->session->peer);
   1313 		CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
   1314 		s->session->peer=x;
   1315 		}
   1316 	else
   1317 		{
   1318 		sc->peer_cert_type=i;
   1319 		sc->peer_key= NULL;
   1320 
   1321 		if (s->session->peer != NULL)
   1322 			X509_free(s->session->peer);
   1323 		s->session->peer=NULL;
   1324 		}
   1325 	s->session->verify_result = s->verify_result;
   1326 
   1327 	x=NULL;
   1328 	ret=1;
   1329 
   1330 	if (0)
   1331 		{
   1332 f_err:
   1333 		ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1334 		}
   1335 err:
   1336 	EVP_PKEY_free(pkey);
   1337 	X509_free(x);
   1338 	sk_X509_pop_free(sk,X509_free);
   1339 	return(ret);
   1340 	}
   1341 
   1342 int ssl3_get_key_exchange(SSL *s)
   1343 	{
   1344 #ifndef OPENSSL_NO_RSA
   1345 	unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
   1346 #endif
   1347 	EVP_MD_CTX md_ctx;
   1348 	unsigned char *param,*p;
   1349 	int al,i,j,param_len,ok;
   1350 	long n,alg_k,alg_a;
   1351 	EVP_PKEY *pkey=NULL;
   1352 	const EVP_MD *md = NULL;
   1353 #ifndef OPENSSL_NO_RSA
   1354 	RSA *rsa=NULL;
   1355 #endif
   1356 #ifndef OPENSSL_NO_DH
   1357 	DH *dh=NULL;
   1358 #endif
   1359 #ifndef OPENSSL_NO_ECDH
   1360 	EC_KEY *ecdh = NULL;
   1361 	BN_CTX *bn_ctx = NULL;
   1362 	EC_POINT *srvr_ecpoint = NULL;
   1363 	int curve_nid = 0;
   1364 	int encoded_pt_len = 0;
   1365 #endif
   1366 
   1367 	/* use same message size as in ssl3_get_certificate_request()
   1368 	 * as ServerKeyExchange message may be skipped */
   1369 	n=s->method->ssl_get_message(s,
   1370 		SSL3_ST_CR_KEY_EXCH_A,
   1371 		SSL3_ST_CR_KEY_EXCH_B,
   1372 		-1,
   1373 		s->max_cert_list,
   1374 		&ok);
   1375 	if (!ok) return((int)n);
   1376 
   1377 	if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
   1378 		{
   1379 #ifndef OPENSSL_NO_PSK
   1380 		/* In plain PSK ciphersuite, ServerKeyExchange can be
   1381 		   omitted if no identity hint is sent. Set
   1382 		   session->sess_cert anyway to avoid problems
   1383 		   later.*/
   1384 		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK)
   1385 			{
   1386 			s->session->sess_cert=ssl_sess_cert_new();
   1387 			if (s->session->psk_identity_hint)
   1388 				{
   1389 				OPENSSL_free(s->session->psk_identity_hint);
   1390 				s->session->psk_identity_hint = NULL;
   1391 				}
   1392 			}
   1393 #endif
   1394 		s->s3->tmp.reuse_message=1;
   1395 		return(1);
   1396 		}
   1397 
   1398 	param=p=(unsigned char *)s->init_msg;
   1399 	if (s->session->sess_cert != NULL)
   1400 		{
   1401 #ifndef OPENSSL_NO_RSA
   1402 		if (s->session->sess_cert->peer_rsa_tmp != NULL)
   1403 			{
   1404 			RSA_free(s->session->sess_cert->peer_rsa_tmp);
   1405 			s->session->sess_cert->peer_rsa_tmp=NULL;
   1406 			}
   1407 #endif
   1408 #ifndef OPENSSL_NO_DH
   1409 		if (s->session->sess_cert->peer_dh_tmp)
   1410 			{
   1411 			DH_free(s->session->sess_cert->peer_dh_tmp);
   1412 			s->session->sess_cert->peer_dh_tmp=NULL;
   1413 			}
   1414 #endif
   1415 #ifndef OPENSSL_NO_ECDH
   1416 		if (s->session->sess_cert->peer_ecdh_tmp)
   1417 			{
   1418 			EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
   1419 			s->session->sess_cert->peer_ecdh_tmp=NULL;
   1420 			}
   1421 #endif
   1422 		}
   1423 	else
   1424 		{
   1425 		s->session->sess_cert=ssl_sess_cert_new();
   1426 		}
   1427 
   1428 	param_len=0;
   1429 	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   1430 	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   1431 	EVP_MD_CTX_init(&md_ctx);
   1432 
   1433 #ifndef OPENSSL_NO_PSK
   1434 	if (alg_a & SSL_aPSK)
   1435 		{
   1436 		char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
   1437 
   1438 		al=SSL_AD_HANDSHAKE_FAILURE;
   1439 		n2s(p,i);
   1440 		param_len=i+2;
   1441 		if (s->session->psk_identity_hint)
   1442 			{
   1443 			OPENSSL_free(s->session->psk_identity_hint);
   1444 			s->session->psk_identity_hint = NULL;
   1445 			}
   1446 		if (i != 0)
   1447 			{
   1448 			/* Store PSK identity hint for later use, hint is used
   1449 			 * in ssl3_send_client_key_exchange.  Assume that the
   1450 			 * maximum length of a PSK identity hint can be as
   1451 			 * long as the maximum length of a PSK identity. */
   1452 			if (i > PSK_MAX_IDENTITY_LEN)
   1453 				{
   1454 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
   1455 					SSL_R_DATA_LENGTH_TOO_LONG);
   1456 				goto f_err;
   1457 				}
   1458 			if (param_len > n)
   1459 				{
   1460 				al=SSL_AD_DECODE_ERROR;
   1461 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
   1462 					SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
   1463 				goto f_err;
   1464 				}
   1465 			/* If received PSK identity hint contains NULL
   1466 			 * characters, the hint is truncated from the first
   1467 			 * NULL. p may not be ending with NULL, so create a
   1468 			 * NULL-terminated string. */
   1469 			memcpy(tmp_id_hint, p, i);
   1470 			memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
   1471 			s->session->psk_identity_hint = BUF_strdup(tmp_id_hint);
   1472 			if (s->session->psk_identity_hint == NULL)
   1473 				{
   1474 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
   1475 				goto f_err;
   1476 				}
   1477 			}
   1478 		p+=i;
   1479 		n-=param_len;
   1480 		}
   1481 #endif /* !OPENSSL_NO_PSK */
   1482 
   1483 	if (0) {}
   1484 #ifndef OPENSSL_NO_SRP
   1485 	else if (alg_k & SSL_kSRP)
   1486 		{
   1487 		n2s(p,i);
   1488 		param_len=i+2;
   1489 		if (param_len > n)
   1490 			{
   1491 			al=SSL_AD_DECODE_ERROR;
   1492 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
   1493 			goto f_err;
   1494 			}
   1495 		if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
   1496 			{
   1497 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1498 			goto err;
   1499 			}
   1500 		p+=i;
   1501 
   1502 		n2s(p,i);
   1503 		param_len+=i+2;
   1504 		if (param_len > n)
   1505 			{
   1506 			al=SSL_AD_DECODE_ERROR;
   1507 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
   1508 			goto f_err;
   1509 			}
   1510 		if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
   1511 			{
   1512 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1513 			goto err;
   1514 			}
   1515 		p+=i;
   1516 
   1517 		i = (unsigned int)(p[0]);
   1518 		p++;
   1519 		param_len+=i+1;
   1520 		if (param_len > n)
   1521 			{
   1522 			al=SSL_AD_DECODE_ERROR;
   1523 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
   1524 			goto f_err;
   1525 			}
   1526 		if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
   1527 			{
   1528 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1529 			goto err;
   1530 			}
   1531 		p+=i;
   1532 
   1533 		n2s(p,i);
   1534 		param_len+=i+2;
   1535 		if (param_len > n)
   1536 			{
   1537 			al=SSL_AD_DECODE_ERROR;
   1538 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
   1539 			goto f_err;
   1540 			}
   1541 		if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
   1542 			{
   1543 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1544 			goto err;
   1545 			}
   1546 		p+=i;
   1547 		n-=param_len;
   1548 
   1549 /* We must check if there is a certificate */
   1550 #ifndef OPENSSL_NO_RSA
   1551 		if (alg_a & SSL_aRSA)
   1552 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1553 #else
   1554 		if (0)
   1555 			;
   1556 #endif
   1557 #ifndef OPENSSL_NO_DSA
   1558 		else if (alg_a & SSL_aDSS)
   1559 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
   1560 #endif
   1561 		}
   1562 #endif /* !OPENSSL_NO_SRP */
   1563 #ifndef OPENSSL_NO_RSA
   1564 	else if (alg_k & SSL_kRSA)
   1565 		{
   1566 		if ((rsa=RSA_new()) == NULL)
   1567 			{
   1568 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1569 			goto err;
   1570 			}
   1571 		n2s(p,i);
   1572 		param_len=i+2;
   1573 		if (param_len > n)
   1574 			{
   1575 			al=SSL_AD_DECODE_ERROR;
   1576 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
   1577 			goto f_err;
   1578 			}
   1579 		if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
   1580 			{
   1581 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1582 			goto err;
   1583 			}
   1584 		p+=i;
   1585 
   1586 		n2s(p,i);
   1587 		param_len+=i+2;
   1588 		if (param_len > n)
   1589 			{
   1590 			al=SSL_AD_DECODE_ERROR;
   1591 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
   1592 			goto f_err;
   1593 			}
   1594 		if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
   1595 			{
   1596 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1597 			goto err;
   1598 			}
   1599 		p+=i;
   1600 		n-=param_len;
   1601 
   1602 		/* this should be because we are using an export cipher */
   1603 		if (alg_a & SSL_aRSA)
   1604 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1605 		else
   1606 			{
   1607 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   1608 			goto err;
   1609 			}
   1610 		s->session->sess_cert->peer_rsa_tmp=rsa;
   1611 		rsa=NULL;
   1612 		}
   1613 #endif
   1614 #ifndef OPENSSL_NO_DH
   1615 	else if (alg_k & SSL_kEDH)
   1616 		{
   1617 		if ((dh=DH_new()) == NULL)
   1618 			{
   1619 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
   1620 			goto err;
   1621 			}
   1622 		n2s(p,i);
   1623 		param_len=i+2;
   1624 		if (param_len > n)
   1625 			{
   1626 			al=SSL_AD_DECODE_ERROR;
   1627 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
   1628 			goto f_err;
   1629 			}
   1630 		if (!(dh->p=BN_bin2bn(p,i,NULL)))
   1631 			{
   1632 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1633 			goto err;
   1634 			}
   1635 		p+=i;
   1636 
   1637 		n2s(p,i);
   1638 		param_len+=i+2;
   1639 		if (param_len > n)
   1640 			{
   1641 			al=SSL_AD_DECODE_ERROR;
   1642 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
   1643 			goto f_err;
   1644 			}
   1645 		if (!(dh->g=BN_bin2bn(p,i,NULL)))
   1646 			{
   1647 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1648 			goto err;
   1649 			}
   1650 		p+=i;
   1651 
   1652 		n2s(p,i);
   1653 		param_len+=i+2;
   1654 		if (param_len > n)
   1655 			{
   1656 			al=SSL_AD_DECODE_ERROR;
   1657 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
   1658 			goto f_err;
   1659 			}
   1660 		if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
   1661 			{
   1662 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
   1663 			goto err;
   1664 			}
   1665 		p+=i;
   1666 		n-=param_len;
   1667 
   1668 #ifndef OPENSSL_NO_RSA
   1669 		if (alg_a & SSL_aRSA)
   1670 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1671 #else
   1672 		if (0)
   1673 			;
   1674 #endif
   1675 #ifndef OPENSSL_NO_DSA
   1676 		else if (alg_a & SSL_aDSS)
   1677 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
   1678 #endif
   1679 		/* else anonymous DH, so no certificate or pkey. */
   1680 
   1681 		s->session->sess_cert->peer_dh_tmp=dh;
   1682 		dh=NULL;
   1683 		}
   1684 	else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
   1685 		{
   1686 		al=SSL_AD_ILLEGAL_PARAMETER;
   1687 		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
   1688 		goto f_err;
   1689 		}
   1690 #endif /* !OPENSSL_NO_DH */
   1691 
   1692 #ifndef OPENSSL_NO_ECDH
   1693 	else if (alg_k & SSL_kEECDH)
   1694 		{
   1695 		EC_GROUP *ngroup;
   1696 		const EC_GROUP *group;
   1697 
   1698 		if ((ecdh=EC_KEY_new()) == NULL)
   1699 			{
   1700 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1701 			goto err;
   1702 			}
   1703 
   1704 		/* Extract elliptic curve parameters and the
   1705 		 * server's ephemeral ECDH public key.
   1706 		 * Keep accumulating lengths of various components in
   1707 		 * param_len and make sure it never exceeds n.
   1708 		 */
   1709 
   1710 		/* XXX: For now we only support named (not generic) curves
   1711 		 * and the ECParameters in this case is just three bytes.
   1712 		 */
   1713 		param_len=3;
   1714 		if ((param_len > n) ||
   1715 		    (*p != NAMED_CURVE_TYPE) ||
   1716 		    ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0))
   1717 			{
   1718 			al=SSL_AD_INTERNAL_ERROR;
   1719 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
   1720 			goto f_err;
   1721 			}
   1722 
   1723 		ngroup = EC_GROUP_new_by_curve_name(curve_nid);
   1724 		if (ngroup == NULL)
   1725 			{
   1726 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
   1727 			goto err;
   1728 			}
   1729 		if (EC_KEY_set_group(ecdh, ngroup) == 0)
   1730 			{
   1731 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
   1732 			goto err;
   1733 			}
   1734 		EC_GROUP_free(ngroup);
   1735 
   1736 		group = EC_KEY_get0_group(ecdh);
   1737 
   1738 		if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
   1739 		    (EC_GROUP_get_degree(group) > 163))
   1740 			{
   1741 			al=SSL_AD_EXPORT_RESTRICTION;
   1742 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
   1743 			goto f_err;
   1744 			}
   1745 
   1746 		p+=3;
   1747 
   1748 		/* Next, get the encoded ECPoint */
   1749 		if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
   1750 		    ((bn_ctx = BN_CTX_new()) == NULL))
   1751 			{
   1752 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1753 			goto err;
   1754 			}
   1755 
   1756 		encoded_pt_len = *p;  /* length of encoded point */
   1757 		p+=1;
   1758 		param_len += (1 + encoded_pt_len);
   1759 		if ((param_len > n) ||
   1760 		    (EC_POINT_oct2point(group, srvr_ecpoint,
   1761 			p, encoded_pt_len, bn_ctx) == 0))
   1762 			{
   1763 			al=SSL_AD_DECODE_ERROR;
   1764 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
   1765 			goto f_err;
   1766 			}
   1767 
   1768 		n-=param_len;
   1769 		p+=encoded_pt_len;
   1770 
   1771 		/* The ECC/TLS specification does not mention
   1772 		 * the use of DSA to sign ECParameters in the server
   1773 		 * key exchange message. We do support RSA and ECDSA.
   1774 		 */
   1775 		if (0) ;
   1776 #ifndef OPENSSL_NO_RSA
   1777 		else if (alg_a & SSL_aRSA)
   1778 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   1779 #endif
   1780 #ifndef OPENSSL_NO_ECDSA
   1781 		else if (alg_a & SSL_aECDSA)
   1782 			pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
   1783 #endif
   1784 		/* else anonymous ECDH, so no certificate or pkey. */
   1785 		EC_KEY_set_public_key(ecdh, srvr_ecpoint);
   1786 		s->session->sess_cert->peer_ecdh_tmp=ecdh;
   1787 		ecdh=NULL;
   1788 		BN_CTX_free(bn_ctx);
   1789 		bn_ctx = NULL;
   1790 		EC_POINT_free(srvr_ecpoint);
   1791 		srvr_ecpoint = NULL;
   1792 		}
   1793 #endif /* !OPENSSL_NO_ECDH */
   1794 
   1795 	else if (!(alg_k & SSL_kPSK))
   1796 		{
   1797 		al=SSL_AD_UNEXPECTED_MESSAGE;
   1798 		SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
   1799 		goto f_err;
   1800 		}
   1801 
   1802 	/* p points to the next byte, there are 'n' bytes left */
   1803 
   1804 	/* if it was signed, check the signature */
   1805 	if (pkey != NULL)
   1806 		{
   1807 		if (TLS1_get_version(s) >= TLS1_2_VERSION)
   1808 			{
   1809 			int sigalg = tls12_get_sigid(pkey);
   1810 			/* Should never happen */
   1811 			if (sigalg == -1)
   1812 				{
   1813 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   1814 				goto err;
   1815 				}
   1816 			/* Check key type is consistent with signature */
   1817 			if (sigalg != (int)p[1])
   1818 				{
   1819 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_TYPE);
   1820 				al=SSL_AD_DECODE_ERROR;
   1821 				goto f_err;
   1822 				}
   1823 			md = tls12_get_hash(p[0]);
   1824 			if (md == NULL)
   1825 				{
   1826 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNKNOWN_DIGEST);
   1827 				al=SSL_AD_DECODE_ERROR;
   1828 				goto f_err;
   1829 				}
   1830 #ifdef SSL_DEBUG
   1831 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
   1832 #endif
   1833 			p += 2;
   1834 			n -= 2;
   1835 			}
   1836 		else
   1837 			md = EVP_sha1();
   1838 
   1839 		n2s(p,i);
   1840 		n-=2;
   1841 		j=EVP_PKEY_size(pkey);
   1842 
   1843 		if ((i != n) || (n > j) || (n <= 0))
   1844 			{
   1845 			/* wrong packet length */
   1846 			al=SSL_AD_DECODE_ERROR;
   1847 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
   1848 			goto f_err;
   1849 			}
   1850 
   1851 #ifndef OPENSSL_NO_RSA
   1852 		if (pkey->type == EVP_PKEY_RSA && TLS1_get_version(s) < TLS1_2_VERSION)
   1853 			{
   1854 			int num;
   1855 
   1856 			j=0;
   1857 			q=md_buf;
   1858 			for (num=2; num > 0; num--)
   1859 				{
   1860 				EVP_MD_CTX_set_flags(&md_ctx,
   1861 					EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
   1862 				EVP_DigestInit_ex(&md_ctx,(num == 2)
   1863 					?s->ctx->md5:s->ctx->sha1, NULL);
   1864 				EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
   1865 				EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
   1866 				EVP_DigestUpdate(&md_ctx,param,param_len);
   1867 				EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
   1868 				q+=i;
   1869 				j+=i;
   1870 				}
   1871 			i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
   1872 								pkey->pkey.rsa);
   1873 			if (i < 0)
   1874 				{
   1875 				al=SSL_AD_DECRYPT_ERROR;
   1876 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
   1877 				goto f_err;
   1878 				}
   1879 			if (i == 0)
   1880 				{
   1881 				/* bad signature */
   1882 				al=SSL_AD_DECRYPT_ERROR;
   1883 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
   1884 				goto f_err;
   1885 				}
   1886 			}
   1887 		else
   1888 #endif
   1889 			{
   1890 			EVP_VerifyInit_ex(&md_ctx, md, NULL);
   1891 			EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
   1892 			EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
   1893 			EVP_VerifyUpdate(&md_ctx,param,param_len);
   1894 			if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
   1895 				{
   1896 				/* bad signature */
   1897 				al=SSL_AD_DECRYPT_ERROR;
   1898 				SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
   1899 				goto f_err;
   1900 				}
   1901 			}
   1902 		}
   1903 	else
   1904 		{
   1905 		if (!(alg_a & SSL_aNULL) &&
   1906 			/* Among PSK ciphers only RSA_PSK needs a public key */
   1907 			!((alg_a & SSL_aPSK) && !(alg_k & SSL_kRSA)))
   1908 			{
   1909 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   1910 			goto err;
   1911 			}
   1912 		/* still data left over */
   1913 		if (n != 0)
   1914 			{
   1915 			al=SSL_AD_DECODE_ERROR;
   1916 			SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
   1917 			goto f_err;
   1918 			}
   1919 		}
   1920 	EVP_PKEY_free(pkey);
   1921 	EVP_MD_CTX_cleanup(&md_ctx);
   1922 	return(1);
   1923 f_err:
   1924 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   1925 err:
   1926 	EVP_PKEY_free(pkey);
   1927 #ifndef OPENSSL_NO_RSA
   1928 	if (rsa != NULL)
   1929 		RSA_free(rsa);
   1930 #endif
   1931 #ifndef OPENSSL_NO_DH
   1932 	if (dh != NULL)
   1933 		DH_free(dh);
   1934 #endif
   1935 #ifndef OPENSSL_NO_ECDH
   1936 	BN_CTX_free(bn_ctx);
   1937 	EC_POINT_free(srvr_ecpoint);
   1938 	if (ecdh != NULL)
   1939 		EC_KEY_free(ecdh);
   1940 #endif
   1941 	EVP_MD_CTX_cleanup(&md_ctx);
   1942 	return(-1);
   1943 	}
   1944 
   1945 int ssl3_get_certificate_request(SSL *s)
   1946 	{
   1947 	int ok,ret=0;
   1948 	unsigned long n,nc,l;
   1949 	unsigned int llen, ctype_num,i;
   1950 	X509_NAME *xn=NULL;
   1951 	const unsigned char *p,*q;
   1952 	unsigned char *d;
   1953 	STACK_OF(X509_NAME) *ca_sk=NULL;
   1954 
   1955 	n=s->method->ssl_get_message(s,
   1956 		SSL3_ST_CR_CERT_REQ_A,
   1957 		SSL3_ST_CR_CERT_REQ_B,
   1958 		-1,
   1959 		s->max_cert_list,
   1960 		&ok);
   1961 
   1962 	if (!ok) return((int)n);
   1963 
   1964 	s->s3->tmp.cert_req=0;
   1965 
   1966 	if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
   1967 		{
   1968 		s->s3->tmp.reuse_message=1;
   1969 		/* If we get here we don't need any cached handshake records
   1970 		 * as we wont be doing client auth.
   1971 		 */
   1972 		if (s->s3->handshake_buffer)
   1973 			{
   1974 			if (!ssl3_digest_cached_records(s))
   1975 				goto err;
   1976 			}
   1977 		return(1);
   1978 		}
   1979 
   1980 	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
   1981 		{
   1982 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   1983 		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
   1984 		goto err;
   1985 		}
   1986 
   1987 	/* TLS does not like anon-DH with client cert */
   1988 	if (s->version > SSL3_VERSION)
   1989 		{
   1990 		if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
   1991 			{
   1992 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   1993 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
   1994 			goto err;
   1995 			}
   1996 		}
   1997 
   1998 	p=d=(unsigned char *)s->init_msg;
   1999 
   2000 	if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
   2001 		{
   2002 		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
   2003 		goto err;
   2004 		}
   2005 
   2006 	/* get the certificate types */
   2007 	ctype_num= *(p++);
   2008 	if (ctype_num > SSL3_CT_NUMBER)
   2009 		ctype_num=SSL3_CT_NUMBER;
   2010 	for (i=0; i<ctype_num; i++)
   2011 		s->s3->tmp.ctype[i]= p[i];
   2012 	p+=ctype_num;
   2013 	if (TLS1_get_version(s) >= TLS1_2_VERSION)
   2014 		{
   2015 		n2s(p, llen);
   2016 		/* Check we have enough room for signature algorithms and
   2017 		 * following length value.
   2018 		 */
   2019 		if ((unsigned long)(p - d + llen + 2) > n)
   2020 			{
   2021 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2022 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG);
   2023 			goto err;
   2024 			}
   2025 		if (llen & 1)
   2026 			{
   2027 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2028 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR);
   2029 			goto err;
   2030 			}
   2031 		tls1_process_sigalgs(s, p, llen);
   2032 		p += llen;
   2033 		}
   2034 
   2035 	/* get the CA RDNs */
   2036 	n2s(p,llen);
   2037 #if 0
   2038 {
   2039 FILE *out;
   2040 out=fopen("/tmp/vsign.der","w");
   2041 fwrite(p,1,llen,out);
   2042 fclose(out);
   2043 }
   2044 #endif
   2045 
   2046 	if ((unsigned long)(p - d + llen) != n)
   2047 		{
   2048 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2049 		SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
   2050 		goto err;
   2051 		}
   2052 
   2053 	for (nc=0; nc<llen; )
   2054 		{
   2055 		n2s(p,l);
   2056 		if ((l+nc+2) > llen)
   2057 			{
   2058 			if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
   2059 				goto cont; /* netscape bugs */
   2060 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2061 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
   2062 			goto err;
   2063 			}
   2064 
   2065 		q=p;
   2066 
   2067 		if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
   2068 			{
   2069 			/* If netscape tolerance is on, ignore errors */
   2070 			if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
   2071 				goto cont;
   2072 			else
   2073 				{
   2074 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2075 				SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
   2076 				goto err;
   2077 				}
   2078 			}
   2079 
   2080 		if (q != (p+l))
   2081 			{
   2082 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2083 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
   2084 			goto err;
   2085 			}
   2086 		if (!sk_X509_NAME_push(ca_sk,xn))
   2087 			{
   2088 			SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
   2089 			goto err;
   2090 			}
   2091 
   2092 		p+=l;
   2093 		nc+=l+2;
   2094 		}
   2095 
   2096 	if (0)
   2097 		{
   2098 cont:
   2099 		ERR_clear_error();
   2100 		}
   2101 
   2102 	/* we should setup a certificate to return.... */
   2103 	s->s3->tmp.cert_req=1;
   2104 	s->s3->tmp.ctype_num=ctype_num;
   2105 	if (s->s3->tmp.ca_names != NULL)
   2106 		sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
   2107 	s->s3->tmp.ca_names=ca_sk;
   2108 	ca_sk=NULL;
   2109 
   2110 	ret=1;
   2111 err:
   2112 	if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
   2113 	return(ret);
   2114 	}
   2115 
   2116 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
   2117 	{
   2118 	return(X509_NAME_cmp(*a,*b));
   2119 	}
   2120 #ifndef OPENSSL_NO_TLSEXT
   2121 int ssl3_get_new_session_ticket(SSL *s)
   2122 	{
   2123 	int ok,al,ret=0, ticklen;
   2124 	long n;
   2125 	const unsigned char *p;
   2126 	unsigned char *d;
   2127 
   2128 	n=s->method->ssl_get_message(s,
   2129 		SSL3_ST_CR_SESSION_TICKET_A,
   2130 		SSL3_ST_CR_SESSION_TICKET_B,
   2131 		-1,
   2132 		16384,
   2133 		&ok);
   2134 
   2135 	if (!ok)
   2136 		return((int)n);
   2137 
   2138 	if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
   2139 		{
   2140 		s->s3->tmp.reuse_message=1;
   2141 		return(1);
   2142 		}
   2143 	if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
   2144 		{
   2145 		al=SSL_AD_UNEXPECTED_MESSAGE;
   2146 		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
   2147 		goto f_err;
   2148 		}
   2149 	if (n < 6)
   2150 		{
   2151 		/* need at least ticket_lifetime_hint + ticket length */
   2152 		al = SSL_AD_DECODE_ERROR;
   2153 		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
   2154 		goto f_err;
   2155 		}
   2156 
   2157 	p=d=(unsigned char *)s->init_msg;
   2158 	n2l(p, s->session->tlsext_tick_lifetime_hint);
   2159 	n2s(p, ticklen);
   2160 	/* ticket_lifetime_hint + ticket_length + ticket */
   2161 	if (ticklen + 6 != n)
   2162 		{
   2163 		al = SSL_AD_DECODE_ERROR;
   2164 		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
   2165 		goto f_err;
   2166 		}
   2167 	if (s->session->tlsext_tick)
   2168 		{
   2169 		OPENSSL_free(s->session->tlsext_tick);
   2170 		s->session->tlsext_ticklen = 0;
   2171 		}
   2172 	s->session->tlsext_tick = OPENSSL_malloc(ticklen);
   2173 	if (!s->session->tlsext_tick)
   2174 		{
   2175 		SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
   2176 		goto err;
   2177 		}
   2178 	memcpy(s->session->tlsext_tick, p, ticklen);
   2179 	s->session->tlsext_ticklen = ticklen;
   2180 	/* There are two ways to detect a resumed ticket sesion.
   2181 	 * One is to set an appropriate session ID and then the server
   2182 	 * must return a match in ServerHello. This allows the normal
   2183 	 * client session ID matching to work and we know much
   2184 	 * earlier that the ticket has been accepted.
   2185 	 *
   2186 	 * The other way is to set zero length session ID when the
   2187 	 * ticket is presented and rely on the handshake to determine
   2188 	 * session resumption.
   2189 	 *
   2190 	 * We choose the former approach because this fits in with
   2191 	 * assumptions elsewhere in OpenSSL. The session ID is set
   2192 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
   2193 	 * ticket.
   2194 	 */
   2195 	EVP_Digest(p, ticklen,
   2196 			s->session->session_id, &s->session->session_id_length,
   2197 #ifndef OPENSSL_NO_SHA256
   2198 							EVP_sha256(), NULL);
   2199 #else
   2200 							EVP_sha1(), NULL);
   2201 #endif
   2202 	ret=1;
   2203 	return(ret);
   2204 f_err:
   2205 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   2206 err:
   2207 	return(-1);
   2208 	}
   2209 
   2210 int ssl3_get_cert_status(SSL *s)
   2211 	{
   2212 	int ok, al;
   2213 	unsigned long resplen,n;
   2214 	const unsigned char *p;
   2215 
   2216 	n=s->method->ssl_get_message(s,
   2217 		SSL3_ST_CR_CERT_STATUS_A,
   2218 		SSL3_ST_CR_CERT_STATUS_B,
   2219 		SSL3_MT_CERTIFICATE_STATUS,
   2220 		16384,
   2221 		&ok);
   2222 
   2223 	if (!ok) return((int)n);
   2224 	if (n < 4)
   2225 		{
   2226 		/* need at least status type + length */
   2227 		al = SSL_AD_DECODE_ERROR;
   2228 		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
   2229 		goto f_err;
   2230 		}
   2231 	p = (unsigned char *)s->init_msg;
   2232 	if (*p++ != TLSEXT_STATUSTYPE_ocsp)
   2233 		{
   2234 		al = SSL_AD_DECODE_ERROR;
   2235 		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
   2236 		goto f_err;
   2237 		}
   2238 	n2l3(p, resplen);
   2239 	if (resplen + 4 != n)
   2240 		{
   2241 		al = SSL_AD_DECODE_ERROR;
   2242 		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
   2243 		goto f_err;
   2244 		}
   2245 	if (s->tlsext_ocsp_resp)
   2246 		OPENSSL_free(s->tlsext_ocsp_resp);
   2247 	s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
   2248 	if (!s->tlsext_ocsp_resp)
   2249 		{
   2250 		al = SSL_AD_INTERNAL_ERROR;
   2251 		SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
   2252 		goto f_err;
   2253 		}
   2254 	s->tlsext_ocsp_resplen = resplen;
   2255 	if (s->ctx->tlsext_status_cb)
   2256 		{
   2257 		int ret;
   2258 		ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
   2259 		if (ret == 0)
   2260 			{
   2261 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
   2262 			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
   2263 			goto f_err;
   2264 			}
   2265 		if (ret < 0)
   2266 			{
   2267 			al = SSL_AD_INTERNAL_ERROR;
   2268 			SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
   2269 			goto f_err;
   2270 			}
   2271 		}
   2272 	return 1;
   2273 f_err:
   2274 	ssl3_send_alert(s,SSL3_AL_FATAL,al);
   2275 	return(-1);
   2276 	}
   2277 #endif
   2278 
   2279 int ssl3_get_server_done(SSL *s)
   2280 	{
   2281 	int ok,ret=0;
   2282 	long n;
   2283 
   2284 	n=s->method->ssl_get_message(s,
   2285 		SSL3_ST_CR_SRVR_DONE_A,
   2286 		SSL3_ST_CR_SRVR_DONE_B,
   2287 		SSL3_MT_SERVER_DONE,
   2288 		30, /* should be very small, like 0 :-) */
   2289 		&ok);
   2290 
   2291 	if (!ok) return((int)n);
   2292 	if (n > 0)
   2293 		{
   2294 		/* should contain no data */
   2295 		ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
   2296 		SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
   2297 		return -1;
   2298 		}
   2299 	ret=1;
   2300 	return(ret);
   2301 	}
   2302 
   2303 
   2304 int ssl3_send_client_key_exchange(SSL *s)
   2305 	{
   2306 	unsigned char *p,*d;
   2307 	int n = 0;
   2308 	unsigned long alg_k;
   2309 	unsigned long alg_a;
   2310 #ifndef OPENSSL_NO_RSA
   2311 	unsigned char *q;
   2312 	EVP_PKEY *pkey=NULL;
   2313 #endif
   2314 #ifndef OPENSSL_NO_KRB5
   2315 	KSSL_ERR kssl_err;
   2316 #endif /* OPENSSL_NO_KRB5 */
   2317 #ifndef OPENSSL_NO_ECDH
   2318 	EC_KEY *clnt_ecdh = NULL;
   2319 	const EC_POINT *srvr_ecpoint = NULL;
   2320 	EVP_PKEY *srvr_pub_pkey = NULL;
   2321 	unsigned char *encodedPoint = NULL;
   2322 	int encoded_pt_len = 0;
   2323 	BN_CTX * bn_ctx = NULL;
   2324 #ifndef OPENSSL_NO_PSK
   2325 	unsigned int psk_len = 0;
   2326 	unsigned char psk[PSK_MAX_PSK_LEN];
   2327 #endif /* OPENSSL_NO_PSK */
   2328 #endif /* OPENSSL_NO_ECDH */
   2329 
   2330 	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
   2331 		{
   2332 		d=(unsigned char *)s->init_buf->data;
   2333 		p= &(d[4]);
   2334 
   2335 		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   2336 		alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   2337 
   2338 #ifndef OPENSSL_NO_PSK
   2339 		if (alg_a & SSL_aPSK)
   2340 			{
   2341 			char identity[PSK_MAX_IDENTITY_LEN + 1];
   2342 			size_t identity_len;
   2343 			unsigned char *t = NULL;
   2344 			unsigned char pre_ms[PSK_MAX_PSK_LEN*2+4];
   2345 			unsigned int pre_ms_len = 0;
   2346 			int psk_err = 1;
   2347 
   2348 			n = 0;
   2349 			if (s->psk_client_callback == NULL)
   2350 				{
   2351 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2352 					SSL_R_PSK_NO_CLIENT_CB);
   2353 				goto err;
   2354 				}
   2355 
   2356 			memset(identity, 0, sizeof(identity));
   2357 			psk_len = s->psk_client_callback(s, s->session->psk_identity_hint,
   2358 				identity, sizeof(identity), psk, sizeof(psk));
   2359 			if (psk_len > PSK_MAX_PSK_LEN)
   2360 				{
   2361 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2362 					ERR_R_INTERNAL_ERROR);
   2363 				goto psk_err;
   2364 				}
   2365 			else if (psk_len == 0)
   2366 				{
   2367 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2368 					SSL_R_PSK_IDENTITY_NOT_FOUND);
   2369 				goto psk_err;
   2370 				}
   2371 			identity_len = strnlen(identity, sizeof(identity));
   2372 			if (identity_len > PSK_MAX_IDENTITY_LEN)
   2373 				{
   2374 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2375 					ERR_R_INTERNAL_ERROR);
   2376 				goto psk_err;
   2377 				}
   2378 
   2379 			if (!(alg_k & SSL_kEECDH))
   2380 				{
   2381 				/* Create the shared secret now if we're not using ECDHE-PSK.*/
   2382 				pre_ms_len = 2+psk_len+2+psk_len;
   2383 				t = pre_ms;
   2384 				s2n(psk_len, t);
   2385 				memset(t, 0, psk_len);
   2386 				t+=psk_len;
   2387 				s2n(psk_len, t);
   2388 				memcpy(t, psk, psk_len);
   2389 
   2390 				s->session->master_key_length =
   2391 					s->method->ssl3_enc->generate_master_secret(s,
   2392 						s->session->master_key,
   2393 						pre_ms, pre_ms_len);
   2394 				s2n(identity_len, p);
   2395 				memcpy(p, identity, identity_len);
   2396 				n = 2 + identity_len;
   2397 				}
   2398 
   2399 			if (s->session->psk_identity != NULL)
   2400 				OPENSSL_free(s->session->psk_identity);
   2401 			s->session->psk_identity = BUF_strdup(identity);
   2402 			if (s->session->psk_identity == NULL)
   2403 				{
   2404 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2405 					ERR_R_MALLOC_FAILURE);
   2406 				goto psk_err;
   2407 				}
   2408 			psk_err = 0;
   2409 		psk_err:
   2410 			OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
   2411 			OPENSSL_cleanse(pre_ms, sizeof(pre_ms));
   2412 			if (psk_err != 0)
   2413 				{
   2414 				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   2415 				goto err;
   2416 				}
   2417 			}
   2418 #endif
   2419 		/* Fool emacs indentation */
   2420 		if (0) {}
   2421 #ifndef OPENSSL_NO_RSA
   2422 		else if (alg_k & SSL_kRSA)
   2423 			{
   2424 			RSA *rsa;
   2425 			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
   2426 
   2427 			if (s->session->sess_cert->peer_rsa_tmp != NULL)
   2428 				rsa=s->session->sess_cert->peer_rsa_tmp;
   2429 			else
   2430 				{
   2431 				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
   2432 				if ((pkey == NULL) ||
   2433 					(pkey->type != EVP_PKEY_RSA) ||
   2434 					(pkey->pkey.rsa == NULL))
   2435 					{
   2436 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   2437 					goto err;
   2438 					}
   2439 				rsa=pkey->pkey.rsa;
   2440 				EVP_PKEY_free(pkey);
   2441 				}
   2442 
   2443 			tmp_buf[0]=s->client_version>>8;
   2444 			tmp_buf[1]=s->client_version&0xff;
   2445 			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
   2446 					goto err;
   2447 
   2448 			s->session->master_key_length=sizeof tmp_buf;
   2449 
   2450 			q=p;
   2451 			/* Fix buf for TLS and beyond */
   2452 			if (s->version > SSL3_VERSION)
   2453 				p+=2;
   2454 			n=RSA_public_encrypt(sizeof tmp_buf,
   2455 				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
   2456 #ifdef PKCS1_CHECK
   2457 			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
   2458 			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
   2459 #endif
   2460 			if (n <= 0)
   2461 				{
   2462 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
   2463 				goto err;
   2464 				}
   2465 
   2466 			/* Fix buf for TLS and beyond */
   2467 			if (s->version > SSL3_VERSION)
   2468 				{
   2469 				s2n(n,q);
   2470 				n+=2;
   2471 				}
   2472 
   2473 			s->session->master_key_length=
   2474 				s->method->ssl3_enc->generate_master_secret(s,
   2475 					s->session->master_key,
   2476 					tmp_buf,sizeof tmp_buf);
   2477 			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
   2478 			}
   2479 #endif
   2480 #ifndef OPENSSL_NO_KRB5
   2481 		else if (alg_k & SSL_kKRB5)
   2482 			{
   2483 			krb5_error_code	krb5rc;
   2484 			KSSL_CTX	*kssl_ctx = s->kssl_ctx;
   2485 			/*  krb5_data	krb5_ap_req;  */
   2486 			krb5_data	*enc_ticket;
   2487 			krb5_data	authenticator, *authp = NULL;
   2488 			EVP_CIPHER_CTX	ciph_ctx;
   2489 			const EVP_CIPHER *enc = NULL;
   2490 			unsigned char	iv[EVP_MAX_IV_LENGTH];
   2491 			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
   2492 			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
   2493 						+ EVP_MAX_IV_LENGTH];
   2494 			int 		padl, outl = sizeof(epms);
   2495 
   2496 			EVP_CIPHER_CTX_init(&ciph_ctx);
   2497 
   2498 #ifdef KSSL_DEBUG
   2499 			printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
   2500 				alg_k, SSL_kKRB5);
   2501 #endif	/* KSSL_DEBUG */
   2502 
   2503 			authp = NULL;
   2504 #ifdef KRB5SENDAUTH
   2505 			if (KRB5SENDAUTH)  authp = &authenticator;
   2506 #endif	/* KRB5SENDAUTH */
   2507 
   2508 			krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
   2509 				&kssl_err);
   2510 			enc = kssl_map_enc(kssl_ctx->enctype);
   2511 			if (enc == NULL)
   2512 			    goto err;
   2513 #ifdef KSSL_DEBUG
   2514 			{
   2515 			printf("kssl_cget_tkt rtn %d\n", krb5rc);
   2516 			if (krb5rc && kssl_err.text)
   2517 			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
   2518 			}
   2519 #endif	/* KSSL_DEBUG */
   2520 
   2521 			if (krb5rc)
   2522 				{
   2523 				ssl3_send_alert(s,SSL3_AL_FATAL,
   2524 						SSL_AD_HANDSHAKE_FAILURE);
   2525 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2526 						kssl_err.reason);
   2527 				goto err;
   2528 				}
   2529 
   2530 			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
   2531 			**  in place of RFC 2712 KerberosWrapper, as in:
   2532 			**
   2533 			**  Send ticket (copy to *p, set n = length)
   2534 			**  n = krb5_ap_req.length;
   2535 			**  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
   2536 			**  if (krb5_ap_req.data)
   2537 			**    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
   2538 			**
   2539 			**  Now using real RFC 2712 KerberosWrapper
   2540 			**  (Thanks to Simon Wilkinson <sxw (at) sxw.org.uk>)
   2541 			**  Note: 2712 "opaque" types are here replaced
   2542 			**  with a 2-byte length followed by the value.
   2543 			**  Example:
   2544 			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
   2545 			**  Where "xx xx" = length bytes.  Shown here with
   2546 			**  optional authenticator omitted.
   2547 			*/
   2548 
   2549 			/*  KerberosWrapper.Ticket		*/
   2550 			s2n(enc_ticket->length,p);
   2551 			memcpy(p, enc_ticket->data, enc_ticket->length);
   2552 			p+= enc_ticket->length;
   2553 			n = enc_ticket->length + 2;
   2554 
   2555 			/*  KerberosWrapper.Authenticator	*/
   2556 			if (authp  &&  authp->length)
   2557 				{
   2558 				s2n(authp->length,p);
   2559 				memcpy(p, authp->data, authp->length);
   2560 				p+= authp->length;
   2561 				n+= authp->length + 2;
   2562 
   2563 				free(authp->data);
   2564 				authp->data = NULL;
   2565 				authp->length = 0;
   2566 				}
   2567 			else
   2568 				{
   2569 				s2n(0,p);/*  null authenticator length	*/
   2570 				n+=2;
   2571 				}
   2572 
   2573 			    tmp_buf[0]=s->client_version>>8;
   2574 			    tmp_buf[1]=s->client_version&0xff;
   2575 			    if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
   2576 				goto err;
   2577 
   2578 			/*  20010420 VRS.  Tried it this way; failed.
   2579 			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
   2580 			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
   2581 			**				kssl_ctx->length);
   2582 			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
   2583 			*/
   2584 
   2585 			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
   2586 			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
   2587 				kssl_ctx->key,iv);
   2588 			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
   2589 				sizeof tmp_buf);
   2590 			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
   2591 			outl += padl;
   2592 			if (outl > (int)sizeof epms)
   2593 				{
   2594 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
   2595 				goto err;
   2596 				}
   2597 			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
   2598 
   2599 			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
   2600 			s2n(outl,p);
   2601 			memcpy(p, epms, outl);
   2602 			p+=outl;
   2603 			n+=outl + 2;
   2604 
   2605 			s->session->master_key_length=
   2606 				s->method->ssl3_enc->generate_master_secret(s,
   2607 					s->session->master_key,
   2608 					tmp_buf, sizeof tmp_buf);
   2609 
   2610 			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
   2611 			OPENSSL_cleanse(epms, outl);
   2612 			}
   2613 #endif
   2614 #ifndef OPENSSL_NO_DH
   2615 		else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
   2616 			{
   2617 			DH *dh_srvr,*dh_clnt;
   2618 
   2619 			if (s->session->sess_cert == NULL)
   2620 				{
   2621 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   2622 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
   2623 				goto err;
   2624 				}
   2625 
   2626 			if (s->session->sess_cert->peer_dh_tmp != NULL)
   2627 				dh_srvr=s->session->sess_cert->peer_dh_tmp;
   2628 			else
   2629 				{
   2630 				/* we get them from the cert */
   2631 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   2632 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
   2633 				goto err;
   2634 				}
   2635 
   2636 			/* generate a new random key */
   2637 			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
   2638 				{
   2639 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   2640 				goto err;
   2641 				}
   2642 			if (!DH_generate_key(dh_clnt))
   2643 				{
   2644 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   2645 				DH_free(dh_clnt);
   2646 				goto err;
   2647 				}
   2648 
   2649 			/* use the 'p' output buffer for the DH key, but
   2650 			 * make sure to clear it out afterwards */
   2651 
   2652 			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
   2653 
   2654 			if (n <= 0)
   2655 				{
   2656 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   2657 				DH_free(dh_clnt);
   2658 				goto err;
   2659 				}
   2660 
   2661 			/* generate master key from the result */
   2662 			s->session->master_key_length=
   2663 				s->method->ssl3_enc->generate_master_secret(s,
   2664 					s->session->master_key,p,n);
   2665 			/* clean up */
   2666 			memset(p,0,n);
   2667 
   2668 			/* send off the data */
   2669 			n=BN_num_bytes(dh_clnt->pub_key);
   2670 			s2n(n,p);
   2671 			BN_bn2bin(dh_clnt->pub_key,p);
   2672 			n+=2;
   2673 
   2674 			DH_free(dh_clnt);
   2675 
   2676 			/* perhaps clean things up a bit EAY EAY EAY EAY*/
   2677 			}
   2678 #endif
   2679 #ifndef OPENSSL_NO_ECDH
   2680 		else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
   2681 			{
   2682 			const EC_GROUP *srvr_group = NULL;
   2683 			EC_KEY *tkey;
   2684 			int ecdh_clnt_cert = 0;
   2685 			int field_size = 0;
   2686 #ifndef OPENSSL_NO_PSK
   2687 			unsigned char *pre_ms;
   2688 			unsigned char *t;
   2689 			unsigned int pre_ms_len;
   2690 			unsigned int i;
   2691 #endif
   2692 
   2693 			if (s->session->sess_cert == NULL)
   2694 				{
   2695 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
   2696 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
   2697 				goto err;
   2698 				}
   2699 
   2700 			/* Did we send out the client's
   2701 			 * ECDH share for use in premaster
   2702 			 * computation as part of client certificate?
   2703 			 * If so, set ecdh_clnt_cert to 1.
   2704 			 */
   2705 			if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL))
   2706 				{
   2707 				/* XXX: For now, we do not support client
   2708 				 * authentication using ECDH certificates.
   2709 				 * To add such support, one needs to add
   2710 				 * code that checks for appropriate
   2711 				 * conditions and sets ecdh_clnt_cert to 1.
   2712 				 * For example, the cert have an ECC
   2713 				 * key on the same curve as the server's
   2714 				 * and the key should be authorized for
   2715 				 * key agreement.
   2716 				 *
   2717 				 * One also needs to add code in ssl3_connect
   2718 				 * to skip sending the certificate verify
   2719 				 * message.
   2720 				 *
   2721 				 * if ((s->cert->key->privatekey != NULL) &&
   2722 				 *     (s->cert->key->privatekey->type ==
   2723 				 *      EVP_PKEY_EC) && ...)
   2724 				 * ecdh_clnt_cert = 1;
   2725 				 */
   2726 				}
   2727 
   2728 			if (s->session->sess_cert->peer_ecdh_tmp != NULL)
   2729 				{
   2730 				tkey = s->session->sess_cert->peer_ecdh_tmp;
   2731 				}
   2732 			else
   2733 				{
   2734 				/* Get the Server Public Key from Cert */
   2735 				srvr_pub_pkey = X509_get_pubkey(s->session-> \
   2736 				    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
   2737 				if ((srvr_pub_pkey == NULL) ||
   2738 				    (srvr_pub_pkey->type != EVP_PKEY_EC) ||
   2739 				    (srvr_pub_pkey->pkey.ec == NULL))
   2740 					{
   2741 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2742 					    ERR_R_INTERNAL_ERROR);
   2743 					goto err;
   2744 					}
   2745 
   2746 				tkey = srvr_pub_pkey->pkey.ec;
   2747 				}
   2748 
   2749 			srvr_group   = EC_KEY_get0_group(tkey);
   2750 			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
   2751 
   2752 			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
   2753 				{
   2754 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2755 				    ERR_R_INTERNAL_ERROR);
   2756 				goto err;
   2757 				}
   2758 
   2759 			if ((clnt_ecdh=EC_KEY_new()) == NULL)
   2760 				{
   2761 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   2762 				goto err;
   2763 				}
   2764 
   2765 			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
   2766 				{
   2767 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
   2768 				goto err;
   2769 				}
   2770 			if (ecdh_clnt_cert)
   2771 				{
   2772 				/* Reuse key info from our certificate
   2773 				 * We only need our private key to perform
   2774 				 * the ECDH computation.
   2775 				 */
   2776 				const BIGNUM *priv_key;
   2777 				tkey = s->cert->key->privatekey->pkey.ec;
   2778 				priv_key = EC_KEY_get0_private_key(tkey);
   2779 				if (priv_key == NULL)
   2780 					{
   2781 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   2782 					goto err;
   2783 					}
   2784 				if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
   2785 					{
   2786 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
   2787 					goto err;
   2788 					}
   2789 				}
   2790 			else
   2791 				{
   2792 				/* Generate a new ECDH key pair */
   2793 				if (!(EC_KEY_generate_key(clnt_ecdh)))
   2794 					{
   2795 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
   2796 					goto err;
   2797 					}
   2798 				}
   2799 
   2800 			/* use the 'p' output buffer for the ECDH key, but
   2801 			 * make sure to clear it out afterwards
   2802 			 */
   2803 
   2804 			field_size = EC_GROUP_get_degree(srvr_group);
   2805 			if (field_size <= 0)
   2806 				{
   2807 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2808 				       ERR_R_ECDH_LIB);
   2809 				goto err;
   2810 				}
   2811 			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
   2812 			if (n <= 0)
   2813 				{
   2814 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2815 				       ERR_R_ECDH_LIB);
   2816 				goto err;
   2817 				}
   2818 
   2819 #ifndef OPENSSL_NO_PSK
   2820 			/* ECDHE PSK ciphersuites from RFC 5489 */
   2821 			if ((alg_a & SSL_aPSK) && psk_len != 0)
   2822 				{
   2823 				pre_ms_len = 2+psk_len+2+n;
   2824 				pre_ms = OPENSSL_malloc(pre_ms_len);
   2825 				if (pre_ms == NULL)
   2826 					{
   2827 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2828 			    		ERR_R_MALLOC_FAILURE);
   2829 					goto err;
   2830 					}
   2831 				memset(pre_ms, 0, pre_ms_len);
   2832 				t = pre_ms;
   2833 				s2n(psk_len, t);
   2834 				memcpy(t, psk, psk_len);
   2835 				t += psk_len;
   2836 				s2n(n, t);
   2837 				memcpy(t, p, n);
   2838 				s->session->master_key_length = s->method->ssl3_enc \
   2839 					-> generate_master_secret(s,
   2840 						s->session->master_key, pre_ms, pre_ms_len);
   2841 				OPENSSL_cleanse(pre_ms, pre_ms_len);
   2842 				OPENSSL_free(pre_ms);
   2843 				}
   2844 #endif /* OPENSSL_NO_PSK */
   2845 			if (!(alg_a & SSL_aPSK))
   2846 				{
   2847 				/* generate master key from the result */
   2848 				s->session->master_key_length = s->method->ssl3_enc \
   2849 					-> generate_master_secret(s,
   2850 						s->session->master_key, p, n);
   2851 				}
   2852 			memset(p, 0, n); /* clean up */
   2853 			if (ecdh_clnt_cert)
   2854 				{
   2855 				/* Send empty client key exch message */
   2856 				n = 0;
   2857 				}
   2858 			else
   2859 				{
   2860 				/* First check the size of encoding and
   2861 				 * allocate memory accordingly.
   2862 				 */
   2863 				encoded_pt_len =
   2864 				    EC_POINT_point2oct(srvr_group,
   2865 					EC_KEY_get0_public_key(clnt_ecdh),
   2866 					POINT_CONVERSION_UNCOMPRESSED,
   2867 					NULL, 0, NULL);
   2868 
   2869 				encodedPoint = (unsigned char *)
   2870 				    OPENSSL_malloc(encoded_pt_len *
   2871 					sizeof(unsigned char));
   2872 				bn_ctx = BN_CTX_new();
   2873 				if ((encodedPoint == NULL) ||
   2874 				    (bn_ctx == NULL))
   2875 					{
   2876 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   2877 					goto err;
   2878 					}
   2879 
   2880 				/* Encode the public key */
   2881 				encoded_pt_len = EC_POINT_point2oct(srvr_group,
   2882 				    EC_KEY_get0_public_key(clnt_ecdh),
   2883 				    POINT_CONVERSION_UNCOMPRESSED,
   2884 				    encodedPoint, encoded_pt_len, bn_ctx);
   2885 
   2886 				n = 0;
   2887 #ifndef OPENSSL_NO_PSK
   2888 				if ((alg_a & SSL_aPSK) && psk_len != 0)
   2889 					{
   2890 					i = strlen(s->session->psk_identity);
   2891 					s2n(i, p);
   2892 					memcpy(p, s->session->psk_identity, i);
   2893 					p += i;
   2894 					n = i + 2;
   2895 					}
   2896 #endif
   2897 
   2898 				*p = encoded_pt_len; /* length of encoded point */
   2899 				/* Encoded point will be copied here */
   2900 				p += 1;
   2901 				n += 1;
   2902 				/* copy the point */
   2903 				memcpy((unsigned char *)p, encodedPoint, encoded_pt_len);
   2904 				/* increment n to account for length field */
   2905 				n += encoded_pt_len;
   2906 				}
   2907 
   2908 			/* Free allocated memory */
   2909 			BN_CTX_free(bn_ctx);
   2910 			if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
   2911 			if (clnt_ecdh != NULL)
   2912 				 EC_KEY_free(clnt_ecdh);
   2913 			EVP_PKEY_free(srvr_pub_pkey);
   2914 			}
   2915 #endif /* !OPENSSL_NO_ECDH */
   2916 		else if (alg_k & SSL_kGOST)
   2917 			{
   2918 			/* GOST key exchange message creation */
   2919 			EVP_PKEY_CTX *pkey_ctx;
   2920 			X509 *peer_cert;
   2921 			size_t msglen;
   2922 			unsigned int md_len;
   2923 			int keytype;
   2924 			unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
   2925 			EVP_MD_CTX *ukm_hash;
   2926 			EVP_PKEY *pub_key;
   2927 
   2928 			/* Get server sertificate PKEY and create ctx from it */
   2929 			peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
   2930 			if (!peer_cert)
   2931 				peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
   2932 			if (!peer_cert)		{
   2933 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
   2934 					goto err;
   2935 				}
   2936 
   2937 			pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
   2938 			/* If we have send a certificate, and certificate key
   2939 
   2940 			 * parameters match those of server certificate, use
   2941 			 * certificate key for key exchange
   2942 			 */
   2943 
   2944 			 /* Otherwise, generate ephemeral key pair */
   2945 
   2946 			EVP_PKEY_encrypt_init(pkey_ctx);
   2947 			  /* Generate session key */
   2948 		    RAND_bytes(premaster_secret,32);
   2949 			/* If we have client certificate, use its secret as peer key */
   2950 			if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
   2951 				if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
   2952 					/* If there was an error - just ignore it. Ephemeral key
   2953 					* would be used
   2954 					*/
   2955 					ERR_clear_error();
   2956 				}
   2957 			}
   2958 			/* Compute shared IV and store it in algorithm-specific
   2959 			 * context data */
   2960 			ukm_hash = EVP_MD_CTX_create();
   2961 			EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
   2962 			EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
   2963 			EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
   2964 			EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
   2965 			EVP_MD_CTX_destroy(ukm_hash);
   2966 			if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
   2967 				8,shared_ukm)<0) {
   2968 					SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2969 						SSL_R_LIBRARY_BUG);
   2970 					goto err;
   2971 				}
   2972 			/* Make GOST keytransport blob message */
   2973 			/*Encapsulate it into sequence */
   2974 			*(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
   2975 			msglen=255;
   2976 			if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
   2977 			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   2978 					SSL_R_LIBRARY_BUG);
   2979 				goto err;
   2980 			}
   2981 			if (msglen >= 0x80)
   2982 				{
   2983 				*(p++)=0x81;
   2984 				*(p++)= msglen & 0xff;
   2985 				n=msglen+3;
   2986 				}
   2987 			else
   2988 				{
   2989 				*(p++)= msglen & 0xff;
   2990 				n=msglen+2;
   2991 				}
   2992 			memcpy(p, tmp, msglen);
   2993 			/* Check if pubkey from client certificate was used */
   2994 			if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
   2995 				{
   2996 				/* Set flag "skip certificate verify" */
   2997 				s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
   2998 				}
   2999 			EVP_PKEY_CTX_free(pkey_ctx);
   3000 			s->session->master_key_length=
   3001 				s->method->ssl3_enc->generate_master_secret(s,
   3002 					s->session->master_key,premaster_secret,32);
   3003 			EVP_PKEY_free(pub_key);
   3004 
   3005 			}
   3006 #ifndef OPENSSL_NO_SRP
   3007 		else if (alg_k & SSL_kSRP)
   3008 			{
   3009 			if (s->srp_ctx.A != NULL)
   3010 				{
   3011 				/* send off the data */
   3012 				n=BN_num_bytes(s->srp_ctx.A);
   3013 				s2n(n,p);
   3014 				BN_bn2bin(s->srp_ctx.A,p);
   3015 				n+=2;
   3016 				}
   3017 			else
   3018 				{
   3019 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   3020 				goto err;
   3021 				}
   3022 			if (s->session->srp_username != NULL)
   3023 				OPENSSL_free(s->session->srp_username);
   3024 			s->session->srp_username = BUF_strdup(s->srp_ctx.login);
   3025 			if (s->session->srp_username == NULL)
   3026 				{
   3027 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   3028 					ERR_R_MALLOC_FAILURE);
   3029 				goto err;
   3030 				}
   3031 
   3032 			if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0)
   3033 				{
   3034 				SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   3035 				goto err;
   3036 				}
   3037 			}
   3038 #endif
   3039 		else if (!(alg_k & SSL_kPSK) || ((alg_k & SSL_kPSK) && !(alg_a & SSL_aPSK)))
   3040 			{
   3041 			ssl3_send_alert(s, SSL3_AL_FATAL,
   3042 			    SSL_AD_HANDSHAKE_FAILURE);
   3043 			SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
   3044 			    ERR_R_INTERNAL_ERROR);
   3045 			goto err;
   3046 			}
   3047 
   3048 		*(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
   3049 		l2n3(n,d);
   3050 
   3051 		s->state=SSL3_ST_CW_KEY_EXCH_B;
   3052 		/* number of bytes to write */
   3053 		s->init_num=n+4;
   3054 		s->init_off=0;
   3055 		}
   3056 
   3057 	/* SSL3_ST_CW_KEY_EXCH_B */
   3058 	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
   3059 err:
   3060 #ifndef OPENSSL_NO_ECDH
   3061 	BN_CTX_free(bn_ctx);
   3062 	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
   3063 	if (clnt_ecdh != NULL)
   3064 		EC_KEY_free(clnt_ecdh);
   3065 	EVP_PKEY_free(srvr_pub_pkey);
   3066 #endif
   3067 	return(-1);
   3068 	}
   3069 
   3070 int ssl3_send_client_verify(SSL *s)
   3071 	{
   3072 	unsigned char *p,*d;
   3073 	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
   3074 	EVP_PKEY *pkey;
   3075 	EVP_PKEY_CTX *pctx=NULL;
   3076 	EVP_MD_CTX mctx;
   3077 	unsigned u=0;
   3078 	unsigned long n;
   3079 	int j;
   3080 
   3081 	EVP_MD_CTX_init(&mctx);
   3082 
   3083 	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
   3084 		{
   3085 		d=(unsigned char *)s->init_buf->data;
   3086 		p= &(d[4]);
   3087 		pkey=s->cert->key->privatekey;
   3088 /* Create context from key and test if sha1 is allowed as digest */
   3089 		pctx = EVP_PKEY_CTX_new(pkey,NULL);
   3090 		EVP_PKEY_sign_init(pctx);
   3091 		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
   3092 			{
   3093 			if (TLS1_get_version(s) < TLS1_2_VERSION)
   3094 				s->method->ssl3_enc->cert_verify_mac(s,
   3095 						NID_sha1,
   3096 						&(data[MD5_DIGEST_LENGTH]));
   3097 			}
   3098 		else
   3099 			{
   3100 			ERR_clear_error();
   3101 			}
   3102 		/* For TLS v1.2 send signature algorithm and signature
   3103 		 * using agreed digest and cached handshake records.
   3104 		 */
   3105 		if (TLS1_get_version(s) >= TLS1_2_VERSION)
   3106 			{
   3107 			long hdatalen = 0;
   3108 			void *hdata;
   3109 			const EVP_MD *md;
   3110 			switch (ssl_cert_type(NULL, pkey))
   3111 				{
   3112 			case SSL_PKEY_RSA_ENC:
   3113 				md = s->s3->digest_rsa;
   3114 				break;
   3115 			case SSL_PKEY_DSA_SIGN:
   3116 				md = s->s3->digest_dsa;
   3117 				break;
   3118 			case SSL_PKEY_ECC:
   3119 				md = s->s3->digest_ecdsa;
   3120 				break;
   3121 			default:
   3122 				md = NULL;
   3123 				}
   3124 			if (!md)
   3125 				/* Unlike with the SignatureAlgorithm extension (sent by clients),
   3126 				 * there are no default algorithms for the CertificateRequest message
   3127 				 * (sent by servers). However, now that we've sent a certificate
   3128 				 * for which we don't really know what hash to use for signing, the
   3129 				 * best we can do is try a default algorithm. */
   3130 				md = EVP_sha1();
   3131 			hdatalen = BIO_get_mem_data(s->s3->handshake_buffer,
   3132 								&hdata);
   3133 			if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md))
   3134 				{
   3135 				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
   3136 						ERR_R_INTERNAL_ERROR);
   3137 				goto err;
   3138 				}
   3139 			p += 2;
   3140 #ifdef SSL_DEBUG
   3141 			fprintf(stderr, "Using TLS 1.2 with client alg %s\n",
   3142 							EVP_MD_name(md));
   3143 #endif
   3144 			if (!EVP_SignInit_ex(&mctx, md, NULL)
   3145 				|| !EVP_SignUpdate(&mctx, hdata, hdatalen)
   3146 				|| !EVP_SignFinal(&mctx, p + 2, &u, pkey))
   3147 				{
   3148 				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
   3149 						ERR_R_EVP_LIB);
   3150 				goto err;
   3151 				}
   3152 			s2n(u,p);
   3153 			n = u + 4;
   3154 			if (!ssl3_digest_cached_records(s))
   3155 				goto err;
   3156 			}
   3157 		else
   3158 #ifndef OPENSSL_NO_RSA
   3159 		if (pkey->type == EVP_PKEY_RSA)
   3160 			{
   3161 			s->method->ssl3_enc->cert_verify_mac(s,
   3162 				NID_md5,
   3163 			 	&(data[0]));
   3164 			if (RSA_sign(NID_md5_sha1, data,
   3165 					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
   3166 					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
   3167 				{
   3168 				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
   3169 				goto err;
   3170 				}
   3171 			s2n(u,p);
   3172 			n=u+2;
   3173 			}
   3174 		else
   3175 #endif
   3176 #ifndef OPENSSL_NO_DSA
   3177 			if (pkey->type == EVP_PKEY_DSA)
   3178 			{
   3179 			if (!DSA_sign(pkey->save_type,
   3180 				&(data[MD5_DIGEST_LENGTH]),
   3181 				SHA_DIGEST_LENGTH,&(p[2]),
   3182 				(unsigned int *)&j,pkey->pkey.dsa))
   3183 				{
   3184 				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
   3185 				goto err;
   3186 				}
   3187 			s2n(j,p);
   3188 			n=j+2;
   3189 			}
   3190 		else
   3191 #endif
   3192 #ifndef OPENSSL_NO_ECDSA
   3193 			if (pkey->type == EVP_PKEY_EC)
   3194 			{
   3195 			if (!ECDSA_sign(pkey->save_type,
   3196 				&(data[MD5_DIGEST_LENGTH]),
   3197 				SHA_DIGEST_LENGTH,&(p[2]),
   3198 				(unsigned int *)&j,pkey->pkey.ec))
   3199 				{
   3200 				SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
   3201 				    ERR_R_ECDSA_LIB);
   3202 				goto err;
   3203 				}
   3204 			s2n(j,p);
   3205 			n=j+2;
   3206 			}
   3207 		else
   3208 #endif
   3209 		if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
   3210 		{
   3211 		unsigned char signbuf[64];
   3212 		int i;
   3213 		size_t sigsize=64;
   3214 		s->method->ssl3_enc->cert_verify_mac(s,
   3215 			NID_id_GostR3411_94,
   3216 			data);
   3217 		if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) {
   3218 			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
   3219 			ERR_R_INTERNAL_ERROR);
   3220 			goto err;
   3221 		}
   3222 		for (i=63,j=0; i>=0; j++, i--) {
   3223 			p[2+j]=signbuf[i];
   3224 		}
   3225 		s2n(j,p);
   3226 		n=j+2;
   3227 		}
   3228 		else
   3229 		{
   3230 			SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
   3231 			goto err;
   3232 		}
   3233 		*(d++)=SSL3_MT_CERTIFICATE_VERIFY;
   3234 		l2n3(n,d);
   3235 
   3236 		s->state=SSL3_ST_CW_CERT_VRFY_B;
   3237 		s->init_num=(int)n+4;
   3238 		s->init_off=0;
   3239 		}
   3240 	EVP_MD_CTX_cleanup(&mctx);
   3241 	EVP_PKEY_CTX_free(pctx);
   3242 	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
   3243 err:
   3244 	EVP_MD_CTX_cleanup(&mctx);
   3245 	EVP_PKEY_CTX_free(pctx);
   3246 	return(-1);
   3247 	}
   3248 
   3249 int ssl3_send_client_certificate(SSL *s)
   3250 	{
   3251 	X509 *x509=NULL;
   3252 	EVP_PKEY *pkey=NULL;
   3253 	int i;
   3254 	unsigned long l;
   3255 
   3256 	if (s->state ==	SSL3_ST_CW_CERT_A)
   3257 		{
   3258 		if ((s->cert == NULL) ||
   3259 			(s->cert->key->x509 == NULL) ||
   3260 			(s->cert->key->privatekey == NULL))
   3261 			s->state=SSL3_ST_CW_CERT_B;
   3262 		else
   3263 			s->state=SSL3_ST_CW_CERT_C;
   3264 		}
   3265 
   3266 	/* We need to get a client cert */
   3267 	if (s->state == SSL3_ST_CW_CERT_B)
   3268 		{
   3269 		/* If we get an error, we need to
   3270 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
   3271 		 * We then get retied later */
   3272 		i=0;
   3273 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
   3274 		if (i < 0)
   3275 			{
   3276 			s->rwstate=SSL_X509_LOOKUP;
   3277 			return(-1);
   3278 			}
   3279 		s->rwstate=SSL_NOTHING;
   3280 		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
   3281 			{
   3282 			s->state=SSL3_ST_CW_CERT_B;
   3283 			if (	!SSL_use_certificate(s,x509) ||
   3284 				!SSL_use_PrivateKey(s,pkey))
   3285 				i=0;
   3286 			}
   3287 		else if (i == 1)
   3288 			{
   3289 			i=0;
   3290 			SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
   3291 			}
   3292 
   3293 		if (x509 != NULL) X509_free(x509);
   3294 		if (pkey != NULL) EVP_PKEY_free(pkey);
   3295 		if (i == 0)
   3296 			{
   3297 			if (s->version == SSL3_VERSION)
   3298 				{
   3299 				s->s3->tmp.cert_req=0;
   3300 				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
   3301 				return(1);
   3302 				}
   3303 			else
   3304 				{
   3305 				s->s3->tmp.cert_req=2;
   3306 				}
   3307 			}
   3308 
   3309 		/* Ok, we have a cert */
   3310 		s->state=SSL3_ST_CW_CERT_C;
   3311 		}
   3312 
   3313 	if (s->state == SSL3_ST_CW_CERT_C)
   3314 		{
   3315 		s->state=SSL3_ST_CW_CERT_D;
   3316 		l=ssl3_output_cert_chain(s,
   3317 			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
   3318 		s->init_num=(int)l;
   3319 		s->init_off=0;
   3320 		}
   3321 	/* SSL3_ST_CW_CERT_D */
   3322 	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
   3323 	}
   3324 
   3325 #define has_bits(i,m)	(((i)&(m)) == (m))
   3326 
   3327 int ssl3_check_cert_and_algorithm(SSL *s)
   3328 	{
   3329 	int i,idx;
   3330 	long alg_k,alg_a;
   3331 	EVP_PKEY *pkey=NULL;
   3332 	SESS_CERT *sc;
   3333 #ifndef OPENSSL_NO_RSA
   3334 	RSA *rsa;
   3335 #endif
   3336 #ifndef OPENSSL_NO_DH
   3337 	DH *dh;
   3338 #endif
   3339 
   3340 	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
   3341 	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
   3342 
   3343 	/* we don't have a certificate */
   3344 	if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || ((alg_a & SSL_aPSK) && !(alg_k & SSL_kRSA)))
   3345 		return(1);
   3346 
   3347 	sc=s->session->sess_cert;
   3348 	if (sc == NULL)
   3349 		{
   3350 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
   3351 		goto err;
   3352 		}
   3353 
   3354 #ifndef OPENSSL_NO_RSA
   3355 	rsa=s->session->sess_cert->peer_rsa_tmp;
   3356 #endif
   3357 #ifndef OPENSSL_NO_DH
   3358 	dh=s->session->sess_cert->peer_dh_tmp;
   3359 #endif
   3360 
   3361 	/* This is the passed certificate */
   3362 
   3363 	idx=sc->peer_cert_type;
   3364 #ifndef OPENSSL_NO_ECDH
   3365 	if (idx == SSL_PKEY_ECC)
   3366 		{
   3367 		if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
   3368 		    						s) == 0)
   3369 			{ /* check failed */
   3370 			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
   3371 			goto f_err;
   3372 			}
   3373 		else
   3374 			{
   3375 			return 1;
   3376 			}
   3377 		}
   3378 #endif
   3379 	pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
   3380 	i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
   3381 	EVP_PKEY_free(pkey);
   3382 
   3383 
   3384 	/* Check that we have a certificate if we require one */
   3385 	if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
   3386 		{
   3387 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
   3388 		goto f_err;
   3389 		}
   3390 #ifndef OPENSSL_NO_DSA
   3391 	else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
   3392 		{
   3393 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
   3394 		goto f_err;
   3395 		}
   3396 #endif
   3397 #ifndef OPENSSL_NO_RSA
   3398 	if ((alg_k & SSL_kRSA) &&
   3399 		!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
   3400 		{
   3401 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
   3402 		goto f_err;
   3403 		}
   3404 #endif
   3405 #ifndef OPENSSL_NO_DH
   3406 	if ((alg_k & SSL_kEDH) &&
   3407 		!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
   3408 		{
   3409 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
   3410 		goto f_err;
   3411 		}
   3412 	else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
   3413 		{
   3414 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
   3415 		goto f_err;
   3416 		}
   3417 #ifndef OPENSSL_NO_DSA
   3418 	else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
   3419 		{
   3420 		SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
   3421 		goto f_err;
   3422 		}
   3423 #endif
   3424 #endif
   3425 
   3426 	if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
   3427 		{
   3428 #ifndef OPENSSL_NO_RSA
   3429 		if (alg_k & SSL_kRSA)
   3430 			{
   3431 			if (rsa == NULL
   3432 			    || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
   3433 				{
   3434 				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
   3435 				goto f_err;
   3436 				}
   3437 			}
   3438 		else
   3439 #endif
   3440 #ifndef OPENSSL_NO_DH
   3441 			if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
   3442 			    {
   3443 			    if (dh == NULL
   3444 				|| DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
   3445 				{
   3446 				SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
   3447 				goto f_err;
   3448 				}
   3449 			}
   3450 		else
   3451 #endif
   3452 			{
   3453 			SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
   3454 			goto f_err;
   3455 			}
   3456 		}
   3457 	return(1);
   3458 f_err:
   3459 	ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   3460 err:
   3461 	return(0);
   3462 	}
   3463 
   3464 #if !defined(OPENSSL_NO_TLSEXT)
   3465 # if !defined(OPENSSL_NO_NEXTPROTONEG)
   3466 int ssl3_send_next_proto(SSL *s)
   3467 	{
   3468 	unsigned int len, padding_len;
   3469 	unsigned char *d;
   3470 
   3471 	if (s->state == SSL3_ST_CW_NEXT_PROTO_A)
   3472 		{
   3473 		len = s->next_proto_negotiated_len;
   3474 		padding_len = 32 - ((len + 2) % 32);
   3475 		d = (unsigned char *)s->init_buf->data;
   3476 		d[4] = len;
   3477 		memcpy(d + 5, s->next_proto_negotiated, len);
   3478 		d[5 + len] = padding_len;
   3479 		memset(d + 6 + len, 0, padding_len);
   3480 		*(d++)=SSL3_MT_NEXT_PROTO;
   3481 		l2n3(2 + len + padding_len, d);
   3482 		s->state = SSL3_ST_CW_NEXT_PROTO_B;
   3483 		s->init_num = 4 + 2 + len + padding_len;
   3484 		s->init_off = 0;
   3485 		}
   3486 
   3487 	return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   3488 }
   3489 # endif  /* !OPENSSL_NO_NEXTPROTONEG */
   3490 
   3491 int ssl3_send_channel_id(SSL *s)
   3492 	{
   3493 	unsigned char *d;
   3494 	int ret = -1, public_key_len;
   3495 	EVP_MD_CTX md_ctx;
   3496 	size_t sig_len;
   3497 	ECDSA_SIG *sig = NULL;
   3498 	unsigned char *public_key = NULL, *derp, *der_sig = NULL;
   3499 
   3500 	if (s->state != SSL3_ST_CW_CHANNEL_ID_A)
   3501 		return ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   3502 
   3503 	if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb)
   3504 		{
   3505 		EVP_PKEY *key = NULL;
   3506 		s->ctx->channel_id_cb(s, &key);
   3507 		if (key != NULL)
   3508 			{
   3509 			s->tlsext_channel_id_private = key;
   3510 			}
   3511 		}
   3512 	if (!s->tlsext_channel_id_private)
   3513 		{
   3514 		s->rwstate=SSL_CHANNEL_ID_LOOKUP;
   3515 		return (-1);
   3516 		}
   3517 	s->rwstate=SSL_NOTHING;
   3518 
   3519 	d = (unsigned char *)s->init_buf->data;
   3520 	*(d++)=SSL3_MT_ENCRYPTED_EXTENSIONS;
   3521 	l2n3(2 + 2 + TLSEXT_CHANNEL_ID_SIZE, d);
   3522 	if (s->s3->tlsext_channel_id_new)
   3523 		s2n(TLSEXT_TYPE_channel_id_new, d);
   3524 	else
   3525 		s2n(TLSEXT_TYPE_channel_id, d);
   3526 	s2n(TLSEXT_CHANNEL_ID_SIZE, d);
   3527 
   3528 	EVP_MD_CTX_init(&md_ctx);
   3529 
   3530 	public_key_len = i2d_PublicKey(s->tlsext_channel_id_private, NULL);
   3531 	if (public_key_len <= 0)
   3532 		{
   3533 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
   3534 		goto err;
   3535 		}
   3536 	/* i2d_PublicKey will produce an ANSI X9.62 public key which, for a
   3537 	 * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
   3538 	 * field elements as 32-byte, big-endian numbers. */
   3539 	if (public_key_len != 65)
   3540 		{
   3541 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_CHANNEL_ID_NOT_P256);
   3542 		goto err;
   3543 		}
   3544 	public_key = OPENSSL_malloc(public_key_len);
   3545 	if (!public_key)
   3546 		{
   3547 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,ERR_R_MALLOC_FAILURE);
   3548 		goto err;
   3549 		}
   3550 
   3551 	derp = public_key;
   3552 	i2d_PublicKey(s->tlsext_channel_id_private, &derp);
   3553 
   3554 	if (EVP_DigestSignInit(&md_ctx, NULL, EVP_sha256(), NULL,
   3555 			       s->tlsext_channel_id_private) != 1)
   3556 		{
   3557 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNINIT_FAILED);
   3558 		goto err;
   3559 		}
   3560 
   3561 	if (!tls1_channel_id_hash(&md_ctx, s))
   3562 		goto err;
   3563 
   3564 	if (!EVP_DigestSignFinal(&md_ctx, NULL, &sig_len))
   3565 		{
   3566 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   3567 		goto err;
   3568 		}
   3569 
   3570 	der_sig = OPENSSL_malloc(sig_len);
   3571 	if (!der_sig)
   3572 		{
   3573 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,ERR_R_MALLOC_FAILURE);
   3574 		goto err;
   3575 		}
   3576 
   3577 	if (!EVP_DigestSignFinal(&md_ctx, der_sig, &sig_len))
   3578 		{
   3579 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_EVP_DIGESTSIGNFINAL_FAILED);
   3580 		goto err;
   3581 		}
   3582 
   3583 	derp = der_sig;
   3584 	sig = d2i_ECDSA_SIG(NULL, (const unsigned char**) &derp, sig_len);
   3585 	if (sig == NULL)
   3586 		{
   3587 		SSLerr(SSL_F_SSL3_SEND_CHANNEL_ID,SSL_R_D2I_ECDSA_SIG);
   3588 		goto err;
   3589 		}
   3590 
   3591 	/* The first byte of public_key will be 0x4, denoting an uncompressed key. */
   3592 	memcpy(d, public_key + 1, 64);
   3593 	d += 64;
   3594 	memset(d, 0, 2 * 32);
   3595 	BN_bn2bin(sig->r, d + 32 - BN_num_bytes(sig->r));
   3596 	d += 32;
   3597 	BN_bn2bin(sig->s, d + 32 - BN_num_bytes(sig->s));
   3598 	d += 32;
   3599 
   3600 	s->state = SSL3_ST_CW_CHANNEL_ID_B;
   3601 	s->init_num = 4 + 2 + 2 + TLSEXT_CHANNEL_ID_SIZE;
   3602 	s->init_off = 0;
   3603 
   3604 	ret = ssl3_do_write(s, SSL3_RT_HANDSHAKE);
   3605 
   3606 err:
   3607 	EVP_MD_CTX_cleanup(&md_ctx);
   3608 	if (public_key)
   3609 		OPENSSL_free(public_key);
   3610 	if (der_sig)
   3611 		OPENSSL_free(der_sig);
   3612 	if (sig)
   3613 		ECDSA_SIG_free(sig);
   3614 
   3615 	return ret;
   3616 	}
   3617 #endif  /* !OPENSSL_NO_TLSEXT */
   3618 
   3619 /* Check to see if handshake is full or resumed. Usually this is just a
   3620  * case of checking to see if a cache hit has occurred. In the case of
   3621  * session tickets we have to check the next message to be sure.
   3622  */
   3623 
   3624 #ifndef OPENSSL_NO_TLSEXT
   3625 int ssl3_check_finished(SSL *s)
   3626 	{
   3627 	int ok;
   3628 	long n;
   3629 	/* If we have no ticket it cannot be a resumed session. */
   3630 	if (!s->session->tlsext_tick)
   3631 		return 1;
   3632 	/* this function is called when we really expect a Certificate
   3633 	 * message, so permit appropriate message length */
   3634 	n=s->method->ssl_get_message(s,
   3635 		SSL3_ST_CR_CERT_A,
   3636 		SSL3_ST_CR_CERT_B,
   3637 		-1,
   3638 		s->max_cert_list,
   3639 		&ok);
   3640 	if (!ok) return((int)n);
   3641 	s->s3->tmp.reuse_message = 1;
   3642 	if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
   3643 		|| (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
   3644 		return 2;
   3645 
   3646 	return 1;
   3647 	}
   3648 #endif
   3649 
   3650 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
   3651 	{
   3652 	int i = 0;
   3653 #ifndef OPENSSL_NO_ENGINE
   3654 	if (s->ctx->client_cert_engine)
   3655 		{
   3656 		i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
   3657 						SSL_get_client_CA_list(s),
   3658 						px509, ppkey, NULL, NULL, NULL);
   3659 		if (i != 0)
   3660 			return i;
   3661 		}
   3662 #endif
   3663 	if (s->ctx->client_cert_cb)
   3664 		i = s->ctx->client_cert_cb(s,px509,ppkey);
   3665 	return i;
   3666 	}
   3667