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