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