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