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