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