d71c7f2c969be008b8587523536ae9a062e12ebb
[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 #ifndef OPENSSL_NO_TLSEXT
637                 if ((p = ssl_add_clienthello_dtlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
638                         {
639                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
640                         goto err;
641                         }
642 #endif          
643
644                 l=(p-d);
645                 d=buf;
646
647                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
648
649                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
650                 /* number of bytes to write */
651                 s->init_num=p-buf;
652                 s->init_off=0;
653
654                 /* buffer the message to handle re-xmits */
655                 dtls1_buffer_message(s, 0);
656                 }
657
658         /* SSL3_ST_CW_CLNT_HELLO_B */
659         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
660 err:
661         return(-1);
662         }
663
664 static int dtls1_get_hello_verify(SSL *s)
665         {
666         int n, al, ok = 0;
667         unsigned char *data;
668         unsigned int cookie_len;
669
670         n=s->method->ssl_get_message(s,
671                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
672                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
673                 -1,
674                 s->max_cert_list,
675                 &ok);
676
677         if (!ok) return((int)n);
678
679         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
680                 {
681                 s->d1->send_cookie = 0;
682                 s->s3->tmp.reuse_message=1;
683                 return(1);
684                 }
685
686         data = (unsigned char *)s->init_msg;
687
688         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
689                 {
690                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
691                 s->version=(s->version&0xff00)|data[1];
692                 al = SSL_AD_PROTOCOL_VERSION;
693                 goto f_err;
694                 }
695         data+=2;
696
697         cookie_len = *(data++);
698         if ( cookie_len > sizeof(s->d1->cookie))
699                 {
700                 al=SSL_AD_ILLEGAL_PARAMETER;
701                 goto f_err;
702                 }
703
704         memcpy(s->d1->cookie, data, cookie_len);
705         s->d1->cookie_len = cookie_len;
706
707         s->d1->send_cookie = 1;
708         return 1;
709
710 f_err:
711         ssl3_send_alert(s, SSL3_AL_FATAL, al);
712         return -1;
713         }
714
715 int dtls1_send_client_key_exchange(SSL *s)
716         {
717         unsigned char *p,*d;
718         int n;
719         unsigned long l;
720 #ifndef OPENSSL_NO_RSA
721         unsigned char *q;
722         EVP_PKEY *pkey=NULL;
723 #endif
724 #ifndef OPENSSL_NO_KRB5
725         KSSL_ERR kssl_err;
726 #endif /* OPENSSL_NO_KRB5 */
727
728         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
729                 {
730                 d=(unsigned char *)s->init_buf->data;
731                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
732
733                 l=s->s3->tmp.new_cipher->algorithms;
734
735                 /* Fool emacs indentation */
736                 if (0) {}
737 #ifndef OPENSSL_NO_RSA
738                 else if (l & SSL_kRSA)
739                         {
740                         RSA *rsa;
741                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
742
743                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
744                                 rsa=s->session->sess_cert->peer_rsa_tmp;
745                         else
746                                 {
747                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
748                                 if ((pkey == NULL) ||
749                                         (pkey->type != EVP_PKEY_RSA) ||
750                                         (pkey->pkey.rsa == NULL))
751                                         {
752                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
753                                         goto err;
754                                         }
755                                 rsa=pkey->pkey.rsa;
756                                 EVP_PKEY_free(pkey);
757                                 }
758                                 
759                         tmp_buf[0]=s->client_version>>8;
760                         tmp_buf[1]=s->client_version&0xff;
761                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
762                                         goto err;
763
764                         s->session->master_key_length=sizeof tmp_buf;
765
766                         q=p;
767                         /* Fix buf for TLS and [incidentally] DTLS */
768                         if (s->version > SSL3_VERSION)
769                                 p+=2;
770                         n=RSA_public_encrypt(sizeof tmp_buf,
771                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
772 #ifdef PKCS1_CHECK
773                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
774                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
775 #endif
776                         if (n <= 0)
777                                 {
778                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
779                                 goto err;
780                                 }
781
782                         /* Fix buf for TLS and [incidentally] DTLS */
783                         if (s->version > SSL3_VERSION)
784                                 {
785                                 s2n(n,q);
786                                 n+=2;
787                                 }
788
789                         s->session->master_key_length=
790                                 s->method->ssl3_enc->generate_master_secret(s,
791                                         s->session->master_key,
792                                         tmp_buf,sizeof tmp_buf);
793                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
794                         }
795 #endif
796 #ifndef OPENSSL_NO_KRB5
797                 else if (l & SSL_kKRB5)
798                         {
799                         krb5_error_code krb5rc;
800                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
801                         /*  krb5_data   krb5_ap_req;  */
802                         krb5_data       *enc_ticket;
803                         krb5_data       authenticator, *authp = NULL;
804                         EVP_CIPHER_CTX  ciph_ctx;
805                         EVP_CIPHER      *enc = NULL;
806                         unsigned char   iv[EVP_MAX_IV_LENGTH];
807                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
808                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
809                                                 + EVP_MAX_IV_LENGTH];
810                         int             padl, outl = sizeof(epms);
811
812                         EVP_CIPHER_CTX_init(&ciph_ctx);
813
814 #ifdef KSSL_DEBUG
815                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
816                                 l, SSL_kKRB5);
817 #endif  /* KSSL_DEBUG */
818
819                         authp = NULL;
820 #ifdef KRB5SENDAUTH
821                         if (KRB5SENDAUTH)  authp = &authenticator;
822 #endif  /* KRB5SENDAUTH */
823
824                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
825                                 &kssl_err);
826                         enc = kssl_map_enc(kssl_ctx->enctype);
827                         if (enc == NULL)
828                             goto err;
829 #ifdef KSSL_DEBUG
830                         {
831                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
832                         if (krb5rc && kssl_err.text)
833                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
834                         }
835 #endif  /* KSSL_DEBUG */
836
837                         if (krb5rc)
838                                 {
839                                 ssl3_send_alert(s,SSL3_AL_FATAL,
840                                                 SSL_AD_HANDSHAKE_FAILURE);
841                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
842                                                 kssl_err.reason);
843                                 goto err;
844                                 }
845
846                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
847                         **  in place of RFC 2712 KerberosWrapper, as in:
848                         **
849                         **  Send ticket (copy to *p, set n = length)
850                         **  n = krb5_ap_req.length;
851                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
852                         **  if (krb5_ap_req.data)  
853                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
854                         **
855                         **  Now using real RFC 2712 KerberosWrapper
856                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
857                         **  Note: 2712 "opaque" types are here replaced
858                         **  with a 2-byte length followed by the value.
859                         **  Example:
860                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
861                         **  Where "xx xx" = length bytes.  Shown here with
862                         **  optional authenticator omitted.
863                         */
864
865                         /*  KerberosWrapper.Ticket              */
866                         s2n(enc_ticket->length,p);
867                         memcpy(p, enc_ticket->data, enc_ticket->length);
868                         p+= enc_ticket->length;
869                         n = enc_ticket->length + 2;
870
871                         /*  KerberosWrapper.Authenticator       */
872                         if (authp  &&  authp->length)  
873                                 {
874                                 s2n(authp->length,p);
875                                 memcpy(p, authp->data, authp->length);
876                                 p+= authp->length;
877                                 n+= authp->length + 2;
878                                 
879                                 free(authp->data);
880                                 authp->data = NULL;
881                                 authp->length = 0;
882                                 }
883                         else
884                                 {
885                                 s2n(0,p);/*  null authenticator length  */
886                                 n+=2;
887                                 }
888  
889                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
890                             goto err;
891
892                         /*  20010420 VRS.  Tried it this way; failed.
893                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
894                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
895                         **                              kssl_ctx->length);
896                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
897                         */
898
899                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
900                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
901                                 kssl_ctx->key,iv);
902                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
903                                 sizeof tmp_buf);
904                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
905                         outl += padl;
906                         if (outl > sizeof epms)
907                                 {
908                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
909                                 goto err;
910                                 }
911                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
912
913                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
914                         s2n(outl,p);
915                         memcpy(p, epms, outl);
916                         p+=outl;
917                         n+=outl + 2;
918
919                         s->session->master_key_length=
920                                 s->method->ssl3_enc->generate_master_secret(s,
921                                         s->session->master_key,
922                                         tmp_buf, sizeof tmp_buf);
923
924                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
925                         OPENSSL_cleanse(epms, outl);
926                         }
927 #endif
928 #ifndef OPENSSL_NO_DH
929                 else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
930                         {
931                         DH *dh_srvr,*dh_clnt;
932
933                         if (s->session->sess_cert->peer_dh_tmp != NULL)
934                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
935                         else
936                                 {
937                                 /* we get them from the cert */
938                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
939                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
940                                 goto err;
941                                 }
942                         
943                         /* generate a new random key */
944                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
945                                 {
946                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
947                                 goto err;
948                                 }
949                         if (!DH_generate_key(dh_clnt))
950                                 {
951                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
952                                 goto err;
953                                 }
954
955                         /* use the 'p' output buffer for the DH key, but
956                          * make sure to clear it out afterwards */
957
958                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
959
960                         if (n <= 0)
961                                 {
962                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
963                                 goto err;
964                                 }
965
966                         /* generate master key from the result */
967                         s->session->master_key_length=
968                                 s->method->ssl3_enc->generate_master_secret(s,
969                                         s->session->master_key,p,n);
970                         /* clean up */
971                         memset(p,0,n);
972
973                         /* send off the data */
974                         n=BN_num_bytes(dh_clnt->pub_key);
975                         s2n(n,p);
976                         BN_bn2bin(dh_clnt->pub_key,p);
977                         n+=2;
978
979                         DH_free(dh_clnt);
980
981                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
982                         }
983 #endif
984                 else
985                         {
986                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
987                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
988                         goto err;
989                         }
990                 
991                 d = dtls1_set_message_header(s, d,
992                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
993                 /*
994                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
995                  l2n3(n,d);
996                  l2n(s->d1->handshake_write_seq,d);
997                  s->d1->handshake_write_seq++;
998                 */
999                 
1000                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1001                 /* number of bytes to write */
1002                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1003                 s->init_off=0;
1004
1005                 /* buffer the message to handle re-xmits */
1006                 dtls1_buffer_message(s, 0);
1007                 }
1008         
1009         /* SSL3_ST_CW_KEY_EXCH_B */
1010         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1011 err:
1012         return(-1);
1013         }
1014
1015 int dtls1_send_client_verify(SSL *s)
1016         {
1017         unsigned char *p,*d;
1018         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1019         EVP_PKEY *pkey;
1020 #ifndef OPENSSL_NO_RSA
1021         unsigned u=0;
1022 #endif
1023         unsigned long n;
1024 #ifndef OPENSSL_NO_DSA
1025         int j;
1026 #endif
1027
1028         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1029                 {
1030                 d=(unsigned char *)s->init_buf->data;
1031                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1032                 pkey=s->cert->key->privatekey;
1033
1034                 s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
1035                         &(data[MD5_DIGEST_LENGTH]));
1036
1037 #ifndef OPENSSL_NO_RSA
1038                 if (pkey->type == EVP_PKEY_RSA)
1039                         {
1040                         s->method->ssl3_enc->cert_verify_mac(s,
1041                                 &(s->s3->finish_dgst1),&(data[0]));
1042                         if (RSA_sign(NID_md5_sha1, data,
1043                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1044                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1045                                 {
1046                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1047                                 goto err;
1048                                 }
1049                         s2n(u,p);
1050                         n=u+2;
1051                         }
1052                 else
1053 #endif
1054 #ifndef OPENSSL_NO_DSA
1055                         if (pkey->type == EVP_PKEY_DSA)
1056                         {
1057                         if (!DSA_sign(pkey->save_type,
1058                                 &(data[MD5_DIGEST_LENGTH]),
1059                                 SHA_DIGEST_LENGTH,&(p[2]),
1060                                 (unsigned int *)&j,pkey->pkey.dsa))
1061                                 {
1062                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1063                                 goto err;
1064                                 }
1065                         s2n(j,p);
1066                         n=j+2;
1067                         }
1068                 else
1069 #endif
1070                         {
1071                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1072                         goto err;
1073                         }
1074
1075                 d = dtls1_set_message_header(s, d,
1076                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1077
1078                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1079                 s->init_off=0;
1080
1081                 /* buffer the message to handle re-xmits */
1082                 dtls1_buffer_message(s, 0);
1083
1084                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1085                 }
1086
1087         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1088         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1089 err:
1090         return(-1);
1091         }
1092
1093 int dtls1_send_client_certificate(SSL *s)
1094         {
1095         X509 *x509=NULL;
1096         EVP_PKEY *pkey=NULL;
1097         int i;
1098         unsigned long l;
1099
1100         if (s->state == SSL3_ST_CW_CERT_A)
1101                 {
1102                 if ((s->cert == NULL) ||
1103                         (s->cert->key->x509 == NULL) ||
1104                         (s->cert->key->privatekey == NULL))
1105                         s->state=SSL3_ST_CW_CERT_B;
1106                 else
1107                         s->state=SSL3_ST_CW_CERT_C;
1108                 }
1109
1110         /* We need to get a client cert */
1111         if (s->state == SSL3_ST_CW_CERT_B)
1112                 {
1113                 /* If we get an error, we need to
1114                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1115                  * We then get retied later */
1116                 i=0;
1117                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1118                 if (i < 0)
1119                         {
1120                         s->rwstate=SSL_X509_LOOKUP;
1121                         return(-1);
1122                         }
1123                 s->rwstate=SSL_NOTHING;
1124                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1125                         {
1126                         s->state=SSL3_ST_CW_CERT_B;
1127                         if (    !SSL_use_certificate(s,x509) ||
1128                                 !SSL_use_PrivateKey(s,pkey))
1129                                 i=0;
1130                         }
1131                 else if (i == 1)
1132                         {
1133                         i=0;
1134                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1135                         }
1136
1137                 if (x509 != NULL) X509_free(x509);
1138                 if (pkey != NULL) EVP_PKEY_free(pkey);
1139                 if (i == 0)
1140                         {
1141                         if (s->version == SSL3_VERSION)
1142                                 {
1143                                 s->s3->tmp.cert_req=0;
1144                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1145                                 return(1);
1146                                 }
1147                         else
1148                                 {
1149                                 s->s3->tmp.cert_req=2;
1150                                 }
1151                         }
1152
1153                 /* Ok, we have a cert */
1154                 s->state=SSL3_ST_CW_CERT_C;
1155                 }
1156
1157         if (s->state == SSL3_ST_CW_CERT_C)
1158                 {
1159                 s->state=SSL3_ST_CW_CERT_D;
1160                 l=dtls1_output_cert_chain(s,
1161                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1162                 s->init_num=(int)l;
1163                 s->init_off=0;
1164
1165                 /* set header called by dtls1_output_cert_chain() */
1166
1167                 /* buffer the message to handle re-xmits */
1168                 dtls1_buffer_message(s, 0);
1169                 }
1170         /* SSL3_ST_CW_CERT_D */
1171         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1172         }
1173
1174