• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* ssl/d1_clnt.c */
2 /*
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@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@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@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@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@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@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@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 
dtls1_get_client_method(int ver)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 
IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,ssl_undefined_function,dtls1_connect,dtls1_get_client_method)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 			if (!s->hit)
411 				dtls1_start_timer(s);
412 			ret=dtls1_send_change_cipher_spec(s,
413 				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
414 			if (ret <= 0) goto end;
415 			s->state=SSL3_ST_CW_FINISHED_A;
416 			s->init_num=0;
417 
418 			s->session->cipher=s->s3->tmp.new_cipher;
419 #ifdef OPENSSL_NO_COMP
420 			s->session->compress_meth=0;
421 #else
422 			if (s->s3->tmp.new_compression == NULL)
423 				s->session->compress_meth=0;
424 			else
425 				s->session->compress_meth=
426 					s->s3->tmp.new_compression->id;
427 #endif
428 			if (!s->method->ssl3_enc->setup_key_block(s))
429 				{
430 				ret= -1;
431 				goto end;
432 				}
433 
434 			if (!s->method->ssl3_enc->change_cipher_state(s,
435 				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
436 				{
437 				ret= -1;
438 				goto end;
439 				}
440 
441 			dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
442 			break;
443 
444 		case SSL3_ST_CW_FINISHED_A:
445 		case SSL3_ST_CW_FINISHED_B:
446 			if (!s->hit)
447 				dtls1_start_timer(s);
448 			ret=dtls1_send_finished(s,
449 				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
450 				s->method->ssl3_enc->client_finished_label,
451 				s->method->ssl3_enc->client_finished_label_len);
452 			if (ret <= 0) goto end;
453 			s->state=SSL3_ST_CW_FLUSH;
454 
455 			/* clear flags */
456 			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
457 			if (s->hit)
458 				{
459 				s->s3->tmp.next_state=SSL_ST_OK;
460 				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
461 					{
462 					s->state=SSL_ST_OK;
463 					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
464 					s->s3->delay_buf_pop_ret=0;
465 					}
466 				}
467 			else
468 				{
469 #ifndef OPENSSL_NO_TLSEXT
470 				/* Allow NewSessionTicket if ticket expected */
471 				if (s->tlsext_ticket_expected)
472 					s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
473 				else
474 #endif
475 
476 				s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
477 				}
478 			s->init_num=0;
479 			break;
480 
481 #ifndef OPENSSL_NO_TLSEXT
482 		case SSL3_ST_CR_SESSION_TICKET_A:
483 		case SSL3_ST_CR_SESSION_TICKET_B:
484 			ret=ssl3_get_new_session_ticket(s);
485 			if (ret <= 0) goto end;
486 			s->state=SSL3_ST_CR_FINISHED_A;
487 			s->init_num=0;
488 		break;
489 
490 		case SSL3_ST_CR_CERT_STATUS_A:
491 		case SSL3_ST_CR_CERT_STATUS_B:
492 			ret=ssl3_get_cert_status(s);
493 			if (ret <= 0) goto end;
494 			s->state=SSL3_ST_CR_KEY_EXCH_A;
495 			s->init_num=0;
496 		break;
497 #endif
498 
499 		case SSL3_ST_CR_FINISHED_A:
500 		case SSL3_ST_CR_FINISHED_B:
501 			s->d1->change_cipher_spec_ok = 1;
502 			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
503 				SSL3_ST_CR_FINISHED_B);
504 			if (ret <= 0) goto end;
505 			dtls1_stop_timer(s);
506 
507 			if (s->hit)
508 				s->state=SSL3_ST_CW_CHANGE_A;
509 			else
510 				s->state=SSL_ST_OK;
511 			s->init_num=0;
512 			break;
513 
514 		case SSL3_ST_CW_FLUSH:
515 			s->rwstate=SSL_WRITING;
516 			if (BIO_flush(s->wbio) <= 0)
517 				{
518 				ret= -1;
519 				goto end;
520 				}
521 			s->rwstate=SSL_NOTHING;
522 			s->state=s->s3->tmp.next_state;
523 			break;
524 
525 		case SSL_ST_OK:
526 			/* clean a few things up */
527 			ssl3_cleanup_key_block(s);
528 
529 #if 0
530 			if (s->init_buf != NULL)
531 				{
532 				BUF_MEM_free(s->init_buf);
533 				s->init_buf=NULL;
534 				}
535 #endif
536 
537 			/* If we are not 'joining' the last two packets,
538 			 * remove the buffering now */
539 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
540 				ssl_free_wbio_buffer(s);
541 			/* else do it later in ssl3_write */
542 
543 			s->init_num=0;
544 			s->new_session=0;
545 
546 			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
547 			if (s->hit) s->ctx->stats.sess_hit++;
548 
549 			ret=1;
550 			/* s->server=0; */
551 			s->handshake_func=dtls1_connect;
552 			s->ctx->stats.sess_connect_good++;
553 
554 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
555 
556 			/* done with handshaking */
557 			s->d1->handshake_read_seq  = 0;
558 			s->d1->next_handshake_write_seq = 0;
559 			goto end;
560 			/* break; */
561 
562 		default:
563 			SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
564 			ret= -1;
565 			goto end;
566 			/* break; */
567 			}
568 
569 		/* did we do anything */
570 		if (!s->s3->tmp.reuse_message && !skip)
571 			{
572 			if (s->debug)
573 				{
574 				if ((ret=BIO_flush(s->wbio)) <= 0)
575 					goto end;
576 				}
577 
578 			if ((cb != NULL) && (s->state != state))
579 				{
580 				new_state=s->state;
581 				s->state=state;
582 				cb(s,SSL_CB_CONNECT_LOOP,1);
583 				s->state=new_state;
584 				}
585 			}
586 		skip=0;
587 		}
588 end:
589 	s->in_handshake--;
590 	if (buf != NULL)
591 		BUF_MEM_free(buf);
592 	if (cb != NULL)
593 		cb(s,SSL_CB_CONNECT_EXIT,ret);
594 	return(ret);
595 	}
596 
dtls1_client_hello(SSL * s)597 int dtls1_client_hello(SSL *s)
598 	{
599 	unsigned char *buf;
600 	unsigned char *p,*d;
601 	unsigned int i,j;
602 	unsigned long Time,l;
603 	SSL_COMP *comp;
604 
605 	buf=(unsigned char *)s->init_buf->data;
606 	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
607 		{
608 		SSL_SESSION *sess = s->session;
609 		if ((s->session == NULL) ||
610 			(s->session->ssl_version != s->version) ||
611 #ifdef OPENSSL_NO_TLSEXT
612 			!sess->session_id_length ||
613 #else
614 			(!sess->session_id_length && !sess->tlsext_tick) ||
615 #endif
616 			(s->session->not_resumable))
617 			{
618 		        if (!s->session_creation_enabled)
619 				{
620 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
621 				SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
622 				goto err;
623 				}
624 			if (!ssl_get_new_session(s,0))
625 				goto err;
626 			}
627 		/* else use the pre-loaded session */
628 
629 		p=s->s3->client_random;
630 
631 		/* if client_random is initialized, reuse it, we are
632 		 * required to use same upon reply to HelloVerify */
633 		for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
634 		if (i==sizeof(s->s3->client_random))
635 			{
636 			Time=(unsigned long)time(NULL);	/* Time */
637 			l2n(Time,p);
638 			RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
639 			}
640 
641 		/* Do the message type and length last */
642 		d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
643 
644 		*(p++)=s->version>>8;
645 		*(p++)=s->version&0xff;
646 		s->client_version=s->version;
647 
648 		/* Random stuff */
649 		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
650 		p+=SSL3_RANDOM_SIZE;
651 
652 		/* Session ID */
653 		if (s->new_session)
654 			i=0;
655 		else
656 			i=s->session->session_id_length;
657 		*(p++)=i;
658 		if (i != 0)
659 			{
660 			if (i > sizeof s->session->session_id)
661 				{
662 				SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
663 				goto err;
664 				}
665 			memcpy(p,s->session->session_id,i);
666 			p+=i;
667 			}
668 
669 		/* cookie stuff */
670 		if ( s->d1->cookie_len > sizeof(s->d1->cookie))
671 			{
672 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
673 			goto err;
674 			}
675 		*(p++) = s->d1->cookie_len;
676 		memcpy(p, s->d1->cookie, s->d1->cookie_len);
677 		p += s->d1->cookie_len;
678 
679 		/* Ciphers supported */
680 		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
681 		if (i == 0)
682 			{
683 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
684 			goto err;
685 			}
686 		s2n(i,p);
687 		p+=i;
688 
689 		/* COMPRESSION */
690 		if (s->ctx->comp_methods == NULL)
691 			j=0;
692 		else
693 			j=sk_SSL_COMP_num(s->ctx->comp_methods);
694 		*(p++)=1+j;
695 		for (i=0; i<j; i++)
696 			{
697 			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
698 			*(p++)=comp->id;
699 			}
700 		*(p++)=0; /* Add the NULL method */
701 
702 #ifndef OPENSSL_NO_TLSEXT
703 		if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
704 			{
705 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
706 			goto err;
707 			}
708 #endif
709 
710 		l=(p-d);
711 		d=buf;
712 
713 		d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
714 
715 		s->state=SSL3_ST_CW_CLNT_HELLO_B;
716 		/* number of bytes to write */
717 		s->init_num=p-buf;
718 		s->init_off=0;
719 
720 		/* buffer the message to handle re-xmits */
721 		dtls1_buffer_message(s, 0);
722 		}
723 
724 	/* SSL3_ST_CW_CLNT_HELLO_B */
725 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
726 err:
727 	return(-1);
728 	}
729 
dtls1_get_hello_verify(SSL * s)730 static int dtls1_get_hello_verify(SSL *s)
731 	{
732 	int n, al, ok = 0;
733 	unsigned char *data;
734 	unsigned int cookie_len;
735 
736 	n=s->method->ssl_get_message(s,
737 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
738 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
739 		-1,
740 		s->max_cert_list,
741 		&ok);
742 
743 	if (!ok) return((int)n);
744 
745 	if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
746 		{
747 		s->d1->send_cookie = 0;
748 		s->s3->tmp.reuse_message=1;
749 		return(1);
750 		}
751 
752 	data = (unsigned char *)s->init_msg;
753 
754 	if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
755 		{
756 		SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
757 		s->version=(s->version&0xff00)|data[1];
758 		al = SSL_AD_PROTOCOL_VERSION;
759 		goto f_err;
760 		}
761 	data+=2;
762 
763 	cookie_len = *(data++);
764 	if ( cookie_len > sizeof(s->d1->cookie))
765 		{
766 		al=SSL_AD_ILLEGAL_PARAMETER;
767 		goto f_err;
768 		}
769 
770 	memcpy(s->d1->cookie, data, cookie_len);
771 	s->d1->cookie_len = cookie_len;
772 
773 	s->d1->send_cookie = 1;
774 	return 1;
775 
776 f_err:
777 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
778 	return -1;
779 	}
780 
dtls1_send_client_key_exchange(SSL * s)781 int dtls1_send_client_key_exchange(SSL *s)
782 	{
783 	unsigned char *p,*d;
784 	int n;
785 	unsigned long alg_k;
786 #ifndef OPENSSL_NO_RSA
787 	unsigned char *q;
788 	EVP_PKEY *pkey=NULL;
789 #endif
790 #ifndef OPENSSL_NO_KRB5
791         KSSL_ERR kssl_err;
792 #endif /* OPENSSL_NO_KRB5 */
793 #ifndef OPENSSL_NO_ECDH
794 	EC_KEY *clnt_ecdh = NULL;
795 	const EC_POINT *srvr_ecpoint = NULL;
796 	EVP_PKEY *srvr_pub_pkey = NULL;
797 	unsigned char *encodedPoint = NULL;
798 	int encoded_pt_len = 0;
799 	BN_CTX * bn_ctx = NULL;
800 #endif
801 
802 	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
803 		{
804 		d=(unsigned char *)s->init_buf->data;
805 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
806 
807 		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
808 
809                 /* Fool emacs indentation */
810                 if (0) {}
811 #ifndef OPENSSL_NO_RSA
812 		else if (alg_k & SSL_kRSA)
813 			{
814 			RSA *rsa;
815 			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
816 
817 			if (s->session->sess_cert->peer_rsa_tmp != NULL)
818 				rsa=s->session->sess_cert->peer_rsa_tmp;
819 			else
820 				{
821 				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
822 				if ((pkey == NULL) ||
823 					(pkey->type != EVP_PKEY_RSA) ||
824 					(pkey->pkey.rsa == NULL))
825 					{
826 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
827 					goto err;
828 					}
829 				rsa=pkey->pkey.rsa;
830 				EVP_PKEY_free(pkey);
831 				}
832 
833 			tmp_buf[0]=s->client_version>>8;
834 			tmp_buf[1]=s->client_version&0xff;
835 			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
836 					goto err;
837 
838 			s->session->master_key_length=sizeof tmp_buf;
839 
840 			q=p;
841 			/* Fix buf for TLS and [incidentally] DTLS */
842 			if (s->version > SSL3_VERSION)
843 				p+=2;
844 			n=RSA_public_encrypt(sizeof tmp_buf,
845 				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
846 #ifdef PKCS1_CHECK
847 			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
848 			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
849 #endif
850 			if (n <= 0)
851 				{
852 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
853 				goto err;
854 				}
855 
856 			/* Fix buf for TLS and [incidentally] DTLS */
857 			if (s->version > SSL3_VERSION)
858 				{
859 				s2n(n,q);
860 				n+=2;
861 				}
862 
863 			s->session->master_key_length=
864 				s->method->ssl3_enc->generate_master_secret(s,
865 					s->session->master_key,
866 					tmp_buf,sizeof tmp_buf);
867 			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
868 			}
869 #endif
870 #ifndef OPENSSL_NO_KRB5
871 		else if (alg_k & SSL_kKRB5)
872                         {
873                         krb5_error_code	krb5rc;
874                         KSSL_CTX	*kssl_ctx = s->kssl_ctx;
875                         /*  krb5_data	krb5_ap_req;  */
876                         krb5_data	*enc_ticket;
877                         krb5_data	authenticator, *authp = NULL;
878 			EVP_CIPHER_CTX	ciph_ctx;
879 			const EVP_CIPHER *enc = NULL;
880 			unsigned char	iv[EVP_MAX_IV_LENGTH];
881 			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
882 			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
883 						+ EVP_MAX_IV_LENGTH];
884 			int 		padl, outl = sizeof(epms);
885 
886 			EVP_CIPHER_CTX_init(&ciph_ctx);
887 
888 #ifdef KSSL_DEBUG
889                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
890                                 alg_k, SSL_kKRB5);
891 #endif	/* KSSL_DEBUG */
892 
893 			authp = NULL;
894 #ifdef KRB5SENDAUTH
895 			if (KRB5SENDAUTH)  authp = &authenticator;
896 #endif	/* KRB5SENDAUTH */
897 
898                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
899 				&kssl_err);
900 			enc = kssl_map_enc(kssl_ctx->enctype);
901                         if (enc == NULL)
902                             goto err;
903 #ifdef KSSL_DEBUG
904                         {
905                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
906                         if (krb5rc && kssl_err.text)
907 			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
908                         }
909 #endif	/* KSSL_DEBUG */
910 
911                         if (krb5rc)
912                                 {
913                                 ssl3_send_alert(s,SSL3_AL_FATAL,
914 						SSL_AD_HANDSHAKE_FAILURE);
915                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
916 						kssl_err.reason);
917                                 goto err;
918                                 }
919 
920 			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
921 			**  in place of RFC 2712 KerberosWrapper, as in:
922 			**
923                         **  Send ticket (copy to *p, set n = length)
924                         **  n = krb5_ap_req.length;
925                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
926                         **  if (krb5_ap_req.data)
927                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
928                         **
929 			**  Now using real RFC 2712 KerberosWrapper
930 			**  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
931 			**  Note: 2712 "opaque" types are here replaced
932 			**  with a 2-byte length followed by the value.
933 			**  Example:
934 			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
935 			**  Where "xx xx" = length bytes.  Shown here with
936 			**  optional authenticator omitted.
937 			*/
938 
939 			/*  KerberosWrapper.Ticket		*/
940 			s2n(enc_ticket->length,p);
941 			memcpy(p, enc_ticket->data, enc_ticket->length);
942 			p+= enc_ticket->length;
943 			n = enc_ticket->length + 2;
944 
945 			/*  KerberosWrapper.Authenticator	*/
946 			if (authp  &&  authp->length)
947 				{
948 				s2n(authp->length,p);
949 				memcpy(p, authp->data, authp->length);
950 				p+= authp->length;
951 				n+= authp->length + 2;
952 
953 				free(authp->data);
954 				authp->data = NULL;
955 				authp->length = 0;
956 				}
957 			else
958 				{
959 				s2n(0,p);/*  null authenticator length	*/
960 				n+=2;
961 				}
962 
963 			if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
964 			    goto err;
965 
966 			/*  20010420 VRS.  Tried it this way; failed.
967 			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
968 			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
969 			**				kssl_ctx->length);
970 			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
971 			*/
972 
973 			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
974 			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
975 				kssl_ctx->key,iv);
976 			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
977 				sizeof tmp_buf);
978 			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
979 			outl += padl;
980 			if (outl > (int)sizeof epms)
981 				{
982 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
983 				goto err;
984 				}
985 			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
986 
987 			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
988 			s2n(outl,p);
989 			memcpy(p, epms, outl);
990 			p+=outl;
991 			n+=outl + 2;
992 
993                         s->session->master_key_length=
994                                 s->method->ssl3_enc->generate_master_secret(s,
995 					s->session->master_key,
996 					tmp_buf, sizeof tmp_buf);
997 
998 			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
999 			OPENSSL_cleanse(epms, outl);
1000                         }
1001 #endif
1002 #ifndef OPENSSL_NO_DH
1003 		else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1004 			{
1005 			DH *dh_srvr,*dh_clnt;
1006 
1007 			if (s->session->sess_cert->peer_dh_tmp != NULL)
1008 				dh_srvr=s->session->sess_cert->peer_dh_tmp;
1009 			else
1010 				{
1011 				/* we get them from the cert */
1012 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1013 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1014 				goto err;
1015 				}
1016 
1017 			/* generate a new random key */
1018 			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1019 				{
1020 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1021 				goto err;
1022 				}
1023 			if (!DH_generate_key(dh_clnt))
1024 				{
1025 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1026 				goto err;
1027 				}
1028 
1029 			/* use the 'p' output buffer for the DH key, but
1030 			 * make sure to clear it out afterwards */
1031 
1032 			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1033 
1034 			if (n <= 0)
1035 				{
1036 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1037 				goto err;
1038 				}
1039 
1040 			/* generate master key from the result */
1041 			s->session->master_key_length=
1042 				s->method->ssl3_enc->generate_master_secret(s,
1043 					s->session->master_key,p,n);
1044 			/* clean up */
1045 			memset(p,0,n);
1046 
1047 			/* send off the data */
1048 			n=BN_num_bytes(dh_clnt->pub_key);
1049 			s2n(n,p);
1050 			BN_bn2bin(dh_clnt->pub_key,p);
1051 			n+=2;
1052 
1053 			DH_free(dh_clnt);
1054 
1055 			/* perhaps clean things up a bit EAY EAY EAY EAY*/
1056 			}
1057 #endif
1058 #ifndef OPENSSL_NO_ECDH
1059 		else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
1060 			{
1061 			const EC_GROUP *srvr_group = NULL;
1062 			EC_KEY *tkey;
1063 			int ecdh_clnt_cert = 0;
1064 			int field_size = 0;
1065 
1066 			/* Did we send out the client's
1067 			 * ECDH share for use in premaster
1068 			 * computation as part of client certificate?
1069 			 * If so, set ecdh_clnt_cert to 1.
1070 			 */
1071 			if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL))
1072 				{
1073 				/* XXX: For now, we do not support client
1074 				 * authentication using ECDH certificates.
1075 				 * To add such support, one needs to add
1076 				 * code that checks for appropriate
1077 				 * conditions and sets ecdh_clnt_cert to 1.
1078 				 * For example, the cert have an ECC
1079 				 * key on the same curve as the server's
1080 				 * and the key should be authorized for
1081 				 * key agreement.
1082 				 *
1083 				 * One also needs to add code in ssl3_connect
1084 				 * to skip sending the certificate verify
1085 				 * message.
1086 				 *
1087 				 * if ((s->cert->key->privatekey != NULL) &&
1088 				 *     (s->cert->key->privatekey->type ==
1089 				 *      EVP_PKEY_EC) && ...)
1090 				 * ecdh_clnt_cert = 1;
1091 				 */
1092 				}
1093 
1094 			if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1095 				{
1096 				tkey = s->session->sess_cert->peer_ecdh_tmp;
1097 				}
1098 			else
1099 				{
1100 				/* Get the Server Public Key from Cert */
1101 				srvr_pub_pkey = X509_get_pubkey(s->session-> \
1102 				    sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1103 				if ((srvr_pub_pkey == NULL) ||
1104 				    (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1105 				    (srvr_pub_pkey->pkey.ec == NULL))
1106 					{
1107 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1108 					    ERR_R_INTERNAL_ERROR);
1109 					goto err;
1110 					}
1111 
1112 				tkey = srvr_pub_pkey->pkey.ec;
1113 				}
1114 
1115 			srvr_group   = EC_KEY_get0_group(tkey);
1116 			srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1117 
1118 			if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1119 				{
1120 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1121 				    ERR_R_INTERNAL_ERROR);
1122 				goto err;
1123 				}
1124 
1125 			if ((clnt_ecdh=EC_KEY_new()) == NULL)
1126 				{
1127 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1128 				goto err;
1129 				}
1130 
1131 			if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1132 				{
1133 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1134 				goto err;
1135 				}
1136 			if (ecdh_clnt_cert)
1137 				{
1138 				/* Reuse key info from our certificate
1139 				 * We only need our private key to perform
1140 				 * the ECDH computation.
1141 				 */
1142 				const BIGNUM *priv_key;
1143 				tkey = s->cert->key->privatekey->pkey.ec;
1144 				priv_key = EC_KEY_get0_private_key(tkey);
1145 				if (priv_key == NULL)
1146 					{
1147 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1148 					goto err;
1149 					}
1150 				if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1151 					{
1152 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1153 					goto err;
1154 					}
1155 				}
1156 			else
1157 				{
1158 				/* Generate a new ECDH key pair */
1159 				if (!(EC_KEY_generate_key(clnt_ecdh)))
1160 					{
1161 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1162 					goto err;
1163 					}
1164 				}
1165 
1166 			/* use the 'p' output buffer for the ECDH key, but
1167 			 * make sure to clear it out afterwards
1168 			 */
1169 
1170 			field_size = EC_GROUP_get_degree(srvr_group);
1171 			if (field_size <= 0)
1172 				{
1173 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1174 				       ERR_R_ECDH_LIB);
1175 				goto err;
1176 				}
1177 			n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1178 			if (n <= 0)
1179 				{
1180 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1181 				       ERR_R_ECDH_LIB);
1182 				goto err;
1183 				}
1184 
1185 			/* generate master key from the result */
1186 			s->session->master_key_length = s->method->ssl3_enc \
1187 			    -> generate_master_secret(s,
1188 				s->session->master_key,
1189 				p, n);
1190 
1191 			memset(p, 0, n); /* clean up */
1192 
1193 			if (ecdh_clnt_cert)
1194 				{
1195 				/* Send empty client key exch message */
1196 				n = 0;
1197 				}
1198 			else
1199 				{
1200 				/* First check the size of encoding and
1201 				 * allocate memory accordingly.
1202 				 */
1203 				encoded_pt_len =
1204 				    EC_POINT_point2oct(srvr_group,
1205 					EC_KEY_get0_public_key(clnt_ecdh),
1206 					POINT_CONVERSION_UNCOMPRESSED,
1207 					NULL, 0, NULL);
1208 
1209 				encodedPoint = (unsigned char *)
1210 				    OPENSSL_malloc(encoded_pt_len *
1211 					sizeof(unsigned char));
1212 				bn_ctx = BN_CTX_new();
1213 				if ((encodedPoint == NULL) ||
1214 				    (bn_ctx == NULL))
1215 					{
1216 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1217 					goto err;
1218 					}
1219 
1220 				/* Encode the public key */
1221 				n = EC_POINT_point2oct(srvr_group,
1222 				    EC_KEY_get0_public_key(clnt_ecdh),
1223 				    POINT_CONVERSION_UNCOMPRESSED,
1224 				    encodedPoint, encoded_pt_len, bn_ctx);
1225 
1226 				*p = n; /* length of encoded point */
1227 				/* Encoded point will be copied here */
1228 				p += 1;
1229 				/* copy the point */
1230 				memcpy((unsigned char *)p, encodedPoint, n);
1231 				/* increment n to account for length field */
1232 				n += 1;
1233 				}
1234 
1235 			/* Free allocated memory */
1236 			BN_CTX_free(bn_ctx);
1237 			if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1238 			if (clnt_ecdh != NULL)
1239 				 EC_KEY_free(clnt_ecdh);
1240 			EVP_PKEY_free(srvr_pub_pkey);
1241 			}
1242 #endif /* !OPENSSL_NO_ECDH */
1243 
1244 #ifndef OPENSSL_NO_PSK
1245 		else if (alg_k & SSL_kPSK)
1246 			{
1247 			char identity[PSK_MAX_IDENTITY_LEN];
1248 			unsigned char *t = NULL;
1249 			unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1250 			unsigned int pre_ms_len = 0, psk_len = 0;
1251 			int psk_err = 1;
1252 
1253 			n = 0;
1254 			if (s->psk_client_callback == NULL)
1255 				{
1256 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1257 					SSL_R_PSK_NO_CLIENT_CB);
1258 				goto err;
1259 				}
1260 
1261 			psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1262 				identity, PSK_MAX_IDENTITY_LEN,
1263 				psk_or_pre_ms, sizeof(psk_or_pre_ms));
1264 			if (psk_len > PSK_MAX_PSK_LEN)
1265 				{
1266 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1267 					ERR_R_INTERNAL_ERROR);
1268 				goto psk_err;
1269 				}
1270 			else if (psk_len == 0)
1271 				{
1272 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1273 					SSL_R_PSK_IDENTITY_NOT_FOUND);
1274 				goto psk_err;
1275 				}
1276 
1277 			/* create PSK pre_master_secret */
1278 			pre_ms_len = 2+psk_len+2+psk_len;
1279 			t = psk_or_pre_ms;
1280 			memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1281 			s2n(psk_len, t);
1282 			memset(t, 0, psk_len);
1283 			t+=psk_len;
1284 			s2n(psk_len, t);
1285 
1286 			if (s->session->psk_identity_hint != NULL)
1287 				OPENSSL_free(s->session->psk_identity_hint);
1288 			s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1289 			if (s->ctx->psk_identity_hint != NULL &&
1290 				s->session->psk_identity_hint == NULL)
1291 				{
1292 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1293 					ERR_R_MALLOC_FAILURE);
1294 				goto psk_err;
1295 				}
1296 
1297 			if (s->session->psk_identity != NULL)
1298 				OPENSSL_free(s->session->psk_identity);
1299 			s->session->psk_identity = BUF_strdup(identity);
1300 			if (s->session->psk_identity == NULL)
1301 				{
1302 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1303 					ERR_R_MALLOC_FAILURE);
1304 				goto psk_err;
1305 				}
1306 
1307 			s->session->master_key_length =
1308 				s->method->ssl3_enc->generate_master_secret(s,
1309 					s->session->master_key,
1310 					psk_or_pre_ms, pre_ms_len);
1311 			n = strlen(identity);
1312 			s2n(n, p);
1313 			memcpy(p, identity, n);
1314 			n+=2;
1315 			psk_err = 0;
1316 		psk_err:
1317 			OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1318 			OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1319 			if (psk_err != 0)
1320 				{
1321 				ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1322 				goto err;
1323 				}
1324 			}
1325 #endif
1326 		else
1327 			{
1328 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1329 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1330 			goto err;
1331 			}
1332 
1333 		d = dtls1_set_message_header(s, d,
1334 		SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1335 		/*
1336 		 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1337 		 l2n3(n,d);
1338 		 l2n(s->d1->handshake_write_seq,d);
1339 		 s->d1->handshake_write_seq++;
1340 		*/
1341 
1342 		s->state=SSL3_ST_CW_KEY_EXCH_B;
1343 		/* number of bytes to write */
1344 		s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1345 		s->init_off=0;
1346 
1347 		/* buffer the message to handle re-xmits */
1348 		dtls1_buffer_message(s, 0);
1349 		}
1350 
1351 	/* SSL3_ST_CW_KEY_EXCH_B */
1352 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1353 err:
1354 #ifndef OPENSSL_NO_ECDH
1355 	BN_CTX_free(bn_ctx);
1356 	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1357 	if (clnt_ecdh != NULL)
1358 		EC_KEY_free(clnt_ecdh);
1359 	EVP_PKEY_free(srvr_pub_pkey);
1360 #endif
1361 	return(-1);
1362 	}
1363 
dtls1_send_client_verify(SSL * s)1364 int dtls1_send_client_verify(SSL *s)
1365 	{
1366 	unsigned char *p,*d;
1367 	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1368 	EVP_PKEY *pkey;
1369 #ifndef OPENSSL_NO_RSA
1370 	unsigned u=0;
1371 #endif
1372 	unsigned long n;
1373 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1374 	int j;
1375 #endif
1376 
1377 	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1378 		{
1379 		d=(unsigned char *)s->init_buf->data;
1380 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
1381 		pkey=s->cert->key->privatekey;
1382 
1383 		s->method->ssl3_enc->cert_verify_mac(s,
1384 		NID_sha1,
1385 			&(data[MD5_DIGEST_LENGTH]));
1386 
1387 #ifndef OPENSSL_NO_RSA
1388 		if (pkey->type == EVP_PKEY_RSA)
1389 			{
1390 			s->method->ssl3_enc->cert_verify_mac(s,
1391 				NID_md5,
1392 				&(data[0]));
1393 			if (RSA_sign(NID_md5_sha1, data,
1394 					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1395 					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
1396 				{
1397 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1398 				goto err;
1399 				}
1400 			s2n(u,p);
1401 			n=u+2;
1402 			}
1403 		else
1404 #endif
1405 #ifndef OPENSSL_NO_DSA
1406 			if (pkey->type == EVP_PKEY_DSA)
1407 			{
1408 			if (!DSA_sign(pkey->save_type,
1409 				&(data[MD5_DIGEST_LENGTH]),
1410 				SHA_DIGEST_LENGTH,&(p[2]),
1411 				(unsigned int *)&j,pkey->pkey.dsa))
1412 				{
1413 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1414 				goto err;
1415 				}
1416 			s2n(j,p);
1417 			n=j+2;
1418 			}
1419 		else
1420 #endif
1421 #ifndef OPENSSL_NO_ECDSA
1422 			if (pkey->type == EVP_PKEY_EC)
1423 			{
1424 			if (!ECDSA_sign(pkey->save_type,
1425 				&(data[MD5_DIGEST_LENGTH]),
1426 				SHA_DIGEST_LENGTH,&(p[2]),
1427 				(unsigned int *)&j,pkey->pkey.ec))
1428 				{
1429 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1430 				    ERR_R_ECDSA_LIB);
1431 				goto err;
1432 				}
1433 			s2n(j,p);
1434 			n=j+2;
1435 			}
1436 		else
1437 #endif
1438 			{
1439 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1440 			goto err;
1441 			}
1442 
1443 		d = dtls1_set_message_header(s, d,
1444 			SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1445 
1446 		s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1447 		s->init_off=0;
1448 
1449 		/* buffer the message to handle re-xmits */
1450 		dtls1_buffer_message(s, 0);
1451 
1452 		s->state = SSL3_ST_CW_CERT_VRFY_B;
1453 		}
1454 
1455 	/* s->state = SSL3_ST_CW_CERT_VRFY_B */
1456 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1457 err:
1458 	return(-1);
1459 	}
1460 
dtls1_send_client_certificate(SSL * s)1461 int dtls1_send_client_certificate(SSL *s)
1462 	{
1463 	X509 *x509=NULL;
1464 	EVP_PKEY *pkey=NULL;
1465 	int i;
1466 	unsigned long l;
1467 
1468 	if (s->state ==	SSL3_ST_CW_CERT_A)
1469 		{
1470 		if ((s->cert == NULL) ||
1471 			(s->cert->key->x509 == NULL) ||
1472 			(s->cert->key->privatekey == NULL))
1473 			s->state=SSL3_ST_CW_CERT_B;
1474 		else
1475 			s->state=SSL3_ST_CW_CERT_C;
1476 		}
1477 
1478 	/* We need to get a client cert */
1479 	if (s->state == SSL3_ST_CW_CERT_B)
1480 		{
1481 		/* If we get an error, we need to
1482 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1483 		 * We then get retied later */
1484 		i=0;
1485 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
1486 		if (i < 0)
1487 			{
1488 			s->rwstate=SSL_X509_LOOKUP;
1489 			return(-1);
1490 			}
1491 		s->rwstate=SSL_NOTHING;
1492 		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1493 			{
1494 			s->state=SSL3_ST_CW_CERT_B;
1495 			if (	!SSL_use_certificate(s,x509) ||
1496 				!SSL_use_PrivateKey(s,pkey))
1497 				i=0;
1498 			}
1499 		else if (i == 1)
1500 			{
1501 			i=0;
1502 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1503 			}
1504 
1505 		if (x509 != NULL) X509_free(x509);
1506 		if (pkey != NULL) EVP_PKEY_free(pkey);
1507 		if (i == 0)
1508 			{
1509 			if (s->version == SSL3_VERSION)
1510 				{
1511 				s->s3->tmp.cert_req=0;
1512 				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1513 				return(1);
1514 				}
1515 			else
1516 				{
1517 				s->s3->tmp.cert_req=2;
1518 				}
1519 			}
1520 
1521 		/* Ok, we have a cert */
1522 		s->state=SSL3_ST_CW_CERT_C;
1523 		}
1524 
1525 	if (s->state == SSL3_ST_CW_CERT_C)
1526 		{
1527 		s->state=SSL3_ST_CW_CERT_D;
1528 		l=dtls1_output_cert_chain(s,
1529 			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1530 		s->init_num=(int)l;
1531 		s->init_off=0;
1532 
1533 		/* set header called by dtls1_output_cert_chain() */
1534 
1535 		/* buffer the message to handle re-xmits */
1536 		dtls1_buffer_message(s, 0);
1537 		}
1538 	/* SSL3_ST_CW_CERT_D */
1539 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1540 	}
1541 
1542 
1543