xref: /onnv-gate/usr/src/common/openssl/ssl/d1_clnt.c (revision 5434:d0b14f9f9750)
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-2005 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 #include "kssl_lcl.h"
119 #include <openssl/buffer.h>
120 #include <openssl/rand.h>
121 #include <openssl/objects.h>
122 #include <openssl/evp.h>
123 #include <openssl/md5.h>
124 #ifndef OPENSSL_NO_DH
125 #include <openssl/dh.h>
126 #endif
127 
128 static SSL_METHOD *dtls1_get_client_method(int ver);
129 static int dtls1_get_hello_verify(SSL *s);
130 
dtls1_get_client_method(int ver)131 static SSL_METHOD *dtls1_get_client_method(int ver)
132 	{
133 	if (ver == DTLS1_VERSION)
134 		return(DTLSv1_client_method());
135 	else
136 		return(NULL);
137 	}
138 
IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,ssl_undefined_function,dtls1_connect,dtls1_get_client_method)139 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
140 			ssl_undefined_function,
141 			dtls1_connect,
142 			dtls1_get_client_method)
143 
144 int dtls1_connect(SSL *s)
145 	{
146 	BUF_MEM *buf=NULL;
147 	unsigned long Time=(unsigned long)time(NULL),l;
148 	long num1;
149 	void (*cb)(const SSL *ssl,int type,int val)=NULL;
150 	int ret= -1;
151 	int new_state,state,skip=0;;
152 
153 	RAND_add(&Time,sizeof(Time),0);
154 	ERR_clear_error();
155 	clear_sys_error();
156 
157 	if (s->info_callback != NULL)
158 		cb=s->info_callback;
159 	else if (s->ctx->info_callback != NULL)
160 		cb=s->ctx->info_callback;
161 
162 	s->in_handshake++;
163 	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
164 
165 	for (;;)
166 		{
167 		state=s->state;
168 
169 		switch(s->state)
170 			{
171 		case SSL_ST_RENEGOTIATE:
172 			s->new_session=1;
173 			s->state=SSL_ST_CONNECT;
174 			s->ctx->stats.sess_connect_renegotiate++;
175 			/* break */
176 		case SSL_ST_BEFORE:
177 		case SSL_ST_CONNECT:
178 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
179 		case SSL_ST_OK|SSL_ST_CONNECT:
180 
181 			s->server=0;
182 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
183 
184 			if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00))
185 				{
186 				SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
187 				ret = -1;
188 				goto end;
189 				}
190 
191 			/* s->version=SSL3_VERSION; */
192 			s->type=SSL_ST_CONNECT;
193 
194 			if (s->init_buf == NULL)
195 				{
196 				if ((buf=BUF_MEM_new()) == NULL)
197 					{
198 					ret= -1;
199 					goto end;
200 					}
201 				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
202 					{
203 					ret= -1;
204 					goto end;
205 					}
206 				s->init_buf=buf;
207 				buf=NULL;
208 				}
209 
210 			if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
211 
212 			/* setup buffing BIO */
213 			if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
214 
215 			/* don't push the buffering BIO quite yet */
216 
217 			s->state=SSL3_ST_CW_CLNT_HELLO_A;
218 			s->ctx->stats.sess_connect++;
219 			s->init_num=0;
220 			/* mark client_random uninitialized */
221 			memset(s->s3->client_random,0,sizeof(s->s3->client_random));
222 			break;
223 
224 		case SSL3_ST_CW_CLNT_HELLO_A:
225 		case SSL3_ST_CW_CLNT_HELLO_B:
226 
227 			s->shutdown=0;
228 
229 			/* every DTLS ClientHello resets Finished MAC */
230 			ssl3_init_finished_mac(s);
231 
232 			ret=dtls1_client_hello(s);
233 			if (ret <= 0) goto end;
234 
235 			if ( s->d1->send_cookie)
236 				{
237 				s->state=SSL3_ST_CW_FLUSH;
238 				s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
239 				}
240 			else
241 				s->state=SSL3_ST_CR_SRVR_HELLO_A;
242 
243 			s->init_num=0;
244 
245 			/* turn on buffering for the next lot of output */
246 			if (s->bbio != s->wbio)
247 				s->wbio=BIO_push(s->bbio,s->wbio);
248 
249 			break;
250 
251 		case SSL3_ST_CR_SRVR_HELLO_A:
252 		case SSL3_ST_CR_SRVR_HELLO_B:
253 			ret=ssl3_get_server_hello(s);
254 			if (ret <= 0) goto end;
255 			else
256 				{
257 				if (s->hit)
258 					s->state=SSL3_ST_CR_FINISHED_A;
259 				else
260 					s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
261 				}
262 			s->init_num=0;
263 			break;
264 
265 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
266 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
267 
268 			ret = dtls1_get_hello_verify(s);
269 			if ( ret <= 0)
270 				goto end;
271 			if ( s->d1->send_cookie) /* start again, with a cookie */
272 				s->state=SSL3_ST_CW_CLNT_HELLO_A;
273 			else
274 				s->state = SSL3_ST_CR_CERT_A;
275 			s->init_num = 0;
276 			break;
277 
278 		case SSL3_ST_CR_CERT_A:
279 		case SSL3_ST_CR_CERT_B:
280 			/* Check if it is anon DH */
281 			if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
282 				{
283 				ret=ssl3_get_server_certificate(s);
284 				if (ret <= 0) goto end;
285 				}
286 			else
287 				skip=1;
288 			s->state=SSL3_ST_CR_KEY_EXCH_A;
289 			s->init_num=0;
290 			break;
291 
292 		case SSL3_ST_CR_KEY_EXCH_A:
293 		case SSL3_ST_CR_KEY_EXCH_B:
294 			ret=ssl3_get_key_exchange(s);
295 			if (ret <= 0) goto end;
296 			s->state=SSL3_ST_CR_CERT_REQ_A;
297 			s->init_num=0;
298 
299 			/* at this point we check that we have the
300 			 * required stuff from the server */
301 			if (!ssl3_check_cert_and_algorithm(s))
302 				{
303 				ret= -1;
304 				goto end;
305 				}
306 			break;
307 
308 		case SSL3_ST_CR_CERT_REQ_A:
309 		case SSL3_ST_CR_CERT_REQ_B:
310 			ret=ssl3_get_certificate_request(s);
311 			if (ret <= 0) goto end;
312 			s->state=SSL3_ST_CR_SRVR_DONE_A;
313 			s->init_num=0;
314 			break;
315 
316 		case SSL3_ST_CR_SRVR_DONE_A:
317 		case SSL3_ST_CR_SRVR_DONE_B:
318 			ret=ssl3_get_server_done(s);
319 			if (ret <= 0) goto end;
320 			if (s->s3->tmp.cert_req)
321 				s->state=SSL3_ST_CW_CERT_A;
322 			else
323 				s->state=SSL3_ST_CW_KEY_EXCH_A;
324 			s->init_num=0;
325 
326 			break;
327 
328 		case SSL3_ST_CW_CERT_A:
329 		case SSL3_ST_CW_CERT_B:
330 		case SSL3_ST_CW_CERT_C:
331 		case SSL3_ST_CW_CERT_D:
332 			ret=dtls1_send_client_certificate(s);
333 			if (ret <= 0) goto end;
334 			s->state=SSL3_ST_CW_KEY_EXCH_A;
335 			s->init_num=0;
336 			break;
337 
338 		case SSL3_ST_CW_KEY_EXCH_A:
339 		case SSL3_ST_CW_KEY_EXCH_B:
340 			ret=dtls1_send_client_key_exchange(s);
341 			if (ret <= 0) goto end;
342 			l=s->s3->tmp.new_cipher->algorithms;
343 			/* EAY EAY EAY need to check for DH fix cert
344 			 * sent back */
345 			/* For TLS, cert_req is set to 2, so a cert chain
346 			 * of nothing is sent, but no verify packet is sent */
347 			if (s->s3->tmp.cert_req == 1)
348 				{
349 				s->state=SSL3_ST_CW_CERT_VRFY_A;
350 				}
351 			else
352 				{
353 				s->state=SSL3_ST_CW_CHANGE_A;
354 				s->s3->change_cipher_spec=0;
355 				}
356 
357 			s->init_num=0;
358 			break;
359 
360 		case SSL3_ST_CW_CERT_VRFY_A:
361 		case SSL3_ST_CW_CERT_VRFY_B:
362 			ret=dtls1_send_client_verify(s);
363 			if (ret <= 0) goto end;
364 			s->state=SSL3_ST_CW_CHANGE_A;
365 			s->init_num=0;
366 			s->s3->change_cipher_spec=0;
367 			break;
368 
369 		case SSL3_ST_CW_CHANGE_A:
370 		case SSL3_ST_CW_CHANGE_B:
371 			ret=dtls1_send_change_cipher_spec(s,
372 				SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
373 			if (ret <= 0) goto end;
374 			s->state=SSL3_ST_CW_FINISHED_A;
375 			s->init_num=0;
376 
377 			s->session->cipher=s->s3->tmp.new_cipher;
378 #ifdef OPENSSL_NO_COMP
379 			s->session->compress_meth=0;
380 #else
381 			if (s->s3->tmp.new_compression == NULL)
382 				s->session->compress_meth=0;
383 			else
384 				s->session->compress_meth=
385 					s->s3->tmp.new_compression->id;
386 #endif
387 			if (!s->method->ssl3_enc->setup_key_block(s))
388 				{
389 				ret= -1;
390 				goto end;
391 				}
392 
393 			if (!s->method->ssl3_enc->change_cipher_state(s,
394 				SSL3_CHANGE_CIPHER_CLIENT_WRITE))
395 				{
396 				ret= -1;
397 				goto end;
398 				}
399 
400 			dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
401 			break;
402 
403 		case SSL3_ST_CW_FINISHED_A:
404 		case SSL3_ST_CW_FINISHED_B:
405 			ret=dtls1_send_finished(s,
406 				SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
407 				s->method->ssl3_enc->client_finished_label,
408 				s->method->ssl3_enc->client_finished_label_len);
409 			if (ret <= 0) goto end;
410 			s->state=SSL3_ST_CW_FLUSH;
411 
412 			/* clear flags */
413 			s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
414 			if (s->hit)
415 				{
416 				s->s3->tmp.next_state=SSL_ST_OK;
417 				if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
418 					{
419 					s->state=SSL_ST_OK;
420 					s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
421 					s->s3->delay_buf_pop_ret=0;
422 					}
423 				}
424 			else
425 				{
426 				s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
427 				}
428 			s->init_num=0;
429 			/* mark client_random uninitialized */
430 			memset (s->s3->client_random,0,sizeof(s->s3->client_random));
431 
432 			break;
433 
434 		case SSL3_ST_CR_FINISHED_A:
435 		case SSL3_ST_CR_FINISHED_B:
436 
437 			ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
438 				SSL3_ST_CR_FINISHED_B);
439 			if (ret <= 0) goto end;
440 
441 			if (s->hit)
442 				s->state=SSL3_ST_CW_CHANGE_A;
443 			else
444 				s->state=SSL_ST_OK;
445 			s->init_num=0;
446 			break;
447 
448 		case SSL3_ST_CW_FLUSH:
449 			/* number of bytes to be flushed */
450 			num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
451 			if (num1 > 0)
452 				{
453 				s->rwstate=SSL_WRITING;
454 				num1=BIO_flush(s->wbio);
455 				if (num1 <= 0) { ret= -1; goto end; }
456 				s->rwstate=SSL_NOTHING;
457 				}
458 
459 			s->state=s->s3->tmp.next_state;
460 			break;
461 
462 		case SSL_ST_OK:
463 			/* clean a few things up */
464 			ssl3_cleanup_key_block(s);
465 
466 #if 0
467 			if (s->init_buf != NULL)
468 				{
469 				BUF_MEM_free(s->init_buf);
470 				s->init_buf=NULL;
471 				}
472 #endif
473 
474 			/* If we are not 'joining' the last two packets,
475 			 * remove the buffering now */
476 			if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
477 				ssl_free_wbio_buffer(s);
478 			/* else do it later in ssl3_write */
479 
480 			s->init_num=0;
481 			s->new_session=0;
482 
483 			ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
484 			if (s->hit) s->ctx->stats.sess_hit++;
485 
486 			ret=1;
487 			/* s->server=0; */
488 			s->handshake_func=dtls1_connect;
489 			s->ctx->stats.sess_connect_good++;
490 
491 			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
492 
493 			/* done with handshaking */
494 			s->d1->handshake_read_seq  = 0;
495 			goto end;
496 			/* break; */
497 
498 		default:
499 			SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
500 			ret= -1;
501 			goto end;
502 			/* break; */
503 			}
504 
505 		/* did we do anything */
506 		if (!s->s3->tmp.reuse_message && !skip)
507 			{
508 			if (s->debug)
509 				{
510 				if ((ret=BIO_flush(s->wbio)) <= 0)
511 					goto end;
512 				}
513 
514 			if ((cb != NULL) && (s->state != state))
515 				{
516 				new_state=s->state;
517 				s->state=state;
518 				cb(s,SSL_CB_CONNECT_LOOP,1);
519 				s->state=new_state;
520 				}
521 			}
522 		skip=0;
523 		}
524 end:
525 	s->in_handshake--;
526 	if (buf != NULL)
527 		BUF_MEM_free(buf);
528 	if (cb != NULL)
529 		cb(s,SSL_CB_CONNECT_EXIT,ret);
530 	return(ret);
531 	}
532 
dtls1_client_hello(SSL * s)533 int dtls1_client_hello(SSL *s)
534 	{
535 	unsigned char *buf;
536 	unsigned char *p,*d;
537 	unsigned int i,j;
538 	unsigned long Time,l;
539 	SSL_COMP *comp;
540 
541 	buf=(unsigned char *)s->init_buf->data;
542 	if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
543 		{
544 		if ((s->session == NULL) ||
545 			(s->session->ssl_version != s->version) ||
546 			(s->session->not_resumable))
547 			{
548 			if (!ssl_get_new_session(s,0))
549 				goto err;
550 			}
551 		/* else use the pre-loaded session */
552 
553 		p=s->s3->client_random;
554 		/* if client_random is initialized, reuse it, we are
555 		 * required to use same upon reply to HelloVerify */
556 		for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
557 		if (i==sizeof(s->s3->client_random))
558 			{
559 			Time=(unsigned long)time(NULL);	/* Time */
560 			l2n(Time,p);
561 			RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4);
562 			}
563 
564 		/* Do the message type and length last */
565 		d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
566 
567 		*(p++)=s->version>>8;
568 		*(p++)=s->version&0xff;
569 		s->client_version=s->version;
570 
571 		/* Random stuff */
572 		memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
573 		p+=SSL3_RANDOM_SIZE;
574 
575 		/* Session ID */
576 		if (s->new_session)
577 			i=0;
578 		else
579 			i=s->session->session_id_length;
580 		*(p++)=i;
581 		if (i != 0)
582 			{
583 			if (i > sizeof s->session->session_id)
584 				{
585 				SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
586 				goto err;
587 				}
588 			memcpy(p,s->session->session_id,i);
589 			p+=i;
590 			}
591 
592 		/* cookie stuff */
593 		if ( s->d1->cookie_len > sizeof(s->d1->cookie))
594 			{
595 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
596 			goto err;
597 			}
598 		*(p++) = s->d1->cookie_len;
599 		memcpy(p, s->d1->cookie, s->d1->cookie_len);
600 		p += s->d1->cookie_len;
601 
602 		/* Ciphers supported */
603 		i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
604 		if (i == 0)
605 			{
606 			SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
607 			goto err;
608 			}
609 		s2n(i,p);
610 		p+=i;
611 
612 		/* COMPRESSION */
613 		if (s->ctx->comp_methods == NULL)
614 			j=0;
615 		else
616 			j=sk_SSL_COMP_num(s->ctx->comp_methods);
617 		*(p++)=1+j;
618 		for (i=0; i<j; i++)
619 			{
620 			comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
621 			*(p++)=comp->id;
622 			}
623 		*(p++)=0; /* Add the NULL method */
624 
625 		l=(p-d);
626 		d=buf;
627 
628 		d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
629 
630 		s->state=SSL3_ST_CW_CLNT_HELLO_B;
631 		/* number of bytes to write */
632 		s->init_num=p-buf;
633 		s->init_off=0;
634 
635 		/* buffer the message to handle re-xmits */
636 		dtls1_buffer_message(s, 0);
637 		}
638 
639 	/* SSL3_ST_CW_CLNT_HELLO_B */
640 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
641 err:
642 	return(-1);
643 	}
644 
dtls1_get_hello_verify(SSL * s)645 static int dtls1_get_hello_verify(SSL *s)
646 	{
647 	int n, al, ok = 0;
648 	unsigned char *data;
649 	unsigned int cookie_len;
650 
651 	n=s->method->ssl_get_message(s,
652 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
653 		DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
654 		-1,
655 		s->max_cert_list,
656 		&ok);
657 
658 	if (!ok) return((int)n);
659 
660 	if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
661 		{
662 		s->d1->send_cookie = 0;
663 		s->s3->tmp.reuse_message=1;
664 		return(1);
665 		}
666 
667 	data = (unsigned char *)s->init_msg;
668 
669 	if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
670 		{
671 		SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
672 		s->version=(s->version&0xff00)|data[1];
673 		al = SSL_AD_PROTOCOL_VERSION;
674 		goto f_err;
675 		}
676 	data+=2;
677 
678 	cookie_len = *(data++);
679 	if ( cookie_len > sizeof(s->d1->cookie))
680 		{
681 		al=SSL_AD_ILLEGAL_PARAMETER;
682 		goto f_err;
683 		}
684 
685 	memcpy(s->d1->cookie, data, cookie_len);
686 	s->d1->cookie_len = cookie_len;
687 
688 	s->d1->send_cookie = 1;
689 	return 1;
690 
691 f_err:
692 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
693 	return -1;
694 	}
695 
dtls1_send_client_key_exchange(SSL * s)696 int dtls1_send_client_key_exchange(SSL *s)
697 	{
698 	unsigned char *p,*d;
699 	int n;
700 	unsigned long l;
701 #ifndef OPENSSL_NO_RSA
702 	unsigned char *q;
703 	EVP_PKEY *pkey=NULL;
704 #endif
705 #ifndef OPENSSL_NO_KRB5
706         KSSL_ERR kssl_err;
707 #endif /* OPENSSL_NO_KRB5 */
708 
709 	if (s->state == SSL3_ST_CW_KEY_EXCH_A)
710 		{
711 		d=(unsigned char *)s->init_buf->data;
712 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
713 
714 		l=s->s3->tmp.new_cipher->algorithms;
715 
716                 /* Fool emacs indentation */
717                 if (0) {}
718 #ifndef OPENSSL_NO_RSA
719 		else if (l & SSL_kRSA)
720 			{
721 			RSA *rsa;
722 			unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
723 
724 			if (s->session->sess_cert->peer_rsa_tmp != NULL)
725 				rsa=s->session->sess_cert->peer_rsa_tmp;
726 			else
727 				{
728 				pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
729 				if ((pkey == NULL) ||
730 					(pkey->type != EVP_PKEY_RSA) ||
731 					(pkey->pkey.rsa == NULL))
732 					{
733 					SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
734 					goto err;
735 					}
736 				rsa=pkey->pkey.rsa;
737 				EVP_PKEY_free(pkey);
738 				}
739 
740 			tmp_buf[0]=s->client_version>>8;
741 			tmp_buf[1]=s->client_version&0xff;
742 			if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
743 					goto err;
744 
745 			s->session->master_key_length=sizeof tmp_buf;
746 
747 			q=p;
748 			/* Fix buf for TLS and [incidentally] DTLS */
749 			if (s->version > SSL3_VERSION)
750 				p+=2;
751 			n=RSA_public_encrypt(sizeof tmp_buf,
752 				tmp_buf,p,rsa,RSA_PKCS1_PADDING);
753 #ifdef PKCS1_CHECK
754 			if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
755 			if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
756 #endif
757 			if (n <= 0)
758 				{
759 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
760 				goto err;
761 				}
762 
763 			/* Fix buf for TLS and [incidentally] DTLS */
764 			if (s->version > SSL3_VERSION)
765 				{
766 				s2n(n,q);
767 				n+=2;
768 				}
769 
770 			s->session->master_key_length=
771 				s->method->ssl3_enc->generate_master_secret(s,
772 					s->session->master_key,
773 					tmp_buf,sizeof tmp_buf);
774 			OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
775 			}
776 #endif
777 #ifndef OPENSSL_NO_KRB5
778 		else if (l & SSL_kKRB5)
779                         {
780                         krb5_error_code	krb5rc;
781                         KSSL_CTX	*kssl_ctx = s->kssl_ctx;
782                         /*  krb5_data	krb5_ap_req;  */
783                         krb5_data	*enc_ticket;
784                         krb5_data	authenticator, *authp = NULL;
785 			EVP_CIPHER_CTX	ciph_ctx;
786 			EVP_CIPHER	*enc = NULL;
787 			unsigned char	iv[EVP_MAX_IV_LENGTH];
788 			unsigned char	tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
789 			unsigned char	epms[SSL_MAX_MASTER_KEY_LENGTH
790 						+ EVP_MAX_IV_LENGTH];
791 			int 		padl, outl = sizeof(epms);
792 
793 			EVP_CIPHER_CTX_init(&ciph_ctx);
794 
795 #ifdef KSSL_DEBUG
796                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
797                                 l, SSL_kKRB5);
798 #endif	/* KSSL_DEBUG */
799 
800 			authp = NULL;
801 #ifdef KRB5SENDAUTH
802 			if (KRB5SENDAUTH)  authp = &authenticator;
803 #endif	/* KRB5SENDAUTH */
804 
805                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
806 				&kssl_err);
807 			enc = kssl_map_enc(kssl_ctx->enctype);
808                         if (enc == NULL)
809                             goto err;
810 #ifdef KSSL_DEBUG
811                         {
812                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
813                         if (krb5rc && kssl_err.text)
814 			  printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
815                         }
816 #endif	/* KSSL_DEBUG */
817 
818                         if (krb5rc)
819                                 {
820                                 ssl3_send_alert(s,SSL3_AL_FATAL,
821 						SSL_AD_HANDSHAKE_FAILURE);
822                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
823 						kssl_err.reason);
824                                 goto err;
825                                 }
826 
827 			/*  20010406 VRS - Earlier versions used KRB5 AP_REQ
828 			**  in place of RFC 2712 KerberosWrapper, as in:
829 			**
830                         **  Send ticket (copy to *p, set n = length)
831                         **  n = krb5_ap_req.length;
832                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
833                         **  if (krb5_ap_req.data)
834                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
835                         **
836 			**  Now using real RFC 2712 KerberosWrapper
837 			**  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
838 			**  Note: 2712 "opaque" types are here replaced
839 			**  with a 2-byte length followed by the value.
840 			**  Example:
841 			**  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
842 			**  Where "xx xx" = length bytes.  Shown here with
843 			**  optional authenticator omitted.
844 			*/
845 
846 			/*  KerberosWrapper.Ticket		*/
847 			s2n(enc_ticket->length,p);
848 			memcpy(p, enc_ticket->data, enc_ticket->length);
849 			p+= enc_ticket->length;
850 			n = enc_ticket->length + 2;
851 
852 			/*  KerberosWrapper.Authenticator	*/
853 			if (authp  &&  authp->length)
854 				{
855 				s2n(authp->length,p);
856 				memcpy(p, authp->data, authp->length);
857 				p+= authp->length;
858 				n+= authp->length + 2;
859 
860 				free(authp->data);
861 				authp->data = NULL;
862 				authp->length = 0;
863 				}
864 			else
865 				{
866 				s2n(0,p);/*  null authenticator length	*/
867 				n+=2;
868 				}
869 
870 			if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
871 			    goto err;
872 
873 			/*  20010420 VRS.  Tried it this way; failed.
874 			**	EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
875 			**	EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
876 			**				kssl_ctx->length);
877 			**	EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
878 			*/
879 
880 			memset(iv, 0, sizeof iv);  /* per RFC 1510 */
881 			EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
882 				kssl_ctx->key,iv);
883 			EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
884 				sizeof tmp_buf);
885 			EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
886 			outl += padl;
887 			if (outl > sizeof epms)
888 				{
889 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
890 				goto err;
891 				}
892 			EVP_CIPHER_CTX_cleanup(&ciph_ctx);
893 
894 			/*  KerberosWrapper.EncryptedPreMasterSecret	*/
895 			s2n(outl,p);
896 			memcpy(p, epms, outl);
897 			p+=outl;
898 			n+=outl + 2;
899 
900                         s->session->master_key_length=
901                                 s->method->ssl3_enc->generate_master_secret(s,
902 					s->session->master_key,
903 					tmp_buf, sizeof tmp_buf);
904 
905 			OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
906 			OPENSSL_cleanse(epms, outl);
907                         }
908 #endif
909 #ifndef OPENSSL_NO_DH
910 		else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
911 			{
912 			DH *dh_srvr,*dh_clnt;
913 
914 			if (s->session->sess_cert->peer_dh_tmp != NULL)
915 				dh_srvr=s->session->sess_cert->peer_dh_tmp;
916 			else
917 				{
918 				/* we get them from the cert */
919 				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
920 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
921 				goto err;
922 				}
923 
924 			/* generate a new random key */
925 			if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
926 				{
927 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
928 				goto err;
929 				}
930 			if (!DH_generate_key(dh_clnt))
931 				{
932 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
933 				goto err;
934 				}
935 
936 			/* use the 'p' output buffer for the DH key, but
937 			 * make sure to clear it out afterwards */
938 
939 			n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
940 
941 			if (n <= 0)
942 				{
943 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
944 				goto err;
945 				}
946 
947 			/* generate master key from the result */
948 			s->session->master_key_length=
949 				s->method->ssl3_enc->generate_master_secret(s,
950 					s->session->master_key,p,n);
951 			/* clean up */
952 			memset(p,0,n);
953 
954 			/* send off the data */
955 			n=BN_num_bytes(dh_clnt->pub_key);
956 			s2n(n,p);
957 			BN_bn2bin(dh_clnt->pub_key,p);
958 			n+=2;
959 
960 			DH_free(dh_clnt);
961 
962 			/* perhaps clean things up a bit EAY EAY EAY EAY*/
963 			}
964 #endif
965 		else
966 			{
967 			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
968 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
969 			goto err;
970 			}
971 
972 		d = dtls1_set_message_header(s, d,
973 		SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
974 		/*
975 		 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
976 		 l2n3(n,d);
977 		 l2n(s->d1->handshake_write_seq,d);
978 		 s->d1->handshake_write_seq++;
979 		*/
980 
981 		s->state=SSL3_ST_CW_KEY_EXCH_B;
982 		/* number of bytes to write */
983 		s->init_num=n+DTLS1_HM_HEADER_LENGTH;
984 		s->init_off=0;
985 
986 		/* buffer the message to handle re-xmits */
987 		dtls1_buffer_message(s, 0);
988 		}
989 
990 	/* SSL3_ST_CW_KEY_EXCH_B */
991 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
992 err:
993 	return(-1);
994 	}
995 
dtls1_send_client_verify(SSL * s)996 int dtls1_send_client_verify(SSL *s)
997 	{
998 	unsigned char *p,*d;
999 	unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1000 	EVP_PKEY *pkey;
1001 #ifndef OPENSSL_NO_RSA
1002 	unsigned u=0;
1003 #endif
1004 	unsigned long n;
1005 #ifndef OPENSSL_NO_DSA
1006 	int j;
1007 #endif
1008 
1009 	if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1010 		{
1011 		d=(unsigned char *)s->init_buf->data;
1012 		p= &(d[DTLS1_HM_HEADER_LENGTH]);
1013 		pkey=s->cert->key->privatekey;
1014 
1015 		s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
1016 			&(data[MD5_DIGEST_LENGTH]));
1017 
1018 #ifndef OPENSSL_NO_RSA
1019 		if (pkey->type == EVP_PKEY_RSA)
1020 			{
1021 			s->method->ssl3_enc->cert_verify_mac(s,
1022 				&(s->s3->finish_dgst1),&(data[0]));
1023 			if (RSA_sign(NID_md5_sha1, data,
1024 					 MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1025 					&(p[2]), &u, pkey->pkey.rsa) <= 0 )
1026 				{
1027 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1028 				goto err;
1029 				}
1030 			s2n(u,p);
1031 			n=u+2;
1032 			}
1033 		else
1034 #endif
1035 #ifndef OPENSSL_NO_DSA
1036 			if (pkey->type == EVP_PKEY_DSA)
1037 			{
1038 			if (!DSA_sign(pkey->save_type,
1039 				&(data[MD5_DIGEST_LENGTH]),
1040 				SHA_DIGEST_LENGTH,&(p[2]),
1041 				(unsigned int *)&j,pkey->pkey.dsa))
1042 				{
1043 				SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1044 				goto err;
1045 				}
1046 			s2n(j,p);
1047 			n=j+2;
1048 			}
1049 		else
1050 #endif
1051 			{
1052 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1053 			goto err;
1054 			}
1055 
1056 		d = dtls1_set_message_header(s, d,
1057 			SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1058 
1059 		s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1060 		s->init_off=0;
1061 
1062 		/* buffer the message to handle re-xmits */
1063 		dtls1_buffer_message(s, 0);
1064 
1065 		s->state = SSL3_ST_CW_CERT_VRFY_B;
1066 		}
1067 
1068 	/* s->state = SSL3_ST_CW_CERT_VRFY_B */
1069 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1070 err:
1071 	return(-1);
1072 	}
1073 
dtls1_send_client_certificate(SSL * s)1074 int dtls1_send_client_certificate(SSL *s)
1075 	{
1076 	X509 *x509=NULL;
1077 	EVP_PKEY *pkey=NULL;
1078 	int i;
1079 	unsigned long l;
1080 
1081 	if (s->state ==	SSL3_ST_CW_CERT_A)
1082 		{
1083 		if ((s->cert == NULL) ||
1084 			(s->cert->key->x509 == NULL) ||
1085 			(s->cert->key->privatekey == NULL))
1086 			s->state=SSL3_ST_CW_CERT_B;
1087 		else
1088 			s->state=SSL3_ST_CW_CERT_C;
1089 		}
1090 
1091 	/* We need to get a client cert */
1092 	if (s->state == SSL3_ST_CW_CERT_B)
1093 		{
1094 		/* If we get an error, we need to
1095 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1096 		 * We then get retied later */
1097 		i=0;
1098 		if (s->ctx->client_cert_cb != NULL)
1099 			i=s->ctx->client_cert_cb(s,&(x509),&(pkey));
1100 		if (i < 0)
1101 			{
1102 			s->rwstate=SSL_X509_LOOKUP;
1103 			return(-1);
1104 			}
1105 		s->rwstate=SSL_NOTHING;
1106 		if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1107 			{
1108 			s->state=SSL3_ST_CW_CERT_B;
1109 			if (	!SSL_use_certificate(s,x509) ||
1110 				!SSL_use_PrivateKey(s,pkey))
1111 				i=0;
1112 			}
1113 		else if (i == 1)
1114 			{
1115 			i=0;
1116 			SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1117 			}
1118 
1119 		if (x509 != NULL) X509_free(x509);
1120 		if (pkey != NULL) EVP_PKEY_free(pkey);
1121 		if (i == 0)
1122 			{
1123 			if (s->version == SSL3_VERSION)
1124 				{
1125 				s->s3->tmp.cert_req=0;
1126 				ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1127 				return(1);
1128 				}
1129 			else
1130 				{
1131 				s->s3->tmp.cert_req=2;
1132 				}
1133 			}
1134 
1135 		/* Ok, we have a cert */
1136 		s->state=SSL3_ST_CW_CERT_C;
1137 		}
1138 
1139 	if (s->state == SSL3_ST_CW_CERT_C)
1140 		{
1141 		s->state=SSL3_ST_CW_CERT_D;
1142 		l=dtls1_output_cert_chain(s,
1143 			(s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1144 		s->init_num=(int)l;
1145 		s->init_off=0;
1146 
1147 		/* set header called by dtls1_output_cert_chain() */
1148 
1149 		/* buffer the message to handle re-xmits */
1150 		dtls1_buffer_message(s, 0);
1151 		}
1152 	/* SSL3_ST_CW_CERT_D */
1153 	return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1154 	}
1155 
1156 
1157