Home | History | Annotate | Download | only in ssl
      1 /* ssl/d1_clnt.c */
      2 /*
      3  * DTLS implementation written by Nagendra Modadugu
      4  * (nagendra (at) cs.stanford.edu) for the OpenSSL project 2005.
      5  */
      6 /* ====================================================================
      7  * Copyright (c) 1999-2007 The OpenSSL Project.  All rights reserved.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  *
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  *
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in
     18  *    the documentation and/or other materials provided with the
     19  *    distribution.
     20  *
     21  * 3. All advertising materials mentioning features or use of this
     22  *    software must display the following acknowledgment:
     23  *    "This product includes software developed by the OpenSSL Project
     24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
     25  *
     26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     27  *    endorse or promote products derived from this software without
     28  *    prior written permission. For written permission, please contact
     29  *    openssl-core (at) OpenSSL.org.
     30  *
     31  * 5. Products derived from this software may not be called "OpenSSL"
     32  *    nor may "OpenSSL" appear in their names without prior written
     33  *    permission of the OpenSSL Project.
     34  *
     35  * 6. Redistributions of any form whatsoever must retain the following
     36  *    acknowledgment:
     37  *    "This product includes software developed by the OpenSSL Project
     38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
     39  *
     40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     51  * OF THE POSSIBILITY OF SUCH DAMAGE.
     52  * ====================================================================
     53  *
     54  * This product includes cryptographic software written by Eric Young
     55  * (eay (at) cryptsoft.com).  This product includes software written by Tim
     56  * Hudson (tjh (at) cryptsoft.com).
     57  *
     58  */
     59 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
     60  * All rights reserved.
     61  *
     62  * This package is an SSL implementation written
     63  * by Eric Young (eay (at) cryptsoft.com).
     64  * The implementation was written so as to conform with Netscapes SSL.
     65  *
     66  * This library is free for commercial and non-commercial use as long as
     67  * the following conditions are aheared to.  The following conditions
     68  * apply to all code found in this distribution, be it the RC4, RSA,
     69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     70  * included with this distribution is covered by the same copyright terms
     71  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     72  *
     73  * Copyright remains Eric Young's, and as such any Copyright notices in
     74  * the code are not to be removed.
     75  * If this package is used in a product, Eric Young should be given attribution
     76  * as the author of the parts of the library used.
     77  * This can be in the form of a textual message at program startup or
     78  * in documentation (online or textual) provided with the package.
     79  *
     80  * Redistribution and use in source and binary forms, with or without
     81  * modification, are permitted provided that the following conditions
     82  * are met:
     83  * 1. Redistributions of source code must retain the copyright
     84  *    notice, this list of conditions and the following disclaimer.
     85  * 2. Redistributions in binary form must reproduce the above copyright
     86  *    notice, this list of conditions and the following disclaimer in the
     87  *    documentation and/or other materials provided with the distribution.
     88  * 3. All advertising materials mentioning features or use of this software
     89  *    must display the following acknowledgement:
     90  *    "This product includes cryptographic software written by
     91  *     Eric Young (eay (at) cryptsoft.com)"
     92  *    The word 'cryptographic' can be left out if the rouines from the library
     93  *    being used are not cryptographic related :-).
     94  * 4. If you include any Windows specific code (or a derivative thereof) from
     95  *    the apps directory (application code) you must include an acknowledgement:
     96  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     97  *
     98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
    102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    108  * SUCH DAMAGE.
    109  *
    110  * The licence and distribution terms for any publically available version or
    111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
    112  * copied and put under another distribution licence
    113  * [including the GNU Public Licence.]
    114  */
    115 
    116 #include <stdio.h>
    117 #include "ssl_locl.h"
    118 #ifndef OPENSSL_NO_KRB5
    119 #include "kssl_lcl.h"
    120 #endif
    121 #include <openssl/buffer.h>
    122 #include <openssl/rand.h>
    123 #include <openssl/objects.h>
    124 #include <openssl/evp.h>
    125 #include <openssl/md5.h>
    126 #include <openssl/bn.h>
    127 #ifndef OPENSSL_NO_DH
    128 #include <openssl/dh.h>
    129 #endif
    130 
    131 static const SSL_METHOD *dtls1_get_client_method(int ver);
    132 static int dtls1_get_hello_verify(SSL *s);
    133 
    134 static const SSL_METHOD *dtls1_get_client_method(int ver)
    135 	{
    136 	if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER)
    137 		return(DTLSv1_client_method());
    138 	else
    139 		return(NULL);
    140 	}
    141 
    142 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
    143 			ssl_undefined_function,
    144 			dtls1_connect,
    145 			dtls1_get_client_method)
    146 
    147 int dtls1_connect(SSL *s)
    148 	{
    149 	BUF_MEM *buf=NULL;
    150 	unsigned long Time=(unsigned long)time(NULL);
    151 	void (*cb)(const SSL *ssl,int type,int val)=NULL;
    152 	int ret= -1;
    153 	int new_state,state,skip=0;;
    154 
    155 	RAND_add(&Time,sizeof(Time),0);
    156 	ERR_clear_error();
    157 	clear_sys_error();
    158 
    159 	if (s->info_callback != NULL)
    160 		cb=s->info_callback;
    161 	else if (s->ctx->info_callback != NULL)
    162 		cb=s->ctx->info_callback;
    163 
    164 	s->in_handshake++;
    165 	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
    166 
    167 	for (;;)
    168 		{
    169 		state=s->state;
    170 
    171 		switch(s->state)
    172 			{
    173 		case SSL_ST_RENEGOTIATE:
    174 			s->new_session=1;
    175 			s->state=SSL_ST_CONNECT;
    176 			s->ctx->stats.sess_connect_renegotiate++;
    177 			/* break */
    178 		case SSL_ST_BEFORE:
    179 		case SSL_ST_CONNECT:
    180 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
    181 		case SSL_ST_OK|SSL_ST_CONNECT:
    182 
    183 			s->server=0;
    184 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
    185 
    186 			if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) &&
    187 			    (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00))
    188 				{
    189 				SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
    190 				ret = -1;
    191 				goto end;
    192 				}
    193 
    194 			/* s->version=SSL3_VERSION; */
    195 			s->type=SSL_ST_CONNECT;
    196 
    197 			if (s->init_buf == NULL)
    198 				{
    199 				if ((buf=BUF_MEM_new()) == NULL)
    200 					{
    201 					ret= -1;
    202 					goto end;
    203 					}
    204 				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
    205 					{
    206 					ret= -1;
    207 					goto end;
    208 					}
    209 				s->init_buf=buf;
    210 				buf=NULL;
    211 				}
    212 
    213 			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
    214 
    215 			/* setup buffing BIO */
    216 			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
    217 
    218 			/* don't push the buffering BIO quite yet */
    219 
    220 			s->state=SSL3_ST_CW_CLNT_HELLO_A;
    221 			s->ctx->stats.sess_connect++;
    222 			s->init_num=0;
    223 			/* mark client_random uninitialized */
    224 			memset(s->s3->client_random,0,sizeof(s->s3->client_random));
    225 			s->d1->send_cookie = 0;
    226 			s->hit = 0;
    227 			break;
    228 
    229 		case SSL3_ST_CW_CLNT_HELLO_A:
    230 		case SSL3_ST_CW_CLNT_HELLO_B:
    231 
    232 			s->shutdown=0;
    233 
    234 			/* every DTLS ClientHello resets Finished MAC */
    235 			ssl3_init_finished_mac(s);
    236 
    237 			dtls1_start_timer(s);
    238 			ret=dtls1_client_hello(s);
    239 			if (ret <= 0) goto end;
    240 
    241 			if ( s->d1->send_cookie)
    242 				{
    243 				s->state=SSL3_ST_CW_FLUSH;
    244 				s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
    245 				}
    246 			else
    247 				s->state=SSL3_ST_CR_SRVR_HELLO_A;
    248 
    249 			s->init_num=0;
    250 
    251 			/* turn on buffering for the next lot of output */
    252 			if (s->bbio != s->wbio)
    253 				s->wbio=BIO_push(s->bbio,s->wbio);
    254 
    255 			break;
    256 
    257 		case SSL3_ST_CR_SRVR_HELLO_A:
    258 		case SSL3_ST_CR_SRVR_HELLO_B:
    259 			ret=ssl3_get_server_hello(s);
    260 			if (ret <= 0) goto end;
    261 			else
    262 				{
    263 				dtls1_stop_timer(s);
    264 				if (s->hit)
    265 					s->state=SSL3_ST_CR_FINISHED_A;
    266 				else
    267 					s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
    268 				}
    269 			s->init_num=0;
    270 			break;
    271 
    272 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
    273 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
    274 
    275 			ret = dtls1_get_hello_verify(s);
    276 			if ( ret <= 0)
    277 				goto end;
    278 			dtls1_stop_timer(s);
    279 			if ( s->d1->send_cookie) /* start again, with a cookie */
    280 				s->state=SSL3_ST_CW_CLNT_HELLO_A;
    281 			else
    282 				s->state = SSL3_ST_CR_CERT_A;
    283 			s->init_num = 0;
    284 			break;
    285 
    286 		case SSL3_ST_CR_CERT_A:
    287 		case SSL3_ST_CR_CERT_B:
    288 #ifndef OPENSSL_NO_TLSEXT
    289 			ret=ssl3_check_finished(s);
    290 			if (ret <= 0) goto end;
    291 			if (ret == 2)
    292 				{
    293 				s->hit = 1;
    294 				if (s->tlsext_ticket_expected)
    295 					s->state=SSL3_ST_CR_SESSION_TICKET_A;
    296 				else
    297 					s->state=SSL3_ST_CR_FINISHED_A;
    298 				s->init_num=0;
    299 				break;
    300 				}
    301 #endif
    302 			/* Check if it is anon DH or PSK */
    303 			if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
    304 			    !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
    305 				{
    306 				ret=ssl3_get_server_certificate(s);
    307 				if (ret <= 0) goto end;
    308 #ifndef OPENSSL_NO_TLSEXT
    309 				if (s->tlsext_status_expected)
    310 					s->state=SSL3_ST_CR_CERT_STATUS_A;
    311 				else
    312 					s->state=SSL3_ST_CR_KEY_EXCH_A;
    313 				}
    314 			else
    315 				{
    316 				skip = 1;
    317 				s->state=SSL3_ST_CR_KEY_EXCH_A;
    318 				}
    319 #else
    320 				}
    321 			else
    322 				skip=1;
    323 
    324 			s->state=SSL3_ST_CR_KEY_EXCH_A;
    325 #endif
    326 			s->init_num=0;
    327 			break;
    328 
    329 		case SSL3_ST_CR_KEY_EXCH_A:
    330 		case SSL3_ST_CR_KEY_EXCH_B:
    331 			ret=ssl3_get_key_exchange(s);
    332 			if (ret <= 0) goto end;
    333 			s->state=SSL3_ST_CR_CERT_REQ_A;
    334 			s->init_num=0;
    335 
    336 			/* at this point we check that we have the
    337 			 * required stuff from the server */
    338 			if (!ssl3_check_cert_and_algorithm(s))
    339 				{
    340 				ret= -1;
    341 				goto end;
    342 				}
    343 			break;
    344 
    345 		case SSL3_ST_CR_CERT_REQ_A:
    346 		case SSL3_ST_CR_CERT_REQ_B:
    347 			ret=ssl3_get_certificate_request(s);
    348 			if (ret <= 0) goto end;
    349 			s->state=SSL3_ST_CR_SRVR_DONE_A;
    350 			s->init_num=0;
    351 			break;
    352 
    353 		case SSL3_ST_CR_SRVR_DONE_A:
    354 		case SSL3_ST_CR_SRVR_DONE_B:
    355 			ret=ssl3_get_server_done(s);
    356 			if (ret <= 0) goto end;
    357 			if (s->s3->tmp.cert_req)
    358 				s->state=SSL3_ST_CW_CERT_A;
    359 			else
    360 				s->state=SSL3_ST_CW_KEY_EXCH_A;
    361 			s->init_num=0;
    362 
    363 			break;
    364 
    365 		case SSL3_ST_CW_CERT_A:
    366 		case SSL3_ST_CW_CERT_B:
    367 		case SSL3_ST_CW_CERT_C:
    368 		case SSL3_ST_CW_CERT_D:
    369 			dtls1_start_timer(s);
    370 			ret=dtls1_send_client_certificate(s);
    371 			if (ret <= 0) goto end;
    372 			s->state=SSL3_ST_CW_KEY_EXCH_A;
    373 			s->init_num=0;
    374 			break;
    375 
    376 		case SSL3_ST_CW_KEY_EXCH_A:
    377 		case SSL3_ST_CW_KEY_EXCH_B:
    378 			dtls1_start_timer(s);
    379 			ret=dtls1_send_client_key_exchange(s);
    380 			if (ret <= 0) goto end;
    381 			/* EAY EAY EAY need to check for DH fix cert
    382 			 * sent back */
    383 			/* For TLS, cert_req is set to 2, so a cert chain
    384 			 * of nothing is sent, but no verify packet is sent */
    385 			if (s->s3->tmp.cert_req == 1)
    386 				{
    387 				s->state=SSL3_ST_CW_CERT_VRFY_A;
    388 				}
    389 			else
    390 				{
    391 				s->state=SSL3_ST_CW_CHANGE_A;
    392 				s->s3->change_cipher_spec=0;
    393 				}
    394 
    395 			s->init_num=0;
    396 			break;
    397 
    398 		case SSL3_ST_CW_CERT_VRFY_A:
    399 		case SSL3_ST_CW_CERT_VRFY_B:
    400 			dtls1_start_timer(s);
    401 			ret=dtls1_send_client_verify(s);
    402 			if (ret <= 0) goto end;
    403 			s->state=SSL3_ST_CW_CHANGE_A;
    404 			s->init_num=0;
    405 			s->s3->change_cipher_spec=0;
    406 			break;
    407 
    408 		case SSL3_ST_CW_CHANGE_A:
    409 		case SSL3_ST_CW_CHANGE_B:
    410 			dtls1_start_timer(s);
    411 			ret=dtls1_send_change_cipher_spec(s,
    412 				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
    413 			if (ret <= 0) goto end;
    414 			s->state=SSL3_ST_CW_FINISHED_A;
    415 			s->init_num=0;
    416 
    417 			s->session->cipher=s->s3->tmp.new_cipher;
    418 #ifdef OPENSSL_NO_COMP
    419 			s->session->compress_meth=0;
    420 #else
    421 			if (s->s3->tmp.new_compression == NULL)
    422 				s->session->compress_meth=0;
    423 			else
    424 				s->session->compress_meth=
    425 					s->s3->tmp.new_compression->id;
    426 #endif
    427 			if (!s->method->ssl3_enc->setup_key_block(s))
    428 				{
    429 				ret= -1;
    430 				goto end;
    431 				}
    432 
    433 			if (!s->method->ssl3_enc->change_cipher_state(s,
    434 				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
    435 				{
    436 				ret= -1;
    437 				goto end;
    438 				}
    439 
    440 			dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
    441 			break;
    442 
    443 		case SSL3_ST_CW_FINISHED_A:
    444 		case SSL3_ST_CW_FINISHED_B:
    445 			dtls1_start_timer(s);
    446 			ret=dtls1_send_finished(s,
    447 				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
    448 				s->method->ssl3_enc->client_finished_label,
    449 				s->method->ssl3_enc->client_finished_label_len);
    450 			if (ret <= 0) goto end;
    451 			s->state=SSL3_ST_CW_FLUSH;
    452 
    453 			/* clear flags */
    454 			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
    455 			if (s->hit)
    456 				{
    457 				s->s3->tmp.next_state=SSL_ST_OK;
    458 				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
    459 					{
    460 					s->state=SSL_ST_OK;
    461 					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
    462 					s->s3->delay_buf_pop_ret=0;
    463 					}
    464 				}
    465 			else
    466 				{
    467 #ifndef OPENSSL_NO_TLSEXT
    468 				/* Allow NewSessionTicket if ticket expected */
    469 				if (s->tlsext_ticket_expected)
    470 					s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
    471 				else
    472 #endif
    473 
    474 				s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
    475 				}
    476 			s->init_num=0;
    477 			break;
    478 
    479 #ifndef OPENSSL_NO_TLSEXT
    480 		case SSL3_ST_CR_SESSION_TICKET_A:
    481 		case SSL3_ST_CR_SESSION_TICKET_B:
    482 			ret=ssl3_get_new_session_ticket(s);
    483 			if (ret <= 0) goto end;
    484 			s->state=SSL3_ST_CR_FINISHED_A;
    485 			s->init_num=0;
    486 		break;
    487 
    488 		case SSL3_ST_CR_CERT_STATUS_A:
    489 		case SSL3_ST_CR_CERT_STATUS_B:
    490 			ret=ssl3_get_cert_status(s);
    491 			if (ret <= 0) goto end;
    492 			s->state=SSL3_ST_CR_KEY_EXCH_A;
    493 			s->init_num=0;
    494 		break;
    495 #endif
    496 
    497 		case SSL3_ST_CR_FINISHED_A:
    498 		case SSL3_ST_CR_FINISHED_B:
    499 			s->d1->change_cipher_spec_ok = 1;
    500 			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
    501 				SSL3_ST_CR_FINISHED_B);
    502 			if (ret <= 0) goto end;
    503 			dtls1_stop_timer(s);
    504 
    505 			if (s->hit)
    506 				s->state=SSL3_ST_CW_CHANGE_A;
    507 			else
    508 				s->state=SSL_ST_OK;
    509 			s->init_num=0;
    510 			break;
    511 
    512 		case SSL3_ST_CW_FLUSH:
    513 			s->rwstate=SSL_WRITING;
    514 			if (BIO_flush(s->wbio) <= 0)
    515 				{
    516 				ret= -1;
    517 				goto end;
    518 				}
    519 			s->rwstate=SSL_NOTHING;
    520 			s->state=s->s3->tmp.next_state;
    521 			break;
    522 
    523 		case SSL_ST_OK:
    524 			/* clean a few things up */
    525 			ssl3_cleanup_key_block(s);
    526 
    527 #if 0
    528 			if (s->init_buf != NULL)
    529 				{
    530 				BUF_MEM_free(s->init_buf);
    531 				s->init_buf=NULL;
    532 				}
    533 #endif
    534 
    535 			/* If we are not 'joining' the last two packets,
    536 			 * remove the buffering now */
    537 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
    538 				ssl_free_wbio_buffer(s);
    539 			/* else do it later in ssl3_write */
    540 
    541 			s->init_num=0;
    542 			s->new_session=0;
    543 
    544 			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
    545 			if (s->hit) s->ctx->stats.sess_hit++;
    546 
    547 			ret=1;
    548 			/* s->server=0; */
    549 			s->handshake_func=dtls1_connect;
    550 			s->ctx->stats.sess_connect_good++;
    551 
    552 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
    553 
    554 			/* done with handshaking */
    555 			s->d1->handshake_read_seq  = 0;
    556 			s->d1->next_handshake_write_seq = 0;
    557 			goto end;
    558 			/* break; */
    559 
    560 		default:
    561 			SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
    562 			ret= -1;
    563 			goto end;
    564 			/* break; */
    565 			}
    566 
    567 		/* did we do anything */
    568 		if (!s->s3->tmp.reuse_message && !skip)
    569 			{
    570 			if (s->debug)
    571 				{
    572 				if ((ret=BIO_flush(s->wbio)) <= 0)
    573 					goto end;
    574 				}
    575 
    576 			if ((cb != NULL) && (s->state != state))
    577 				{
    578 				new_state=s->state;
    579 				s->state=state;
    580 				cb(s,SSL_CB_CONNECT_LOOP,1);
    581 				s->state=new_state;
    582 				}
    583 			}
    584 		skip=0;
    585 		}
    586 end:
    587 	s->in_handshake--;
    588 	if (buf != NULL)
    589 		BUF_MEM_free(buf);
    590 	if (cb != NULL)
    591 		cb(s,SSL_CB_CONNECT_EXIT,ret);
    592 	return(ret);
    593 	}
    594 
    595 int dtls1_client_hello(SSL *s)
    596 	{
    597 	unsigned char *buf;
    598 	unsigned char *p,*d;
    599 	unsigned int i,j;
    600 	unsigned long Time,l;
    601 	SSL_COMP *comp;
    602 
    603 	buf=(unsigned char *)s->init_buf->data;
    604 	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
    605 		{
    606 		SSL_SESSION *sess = s->session;
    607 		if ((s->session == NULL) ||
    608 			(s->session->ssl_version != s->version) ||
    609 #ifdef OPENSSL_NO_TLSEXT
    610 			!sess->session_id_length ||
    611 #else
    612 			(!sess->session_id_length && !sess->tlsext_tick) ||
    613 #endif
    614 			(s->session->not_resumable))
    615 			{
    616 		        if (!s->session_creation_enabled)
    617 				{
    618 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
    619 				SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
    620 				goto err;
    621 				}
    622 			if (!ssl_get_new_session(s,0))
    623 				goto err;
    624 			}
    625 		/* else use the pre-loaded session */
    626 
    627 		p=s->s3->client_random;
    628 
    629 		/* if client_random is initialized, reuse it, we are
    630 		 * required to use same upon reply to HelloVerify */
    631 		for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
    632 		if (i==sizeof(s->s3->client_random))
    633 			{
    634 			Time=(unsigned long)time(NULL);	/* Time */
    635 			l2n(Time,p);
    636 			RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
    637 			}
    638 
    639 		/* Do the message type and length last */
    640 		d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
    641 
    642 		*(p++)=s->version>>8;
    643 		*(p++)=s->version&0xff;
    644 		s->client_version=s->version;
    645 
    646 		/* Random stuff */
    647 		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
    648 		p+=SSL3_RANDOM_SIZE;
    649 
    650 		/* Session ID */
    651 		if (s->new_session)
    652 			i=0;
    653 		else
    654 			i=s->session->session_id_length;
    655 		*(p++)=i;
    656 		if (i != 0)
    657 			{
    658 			if (i > sizeof s->session->session_id)
    659 				{
    660 				SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
    661 				goto err;
    662 				}
    663 			memcpy(p,s->session->session_id,i);
    664 			p+=i;
    665 			}
    666 
    667 		/* cookie stuff */
    668 		if ( s->d1->cookie_len > sizeof(s->d1->cookie))
    669 			{
    670 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
    671 			goto err;
    672 			}
    673 		*(p++) = s->d1->cookie_len;
    674 		memcpy(p, s->d1->cookie, s->d1->cookie_len);
    675 		p += s->d1->cookie_len;
    676 
    677 		/* Ciphers supported */
    678 		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
    679 		if (i == 0)
    680 			{
    681 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
    682 			goto err;
    683 			}
    684 		s2n(i,p);
    685 		p+=i;
    686 
    687 		/* COMPRESSION */
    688 		if (s->ctx->comp_methods == NULL)
    689 			j=0;
    690 		else
    691 			j=sk_SSL_COMP_num(s->ctx->comp_methods);
    692 		*(p++)=1+j;
    693 		for (i=0; i<j; i++)
    694 			{
    695 			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
    696 			*(p++)=comp->id;
    697 			}
    698 		*(p++)=0; /* Add the NULL method */
    699 
    700 #ifndef OPENSSL_NO_TLSEXT
    701 		if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
    702 			{
    703 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
    704 			goto err;
    705 			}
    706 #endif
    707 
    708 		l=(p-d);
    709 		d=buf;
    710 
    711 		d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
    712 
    713 		s->state=SSL3_ST_CW_CLNT_HELLO_B;
    714 		/* number of bytes to write */
    715 		s->init_num=p-buf;
    716 		s->init_off=0;
    717 
    718 		/* buffer the message to handle re-xmits */
    719 		dtls1_buffer_message(s, 0);
    720 		}
    721 
    722 	/* SSL3_ST_CW_CLNT_HELLO_B */
    723 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
    724 err:
    725 	return(-1);
    726 	}
    727 
    728 static int dtls1_get_hello_verify(SSL *s)
    729 	{
    730 	int n, al, ok = 0;
    731 	unsigned char *data;
    732 	unsigned int cookie_len;
    733 
    734 	n=s->method->ssl_get_message(s,
    735 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
    736 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
    737 		-1,
    738 		s->max_cert_list,
    739 		&ok);
    740 
    741 	if (!ok) return((int)n);
    742 
    743 	if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
    744 		{
    745 		s->d1->send_cookie = 0;
    746 		s->s3->tmp.reuse_message=1;
    747 		return(1);
    748 		}
    749 
    750 	data = (unsigned char *)s->init_msg;
    751 
    752 	if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
    753 		{
    754 		SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
    755 		s->version=(s->version&0xff00)|data[1];
    756 		al = SSL_AD_PROTOCOL_VERSION;
    757 		goto f_err;
    758 		}
    759 	data+=2;
    760 
    761 	cookie_len = *(data++);
    762 	if ( cookie_len > sizeof(s->d1->cookie))
    763 		{
    764 		al=SSL_AD_ILLEGAL_PARAMETER;
    765 		goto f_err;
    766 		}
    767 
    768 	memcpy(s->d1->cookie, data, cookie_len);
    769 	s->d1->cookie_len = cookie_len;
    770 
    771 	s->d1->send_cookie = 1;
    772 	return 1;
    773 
    774 f_err:
    775 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
    776 	return -1;
    777 	}
    778 
    779 int dtls1_send_client_key_exchange(SSL *s)
    780 	{
    781 	unsigned char *p,*d;
    782 	int n;
    783 	unsigned long alg_k;
    784 #ifndef OPENSSL_NO_RSA
    785 	unsigned char *q;
    786 	EVP_PKEY *pkey=NULL;
    787 #endif
    788 #ifndef OPENSSL_NO_KRB5
    789         KSSL_ERR kssl_err;
    790 #endif /* OPENSSL_NO_KRB5 */
    791 #ifndef OPENSSL_NO_ECDH
    792 	EC_KEY *clnt_ecdh = NULL;
    793 	const EC_POINT *srvr_ecpoint = NULL;
    794 	EVP_PKEY *srvr_pub_pkey = NULL;
    795 	unsigned char *encodedPoint = NULL;
    796 	int encoded_pt_len = 0;
    797 	BN_CTX * bn_ctx = NULL;
    798 #endif
    799 
    800 	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
    801 		{
    802 		d=(unsigned char *)s->init_buf->data;
    803 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
    804 
    805 		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
    806 
    807                 /* Fool emacs indentation */
    808                 if (0) {}
    809 #ifndef OPENSSL_NO_RSA
    810 		else if (alg_k & SSL_kRSA)
    811 			{
    812 			RSA *rsa;
    813 			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
    814 
    815 			if (s->session->sess_cert->peer_rsa_tmp != NULL)
    816 				rsa=s->session->sess_cert->peer_rsa_tmp;
    817 			else
    818 				{
    819 				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
    820 				if ((pkey == NULL) ||
    821 					(pkey->type != EVP_PKEY_RSA) ||
    822 					(pkey->pkey.rsa == NULL))
    823 					{
    824 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
    825 					goto err;
    826 					}
    827 				rsa=pkey->pkey.rsa;
    828 				EVP_PKEY_free(pkey);
    829 				}
    830 
    831 			tmp_buf[0]=s->client_version>>8;
    832 			tmp_buf[1]=s->client_version&0xff;
    833 			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
    834 					goto err;
    835 
    836 			s->session->master_key_length=sizeof tmp_buf;
    837 
    838 			q=p;
    839 			/* Fix buf for TLS and [incidentally] DTLS */
    840 			if (s->version > SSL3_VERSION)
    841 				p+=2;
    842 			n=RSA_public_encrypt(sizeof tmp_buf,
    843 				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
    844 #ifdef PKCS1_CHECK
    845 			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
    846 			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
    847 #endif
    848 			if (n <= 0)
    849 				{
    850 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
    851 				goto err;
    852 				}
    853 
    854 			/* Fix buf for TLS and [incidentally] DTLS */
    855 			if (s->version > SSL3_VERSION)
    856 				{
    857 				s2n(n,q);
    858 				n+=2;
    859 				}
    860 
    861 			s->session->master_key_length=
    862 				s->method->ssl3_enc->generate_master_secret(s,
    863 					s->session->master_key,
    864 					tmp_buf,sizeof tmp_buf);
    865 			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
    866 			}
    867 #endif
    868 #ifndef OPENSSL_NO_KRB5
    869 		else if (alg_k & SSL_kKRB5)
    870                         {
    871                         krb5_error_code	krb5rc;
    872                         KSSL_CTX	*kssl_ctx = s->kssl_ctx;
    873                         /*  krb5_data	krb5_ap_req;  */
    874                         krb5_data	*enc_ticket;
    875                         krb5_data	authenticator, *authp = NULL;
    876 			EVP_CIPHER_CTX	ciph_ctx;
    877 			const EVP_CIPHER *enc = NULL;
    878 			unsigned char	iv[EVP_MAX_IV_LENGTH];
    879 			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
    880 			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
    881 						+ EVP_MAX_IV_LENGTH];
    882 			int 		padl, outl = sizeof(epms);
    883 
    884 			EVP_CIPHER_CTX_init(&ciph_ctx);
    885 
    886 #ifdef KSSL_DEBUG
    887                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
    888                                 alg_k, SSL_kKRB5);
    889 #endif	/* KSSL_DEBUG */
    890 
    891 			authp = NULL;
    892 #ifdef KRB5SENDAUTH
    893 			if (KRB5SENDAUTH)  authp = &authenticator;
    894 #endif	/* KRB5SENDAUTH */
    895 
    896                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
    897 				&kssl_err);
    898 			enc = kssl_map_enc(kssl_ctx->enctype);
    899                         if (enc == NULL)
    900                             goto err;
    901 #ifdef KSSL_DEBUG
    902                         {
    903                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
    904                         if (krb5rc && kssl_err.text)
    905 			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
    906                         }
    907 #endif	/* KSSL_DEBUG */
    908 
    909                         if (krb5rc)
    910                                 {
    911                                 ssl3_send_alert(s,SSL3_AL_FATAL,
    912 						SSL_AD_HANDSHAKE_FAILURE);
    913                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
    914 						kssl_err.reason);
    915                                 goto err;
    916                                 }
    917 
    918 			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
    919 			**  in place of RFC 2712 KerberosWrapper, as in:
    920 			**
    921                         **  Send ticket (copy to *p, set n = length)
    922                         **  n = krb5_ap_req.length;
    923                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
    924                         **  if (krb5_ap_req.data)
    925                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
    926                         **
    927 			**  Now using real RFC 2712 KerberosWrapper
    928 			**  (Thanks to Simon Wilkinson <sxw (at) sxw.org.uk>)
    929 			**  Note: 2712 "opaque" types are here replaced
    930 			**  with a 2-byte length followed by the value.
    931 			**  Example:
    932 			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
    933 			**  Where "xx xx" = length bytes.  Shown here with
    934 			**  optional authenticator omitted.
    935 			*/
    936 
    937 			/*  KerberosWrapper.Ticket		*/
    938 			s2n(enc_ticket->length,p);
    939 			memcpy(p, enc_ticket->data, enc_ticket->length);
    940 			p+= enc_ticket->length;
    941 			n = enc_ticket->length + 2;
    942 
    943 			/*  KerberosWrapper.Authenticator	*/
    944 			if (authp  &&  authp->length)
    945 				{
    946 				s2n(authp->length,p);
    947 				memcpy(p, authp->data, authp->length);
    948 				p+= authp->length;
    949 				n+= authp->length + 2;
    950 
    951 				free(authp->data);
    952 				authp->data = NULL;
    953 				authp->length = 0;
    954 				}
    955 			else
    956 				{
    957 				s2n(0,p);/*  null authenticator length	*/
    958 				n+=2;
    959 				}
    960 
    961 			if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
    962 			    goto err;
    963 
    964 			/*  20010420 VRS.  Tried it this way; failed.
    965 			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
    966 			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
    967 			**				kssl_ctx->length);
    968 			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
    969 			*/
    970 
    971 			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
    972 			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
    973 				kssl_ctx->key,iv);
    974 			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
    975 				sizeof tmp_buf);
    976 			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
    977 			outl += padl;
    978 			if (outl > (int)sizeof epms)
    979 				{
    980 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
    981 				goto err;
    982 				}
    983 			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
    984 
    985 			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
    986 			s2n(outl,p);
    987 			memcpy(p, epms, outl);
    988 			p+=outl;
    989 			n+=outl + 2;
    990 
    991                         s->session->master_key_length=
    992                                 s->method->ssl3_enc->generate_master_secret(s,
    993 					s->session->master_key,
    994 					tmp_buf, sizeof tmp_buf);
    995 
    996 			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
    997 			OPENSSL_cleanse(epms, outl);
    998                         }
    999 #endif
   1000 #ifndef OPENSSL_NO_DH
   1001 		else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
   1002 			{
   1003 			DH *dh_srvr,*dh_clnt;
   1004 
   1005 			if (s->session->sess_cert->peer_dh_tmp != NULL)
   1006 				dh_srvr=s->session->sess_cert->peer_dh_tmp;
   1007 			else
   1008 				{
   1009 				/* we get them from the cert */
   1010 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   1011 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
   1012 				goto err;
   1013 				}
   1014 
   1015 			/* generate a new random key */
   1016 			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
   1017 				{
   1018 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   1019 				goto err;
   1020 				}
   1021 			if (!DH_generate_key(dh_clnt))
   1022 				{
   1023 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   1024 				goto err;
   1025 				}
   1026 
   1027 			/* use the 'p' output buffer for the DH key, but
   1028 			 * make sure to clear it out afterwards */
   1029 
   1030 			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
   1031 
   1032 			if (n <= 0)
   1033 				{
   1034 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
   1035 				goto err;
   1036 				}
   1037 
   1038 			/* generate master key from the result */
   1039 			s->session->master_key_length=
   1040 				s->method->ssl3_enc->generate_master_secret(s,
   1041 					s->session->master_key,p,n);
   1042 			/* clean up */
   1043 			memset(p,0,n);
   1044 
   1045 			/* send off the data */
   1046 			n=BN_num_bytes(dh_clnt->pub_key);
   1047 			s2n(n,p);
   1048 			BN_bn2bin(dh_clnt->pub_key,p);
   1049 			n+=2;
   1050 
   1051 			DH_free(dh_clnt);
   1052 
   1053 			/* perhaps clean things up a bit EAY EAY EAY EAY*/
   1054 			}
   1055 #endif
   1056 #ifndef OPENSSL_NO_ECDH
   1057 		else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
   1058 			{
   1059 			const EC_GROUP *srvr_group = NULL;
   1060 			EC_KEY *tkey;
   1061 			int ecdh_clnt_cert = 0;
   1062 			int field_size = 0;
   1063 
   1064 			/* Did we send out the client's
   1065 			 * ECDH share for use in premaster
   1066 			 * computation as part of client certificate?
   1067 			 * If so, set ecdh_clnt_cert to 1.
   1068 			 */
   1069 			if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL))
   1070 				{
   1071 				/* XXX: For now, we do not support client
   1072 				 * authentication using ECDH certificates.
   1073 				 * To add such support, one needs to add
   1074 				 * code that checks for appropriate
   1075 				 * conditions and sets ecdh_clnt_cert to 1.
   1076 				 * For example, the cert have an ECC
   1077 				 * key on the same curve as the server's
   1078 				 * and the key should be authorized for
   1079 				 * key agreement.
   1080 				 *
   1081 				 * One also needs to add code in ssl3_connect
   1082 				 * to skip sending the certificate verify
   1083 				 * message.
   1084 				 *
   1085 				 * if ((s->cert->key->privatekey != NULL) &&
   1086 				 *     (s->cert->key->privatekey->type ==
   1087 				 *      EVP_PKEY_EC) && ...)
   1088 				 * ecdh_clnt_cert = 1;
   1089 				 */
   1090 				}
   1091 
   1092 			if (s->session->sess_cert->peer_ecdh_tmp != NULL)
   1093 				{
   1094 				tkey = s->session->sess_cert->peer_ecdh_tmp;
   1095 				}
   1096 			else
   1097 				{
   1098 				/* Get the Server Public Key from Cert */
   1099 				srvr_pub_pkey = X509_get_pubkey(s->session-> \
   1100 				    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
   1101 				if ((srvr_pub_pkey == NULL) ||
   1102 				    (srvr_pub_pkey->type != EVP_PKEY_EC) ||
   1103 				    (srvr_pub_pkey->pkey.ec == NULL))
   1104 					{
   1105 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1106 					    ERR_R_INTERNAL_ERROR);
   1107 					goto err;
   1108 					}
   1109 
   1110 				tkey = srvr_pub_pkey->pkey.ec;
   1111 				}
   1112 
   1113 			srvr_group   = EC_KEY_get0_group(tkey);
   1114 			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
   1115 
   1116 			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
   1117 				{
   1118 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1119 				    ERR_R_INTERNAL_ERROR);
   1120 				goto err;
   1121 				}
   1122 
   1123 			if ((clnt_ecdh=EC_KEY_new()) == NULL)
   1124 				{
   1125 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1126 				goto err;
   1127 				}
   1128 
   1129 			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
   1130 				{
   1131 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
   1132 				goto err;
   1133 				}
   1134 			if (ecdh_clnt_cert)
   1135 				{
   1136 				/* Reuse key info from our certificate
   1137 				 * We only need our private key to perform
   1138 				 * the ECDH computation.
   1139 				 */
   1140 				const BIGNUM *priv_key;
   1141 				tkey = s->cert->key->privatekey->pkey.ec;
   1142 				priv_key = EC_KEY_get0_private_key(tkey);
   1143 				if (priv_key == NULL)
   1144 					{
   1145 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1146 					goto err;
   1147 					}
   1148 				if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
   1149 					{
   1150 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
   1151 					goto err;
   1152 					}
   1153 				}
   1154 			else
   1155 				{
   1156 				/* Generate a new ECDH key pair */
   1157 				if (!(EC_KEY_generate_key(clnt_ecdh)))
   1158 					{
   1159 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
   1160 					goto err;
   1161 					}
   1162 				}
   1163 
   1164 			/* use the 'p' output buffer for the ECDH key, but
   1165 			 * make sure to clear it out afterwards
   1166 			 */
   1167 
   1168 			field_size = EC_GROUP_get_degree(srvr_group);
   1169 			if (field_size <= 0)
   1170 				{
   1171 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1172 				       ERR_R_ECDH_LIB);
   1173 				goto err;
   1174 				}
   1175 			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
   1176 			if (n <= 0)
   1177 				{
   1178 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1179 				       ERR_R_ECDH_LIB);
   1180 				goto err;
   1181 				}
   1182 
   1183 			/* generate master key from the result */
   1184 			s->session->master_key_length = s->method->ssl3_enc \
   1185 			    -> generate_master_secret(s,
   1186 				s->session->master_key,
   1187 				p, n);
   1188 
   1189 			memset(p, 0, n); /* clean up */
   1190 
   1191 			if (ecdh_clnt_cert)
   1192 				{
   1193 				/* Send empty client key exch message */
   1194 				n = 0;
   1195 				}
   1196 			else
   1197 				{
   1198 				/* First check the size of encoding and
   1199 				 * allocate memory accordingly.
   1200 				 */
   1201 				encoded_pt_len =
   1202 				    EC_POINT_point2oct(srvr_group,
   1203 					EC_KEY_get0_public_key(clnt_ecdh),
   1204 					POINT_CONVERSION_UNCOMPRESSED,
   1205 					NULL, 0, NULL);
   1206 
   1207 				encodedPoint = (unsigned char *)
   1208 				    OPENSSL_malloc(encoded_pt_len *
   1209 					sizeof(unsigned char));
   1210 				bn_ctx = BN_CTX_new();
   1211 				if ((encodedPoint == NULL) ||
   1212 				    (bn_ctx == NULL))
   1213 					{
   1214 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
   1215 					goto err;
   1216 					}
   1217 
   1218 				/* Encode the public key */
   1219 				n = EC_POINT_point2oct(srvr_group,
   1220 				    EC_KEY_get0_public_key(clnt_ecdh),
   1221 				    POINT_CONVERSION_UNCOMPRESSED,
   1222 				    encodedPoint, encoded_pt_len, bn_ctx);
   1223 
   1224 				*p = n; /* length of encoded point */
   1225 				/* Encoded point will be copied here */
   1226 				p += 1;
   1227 				/* copy the point */
   1228 				memcpy((unsigned char *)p, encodedPoint, n);
   1229 				/* increment n to account for length field */
   1230 				n += 1;
   1231 				}
   1232 
   1233 			/* Free allocated memory */
   1234 			BN_CTX_free(bn_ctx);
   1235 			if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
   1236 			if (clnt_ecdh != NULL)
   1237 				 EC_KEY_free(clnt_ecdh);
   1238 			EVP_PKEY_free(srvr_pub_pkey);
   1239 			}
   1240 #endif /* !OPENSSL_NO_ECDH */
   1241 
   1242 #ifndef OPENSSL_NO_PSK
   1243 		else if (alg_k & SSL_kPSK)
   1244 			{
   1245 			char identity[PSK_MAX_IDENTITY_LEN];
   1246 			unsigned char *t = NULL;
   1247 			unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
   1248 			unsigned int pre_ms_len = 0, psk_len = 0;
   1249 			int psk_err = 1;
   1250 
   1251 			n = 0;
   1252 			if (s->psk_client_callback == NULL)
   1253 				{
   1254 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1255 					SSL_R_PSK_NO_CLIENT_CB);
   1256 				goto err;
   1257 				}
   1258 
   1259 			psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
   1260 				identity, PSK_MAX_IDENTITY_LEN,
   1261 				psk_or_pre_ms, sizeof(psk_or_pre_ms));
   1262 			if (psk_len > PSK_MAX_PSK_LEN)
   1263 				{
   1264 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1265 					ERR_R_INTERNAL_ERROR);
   1266 				goto psk_err;
   1267 				}
   1268 			else if (psk_len == 0)
   1269 				{
   1270 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1271 					SSL_R_PSK_IDENTITY_NOT_FOUND);
   1272 				goto psk_err;
   1273 				}
   1274 
   1275 			/* create PSK pre_master_secret */
   1276 			pre_ms_len = 2+psk_len+2+psk_len;
   1277 			t = psk_or_pre_ms;
   1278 			memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
   1279 			s2n(psk_len, t);
   1280 			memset(t, 0, psk_len);
   1281 			t+=psk_len;
   1282 			s2n(psk_len, t);
   1283 
   1284 			if (s->session->psk_identity_hint != NULL)
   1285 				OPENSSL_free(s->session->psk_identity_hint);
   1286 			s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
   1287 			if (s->ctx->psk_identity_hint != NULL &&
   1288 				s->session->psk_identity_hint == NULL)
   1289 				{
   1290 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1291 					ERR_R_MALLOC_FAILURE);
   1292 				goto psk_err;
   1293 				}
   1294 
   1295 			if (s->session->psk_identity != NULL)
   1296 				OPENSSL_free(s->session->psk_identity);
   1297 			s->session->psk_identity = BUF_strdup(identity);
   1298 			if (s->session->psk_identity == NULL)
   1299 				{
   1300 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
   1301 					ERR_R_MALLOC_FAILURE);
   1302 				goto psk_err;
   1303 				}
   1304 
   1305 			s->session->master_key_length =
   1306 				s->method->ssl3_enc->generate_master_secret(s,
   1307 					s->session->master_key,
   1308 					psk_or_pre_ms, pre_ms_len);
   1309 			n = strlen(identity);
   1310 			s2n(n, p);
   1311 			memcpy(p, identity, n);
   1312 			n+=2;
   1313 			psk_err = 0;
   1314 		psk_err:
   1315 			OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
   1316 			OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
   1317 			if (psk_err != 0)
   1318 				{
   1319 				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
   1320 				goto err;
   1321 				}
   1322 			}
   1323 #endif
   1324 		else
   1325 			{
   1326 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
   1327 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
   1328 			goto err;
   1329 			}
   1330 
   1331 		d = dtls1_set_message_header(s, d,
   1332 		SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
   1333 		/*
   1334 		 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
   1335 		 l2n3(n,d);
   1336 		 l2n(s->d1->handshake_write_seq,d);
   1337 		 s->d1->handshake_write_seq++;
   1338 		*/
   1339 
   1340 		s->state=SSL3_ST_CW_KEY_EXCH_B;
   1341 		/* number of bytes to write */
   1342 		s->init_num=n+DTLS1_HM_HEADER_LENGTH;
   1343 		s->init_off=0;
   1344 
   1345 		/* buffer the message to handle re-xmits */
   1346 		dtls1_buffer_message(s, 0);
   1347 		}
   1348 
   1349 	/* SSL3_ST_CW_KEY_EXCH_B */
   1350 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
   1351 err:
   1352 #ifndef OPENSSL_NO_ECDH
   1353 	BN_CTX_free(bn_ctx);
   1354 	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
   1355 	if (clnt_ecdh != NULL)
   1356 		EC_KEY_free(clnt_ecdh);
   1357 	EVP_PKEY_free(srvr_pub_pkey);
   1358 #endif
   1359 	return(-1);
   1360 	}
   1361 
   1362 int dtls1_send_client_verify(SSL *s)
   1363 	{
   1364 	unsigned char *p,*d;
   1365 	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
   1366 	EVP_PKEY *pkey;
   1367 #ifndef OPENSSL_NO_RSA
   1368 	unsigned u=0;
   1369 #endif
   1370 	unsigned long n;
   1371 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
   1372 	int j;
   1373 #endif
   1374 
   1375 	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
   1376 		{
   1377 		d=(unsigned char *)s->init_buf->data;
   1378 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
   1379 		pkey=s->cert->key->privatekey;
   1380 
   1381 		s->method->ssl3_enc->cert_verify_mac(s,
   1382 		NID_sha1,
   1383 			&(data[MD5_DIGEST_LENGTH]));
   1384 
   1385 #ifndef OPENSSL_NO_RSA
   1386 		if (pkey->type == EVP_PKEY_RSA)
   1387 			{
   1388 			s->method->ssl3_enc->cert_verify_mac(s,
   1389 				NID_md5,
   1390 				&(data[0]));
   1391 			if (RSA_sign(NID_md5_sha1, data,
   1392 					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
   1393 					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
   1394 				{
   1395 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
   1396 				goto err;
   1397 				}
   1398 			s2n(u,p);
   1399 			n=u+2;
   1400 			}
   1401 		else
   1402 #endif
   1403 #ifndef OPENSSL_NO_DSA
   1404 			if (pkey->type == EVP_PKEY_DSA)
   1405 			{
   1406 			if (!DSA_sign(pkey->save_type,
   1407 				&(data[MD5_DIGEST_LENGTH]),
   1408 				SHA_DIGEST_LENGTH,&(p[2]),
   1409 				(unsigned int *)&j,pkey->pkey.dsa))
   1410 				{
   1411 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
   1412 				goto err;
   1413 				}
   1414 			s2n(j,p);
   1415 			n=j+2;
   1416 			}
   1417 		else
   1418 #endif
   1419 #ifndef OPENSSL_NO_ECDSA
   1420 			if (pkey->type == EVP_PKEY_EC)
   1421 			{
   1422 			if (!ECDSA_sign(pkey->save_type,
   1423 				&(data[MD5_DIGEST_LENGTH]),
   1424 				SHA_DIGEST_LENGTH,&(p[2]),
   1425 				(unsigned int *)&j,pkey->pkey.ec))
   1426 				{
   1427 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
   1428 				    ERR_R_ECDSA_LIB);
   1429 				goto err;
   1430 				}
   1431 			s2n(j,p);
   1432 			n=j+2;
   1433 			}
   1434 		else
   1435 #endif
   1436 			{
   1437 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
   1438 			goto err;
   1439 			}
   1440 
   1441 		d = dtls1_set_message_header(s, d,
   1442 			SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
   1443 
   1444 		s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
   1445 		s->init_off=0;
   1446 
   1447 		/* buffer the message to handle re-xmits */
   1448 		dtls1_buffer_message(s, 0);
   1449 
   1450 		s->state = SSL3_ST_CW_CERT_VRFY_B;
   1451 		}
   1452 
   1453 	/* s->state = SSL3_ST_CW_CERT_VRFY_B */
   1454 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
   1455 err:
   1456 	return(-1);
   1457 	}
   1458 
   1459 int dtls1_send_client_certificate(SSL *s)
   1460 	{
   1461 	X509 *x509=NULL;
   1462 	EVP_PKEY *pkey=NULL;
   1463 	int i;
   1464 	unsigned long l;
   1465 
   1466 	if (s->state ==	SSL3_ST_CW_CERT_A)
   1467 		{
   1468 		if ((s->cert == NULL) ||
   1469 			(s->cert->key->x509 == NULL) ||
   1470 			(s->cert->key->privatekey == NULL))
   1471 			s->state=SSL3_ST_CW_CERT_B;
   1472 		else
   1473 			s->state=SSL3_ST_CW_CERT_C;
   1474 		}
   1475 
   1476 	/* We need to get a client cert */
   1477 	if (s->state == SSL3_ST_CW_CERT_B)
   1478 		{
   1479 		/* If we get an error, we need to
   1480 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
   1481 		 * We then get retied later */
   1482 		i=0;
   1483 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
   1484 		if (i < 0)
   1485 			{
   1486 			s->rwstate=SSL_X509_LOOKUP;
   1487 			return(-1);
   1488 			}
   1489 		s->rwstate=SSL_NOTHING;
   1490 		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
   1491 			{
   1492 			s->state=SSL3_ST_CW_CERT_B;
   1493 			if (	!SSL_use_certificate(s,x509) ||
   1494 				!SSL_use_PrivateKey(s,pkey))
   1495 				i=0;
   1496 			}
   1497 		else if (i == 1)
   1498 			{
   1499 			i=0;
   1500 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
   1501 			}
   1502 
   1503 		if (x509 != NULL) X509_free(x509);
   1504 		if (pkey != NULL) EVP_PKEY_free(pkey);
   1505 		if (i == 0)
   1506 			{
   1507 			if (s->version == SSL3_VERSION)
   1508 				{
   1509 				s->s3->tmp.cert_req=0;
   1510 				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
   1511 				return(1);
   1512 				}
   1513 			else
   1514 				{
   1515 				s->s3->tmp.cert_req=2;
   1516 				}
   1517 			}
   1518 
   1519 		/* Ok, we have a cert */
   1520 		s->state=SSL3_ST_CW_CERT_C;
   1521 		}
   1522 
   1523 	if (s->state == SSL3_ST_CW_CERT_C)
   1524 		{
   1525 		s->state=SSL3_ST_CW_CERT_D;
   1526 		l=dtls1_output_cert_chain(s,
   1527 			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
   1528 		s->init_num=(int)l;
   1529 		s->init_off=0;
   1530 
   1531 		/* set header called by dtls1_output_cert_chain() */
   1532 
   1533 		/* buffer the message to handle re-xmits */
   1534 		dtls1_buffer_message(s, 0);
   1535 		}
   1536 	/* SSL3_ST_CW_CERT_D */
   1537 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
   1538 	}
   1539 
   1540 
   1541