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