Updates from 1.0.0-stable branch.
[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-2007 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  * 
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  * 
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  * 
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from 
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  * 
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  * 
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <stdio.h>
117 #include "ssl_locl.h"
118 #include <openssl/buffer.h>
119 #include <openssl/rand.h>
120 #include <openssl/objects.h>
121 #include <openssl/evp.h>
122 #include <openssl/md5.h>
123 #include <openssl/bn.h>
124 #ifndef OPENSSL_NO_DH
125 #include <openssl/dh.h>
126 #endif
127
128 static const SSL_METHOD *dtls1_get_client_method(int ver);
129 static int dtls1_get_hello_verify(SSL *s);
130
131 static const 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);
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                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
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                                 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 0, NULL);
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                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 0, NULL);
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->algorithm_auth & 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                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
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                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
346                         ret=dtls1_send_client_key_exchange(s);
347                         if (ret <= 0) goto end;
348                         /* EAY EAY EAY need to check for DH fix cert
349                          * sent back */
350                         /* For TLS, cert_req is set to 2, so a cert chain
351                          * of nothing is sent, but no verify packet is sent */
352                         if (s->s3->tmp.cert_req == 1)
353                                 {
354                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
355                                 }
356                         else
357                                 {
358                                 s->state=SSL3_ST_CW_CHANGE_A;
359                                 s->s3->change_cipher_spec=0;
360                                 }
361
362                         s->init_num=0;
363                         break;
364
365                 case SSL3_ST_CW_CERT_VRFY_A:
366                 case SSL3_ST_CW_CERT_VRFY_B:
367                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
368                         ret=dtls1_send_client_verify(s);
369                         if (ret <= 0) goto end;
370                         s->state=SSL3_ST_CW_CHANGE_A;
371                         s->init_num=0;
372                         s->s3->change_cipher_spec=0;
373                         break;
374
375                 case SSL3_ST_CW_CHANGE_A:
376                 case SSL3_ST_CW_CHANGE_B:
377                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
378                         ret=dtls1_send_change_cipher_spec(s,
379                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
380                         if (ret <= 0) goto end;
381                         s->state=SSL3_ST_CW_FINISHED_A;
382                         s->init_num=0;
383
384                         s->session->cipher=s->s3->tmp.new_cipher;
385 #ifdef OPENSSL_NO_COMP
386                         s->session->compress_meth=0;
387 #else
388                         if (s->s3->tmp.new_compression == NULL)
389                                 s->session->compress_meth=0;
390                         else
391                                 s->session->compress_meth=
392                                         s->s3->tmp.new_compression->id;
393 #endif
394                         if (!s->method->ssl3_enc->setup_key_block(s))
395                                 {
396                                 ret= -1;
397                                 goto end;
398                                 }
399
400                         if (!s->method->ssl3_enc->change_cipher_state(s,
401                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
402                                 {
403                                 ret= -1;
404                                 goto end;
405                                 }
406                         
407                         dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
408                         break;
409
410                 case SSL3_ST_CW_FINISHED_A:
411                 case SSL3_ST_CW_FINISHED_B:
412                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 1, NULL);
413                         ret=dtls1_send_finished(s,
414                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
415                                 s->method->ssl3_enc->client_finished_label,
416                                 s->method->ssl3_enc->client_finished_label_len);
417                         if (ret <= 0) goto end;
418                         s->state=SSL3_ST_CW_FLUSH;
419
420                         /* clear flags */
421                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
422                         if (s->hit)
423                                 {
424                                 s->s3->tmp.next_state=SSL_ST_OK;
425                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
426                                         {
427                                         s->state=SSL_ST_OK;
428                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
429                                         s->s3->delay_buf_pop_ret=0;
430                                         }
431                                 }
432                         else
433                                 {
434                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
435                                 }
436                         s->init_num=0;
437                         break;
438
439                 case SSL3_ST_CR_FINISHED_A:
440                 case SSL3_ST_CR_FINISHED_B:
441
442                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
443                                 SSL3_ST_CR_FINISHED_B);
444                         if (ret <= 0) goto end;
445                         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_TIMEOUT, 0, NULL);
446
447                         if (s->hit)
448                                 s->state=SSL3_ST_CW_CHANGE_A;
449                         else
450                                 s->state=SSL_ST_OK;
451                         s->init_num=0;
452                         break;
453
454                 case SSL3_ST_CW_FLUSH:
455                         /* number of bytes to be flushed */
456                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
457                         if (num1 > 0)
458                                 {
459                                 s->rwstate=SSL_WRITING;
460                                 num1=BIO_flush(s->wbio);
461                                 if (num1 <= 0) { ret= -1; goto end; }
462                                 s->rwstate=SSL_NOTHING;
463                                 }
464
465                         s->state=s->s3->tmp.next_state;
466                         break;
467
468                 case SSL_ST_OK:
469                         /* clean a few things up */
470                         ssl3_cleanup_key_block(s);
471
472 #if 0
473                         if (s->init_buf != NULL)
474                                 {
475                                 BUF_MEM_free(s->init_buf);
476                                 s->init_buf=NULL;
477                                 }
478 #endif
479
480                         /* If we are not 'joining' the last two packets,
481                          * remove the buffering now */
482                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
483                                 ssl_free_wbio_buffer(s);
484                         /* else do it later in ssl3_write */
485
486                         s->init_num=0;
487                         s->new_session=0;
488
489                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
490                         if (s->hit) s->ctx->stats.sess_hit++;
491
492                         ret=1;
493                         /* s->server=0; */
494                         s->handshake_func=dtls1_connect;
495                         s->ctx->stats.sess_connect_good++;
496
497                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
498
499                         /* done with handshaking */
500                         s->d1->handshake_read_seq  = 0;
501                         s->d1->next_handshake_write_seq = 0;
502                         goto end;
503                         /* break; */
504                         
505                 default:
506                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
507                         ret= -1;
508                         goto end;
509                         /* break; */
510                         }
511
512                 /* did we do anything */
513                 if (!s->s3->tmp.reuse_message && !skip)
514                         {
515                         if (s->debug)
516                                 {
517                                 if ((ret=BIO_flush(s->wbio)) <= 0)
518                                         goto end;
519                                 }
520
521                         if ((cb != NULL) && (s->state != state))
522                                 {
523                                 new_state=s->state;
524                                 s->state=state;
525                                 cb(s,SSL_CB_CONNECT_LOOP,1);
526                                 s->state=new_state;
527                                 }
528                         }
529                 skip=0;
530                 }
531 end:
532         s->in_handshake--;
533         if (buf != NULL)
534                 BUF_MEM_free(buf);
535         if (cb != NULL)
536                 cb(s,SSL_CB_CONNECT_EXIT,ret);
537         return(ret);
538         }
539
540 int dtls1_client_hello(SSL *s)
541         {
542         unsigned char *buf;
543         unsigned char *p,*d;
544         unsigned int i,j;
545         unsigned long Time,l;
546         SSL_COMP *comp;
547
548         buf=(unsigned char *)s->init_buf->data;
549         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
550                 {
551                 if ((s->session == NULL) ||
552                         (s->session->ssl_version != s->version) ||
553                         (s->session->not_resumable))
554                         {
555                         if (!ssl_get_new_session(s,0))
556                                 goto err;
557                         }
558                 /* else use the pre-loaded session */
559
560                 p=s->s3->client_random;
561
562                 /* if client_random is initialized, reuse it, we are
563                  * required to use same upon reply to HelloVerify */
564                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
565                 if (i==sizeof(s->s3->client_random))
566                         {
567                         Time=(unsigned long)time(NULL); /* Time */
568                         l2n(Time,p);
569                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
570                         }
571
572                 /* Do the message type and length last */
573                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
574
575                 *(p++)=s->version>>8;
576                 *(p++)=s->version&0xff;
577                 s->client_version=s->version;
578
579                 /* Random stuff */
580                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
581                 p+=SSL3_RANDOM_SIZE;
582
583                 /* Session ID */
584                 if (s->new_session)
585                         i=0;
586                 else
587                         i=s->session->session_id_length;
588                 *(p++)=i;
589                 if (i != 0)
590                         {
591                         if (i > sizeof s->session->session_id)
592                                 {
593                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
594                                 goto err;
595                                 }
596                         memcpy(p,s->session->session_id,i);
597                         p+=i;
598                         }
599                 
600                 /* cookie stuff */
601                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
602                         {
603                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
604                         goto err;
605                         }
606                 *(p++) = s->d1->cookie_len;
607                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
608                 p += s->d1->cookie_len;
609
610                 /* Ciphers supported */
611                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
612                 if (i == 0)
613                         {
614                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
615                         goto err;
616                         }
617                 s2n(i,p);
618                 p+=i;
619
620                 /* COMPRESSION */
621                 if (s->ctx->comp_methods == NULL)
622                         j=0;
623                 else
624                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
625                 *(p++)=1+j;
626                 for (i=0; i<j; i++)
627                         {
628                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
629                         *(p++)=comp->id;
630                         }
631                 *(p++)=0; /* Add the NULL method */
632                 
633                 l=(p-d);
634                 d=buf;
635
636                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
637
638                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
639                 /* number of bytes to write */
640                 s->init_num=p-buf;
641                 s->init_off=0;
642
643                 /* buffer the message to handle re-xmits */
644                 dtls1_buffer_message(s, 0);
645                 }
646
647         /* SSL3_ST_CW_CLNT_HELLO_B */
648         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
649 err:
650         return(-1);
651         }
652
653 static int dtls1_get_hello_verify(SSL *s)
654         {
655         int n, al, ok = 0;
656         unsigned char *data;
657         unsigned int cookie_len;
658
659         n=s->method->ssl_get_message(s,
660                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
661                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
662                 -1,
663                 s->max_cert_list,
664                 &ok);
665
666         if (!ok) return((int)n);
667
668         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
669                 {
670                 s->d1->send_cookie = 0;
671                 s->s3->tmp.reuse_message=1;
672                 return(1);
673                 }
674
675         data = (unsigned char *)s->init_msg;
676
677         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
678                 {
679                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
680                 s->version=(s->version&0xff00)|data[1];
681                 al = SSL_AD_PROTOCOL_VERSION;
682                 goto f_err;
683                 }
684         data+=2;
685
686         cookie_len = *(data++);
687         if ( cookie_len > sizeof(s->d1->cookie))
688                 {
689                 al=SSL_AD_ILLEGAL_PARAMETER;
690                 goto f_err;
691                 }
692
693         memcpy(s->d1->cookie, data, cookie_len);
694         s->d1->cookie_len = cookie_len;
695
696         s->d1->send_cookie = 1;
697         return 1;
698
699 f_err:
700         ssl3_send_alert(s, SSL3_AL_FATAL, al);
701         return -1;
702         }
703
704 int dtls1_send_client_key_exchange(SSL *s)
705         {
706         unsigned char *p,*d;
707         int n;
708         unsigned long alg_k;
709 #ifndef OPENSSL_NO_RSA
710         unsigned char *q;
711         EVP_PKEY *pkey=NULL;
712 #endif
713 #ifndef OPENSSL_NO_KRB5
714         KSSL_ERR kssl_err;
715 #endif /* OPENSSL_NO_KRB5 */
716
717         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
718                 {
719                 d=(unsigned char *)s->init_buf->data;
720                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
721                 
722                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
723
724                 /* Fool emacs indentation */
725                 if (0) {}
726 #ifndef OPENSSL_NO_RSA
727                 else if (alg_k & SSL_kRSA)
728                         {
729                         RSA *rsa;
730                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
731
732                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
733                                 rsa=s->session->sess_cert->peer_rsa_tmp;
734                         else
735                                 {
736                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
737                                 if ((pkey == NULL) ||
738                                         (pkey->type != EVP_PKEY_RSA) ||
739                                         (pkey->pkey.rsa == NULL))
740                                         {
741                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
742                                         goto err;
743                                         }
744                                 rsa=pkey->pkey.rsa;
745                                 EVP_PKEY_free(pkey);
746                                 }
747                                 
748                         tmp_buf[0]=s->client_version>>8;
749                         tmp_buf[1]=s->client_version&0xff;
750                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
751                                         goto err;
752
753                         s->session->master_key_length=sizeof tmp_buf;
754
755                         q=p;
756                         /* Fix buf for TLS and [incidentally] DTLS */
757                         if (s->version > SSL3_VERSION)
758                                 p+=2;
759                         n=RSA_public_encrypt(sizeof tmp_buf,
760                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
761 #ifdef PKCS1_CHECK
762                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
763                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
764 #endif
765                         if (n <= 0)
766                                 {
767                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
768                                 goto err;
769                                 }
770
771                         /* Fix buf for TLS and [incidentally] DTLS */
772                         if (s->version > SSL3_VERSION)
773                                 {
774                                 s2n(n,q);
775                                 n+=2;
776                                 }
777
778                         s->session->master_key_length=
779                                 s->method->ssl3_enc->generate_master_secret(s,
780                                         s->session->master_key,
781                                         tmp_buf,sizeof tmp_buf);
782                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
783                         }
784 #endif
785 #ifndef OPENSSL_NO_KRB5
786                 else if (alg_k & SSL_kKRB5)
787                         {
788                         krb5_error_code krb5rc;
789                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
790                         /*  krb5_data   krb5_ap_req;  */
791                         krb5_data       *enc_ticket;
792                         krb5_data       authenticator, *authp = NULL;
793                         EVP_CIPHER_CTX  ciph_ctx;
794                         EVP_CIPHER      *enc = NULL;
795                         unsigned char   iv[EVP_MAX_IV_LENGTH];
796                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
797                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
798                                                 + EVP_MAX_IV_LENGTH];
799                         int             padl, outl = sizeof(epms);
800
801                         EVP_CIPHER_CTX_init(&ciph_ctx);
802
803 #ifdef KSSL_DEBUG
804                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
805                                 alg_k, SSL_kKRB5);
806 #endif  /* KSSL_DEBUG */
807
808                         authp = NULL;
809 #ifdef KRB5SENDAUTH
810                         if (KRB5SENDAUTH)  authp = &authenticator;
811 #endif  /* KRB5SENDAUTH */
812
813                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
814                                 &kssl_err);
815                         enc = kssl_map_enc(kssl_ctx->enctype);
816                         if (enc == NULL)
817                             goto err;
818 #ifdef KSSL_DEBUG
819                         {
820                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
821                         if (krb5rc && kssl_err.text)
822                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
823                         }
824 #endif  /* KSSL_DEBUG */
825
826                         if (krb5rc)
827                                 {
828                                 ssl3_send_alert(s,SSL3_AL_FATAL,
829                                                 SSL_AD_HANDSHAKE_FAILURE);
830                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
831                                                 kssl_err.reason);
832                                 goto err;
833                                 }
834
835                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
836                         **  in place of RFC 2712 KerberosWrapper, as in:
837                         **
838                         **  Send ticket (copy to *p, set n = length)
839                         **  n = krb5_ap_req.length;
840                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
841                         **  if (krb5_ap_req.data)  
842                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
843                         **
844                         **  Now using real RFC 2712 KerberosWrapper
845                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
846                         **  Note: 2712 "opaque" types are here replaced
847                         **  with a 2-byte length followed by the value.
848                         **  Example:
849                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
850                         **  Where "xx xx" = length bytes.  Shown here with
851                         **  optional authenticator omitted.
852                         */
853
854                         /*  KerberosWrapper.Ticket              */
855                         s2n(enc_ticket->length,p);
856                         memcpy(p, enc_ticket->data, enc_ticket->length);
857                         p+= enc_ticket->length;
858                         n = enc_ticket->length + 2;
859
860                         /*  KerberosWrapper.Authenticator       */
861                         if (authp  &&  authp->length)  
862                                 {
863                                 s2n(authp->length,p);
864                                 memcpy(p, authp->data, authp->length);
865                                 p+= authp->length;
866                                 n+= authp->length + 2;
867                                 
868                                 free(authp->data);
869                                 authp->data = NULL;
870                                 authp->length = 0;
871                                 }
872                         else
873                                 {
874                                 s2n(0,p);/*  null authenticator length  */
875                                 n+=2;
876                                 }
877  
878                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
879                             goto err;
880
881                         /*  20010420 VRS.  Tried it this way; failed.
882                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
883                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
884                         **                              kssl_ctx->length);
885                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
886                         */
887
888                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
889                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
890                                 kssl_ctx->key,iv);
891                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
892                                 sizeof tmp_buf);
893                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
894                         outl += padl;
895                         if (outl > sizeof epms)
896                                 {
897                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
898                                 goto err;
899                                 }
900                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
901
902                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
903                         s2n(outl,p);
904                         memcpy(p, epms, outl);
905                         p+=outl;
906                         n+=outl + 2;
907
908                         s->session->master_key_length=
909                                 s->method->ssl3_enc->generate_master_secret(s,
910                                         s->session->master_key,
911                                         tmp_buf, sizeof tmp_buf);
912
913                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
914                         OPENSSL_cleanse(epms, outl);
915                         }
916 #endif
917 #ifndef OPENSSL_NO_DH
918                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
919                         {
920                         DH *dh_srvr,*dh_clnt;
921
922                         if (s->session->sess_cert->peer_dh_tmp != NULL)
923                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
924                         else
925                                 {
926                                 /* we get them from the cert */
927                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
928                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
929                                 goto err;
930                                 }
931                         
932                         /* generate a new random key */
933                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
934                                 {
935                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
936                                 goto err;
937                                 }
938                         if (!DH_generate_key(dh_clnt))
939                                 {
940                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
941                                 goto err;
942                                 }
943
944                         /* use the 'p' output buffer for the DH key, but
945                          * make sure to clear it out afterwards */
946
947                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
948
949                         if (n <= 0)
950                                 {
951                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
952                                 goto err;
953                                 }
954
955                         /* generate master key from the result */
956                         s->session->master_key_length=
957                                 s->method->ssl3_enc->generate_master_secret(s,
958                                         s->session->master_key,p,n);
959                         /* clean up */
960                         memset(p,0,n);
961
962                         /* send off the data */
963                         n=BN_num_bytes(dh_clnt->pub_key);
964                         s2n(n,p);
965                         BN_bn2bin(dh_clnt->pub_key,p);
966                         n+=2;
967
968                         DH_free(dh_clnt);
969
970                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
971                         }
972 #endif
973                 else
974                         {
975                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
976                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
977                         goto err;
978                         }
979                 
980                 d = dtls1_set_message_header(s, d,
981                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
982                 /*
983                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
984                  l2n3(n,d);
985                  l2n(s->d1->handshake_write_seq,d);
986                  s->d1->handshake_write_seq++;
987                 */
988                 
989                 s->state=SSL3_ST_CW_KEY_EXCH_B;
990                 /* number of bytes to write */
991                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
992                 s->init_off=0;
993
994                 /* buffer the message to handle re-xmits */
995                 dtls1_buffer_message(s, 0);
996                 }
997         
998         /* SSL3_ST_CW_KEY_EXCH_B */
999         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1000 err:
1001         return(-1);
1002         }
1003
1004 int dtls1_send_client_verify(SSL *s)
1005         {
1006         unsigned char *p,*d;
1007         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1008         EVP_PKEY *pkey;
1009 #ifndef OPENSSL_NO_RSA
1010         unsigned u=0;
1011 #endif
1012         unsigned long n;
1013 #ifndef OPENSSL_NO_DSA
1014         int j;
1015 #endif
1016
1017         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1018                 {
1019                 d=(unsigned char *)s->init_buf->data;
1020                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1021                 pkey=s->cert->key->privatekey;
1022
1023                 s->method->ssl3_enc->cert_verify_mac(s,
1024                 NID_sha1,
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                                 NID_md5,
1032                                 &(data[0]));
1033                         if (RSA_sign(NID_md5_sha1, data,
1034                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1035                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1036                                 {
1037                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1038                                 goto err;
1039                                 }
1040                         s2n(u,p);
1041                         n=u+2;
1042                         }
1043                 else
1044 #endif
1045 #ifndef OPENSSL_NO_DSA
1046                         if (pkey->type == EVP_PKEY_DSA)
1047                         {
1048                         if (!DSA_sign(pkey->save_type,
1049                                 &(data[MD5_DIGEST_LENGTH]),
1050                                 SHA_DIGEST_LENGTH,&(p[2]),
1051                                 (unsigned int *)&j,pkey->pkey.dsa))
1052                                 {
1053                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1054                                 goto err;
1055                                 }
1056                         s2n(j,p);
1057                         n=j+2;
1058                         }
1059                 else
1060 #endif
1061                         {
1062                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1063                         goto err;
1064                         }
1065
1066                 d = dtls1_set_message_header(s, d,
1067                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1068
1069                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1070                 s->init_off=0;
1071
1072                 /* buffer the message to handle re-xmits */
1073                 dtls1_buffer_message(s, 0);
1074
1075                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1076                 }
1077
1078         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1079         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1080 err:
1081         return(-1);
1082         }
1083
1084 int dtls1_send_client_certificate(SSL *s)
1085         {
1086         X509 *x509=NULL;
1087         EVP_PKEY *pkey=NULL;
1088         int i;
1089         unsigned long l;
1090
1091         if (s->state == SSL3_ST_CW_CERT_A)
1092                 {
1093                 if ((s->cert == NULL) ||
1094                         (s->cert->key->x509 == NULL) ||
1095                         (s->cert->key->privatekey == NULL))
1096                         s->state=SSL3_ST_CW_CERT_B;
1097                 else
1098                         s->state=SSL3_ST_CW_CERT_C;
1099                 }
1100
1101         /* We need to get a client cert */
1102         if (s->state == SSL3_ST_CW_CERT_B)
1103                 {
1104                 /* If we get an error, we need to
1105                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1106                  * We then get retied later */
1107                 i=0;
1108                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1109                 if (i < 0)
1110                         {
1111                         s->rwstate=SSL_X509_LOOKUP;
1112                         return(-1);
1113                         }
1114                 s->rwstate=SSL_NOTHING;
1115                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1116                         {
1117                         s->state=SSL3_ST_CW_CERT_B;
1118                         if (    !SSL_use_certificate(s,x509) ||
1119                                 !SSL_use_PrivateKey(s,pkey))
1120                                 i=0;
1121                         }
1122                 else if (i == 1)
1123                         {
1124                         i=0;
1125                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1126                         }
1127
1128                 if (x509 != NULL) X509_free(x509);
1129                 if (pkey != NULL) EVP_PKEY_free(pkey);
1130                 if (i == 0)
1131                         {
1132                         if (s->version == SSL3_VERSION)
1133                                 {
1134                                 s->s3->tmp.cert_req=0;
1135                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1136                                 return(1);
1137                                 }
1138                         else
1139                                 {
1140                                 s->s3->tmp.cert_req=2;
1141                                 }
1142                         }
1143
1144                 /* Ok, we have a cert */
1145                 s->state=SSL3_ST_CW_CERT_C;
1146                 }
1147
1148         if (s->state == SSL3_ST_CW_CERT_C)
1149                 {
1150                 s->state=SSL3_ST_CW_CERT_D;
1151                 l=dtls1_output_cert_chain(s,
1152                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1153                 s->init_num=(int)l;
1154                 s->init_off=0;
1155
1156                 /* set header called by dtls1_output_cert_chain() */
1157
1158                 /* buffer the message to handle re-xmits */
1159                 dtls1_buffer_message(s, 0);
1160                 }
1161         /* SSL3_ST_CW_CERT_D */
1162         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1163         }
1164
1165