PR: 2115
[openssl.git] / ssl / d1_clnt.c
1 /* ssl/d1_clnt.c */
2 /* 
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
5  */
6 /* ====================================================================
7  * Copyright (c) 1999-2007 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  * 
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  * 
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  * 
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from 
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  * 
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  * 
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <stdio.h>
117 #include "ssl_locl.h"
118 #ifndef OPENSSL_NO_KRB5
119 #include "kssl_lcl.h"
120 #endif
121 #include <openssl/buffer.h>
122 #include <openssl/rand.h>
123 #include <openssl/objects.h>
124 #include <openssl/evp.h>
125 #include <openssl/md5.h>
126 #include <openssl/bn.h>
127 #ifndef OPENSSL_NO_DH
128 #include <openssl/dh.h>
129 #endif
130
131 static const SSL_METHOD *dtls1_get_client_method(int ver);
132 static int dtls1_get_hello_verify(SSL *s);
133
134 static const SSL_METHOD *dtls1_get_client_method(int ver)
135         {
136         if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER)
137                 return(DTLSv1_client_method());
138         else
139                 return(NULL);
140         }
141
142 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
143                         ssl_undefined_function,
144                         dtls1_connect,
145                         dtls1_get_client_method)
146
147 int dtls1_connect(SSL *s)
148         {
149         BUF_MEM *buf=NULL;
150         unsigned long Time=(unsigned long)time(NULL);
151         long num1;
152         void (*cb)(const SSL *ssl,int type,int val)=NULL;
153         int ret= -1;
154         int new_state,state,skip=0;;
155
156         RAND_add(&Time,sizeof(Time),0);
157         ERR_clear_error();
158         clear_sys_error();
159
160         if (s->info_callback != NULL)
161                 cb=s->info_callback;
162         else if (s->ctx->info_callback != NULL)
163                 cb=s->ctx->info_callback;
164         
165         s->in_handshake++;
166         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
167
168         for (;;)
169                 {
170                 state=s->state;
171
172                 switch(s->state)
173                         {
174                 case SSL_ST_RENEGOTIATE:
175                         s->new_session=1;
176                         s->state=SSL_ST_CONNECT;
177                         s->ctx->stats.sess_connect_renegotiate++;
178                         /* break */
179                 case SSL_ST_BEFORE:
180                 case SSL_ST_CONNECT:
181                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
182                 case SSL_ST_OK|SSL_ST_CONNECT:
183
184                         s->server=0;
185                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
186
187                         if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) &&
188                             (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00))
189                                 {
190                                 SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
191                                 ret = -1;
192                                 goto end;
193                                 }
194                                 
195                         /* s->version=SSL3_VERSION; */
196                         s->type=SSL_ST_CONNECT;
197
198                         if (s->init_buf == NULL)
199                                 {
200                                 if ((buf=BUF_MEM_new()) == NULL)
201                                         {
202                                         ret= -1;
203                                         goto end;
204                                         }
205                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
206                                         {
207                                         ret= -1;
208                                         goto end;
209                                         }
210                                 s->init_buf=buf;
211                                 buf=NULL;
212                                 }
213
214                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
215
216                         /* setup buffing BIO */
217                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
218
219                         /* don't push the buffering BIO quite yet */
220
221                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
222                         s->ctx->stats.sess_connect++;
223                         s->init_num=0;
224                         /* mark client_random uninitialized */
225                         memset(s->s3->client_random,0,sizeof(s->s3->client_random));
226                         s->d1->send_cookie = 0;
227                         s->hit = 0;
228                         break;
229
230                 case SSL3_ST_CW_CLNT_HELLO_A:
231                 case SSL3_ST_CW_CLNT_HELLO_B:
232
233                         s->shutdown=0;
234
235                         /* every DTLS ClientHello resets Finished MAC */
236                         ssl3_init_finished_mac(s);
237
238                         dtls1_start_timer(s);
239                         ret=dtls1_client_hello(s);
240                         if (ret <= 0) goto end;
241
242                         if ( s->d1->send_cookie)
243                                 {
244                                 s->state=SSL3_ST_CW_FLUSH;
245                                 s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
246                                 }
247                         else
248                                 s->state=SSL3_ST_CR_SRVR_HELLO_A;
249
250                         s->init_num=0;
251
252                         /* turn on buffering for the next lot of output */
253                         if (s->bbio != s->wbio)
254                                 s->wbio=BIO_push(s->bbio,s->wbio);
255
256                         break;
257
258                 case SSL3_ST_CR_SRVR_HELLO_A:
259                 case SSL3_ST_CR_SRVR_HELLO_B:
260                         ret=ssl3_get_server_hello(s);
261                         if (ret <= 0) goto end;
262                         else
263                                 {
264                                 dtls1_stop_timer(s);
265                                 if (s->hit)
266                                         s->state=SSL3_ST_CR_FINISHED_A;
267                                 else
268                                         s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
269                                 }
270                         s->init_num=0;
271                         break;
272
273                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
274                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
275
276                         ret = dtls1_get_hello_verify(s);
277                         if ( ret <= 0)
278                                 goto end;
279                         dtls1_stop_timer(s);
280                         if ( s->d1->send_cookie) /* start again, with a cookie */
281                                 s->state=SSL3_ST_CW_CLNT_HELLO_A;
282                         else
283                                 s->state = SSL3_ST_CR_CERT_A;
284                         s->init_num = 0;
285                         break;
286
287                 case SSL3_ST_CR_CERT_A:
288                 case SSL3_ST_CR_CERT_B:
289                         /* Check if it is anon DH or PSK */
290                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
291                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
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                         dtls1_start_timer(s);
343                         ret=dtls1_send_client_certificate(s);
344                         if (ret <= 0) goto end;
345                         s->state=SSL3_ST_CW_KEY_EXCH_A;
346                         s->init_num=0;
347                         break;
348
349                 case SSL3_ST_CW_KEY_EXCH_A:
350                 case SSL3_ST_CW_KEY_EXCH_B:
351                         dtls1_start_timer(s);
352                         ret=dtls1_send_client_key_exchange(s);
353                         if (ret <= 0) goto end;
354                         /* EAY EAY EAY need to check for DH fix cert
355                          * sent back */
356                         /* For TLS, cert_req is set to 2, so a cert chain
357                          * of nothing is sent, but no verify packet is sent */
358                         if (s->s3->tmp.cert_req == 1)
359                                 {
360                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
361                                 }
362                         else
363                                 {
364                                 s->state=SSL3_ST_CW_CHANGE_A;
365                                 s->s3->change_cipher_spec=0;
366                                 }
367
368                         s->init_num=0;
369                         break;
370
371                 case SSL3_ST_CW_CERT_VRFY_A:
372                 case SSL3_ST_CW_CERT_VRFY_B:
373                         dtls1_start_timer(s);
374                         ret=dtls1_send_client_verify(s);
375                         if (ret <= 0) goto end;
376                         s->state=SSL3_ST_CW_CHANGE_A;
377                         s->init_num=0;
378                         s->s3->change_cipher_spec=0;
379                         break;
380
381                 case SSL3_ST_CW_CHANGE_A:
382                 case SSL3_ST_CW_CHANGE_B:
383                         dtls1_start_timer(s);
384                         ret=dtls1_send_change_cipher_spec(s,
385                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
386                         if (ret <= 0) goto end;
387                         s->state=SSL3_ST_CW_FINISHED_A;
388                         s->init_num=0;
389
390                         s->session->cipher=s->s3->tmp.new_cipher;
391 #ifdef OPENSSL_NO_COMP
392                         s->session->compress_meth=0;
393 #else
394                         if (s->s3->tmp.new_compression == NULL)
395                                 s->session->compress_meth=0;
396                         else
397                                 s->session->compress_meth=
398                                         s->s3->tmp.new_compression->id;
399 #endif
400                         if (!s->method->ssl3_enc->setup_key_block(s))
401                                 {
402                                 ret= -1;
403                                 goto end;
404                                 }
405
406                         if (!s->method->ssl3_enc->change_cipher_state(s,
407                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
408                                 {
409                                 ret= -1;
410                                 goto end;
411                                 }
412                         
413                         dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
414                         break;
415
416                 case SSL3_ST_CW_FINISHED_A:
417                 case SSL3_ST_CW_FINISHED_B:
418                         dtls1_start_timer(s);
419                         ret=dtls1_send_finished(s,
420                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
421                                 s->method->ssl3_enc->client_finished_label,
422                                 s->method->ssl3_enc->client_finished_label_len);
423                         if (ret <= 0) goto end;
424                         s->state=SSL3_ST_CW_FLUSH;
425
426                         /* clear flags */
427                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
428                         if (s->hit)
429                                 {
430                                 s->s3->tmp.next_state=SSL_ST_OK;
431                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
432                                         {
433                                         s->state=SSL_ST_OK;
434                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
435                                         s->s3->delay_buf_pop_ret=0;
436                                         }
437                                 }
438                         else
439                                 {
440                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
441                                 }
442                         s->init_num=0;
443                         break;
444
445                 case SSL3_ST_CR_FINISHED_A:
446                 case SSL3_ST_CR_FINISHED_B:
447                         s->d1->change_cipher_spec_ok = 1;
448                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
449                                 SSL3_ST_CR_FINISHED_B);
450                         if (ret <= 0) goto end;
451                         dtls1_stop_timer(s);
452
453                         if (s->hit)
454                                 s->state=SSL3_ST_CW_CHANGE_A;
455                         else
456                                 s->state=SSL_ST_OK;
457                         s->init_num=0;
458                         break;
459
460                 case SSL3_ST_CW_FLUSH:
461                         /* number of bytes to be flushed */
462                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
463                         if (num1 > 0)
464                                 {
465                                 s->rwstate=SSL_WRITING;
466                                 num1=BIO_flush(s->wbio);
467                                 if (num1 <= 0) { ret= -1; goto end; }
468                                 s->rwstate=SSL_NOTHING;
469                                 }
470
471                         s->state=s->s3->tmp.next_state;
472                         break;
473
474                 case SSL_ST_OK:
475                         /* clean a few things up */
476                         ssl3_cleanup_key_block(s);
477
478 #if 0
479                         if (s->init_buf != NULL)
480                                 {
481                                 BUF_MEM_free(s->init_buf);
482                                 s->init_buf=NULL;
483                                 }
484 #endif
485
486                         /* If we are not 'joining' the last two packets,
487                          * remove the buffering now */
488                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
489                                 ssl_free_wbio_buffer(s);
490                         /* else do it later in ssl3_write */
491
492                         s->init_num=0;
493                         s->new_session=0;
494
495                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
496                         if (s->hit) s->ctx->stats.sess_hit++;
497
498                         ret=1;
499                         /* s->server=0; */
500                         s->handshake_func=dtls1_connect;
501                         s->ctx->stats.sess_connect_good++;
502
503                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
504
505                         /* done with handshaking */
506                         s->d1->handshake_read_seq  = 0;
507                         s->d1->next_handshake_write_seq = 0;
508                         goto end;
509                         /* break; */
510                         
511                 default:
512                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
513                         ret= -1;
514                         goto end;
515                         /* break; */
516                         }
517
518                 /* did we do anything */
519                 if (!s->s3->tmp.reuse_message && !skip)
520                         {
521                         if (s->debug)
522                                 {
523                                 if ((ret=BIO_flush(s->wbio)) <= 0)
524                                         goto end;
525                                 }
526
527                         if ((cb != NULL) && (s->state != state))
528                                 {
529                                 new_state=s->state;
530                                 s->state=state;
531                                 cb(s,SSL_CB_CONNECT_LOOP,1);
532                                 s->state=new_state;
533                                 }
534                         }
535                 skip=0;
536                 }
537 end:
538         s->in_handshake--;
539         if (buf != NULL)
540                 BUF_MEM_free(buf);
541         if (cb != NULL)
542                 cb(s,SSL_CB_CONNECT_EXIT,ret);
543         return(ret);
544         }
545
546 int dtls1_client_hello(SSL *s)
547         {
548         unsigned char *buf;
549         unsigned char *p,*d;
550         unsigned int i,j;
551         unsigned long Time,l;
552         SSL_COMP *comp;
553
554         buf=(unsigned char *)s->init_buf->data;
555         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
556                 {
557                 if ((s->session == NULL) ||
558                         (s->session->ssl_version != s->version) ||
559                         (s->session->not_resumable))
560                         {
561                         if (!ssl_get_new_session(s,0))
562                                 goto err;
563                         }
564                 /* else use the pre-loaded session */
565
566                 p=s->s3->client_random;
567
568                 /* if client_random is initialized, reuse it, we are
569                  * required to use same upon reply to HelloVerify */
570                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
571                 if (i==sizeof(s->s3->client_random))
572                         {
573                         Time=(unsigned long)time(NULL); /* Time */
574                         l2n(Time,p);
575                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
576                         }
577
578                 /* Do the message type and length last */
579                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
580
581                 *(p++)=s->version>>8;
582                 *(p++)=s->version&0xff;
583                 s->client_version=s->version;
584
585                 /* Random stuff */
586                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
587                 p+=SSL3_RANDOM_SIZE;
588
589                 /* Session ID */
590                 if (s->new_session)
591                         i=0;
592                 else
593                         i=s->session->session_id_length;
594                 *(p++)=i;
595                 if (i != 0)
596                         {
597                         if (i > sizeof s->session->session_id)
598                                 {
599                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
600                                 goto err;
601                                 }
602                         memcpy(p,s->session->session_id,i);
603                         p+=i;
604                         }
605                 
606                 /* cookie stuff */
607                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
608                         {
609                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
610                         goto err;
611                         }
612                 *(p++) = s->d1->cookie_len;
613                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
614                 p += s->d1->cookie_len;
615
616                 /* Ciphers supported */
617                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
618                 if (i == 0)
619                         {
620                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
621                         goto err;
622                         }
623                 s2n(i,p);
624                 p+=i;
625
626                 /* COMPRESSION */
627                 if (s->ctx->comp_methods == NULL)
628                         j=0;
629                 else
630                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
631                 *(p++)=1+j;
632                 for (i=0; i<j; i++)
633                         {
634                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
635                         *(p++)=comp->id;
636                         }
637                 *(p++)=0; /* Add the NULL method */
638
639 #ifndef OPENSSL_NO_TLSEXT
640                 if ((p = ssl_add_clienthello_dtlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
641                         {
642                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
643                         goto err;
644                         }
645 #endif          
646
647                 l=(p-d);
648                 d=buf;
649
650                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
651
652                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
653                 /* number of bytes to write */
654                 s->init_num=p-buf;
655                 s->init_off=0;
656
657                 /* buffer the message to handle re-xmits */
658                 dtls1_buffer_message(s, 0);
659                 }
660
661         /* SSL3_ST_CW_CLNT_HELLO_B */
662         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
663 err:
664         return(-1);
665         }
666
667 static int dtls1_get_hello_verify(SSL *s)
668         {
669         int n, al, ok = 0;
670         unsigned char *data;
671         unsigned int cookie_len;
672
673         n=s->method->ssl_get_message(s,
674                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
675                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
676                 -1,
677                 s->max_cert_list,
678                 &ok);
679
680         if (!ok) return((int)n);
681
682         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
683                 {
684                 s->d1->send_cookie = 0;
685                 s->s3->tmp.reuse_message=1;
686                 return(1);
687                 }
688
689         data = (unsigned char *)s->init_msg;
690
691         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
692                 {
693                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
694                 s->version=(s->version&0xff00)|data[1];
695                 al = SSL_AD_PROTOCOL_VERSION;
696                 goto f_err;
697                 }
698         data+=2;
699
700         cookie_len = *(data++);
701         if ( cookie_len > sizeof(s->d1->cookie))
702                 {
703                 al=SSL_AD_ILLEGAL_PARAMETER;
704                 goto f_err;
705                 }
706
707         memcpy(s->d1->cookie, data, cookie_len);
708         s->d1->cookie_len = cookie_len;
709
710         s->d1->send_cookie = 1;
711         return 1;
712
713 f_err:
714         ssl3_send_alert(s, SSL3_AL_FATAL, al);
715         return -1;
716         }
717
718 int dtls1_send_client_key_exchange(SSL *s)
719         {
720         unsigned char *p,*d;
721         int n;
722         unsigned long alg_k;
723 #ifndef OPENSSL_NO_RSA
724         unsigned char *q;
725         EVP_PKEY *pkey=NULL;
726 #endif
727 #ifndef OPENSSL_NO_KRB5
728         KSSL_ERR kssl_err;
729 #endif /* OPENSSL_NO_KRB5 */
730 #ifndef OPENSSL_NO_ECDH
731         EC_KEY *clnt_ecdh = NULL;
732         const EC_POINT *srvr_ecpoint = NULL;
733         EVP_PKEY *srvr_pub_pkey = NULL;
734         unsigned char *encodedPoint = NULL;
735         int encoded_pt_len = 0;
736         BN_CTX * bn_ctx = NULL;
737 #endif
738
739         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
740                 {
741                 d=(unsigned char *)s->init_buf->data;
742                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
743                 
744                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
745
746                 /* Fool emacs indentation */
747                 if (0) {}
748 #ifndef OPENSSL_NO_RSA
749                 else if (alg_k & SSL_kRSA)
750                         {
751                         RSA *rsa;
752                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
753
754                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
755                                 rsa=s->session->sess_cert->peer_rsa_tmp;
756                         else
757                                 {
758                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
759                                 if ((pkey == NULL) ||
760                                         (pkey->type != EVP_PKEY_RSA) ||
761                                         (pkey->pkey.rsa == NULL))
762                                         {
763                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
764                                         goto err;
765                                         }
766                                 rsa=pkey->pkey.rsa;
767                                 EVP_PKEY_free(pkey);
768                                 }
769                                 
770                         tmp_buf[0]=s->client_version>>8;
771                         tmp_buf[1]=s->client_version&0xff;
772                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
773                                         goto err;
774
775                         s->session->master_key_length=sizeof tmp_buf;
776
777                         q=p;
778                         /* Fix buf for TLS and [incidentally] DTLS */
779                         if (s->version > SSL3_VERSION)
780                                 p+=2;
781                         n=RSA_public_encrypt(sizeof tmp_buf,
782                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
783 #ifdef PKCS1_CHECK
784                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
785                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
786 #endif
787                         if (n <= 0)
788                                 {
789                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
790                                 goto err;
791                                 }
792
793                         /* Fix buf for TLS and [incidentally] DTLS */
794                         if (s->version > SSL3_VERSION)
795                                 {
796                                 s2n(n,q);
797                                 n+=2;
798                                 }
799
800                         s->session->master_key_length=
801                                 s->method->ssl3_enc->generate_master_secret(s,
802                                         s->session->master_key,
803                                         tmp_buf,sizeof tmp_buf);
804                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
805                         }
806 #endif
807 #ifndef OPENSSL_NO_KRB5
808                 else if (alg_k & SSL_kKRB5)
809                         {
810                         krb5_error_code krb5rc;
811                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
812                         /*  krb5_data   krb5_ap_req;  */
813                         krb5_data       *enc_ticket;
814                         krb5_data       authenticator, *authp = NULL;
815                         EVP_CIPHER_CTX  ciph_ctx;
816                         const EVP_CIPHER *enc = NULL;
817                         unsigned char   iv[EVP_MAX_IV_LENGTH];
818                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
819                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
820                                                 + EVP_MAX_IV_LENGTH];
821                         int             padl, outl = sizeof(epms);
822
823                         EVP_CIPHER_CTX_init(&ciph_ctx);
824
825 #ifdef KSSL_DEBUG
826                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
827                                 alg_k, SSL_kKRB5);
828 #endif  /* KSSL_DEBUG */
829
830                         authp = NULL;
831 #ifdef KRB5SENDAUTH
832                         if (KRB5SENDAUTH)  authp = &authenticator;
833 #endif  /* KRB5SENDAUTH */
834
835                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
836                                 &kssl_err);
837                         enc = kssl_map_enc(kssl_ctx->enctype);
838                         if (enc == NULL)
839                             goto err;
840 #ifdef KSSL_DEBUG
841                         {
842                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
843                         if (krb5rc && kssl_err.text)
844                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
845                         }
846 #endif  /* KSSL_DEBUG */
847
848                         if (krb5rc)
849                                 {
850                                 ssl3_send_alert(s,SSL3_AL_FATAL,
851                                                 SSL_AD_HANDSHAKE_FAILURE);
852                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
853                                                 kssl_err.reason);
854                                 goto err;
855                                 }
856
857                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
858                         **  in place of RFC 2712 KerberosWrapper, as in:
859                         **
860                         **  Send ticket (copy to *p, set n = length)
861                         **  n = krb5_ap_req.length;
862                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
863                         **  if (krb5_ap_req.data)  
864                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
865                         **
866                         **  Now using real RFC 2712 KerberosWrapper
867                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
868                         **  Note: 2712 "opaque" types are here replaced
869                         **  with a 2-byte length followed by the value.
870                         **  Example:
871                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
872                         **  Where "xx xx" = length bytes.  Shown here with
873                         **  optional authenticator omitted.
874                         */
875
876                         /*  KerberosWrapper.Ticket              */
877                         s2n(enc_ticket->length,p);
878                         memcpy(p, enc_ticket->data, enc_ticket->length);
879                         p+= enc_ticket->length;
880                         n = enc_ticket->length + 2;
881
882                         /*  KerberosWrapper.Authenticator       */
883                         if (authp  &&  authp->length)  
884                                 {
885                                 s2n(authp->length,p);
886                                 memcpy(p, authp->data, authp->length);
887                                 p+= authp->length;
888                                 n+= authp->length + 2;
889                                 
890                                 free(authp->data);
891                                 authp->data = NULL;
892                                 authp->length = 0;
893                                 }
894                         else
895                                 {
896                                 s2n(0,p);/*  null authenticator length  */
897                                 n+=2;
898                                 }
899  
900                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
901                             goto err;
902
903                         /*  20010420 VRS.  Tried it this way; failed.
904                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
905                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
906                         **                              kssl_ctx->length);
907                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
908                         */
909
910                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
911                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
912                                 kssl_ctx->key,iv);
913                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
914                                 sizeof tmp_buf);
915                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
916                         outl += padl;
917                         if (outl > (int)sizeof epms)
918                                 {
919                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
920                                 goto err;
921                                 }
922                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
923
924                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
925                         s2n(outl,p);
926                         memcpy(p, epms, outl);
927                         p+=outl;
928                         n+=outl + 2;
929
930                         s->session->master_key_length=
931                                 s->method->ssl3_enc->generate_master_secret(s,
932                                         s->session->master_key,
933                                         tmp_buf, sizeof tmp_buf);
934
935                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
936                         OPENSSL_cleanse(epms, outl);
937                         }
938 #endif
939 #ifndef OPENSSL_NO_DH
940                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
941                         {
942                         DH *dh_srvr,*dh_clnt;
943
944                         if (s->session->sess_cert->peer_dh_tmp != NULL)
945                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
946                         else
947                                 {
948                                 /* we get them from the cert */
949                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
950                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
951                                 goto err;
952                                 }
953                         
954                         /* generate a new random key */
955                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
956                                 {
957                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
958                                 goto err;
959                                 }
960                         if (!DH_generate_key(dh_clnt))
961                                 {
962                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
963                                 goto err;
964                                 }
965
966                         /* use the 'p' output buffer for the DH key, but
967                          * make sure to clear it out afterwards */
968
969                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
970
971                         if (n <= 0)
972                                 {
973                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
974                                 goto err;
975                                 }
976
977                         /* generate master key from the result */
978                         s->session->master_key_length=
979                                 s->method->ssl3_enc->generate_master_secret(s,
980                                         s->session->master_key,p,n);
981                         /* clean up */
982                         memset(p,0,n);
983
984                         /* send off the data */
985                         n=BN_num_bytes(dh_clnt->pub_key);
986                         s2n(n,p);
987                         BN_bn2bin(dh_clnt->pub_key,p);
988                         n+=2;
989
990                         DH_free(dh_clnt);
991
992                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
993                         }
994 #endif
995 #ifndef OPENSSL_NO_ECDH 
996                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
997                         {
998                         const EC_GROUP *srvr_group = NULL;
999                         EC_KEY *tkey;
1000                         int ecdh_clnt_cert = 0;
1001                         int field_size = 0;
1002
1003                         /* Did we send out the client's
1004                          * ECDH share for use in premaster
1005                          * computation as part of client certificate?
1006                          * If so, set ecdh_clnt_cert to 1.
1007                          */
1008                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
1009                                 {
1010                                 /* XXX: For now, we do not support client
1011                                  * authentication using ECDH certificates.
1012                                  * To add such support, one needs to add
1013                                  * code that checks for appropriate 
1014                                  * conditions and sets ecdh_clnt_cert to 1.
1015                                  * For example, the cert have an ECC
1016                                  * key on the same curve as the server's
1017                                  * and the key should be authorized for
1018                                  * key agreement.
1019                                  *
1020                                  * One also needs to add code in ssl3_connect
1021                                  * to skip sending the certificate verify
1022                                  * message.
1023                                  *
1024                                  * if ((s->cert->key->privatekey != NULL) &&
1025                                  *     (s->cert->key->privatekey->type ==
1026                                  *      EVP_PKEY_EC) && ...)
1027                                  * ecdh_clnt_cert = 1;
1028                                  */
1029                                 }
1030
1031                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1032                                 {
1033                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1034                                 }
1035                         else
1036                                 {
1037                                 /* Get the Server Public Key from Cert */
1038                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1039                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1040                                 if ((srvr_pub_pkey == NULL) ||
1041                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1042                                     (srvr_pub_pkey->pkey.ec == NULL))
1043                                         {
1044                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1045                                             ERR_R_INTERNAL_ERROR);
1046                                         goto err;
1047                                         }
1048
1049                                 tkey = srvr_pub_pkey->pkey.ec;
1050                                 }
1051
1052                         srvr_group   = EC_KEY_get0_group(tkey);
1053                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1054
1055                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1056                                 {
1057                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1058                                     ERR_R_INTERNAL_ERROR);
1059                                 goto err;
1060                                 }
1061
1062                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1063                                 {
1064                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1065                                 goto err;
1066                                 }
1067
1068                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1069                                 {
1070                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1071                                 goto err;
1072                                 }
1073                         if (ecdh_clnt_cert) 
1074                                 { 
1075                                 /* Reuse key info from our certificate
1076                                  * We only need our private key to perform
1077                                  * the ECDH computation.
1078                                  */
1079                                 const BIGNUM *priv_key;
1080                                 tkey = s->cert->key->privatekey->pkey.ec;
1081                                 priv_key = EC_KEY_get0_private_key(tkey);
1082                                 if (priv_key == NULL)
1083                                         {
1084                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1085                                         goto err;
1086                                         }
1087                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1088                                         {
1089                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1090                                         goto err;
1091                                         }
1092                                 }
1093                         else 
1094                                 {
1095                                 /* Generate a new ECDH key pair */
1096                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1097                                         {
1098                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1099                                         goto err;
1100                                         }
1101                                 }
1102
1103                         /* use the 'p' output buffer for the ECDH key, but
1104                          * make sure to clear it out afterwards
1105                          */
1106
1107                         field_size = EC_GROUP_get_degree(srvr_group);
1108                         if (field_size <= 0)
1109                                 {
1110                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1111                                        ERR_R_ECDH_LIB);
1112                                 goto err;
1113                                 }
1114                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1115                         if (n <= 0)
1116                                 {
1117                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1118                                        ERR_R_ECDH_LIB);
1119                                 goto err;
1120                                 }
1121
1122                         /* generate master key from the result */
1123                         s->session->master_key_length = s->method->ssl3_enc \
1124                             -> generate_master_secret(s, 
1125                                 s->session->master_key,
1126                                 p, n);
1127
1128                         memset(p, 0, n); /* clean up */
1129
1130                         if (ecdh_clnt_cert) 
1131                                 {
1132                                 /* Send empty client key exch message */
1133                                 n = 0;
1134                                 }
1135                         else 
1136                                 {
1137                                 /* First check the size of encoding and
1138                                  * allocate memory accordingly.
1139                                  */
1140                                 encoded_pt_len = 
1141                                     EC_POINT_point2oct(srvr_group, 
1142                                         EC_KEY_get0_public_key(clnt_ecdh), 
1143                                         POINT_CONVERSION_UNCOMPRESSED, 
1144                                         NULL, 0, NULL);
1145
1146                                 encodedPoint = (unsigned char *) 
1147                                     OPENSSL_malloc(encoded_pt_len * 
1148                                         sizeof(unsigned char)); 
1149                                 bn_ctx = BN_CTX_new();
1150                                 if ((encodedPoint == NULL) || 
1151                                     (bn_ctx == NULL)) 
1152                                         {
1153                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1154                                         goto err;
1155                                         }
1156
1157                                 /* Encode the public key */
1158                                 n = EC_POINT_point2oct(srvr_group, 
1159                                     EC_KEY_get0_public_key(clnt_ecdh), 
1160                                     POINT_CONVERSION_UNCOMPRESSED, 
1161                                     encodedPoint, encoded_pt_len, bn_ctx);
1162
1163                                 *p = n; /* length of encoded point */
1164                                 /* Encoded point will be copied here */
1165                                 p += 1; 
1166                                 /* copy the point */
1167                                 memcpy((unsigned char *)p, encodedPoint, n);
1168                                 /* increment n to account for length field */
1169                                 n += 1; 
1170                                 }
1171
1172                         /* Free allocated memory */
1173                         BN_CTX_free(bn_ctx);
1174                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1175                         if (clnt_ecdh != NULL) 
1176                                  EC_KEY_free(clnt_ecdh);
1177                         EVP_PKEY_free(srvr_pub_pkey);
1178                         }
1179 #endif /* !OPENSSL_NO_ECDH */
1180
1181 #ifndef OPENSSL_NO_PSK
1182                 else if (alg_k & SSL_kPSK)
1183                         {
1184                         char identity[PSK_MAX_IDENTITY_LEN];
1185                         unsigned char *t = NULL;
1186                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1187                         unsigned int pre_ms_len = 0, psk_len = 0;
1188                         int psk_err = 1;
1189
1190                         n = 0;
1191                         if (s->psk_client_callback == NULL)
1192                                 {
1193                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1194                                         SSL_R_PSK_NO_CLIENT_CB);
1195                                 goto err;
1196                                 }
1197
1198                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1199                                 identity, PSK_MAX_IDENTITY_LEN,
1200                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1201                         if (psk_len > PSK_MAX_PSK_LEN)
1202                                 {
1203                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1204                                         ERR_R_INTERNAL_ERROR);
1205                                 goto psk_err;
1206                                 }
1207                         else if (psk_len == 0)
1208                                 {
1209                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1210                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1211                                 goto psk_err;
1212                                 }
1213
1214                         /* create PSK pre_master_secret */
1215                         pre_ms_len = 2+psk_len+2+psk_len;
1216                         t = psk_or_pre_ms;
1217                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1218                         s2n(psk_len, t);
1219                         memset(t, 0, psk_len);
1220                         t+=psk_len;
1221                         s2n(psk_len, t);
1222
1223                         if (s->session->psk_identity_hint != NULL)
1224                                 OPENSSL_free(s->session->psk_identity_hint);
1225                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1226                         if (s->ctx->psk_identity_hint != NULL &&
1227                                 s->session->psk_identity_hint == NULL)
1228                                 {
1229                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1230                                         ERR_R_MALLOC_FAILURE);
1231                                 goto psk_err;
1232                                 }
1233
1234                         if (s->session->psk_identity != NULL)
1235                                 OPENSSL_free(s->session->psk_identity);
1236                         s->session->psk_identity = BUF_strdup(identity);
1237                         if (s->session->psk_identity == NULL)
1238                                 {
1239                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1240                                         ERR_R_MALLOC_FAILURE);
1241                                 goto psk_err;
1242                                 }
1243
1244                         s->session->master_key_length =
1245                                 s->method->ssl3_enc->generate_master_secret(s,
1246                                         s->session->master_key,
1247                                         psk_or_pre_ms, pre_ms_len); 
1248                         n = strlen(identity);
1249                         s2n(n, p);
1250                         memcpy(p, identity, n);
1251                         n+=2;
1252                         psk_err = 0;
1253                 psk_err:
1254                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1255                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1256                         if (psk_err != 0)
1257                                 {
1258                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1259                                 goto err;
1260                                 }
1261                         }
1262 #endif
1263                 else
1264                         {
1265                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1266                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1267                         goto err;
1268                         }
1269                 
1270                 d = dtls1_set_message_header(s, d,
1271                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1272                 /*
1273                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1274                  l2n3(n,d);
1275                  l2n(s->d1->handshake_write_seq,d);
1276                  s->d1->handshake_write_seq++;
1277                 */
1278                 
1279                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1280                 /* number of bytes to write */
1281                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1282                 s->init_off=0;
1283
1284                 /* buffer the message to handle re-xmits */
1285                 dtls1_buffer_message(s, 0);
1286                 }
1287         
1288         /* SSL3_ST_CW_KEY_EXCH_B */
1289         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1290 err:
1291 #ifndef OPENSSL_NO_ECDH
1292         BN_CTX_free(bn_ctx);
1293         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1294         if (clnt_ecdh != NULL) 
1295                 EC_KEY_free(clnt_ecdh);
1296         EVP_PKEY_free(srvr_pub_pkey);
1297 #endif
1298         return(-1);
1299         }
1300
1301 int dtls1_send_client_verify(SSL *s)
1302         {
1303         unsigned char *p,*d;
1304         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1305         EVP_PKEY *pkey;
1306 #ifndef OPENSSL_NO_RSA
1307         unsigned u=0;
1308 #endif
1309         unsigned long n;
1310 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1311         int j;
1312 #endif
1313
1314         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1315                 {
1316                 d=(unsigned char *)s->init_buf->data;
1317                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1318                 pkey=s->cert->key->privatekey;
1319
1320                 s->method->ssl3_enc->cert_verify_mac(s,
1321                 NID_sha1,
1322                         &(data[MD5_DIGEST_LENGTH]));
1323
1324 #ifndef OPENSSL_NO_RSA
1325                 if (pkey->type == EVP_PKEY_RSA)
1326                         {
1327                         s->method->ssl3_enc->cert_verify_mac(s,
1328                                 NID_md5,
1329                                 &(data[0]));
1330                         if (RSA_sign(NID_md5_sha1, data,
1331                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1332                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1333                                 {
1334                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1335                                 goto err;
1336                                 }
1337                         s2n(u,p);
1338                         n=u+2;
1339                         }
1340                 else
1341 #endif
1342 #ifndef OPENSSL_NO_DSA
1343                         if (pkey->type == EVP_PKEY_DSA)
1344                         {
1345                         if (!DSA_sign(pkey->save_type,
1346                                 &(data[MD5_DIGEST_LENGTH]),
1347                                 SHA_DIGEST_LENGTH,&(p[2]),
1348                                 (unsigned int *)&j,pkey->pkey.dsa))
1349                                 {
1350                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1351                                 goto err;
1352                                 }
1353                         s2n(j,p);
1354                         n=j+2;
1355                         }
1356                 else
1357 #endif
1358 #ifndef OPENSSL_NO_ECDSA
1359                         if (pkey->type == EVP_PKEY_EC)
1360                         {
1361                         if (!ECDSA_sign(pkey->save_type,
1362                                 &(data[MD5_DIGEST_LENGTH]),
1363                                 SHA_DIGEST_LENGTH,&(p[2]),
1364                                 (unsigned int *)&j,pkey->pkey.ec))
1365                                 {
1366                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1367                                     ERR_R_ECDSA_LIB);
1368                                 goto err;
1369                                 }
1370                         s2n(j,p);
1371                         n=j+2;
1372                         }
1373                 else
1374 #endif
1375                         {
1376                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1377                         goto err;
1378                         }
1379
1380                 d = dtls1_set_message_header(s, d,
1381                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1382
1383                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1384                 s->init_off=0;
1385
1386                 /* buffer the message to handle re-xmits */
1387                 dtls1_buffer_message(s, 0);
1388
1389                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1390                 }
1391
1392         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1393         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1394 err:
1395         return(-1);
1396         }
1397
1398 int dtls1_send_client_certificate(SSL *s)
1399         {
1400         X509 *x509=NULL;
1401         EVP_PKEY *pkey=NULL;
1402         int i;
1403         unsigned long l;
1404
1405         if (s->state == SSL3_ST_CW_CERT_A)
1406                 {
1407                 if ((s->cert == NULL) ||
1408                         (s->cert->key->x509 == NULL) ||
1409                         (s->cert->key->privatekey == NULL))
1410                         s->state=SSL3_ST_CW_CERT_B;
1411                 else
1412                         s->state=SSL3_ST_CW_CERT_C;
1413                 }
1414
1415         /* We need to get a client cert */
1416         if (s->state == SSL3_ST_CW_CERT_B)
1417                 {
1418                 /* If we get an error, we need to
1419                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1420                  * We then get retied later */
1421                 i=0;
1422                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1423                 if (i < 0)
1424                         {
1425                         s->rwstate=SSL_X509_LOOKUP;
1426                         return(-1);
1427                         }
1428                 s->rwstate=SSL_NOTHING;
1429                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1430                         {
1431                         s->state=SSL3_ST_CW_CERT_B;
1432                         if (    !SSL_use_certificate(s,x509) ||
1433                                 !SSL_use_PrivateKey(s,pkey))
1434                                 i=0;
1435                         }
1436                 else if (i == 1)
1437                         {
1438                         i=0;
1439                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1440                         }
1441
1442                 if (x509 != NULL) X509_free(x509);
1443                 if (pkey != NULL) EVP_PKEY_free(pkey);
1444                 if (i == 0)
1445                         {
1446                         if (s->version == SSL3_VERSION)
1447                                 {
1448                                 s->s3->tmp.cert_req=0;
1449                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1450                                 return(1);
1451                                 }
1452                         else
1453                                 {
1454                                 s->s3->tmp.cert_req=2;
1455                                 }
1456                         }
1457
1458                 /* Ok, we have a cert */
1459                 s->state=SSL3_ST_CW_CERT_C;
1460                 }
1461
1462         if (s->state == SSL3_ST_CW_CERT_C)
1463                 {
1464                 s->state=SSL3_ST_CW_CERT_D;
1465                 l=dtls1_output_cert_chain(s,
1466                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1467                 s->init_num=(int)l;
1468                 s->init_off=0;
1469
1470                 /* set header called by dtls1_output_cert_chain() */
1471
1472                 /* buffer the message to handle re-xmits */
1473                 dtls1_buffer_message(s, 0);
1474                 }
1475         /* SSL3_ST_CW_CERT_D */
1476         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1477         }
1478
1479