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