2364ad2f8d148a23c6957df2c8b1e28dbea5fa84
[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                         break;
227
228                 case SSL3_ST_CW_CLNT_HELLO_A:
229                 case SSL3_ST_CW_CLNT_HELLO_B:
230
231                         s->shutdown=0;
232
233                         /* every DTLS ClientHello resets Finished MAC */
234                         ssl3_init_finished_mac(s);
235
236                         dtls1_start_timer(s);
237                         ret=dtls1_client_hello(s);
238                         if (ret <= 0) goto end;
239
240                         if ( s->d1->send_cookie)
241                                 {
242                                 s->state=SSL3_ST_CW_FLUSH;
243                                 s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
244                                 }
245                         else
246                                 s->state=SSL3_ST_CR_SRVR_HELLO_A;
247
248                         s->init_num=0;
249
250                         /* turn on buffering for the next lot of output */
251                         if (s->bbio != s->wbio)
252                                 s->wbio=BIO_push(s->bbio,s->wbio);
253
254                         break;
255
256                 case SSL3_ST_CR_SRVR_HELLO_A:
257                 case SSL3_ST_CR_SRVR_HELLO_B:
258                         ret=ssl3_get_server_hello(s);
259                         if (ret <= 0) goto end;
260                         else
261                                 {
262                                 dtls1_stop_timer(s);
263                                 if (s->hit)
264                                         s->state=SSL3_ST_CR_FINISHED_A;
265                                 else
266                                         s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
267                                 }
268                         s->init_num=0;
269                         break;
270
271                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
272                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
273
274                         ret = dtls1_get_hello_verify(s);
275                         if ( ret <= 0)
276                                 goto end;
277                         dtls1_stop_timer(s);
278                         if ( s->d1->send_cookie) /* start again, with a cookie */
279                                 s->state=SSL3_ST_CW_CLNT_HELLO_A;
280                         else
281                                 s->state = SSL3_ST_CR_CERT_A;
282                         s->init_num = 0;
283                         break;
284
285                 case SSL3_ST_CR_CERT_A:
286                 case SSL3_ST_CR_CERT_B:
287                         /* Check if it is anon DH or PSK */
288                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
289                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
290                                 {
291                                 ret=ssl3_get_server_certificate(s);
292                                 if (ret <= 0) goto end;
293                                 }
294                         else
295                                 skip=1;
296                         s->state=SSL3_ST_CR_KEY_EXCH_A;
297                         s->init_num=0;
298                         break;
299
300                 case SSL3_ST_CR_KEY_EXCH_A:
301                 case SSL3_ST_CR_KEY_EXCH_B:
302                         ret=ssl3_get_key_exchange(s);
303                         if (ret <= 0) goto end;
304                         s->state=SSL3_ST_CR_CERT_REQ_A;
305                         s->init_num=0;
306
307                         /* at this point we check that we have the
308                          * required stuff from the server */
309                         if (!ssl3_check_cert_and_algorithm(s))
310                                 {
311                                 ret= -1;
312                                 goto end;
313                                 }
314                         break;
315
316                 case SSL3_ST_CR_CERT_REQ_A:
317                 case SSL3_ST_CR_CERT_REQ_B:
318                         ret=ssl3_get_certificate_request(s);
319                         if (ret <= 0) goto end;
320                         s->state=SSL3_ST_CR_SRVR_DONE_A;
321                         s->init_num=0;
322                         break;
323
324                 case SSL3_ST_CR_SRVR_DONE_A:
325                 case SSL3_ST_CR_SRVR_DONE_B:
326                         ret=ssl3_get_server_done(s);
327                         if (ret <= 0) goto end;
328                         if (s->s3->tmp.cert_req)
329                                 s->state=SSL3_ST_CW_CERT_A;
330                         else
331                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
332                         s->init_num=0;
333
334                         break;
335
336                 case SSL3_ST_CW_CERT_A:
337                 case SSL3_ST_CW_CERT_B:
338                 case SSL3_ST_CW_CERT_C:
339                 case SSL3_ST_CW_CERT_D:
340                         dtls1_start_timer(s);
341                         ret=dtls1_send_client_certificate(s);
342                         if (ret <= 0) goto end;
343                         s->state=SSL3_ST_CW_KEY_EXCH_A;
344                         s->init_num=0;
345                         break;
346
347                 case SSL3_ST_CW_KEY_EXCH_A:
348                 case SSL3_ST_CW_KEY_EXCH_B:
349                         dtls1_start_timer(s);
350                         ret=dtls1_send_client_key_exchange(s);
351                         if (ret <= 0) goto end;
352                         /* EAY EAY EAY need to check for DH fix cert
353                          * sent back */
354                         /* For TLS, cert_req is set to 2, so a cert chain
355                          * of nothing is sent, but no verify packet is sent */
356                         if (s->s3->tmp.cert_req == 1)
357                                 {
358                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
359                                 }
360                         else
361                                 {
362                                 s->state=SSL3_ST_CW_CHANGE_A;
363                                 s->s3->change_cipher_spec=0;
364                                 }
365
366                         s->init_num=0;
367                         break;
368
369                 case SSL3_ST_CW_CERT_VRFY_A:
370                 case SSL3_ST_CW_CERT_VRFY_B:
371                         dtls1_start_timer(s);
372                         ret=dtls1_send_client_verify(s);
373                         if (ret <= 0) goto end;
374                         s->state=SSL3_ST_CW_CHANGE_A;
375                         s->init_num=0;
376                         s->s3->change_cipher_spec=0;
377                         break;
378
379                 case SSL3_ST_CW_CHANGE_A:
380                 case SSL3_ST_CW_CHANGE_B:
381                         dtls1_start_timer(s);
382                         ret=dtls1_send_change_cipher_spec(s,
383                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
384                         if (ret <= 0) goto end;
385                         s->state=SSL3_ST_CW_FINISHED_A;
386                         s->init_num=0;
387
388                         s->session->cipher=s->s3->tmp.new_cipher;
389 #ifdef OPENSSL_NO_COMP
390                         s->session->compress_meth=0;
391 #else
392                         if (s->s3->tmp.new_compression == NULL)
393                                 s->session->compress_meth=0;
394                         else
395                                 s->session->compress_meth=
396                                         s->s3->tmp.new_compression->id;
397 #endif
398                         if (!s->method->ssl3_enc->setup_key_block(s))
399                                 {
400                                 ret= -1;
401                                 goto end;
402                                 }
403
404                         if (!s->method->ssl3_enc->change_cipher_state(s,
405                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
406                                 {
407                                 ret= -1;
408                                 goto end;
409                                 }
410                         
411                         dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
412                         break;
413
414                 case SSL3_ST_CW_FINISHED_A:
415                 case SSL3_ST_CW_FINISHED_B:
416                         dtls1_start_timer(s);
417                         ret=dtls1_send_finished(s,
418                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
419                                 s->method->ssl3_enc->client_finished_label,
420                                 s->method->ssl3_enc->client_finished_label_len);
421                         if (ret <= 0) goto end;
422                         s->state=SSL3_ST_CW_FLUSH;
423
424                         /* clear flags */
425                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
426                         if (s->hit)
427                                 {
428                                 s->s3->tmp.next_state=SSL_ST_OK;
429                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
430                                         {
431                                         s->state=SSL_ST_OK;
432                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
433                                         s->s3->delay_buf_pop_ret=0;
434                                         }
435                                 }
436                         else
437                                 {
438                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
439                                 }
440                         s->init_num=0;
441                         break;
442
443                 case SSL3_ST_CR_FINISHED_A:
444                 case SSL3_ST_CR_FINISHED_B:
445
446                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
447                                 SSL3_ST_CR_FINISHED_B);
448                         if (ret <= 0) goto end;
449                         dtls1_stop_timer(s);
450
451                         if (s->hit)
452                                 s->state=SSL3_ST_CW_CHANGE_A;
453                         else
454                                 s->state=SSL_ST_OK;
455                         s->init_num=0;
456                         break;
457
458                 case SSL3_ST_CW_FLUSH:
459                         /* number of bytes to be flushed */
460                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
461                         if (num1 > 0)
462                                 {
463                                 s->rwstate=SSL_WRITING;
464                                 num1=BIO_flush(s->wbio);
465                                 if (num1 <= 0) { ret= -1; goto end; }
466                                 s->rwstate=SSL_NOTHING;
467                                 }
468
469                         s->state=s->s3->tmp.next_state;
470                         break;
471
472                 case SSL_ST_OK:
473                         /* clean a few things up */
474                         ssl3_cleanup_key_block(s);
475
476 #if 0
477                         if (s->init_buf != NULL)
478                                 {
479                                 BUF_MEM_free(s->init_buf);
480                                 s->init_buf=NULL;
481                                 }
482 #endif
483
484                         /* If we are not 'joining' the last two packets,
485                          * remove the buffering now */
486                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
487                                 ssl_free_wbio_buffer(s);
488                         /* else do it later in ssl3_write */
489
490                         s->init_num=0;
491                         s->new_session=0;
492
493                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
494                         if (s->hit) s->ctx->stats.sess_hit++;
495
496                         ret=1;
497                         /* s->server=0; */
498                         s->handshake_func=dtls1_connect;
499                         s->ctx->stats.sess_connect_good++;
500
501                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
502
503                         /* done with handshaking */
504                         s->d1->handshake_read_seq  = 0;
505                         s->d1->next_handshake_write_seq = 0;
506                         goto end;
507                         /* break; */
508                         
509                 default:
510                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
511                         ret= -1;
512                         goto end;
513                         /* break; */
514                         }
515
516                 /* did we do anything */
517                 if (!s->s3->tmp.reuse_message && !skip)
518                         {
519                         if (s->debug)
520                                 {
521                                 if ((ret=BIO_flush(s->wbio)) <= 0)
522                                         goto end;
523                                 }
524
525                         if ((cb != NULL) && (s->state != state))
526                                 {
527                                 new_state=s->state;
528                                 s->state=state;
529                                 cb(s,SSL_CB_CONNECT_LOOP,1);
530                                 s->state=new_state;
531                                 }
532                         }
533                 skip=0;
534                 }
535 end:
536         s->in_handshake--;
537         if (buf != NULL)
538                 BUF_MEM_free(buf);
539         if (cb != NULL)
540                 cb(s,SSL_CB_CONNECT_EXIT,ret);
541         return(ret);
542         }
543
544 int dtls1_client_hello(SSL *s)
545         {
546         unsigned char *buf;
547         unsigned char *p,*d;
548         unsigned int i,j;
549         unsigned long Time,l;
550         SSL_COMP *comp;
551
552         buf=(unsigned char *)s->init_buf->data;
553         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
554                 {
555                 if ((s->session == NULL) ||
556                         (s->session->ssl_version != s->version) ||
557                         (s->session->not_resumable))
558                         {
559                         if (!ssl_get_new_session(s,0))
560                                 goto err;
561                         }
562                 /* else use the pre-loaded session */
563
564                 p=s->s3->client_random;
565
566                 /* if client_random is initialized, reuse it, we are
567                  * required to use same upon reply to HelloVerify */
568                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
569                 if (i==sizeof(s->s3->client_random))
570                         {
571                         Time=(unsigned long)time(NULL); /* Time */
572                         l2n(Time,p);
573                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
574                         }
575
576                 /* Do the message type and length last */
577                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
578
579                 *(p++)=s->version>>8;
580                 *(p++)=s->version&0xff;
581                 s->client_version=s->version;
582
583                 /* Random stuff */
584                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
585                 p+=SSL3_RANDOM_SIZE;
586
587                 /* Session ID */
588                 if (s->new_session)
589                         i=0;
590                 else
591                         i=s->session->session_id_length;
592                 *(p++)=i;
593                 if (i != 0)
594                         {
595                         if (i > sizeof s->session->session_id)
596                                 {
597                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
598                                 goto err;
599                                 }
600                         memcpy(p,s->session->session_id,i);
601                         p+=i;
602                         }
603                 
604                 /* cookie stuff */
605                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
606                         {
607                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
608                         goto err;
609                         }
610                 *(p++) = s->d1->cookie_len;
611                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
612                 p += s->d1->cookie_len;
613
614                 /* Ciphers supported */
615                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
616                 if (i == 0)
617                         {
618                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
619                         goto err;
620                         }
621                 s2n(i,p);
622                 p+=i;
623
624                 /* COMPRESSION */
625                 if (s->ctx->comp_methods == NULL)
626                         j=0;
627                 else
628                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
629                 *(p++)=1+j;
630                 for (i=0; i<j; i++)
631                         {
632                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
633                         *(p++)=comp->id;
634                         }
635                 *(p++)=0; /* Add the NULL method */
636                 
637                 l=(p-d);
638                 d=buf;
639
640                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
641
642                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
643                 /* number of bytes to write */
644                 s->init_num=p-buf;
645                 s->init_off=0;
646
647                 /* buffer the message to handle re-xmits */
648                 dtls1_buffer_message(s, 0);
649                 }
650
651         /* SSL3_ST_CW_CLNT_HELLO_B */
652         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
653 err:
654         return(-1);
655         }
656
657 static int dtls1_get_hello_verify(SSL *s)
658         {
659         int n, al, ok = 0;
660         unsigned char *data;
661         unsigned int cookie_len;
662
663         n=s->method->ssl_get_message(s,
664                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
665                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
666                 -1,
667                 s->max_cert_list,
668                 &ok);
669
670         if (!ok) return((int)n);
671
672         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
673                 {
674                 s->d1->send_cookie = 0;
675                 s->s3->tmp.reuse_message=1;
676                 return(1);
677                 }
678
679         data = (unsigned char *)s->init_msg;
680
681         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
682                 {
683                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
684                 s->version=(s->version&0xff00)|data[1];
685                 al = SSL_AD_PROTOCOL_VERSION;
686                 goto f_err;
687                 }
688         data+=2;
689
690         cookie_len = *(data++);
691         if ( cookie_len > sizeof(s->d1->cookie))
692                 {
693                 al=SSL_AD_ILLEGAL_PARAMETER;
694                 goto f_err;
695                 }
696
697         memcpy(s->d1->cookie, data, cookie_len);
698         s->d1->cookie_len = cookie_len;
699
700         s->d1->send_cookie = 1;
701         return 1;
702
703 f_err:
704         ssl3_send_alert(s, SSL3_AL_FATAL, al);
705         return -1;
706         }
707
708 int dtls1_send_client_key_exchange(SSL *s)
709         {
710         unsigned char *p,*d;
711         int n;
712         unsigned long alg_k;
713 #ifndef OPENSSL_NO_RSA
714         unsigned char *q;
715         EVP_PKEY *pkey=NULL;
716 #endif
717 #ifndef OPENSSL_NO_KRB5
718         KSSL_ERR kssl_err;
719 #endif /* OPENSSL_NO_KRB5 */
720 #ifndef OPENSSL_NO_ECDH
721         EC_KEY *clnt_ecdh = NULL;
722         const EC_POINT *srvr_ecpoint = NULL;
723         EVP_PKEY *srvr_pub_pkey = NULL;
724         unsigned char *encodedPoint = NULL;
725         int encoded_pt_len = 0;
726         BN_CTX * bn_ctx = NULL;
727 #endif
728
729         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
730                 {
731                 d=(unsigned char *)s->init_buf->data;
732                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
733                 
734                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
735
736                 /* Fool emacs indentation */
737                 if (0) {}
738 #ifndef OPENSSL_NO_RSA
739                 else if (alg_k & SSL_kRSA)
740                         {
741                         RSA *rsa;
742                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
743
744                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
745                                 rsa=s->session->sess_cert->peer_rsa_tmp;
746                         else
747                                 {
748                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
749                                 if ((pkey == NULL) ||
750                                         (pkey->type != EVP_PKEY_RSA) ||
751                                         (pkey->pkey.rsa == NULL))
752                                         {
753                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
754                                         goto err;
755                                         }
756                                 rsa=pkey->pkey.rsa;
757                                 EVP_PKEY_free(pkey);
758                                 }
759                                 
760                         tmp_buf[0]=s->client_version>>8;
761                         tmp_buf[1]=s->client_version&0xff;
762                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
763                                         goto err;
764
765                         s->session->master_key_length=sizeof tmp_buf;
766
767                         q=p;
768                         /* Fix buf for TLS and [incidentally] DTLS */
769                         if (s->version > SSL3_VERSION)
770                                 p+=2;
771                         n=RSA_public_encrypt(sizeof tmp_buf,
772                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
773 #ifdef PKCS1_CHECK
774                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
775                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
776 #endif
777                         if (n <= 0)
778                                 {
779                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
780                                 goto err;
781                                 }
782
783                         /* Fix buf for TLS and [incidentally] DTLS */
784                         if (s->version > SSL3_VERSION)
785                                 {
786                                 s2n(n,q);
787                                 n+=2;
788                                 }
789
790                         s->session->master_key_length=
791                                 s->method->ssl3_enc->generate_master_secret(s,
792                                         s->session->master_key,
793                                         tmp_buf,sizeof tmp_buf);
794                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
795                         }
796 #endif
797 #ifndef OPENSSL_NO_KRB5
798                 else if (alg_k & SSL_kKRB5)
799                         {
800                         krb5_error_code krb5rc;
801                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
802                         /*  krb5_data   krb5_ap_req;  */
803                         krb5_data       *enc_ticket;
804                         krb5_data       authenticator, *authp = NULL;
805                         EVP_CIPHER_CTX  ciph_ctx;
806                         const EVP_CIPHER *enc = NULL;
807                         unsigned char   iv[EVP_MAX_IV_LENGTH];
808                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
809                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
810                                                 + EVP_MAX_IV_LENGTH];
811                         int             padl, outl = sizeof(epms);
812
813                         EVP_CIPHER_CTX_init(&ciph_ctx);
814
815 #ifdef KSSL_DEBUG
816                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
817                                 alg_k, SSL_kKRB5);
818 #endif  /* KSSL_DEBUG */
819
820                         authp = NULL;
821 #ifdef KRB5SENDAUTH
822                         if (KRB5SENDAUTH)  authp = &authenticator;
823 #endif  /* KRB5SENDAUTH */
824
825                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
826                                 &kssl_err);
827                         enc = kssl_map_enc(kssl_ctx->enctype);
828                         if (enc == NULL)
829                             goto err;
830 #ifdef KSSL_DEBUG
831                         {
832                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
833                         if (krb5rc && kssl_err.text)
834                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
835                         }
836 #endif  /* KSSL_DEBUG */
837
838                         if (krb5rc)
839                                 {
840                                 ssl3_send_alert(s,SSL3_AL_FATAL,
841                                                 SSL_AD_HANDSHAKE_FAILURE);
842                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
843                                                 kssl_err.reason);
844                                 goto err;
845                                 }
846
847                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
848                         **  in place of RFC 2712 KerberosWrapper, as in:
849                         **
850                         **  Send ticket (copy to *p, set n = length)
851                         **  n = krb5_ap_req.length;
852                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
853                         **  if (krb5_ap_req.data)  
854                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
855                         **
856                         **  Now using real RFC 2712 KerberosWrapper
857                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
858                         **  Note: 2712 "opaque" types are here replaced
859                         **  with a 2-byte length followed by the value.
860                         **  Example:
861                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
862                         **  Where "xx xx" = length bytes.  Shown here with
863                         **  optional authenticator omitted.
864                         */
865
866                         /*  KerberosWrapper.Ticket              */
867                         s2n(enc_ticket->length,p);
868                         memcpy(p, enc_ticket->data, enc_ticket->length);
869                         p+= enc_ticket->length;
870                         n = enc_ticket->length + 2;
871
872                         /*  KerberosWrapper.Authenticator       */
873                         if (authp  &&  authp->length)  
874                                 {
875                                 s2n(authp->length,p);
876                                 memcpy(p, authp->data, authp->length);
877                                 p+= authp->length;
878                                 n+= authp->length + 2;
879                                 
880                                 free(authp->data);
881                                 authp->data = NULL;
882                                 authp->length = 0;
883                                 }
884                         else
885                                 {
886                                 s2n(0,p);/*  null authenticator length  */
887                                 n+=2;
888                                 }
889  
890                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
891                             goto err;
892
893                         /*  20010420 VRS.  Tried it this way; failed.
894                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
895                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
896                         **                              kssl_ctx->length);
897                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
898                         */
899
900                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
901                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
902                                 kssl_ctx->key,iv);
903                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
904                                 sizeof tmp_buf);
905                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
906                         outl += padl;
907                         if (outl > (int)sizeof epms)
908                                 {
909                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
910                                 goto err;
911                                 }
912                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
913
914                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
915                         s2n(outl,p);
916                         memcpy(p, epms, outl);
917                         p+=outl;
918                         n+=outl + 2;
919
920                         s->session->master_key_length=
921                                 s->method->ssl3_enc->generate_master_secret(s,
922                                         s->session->master_key,
923                                         tmp_buf, sizeof tmp_buf);
924
925                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
926                         OPENSSL_cleanse(epms, outl);
927                         }
928 #endif
929 #ifndef OPENSSL_NO_DH
930                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
931                         {
932                         DH *dh_srvr,*dh_clnt;
933
934                         if (s->session->sess_cert->peer_dh_tmp != NULL)
935                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
936                         else
937                                 {
938                                 /* we get them from the cert */
939                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
940                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
941                                 goto err;
942                                 }
943                         
944                         /* generate a new random key */
945                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
946                                 {
947                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
948                                 goto err;
949                                 }
950                         if (!DH_generate_key(dh_clnt))
951                                 {
952                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
953                                 goto err;
954                                 }
955
956                         /* use the 'p' output buffer for the DH key, but
957                          * make sure to clear it out afterwards */
958
959                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
960
961                         if (n <= 0)
962                                 {
963                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
964                                 goto err;
965                                 }
966
967                         /* generate master key from the result */
968                         s->session->master_key_length=
969                                 s->method->ssl3_enc->generate_master_secret(s,
970                                         s->session->master_key,p,n);
971                         /* clean up */
972                         memset(p,0,n);
973
974                         /* send off the data */
975                         n=BN_num_bytes(dh_clnt->pub_key);
976                         s2n(n,p);
977                         BN_bn2bin(dh_clnt->pub_key,p);
978                         n+=2;
979
980                         DH_free(dh_clnt);
981
982                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
983                         }
984 #endif
985 #ifndef OPENSSL_NO_ECDH 
986                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
987                         {
988                         const EC_GROUP *srvr_group = NULL;
989                         EC_KEY *tkey;
990                         int ecdh_clnt_cert = 0;
991                         int field_size = 0;
992
993                         /* Did we send out the client's
994                          * ECDH share for use in premaster
995                          * computation as part of client certificate?
996                          * If so, set ecdh_clnt_cert to 1.
997                          */
998                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
999                                 {
1000                                 /* XXX: For now, we do not support client
1001                                  * authentication using ECDH certificates.
1002                                  * To add such support, one needs to add
1003                                  * code that checks for appropriate 
1004                                  * conditions and sets ecdh_clnt_cert to 1.
1005                                  * For example, the cert have an ECC
1006                                  * key on the same curve as the server's
1007                                  * and the key should be authorized for
1008                                  * key agreement.
1009                                  *
1010                                  * One also needs to add code in ssl3_connect
1011                                  * to skip sending the certificate verify
1012                                  * message.
1013                                  *
1014                                  * if ((s->cert->key->privatekey != NULL) &&
1015                                  *     (s->cert->key->privatekey->type ==
1016                                  *      EVP_PKEY_EC) && ...)
1017                                  * ecdh_clnt_cert = 1;
1018                                  */
1019                                 }
1020
1021                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1022                                 {
1023                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1024                                 }
1025                         else
1026                                 {
1027                                 /* Get the Server Public Key from Cert */
1028                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1029                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1030                                 if ((srvr_pub_pkey == NULL) ||
1031                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1032                                     (srvr_pub_pkey->pkey.ec == NULL))
1033                                         {
1034                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1035                                             ERR_R_INTERNAL_ERROR);
1036                                         goto err;
1037                                         }
1038
1039                                 tkey = srvr_pub_pkey->pkey.ec;
1040                                 }
1041
1042                         srvr_group   = EC_KEY_get0_group(tkey);
1043                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1044
1045                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1046                                 {
1047                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1048                                     ERR_R_INTERNAL_ERROR);
1049                                 goto err;
1050                                 }
1051
1052                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1053                                 {
1054                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1055                                 goto err;
1056                                 }
1057
1058                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1059                                 {
1060                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1061                                 goto err;
1062                                 }
1063                         if (ecdh_clnt_cert) 
1064                                 { 
1065                                 /* Reuse key info from our certificate
1066                                  * We only need our private key to perform
1067                                  * the ECDH computation.
1068                                  */
1069                                 const BIGNUM *priv_key;
1070                                 tkey = s->cert->key->privatekey->pkey.ec;
1071                                 priv_key = EC_KEY_get0_private_key(tkey);
1072                                 if (priv_key == NULL)
1073                                         {
1074                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1075                                         goto err;
1076                                         }
1077                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1078                                         {
1079                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1080                                         goto err;
1081                                         }
1082                                 }
1083                         else 
1084                                 {
1085                                 /* Generate a new ECDH key pair */
1086                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1087                                         {
1088                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1089                                         goto err;
1090                                         }
1091                                 }
1092
1093                         /* use the 'p' output buffer for the ECDH key, but
1094                          * make sure to clear it out afterwards
1095                          */
1096
1097                         field_size = EC_GROUP_get_degree(srvr_group);
1098                         if (field_size <= 0)
1099                                 {
1100                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1101                                        ERR_R_ECDH_LIB);
1102                                 goto err;
1103                                 }
1104                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1105                         if (n <= 0)
1106                                 {
1107                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1108                                        ERR_R_ECDH_LIB);
1109                                 goto err;
1110                                 }
1111
1112                         /* generate master key from the result */
1113                         s->session->master_key_length = s->method->ssl3_enc \
1114                             -> generate_master_secret(s, 
1115                                 s->session->master_key,
1116                                 p, n);
1117
1118                         memset(p, 0, n); /* clean up */
1119
1120                         if (ecdh_clnt_cert) 
1121                                 {
1122                                 /* Send empty client key exch message */
1123                                 n = 0;
1124                                 }
1125                         else 
1126                                 {
1127                                 /* First check the size of encoding and
1128                                  * allocate memory accordingly.
1129                                  */
1130                                 encoded_pt_len = 
1131                                     EC_POINT_point2oct(srvr_group, 
1132                                         EC_KEY_get0_public_key(clnt_ecdh), 
1133                                         POINT_CONVERSION_UNCOMPRESSED, 
1134                                         NULL, 0, NULL);
1135
1136                                 encodedPoint = (unsigned char *) 
1137                                     OPENSSL_malloc(encoded_pt_len * 
1138                                         sizeof(unsigned char)); 
1139                                 bn_ctx = BN_CTX_new();
1140                                 if ((encodedPoint == NULL) || 
1141                                     (bn_ctx == NULL)) 
1142                                         {
1143                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1144                                         goto err;
1145                                         }
1146
1147                                 /* Encode the public key */
1148                                 n = EC_POINT_point2oct(srvr_group, 
1149                                     EC_KEY_get0_public_key(clnt_ecdh), 
1150                                     POINT_CONVERSION_UNCOMPRESSED, 
1151                                     encodedPoint, encoded_pt_len, bn_ctx);
1152
1153                                 *p = n; /* length of encoded point */
1154                                 /* Encoded point will be copied here */
1155                                 p += 1; 
1156                                 /* copy the point */
1157                                 memcpy((unsigned char *)p, encodedPoint, n);
1158                                 /* increment n to account for length field */
1159                                 n += 1; 
1160                                 }
1161
1162                         /* Free allocated memory */
1163                         BN_CTX_free(bn_ctx);
1164                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1165                         if (clnt_ecdh != NULL) 
1166                                  EC_KEY_free(clnt_ecdh);
1167                         EVP_PKEY_free(srvr_pub_pkey);
1168                         }
1169 #endif /* !OPENSSL_NO_ECDH */
1170
1171 #ifndef OPENSSL_NO_PSK
1172                 else if (alg_k & SSL_kPSK)
1173                         {
1174                         char identity[PSK_MAX_IDENTITY_LEN];
1175                         unsigned char *t = NULL;
1176                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1177                         unsigned int pre_ms_len = 0, psk_len = 0;
1178                         int psk_err = 1;
1179
1180                         n = 0;
1181                         if (s->psk_client_callback == NULL)
1182                                 {
1183                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1184                                         SSL_R_PSK_NO_CLIENT_CB);
1185                                 goto err;
1186                                 }
1187
1188                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1189                                 identity, PSK_MAX_IDENTITY_LEN,
1190                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1191                         if (psk_len > PSK_MAX_PSK_LEN)
1192                                 {
1193                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1194                                         ERR_R_INTERNAL_ERROR);
1195                                 goto psk_err;
1196                                 }
1197                         else if (psk_len == 0)
1198                                 {
1199                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1200                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1201                                 goto psk_err;
1202                                 }
1203
1204                         /* create PSK pre_master_secret */
1205                         pre_ms_len = 2+psk_len+2+psk_len;
1206                         t = psk_or_pre_ms;
1207                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1208                         s2n(psk_len, t);
1209                         memset(t, 0, psk_len);
1210                         t+=psk_len;
1211                         s2n(psk_len, t);
1212
1213                         if (s->session->psk_identity_hint != NULL)
1214                                 OPENSSL_free(s->session->psk_identity_hint);
1215                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1216                         if (s->ctx->psk_identity_hint != NULL &&
1217                                 s->session->psk_identity_hint == NULL)
1218                                 {
1219                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1220                                         ERR_R_MALLOC_FAILURE);
1221                                 goto psk_err;
1222                                 }
1223
1224                         if (s->session->psk_identity != NULL)
1225                                 OPENSSL_free(s->session->psk_identity);
1226                         s->session->psk_identity = BUF_strdup(identity);
1227                         if (s->session->psk_identity == NULL)
1228                                 {
1229                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1230                                         ERR_R_MALLOC_FAILURE);
1231                                 goto psk_err;
1232                                 }
1233
1234                         s->session->master_key_length =
1235                                 s->method->ssl3_enc->generate_master_secret(s,
1236                                         s->session->master_key,
1237                                         psk_or_pre_ms, pre_ms_len); 
1238                         n = strlen(identity);
1239                         s2n(n, p);
1240                         memcpy(p, identity, n);
1241                         n+=2;
1242                         psk_err = 0;
1243                 psk_err:
1244                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1245                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1246                         if (psk_err != 0)
1247                                 {
1248                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1249                                 goto err;
1250                                 }
1251                         }
1252 #endif
1253                 else
1254                         {
1255                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1256                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1257                         goto err;
1258                         }
1259                 
1260                 d = dtls1_set_message_header(s, d,
1261                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1262                 /*
1263                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1264                  l2n3(n,d);
1265                  l2n(s->d1->handshake_write_seq,d);
1266                  s->d1->handshake_write_seq++;
1267                 */
1268                 
1269                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1270                 /* number of bytes to write */
1271                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1272                 s->init_off=0;
1273
1274                 /* buffer the message to handle re-xmits */
1275                 dtls1_buffer_message(s, 0);
1276                 }
1277         
1278         /* SSL3_ST_CW_KEY_EXCH_B */
1279         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1280 err:
1281 #ifndef OPENSSL_NO_ECDH
1282         BN_CTX_free(bn_ctx);
1283         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1284         if (clnt_ecdh != NULL) 
1285                 EC_KEY_free(clnt_ecdh);
1286         EVP_PKEY_free(srvr_pub_pkey);
1287 #endif
1288         return(-1);
1289         }
1290
1291 int dtls1_send_client_verify(SSL *s)
1292         {
1293         unsigned char *p,*d;
1294         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1295         EVP_PKEY *pkey;
1296 #ifndef OPENSSL_NO_RSA
1297         unsigned u=0;
1298 #endif
1299         unsigned long n;
1300 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1301         int j;
1302 #endif
1303
1304         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1305                 {
1306                 d=(unsigned char *)s->init_buf->data;
1307                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1308                 pkey=s->cert->key->privatekey;
1309
1310                 s->method->ssl3_enc->cert_verify_mac(s,
1311                 NID_sha1,
1312                         &(data[MD5_DIGEST_LENGTH]));
1313
1314 #ifndef OPENSSL_NO_RSA
1315                 if (pkey->type == EVP_PKEY_RSA)
1316                         {
1317                         s->method->ssl3_enc->cert_verify_mac(s,
1318                                 NID_md5,
1319                                 &(data[0]));
1320                         if (RSA_sign(NID_md5_sha1, data,
1321                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1322                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1323                                 {
1324                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1325                                 goto err;
1326                                 }
1327                         s2n(u,p);
1328                         n=u+2;
1329                         }
1330                 else
1331 #endif
1332 #ifndef OPENSSL_NO_DSA
1333                         if (pkey->type == EVP_PKEY_DSA)
1334                         {
1335                         if (!DSA_sign(pkey->save_type,
1336                                 &(data[MD5_DIGEST_LENGTH]),
1337                                 SHA_DIGEST_LENGTH,&(p[2]),
1338                                 (unsigned int *)&j,pkey->pkey.dsa))
1339                                 {
1340                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1341                                 goto err;
1342                                 }
1343                         s2n(j,p);
1344                         n=j+2;
1345                         }
1346                 else
1347 #endif
1348 #ifndef OPENSSL_NO_ECDSA
1349                         if (pkey->type == EVP_PKEY_EC)
1350                         {
1351                         if (!ECDSA_sign(pkey->save_type,
1352                                 &(data[MD5_DIGEST_LENGTH]),
1353                                 SHA_DIGEST_LENGTH,&(p[2]),
1354                                 (unsigned int *)&j,pkey->pkey.ec))
1355                                 {
1356                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
1357                                     ERR_R_ECDSA_LIB);
1358                                 goto err;
1359                                 }
1360                         s2n(j,p);
1361                         n=j+2;
1362                         }
1363                 else
1364 #endif
1365                         {
1366                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1367                         goto err;
1368                         }
1369
1370                 d = dtls1_set_message_header(s, d,
1371                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1372
1373                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1374                 s->init_off=0;
1375
1376                 /* buffer the message to handle re-xmits */
1377                 dtls1_buffer_message(s, 0);
1378
1379                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1380                 }
1381
1382         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1383         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1384 err:
1385         return(-1);
1386         }
1387
1388 int dtls1_send_client_certificate(SSL *s)
1389         {
1390         X509 *x509=NULL;
1391         EVP_PKEY *pkey=NULL;
1392         int i;
1393         unsigned long l;
1394
1395         if (s->state == SSL3_ST_CW_CERT_A)
1396                 {
1397                 if ((s->cert == NULL) ||
1398                         (s->cert->key->x509 == NULL) ||
1399                         (s->cert->key->privatekey == NULL))
1400                         s->state=SSL3_ST_CW_CERT_B;
1401                 else
1402                         s->state=SSL3_ST_CW_CERT_C;
1403                 }
1404
1405         /* We need to get a client cert */
1406         if (s->state == SSL3_ST_CW_CERT_B)
1407                 {
1408                 /* If we get an error, we need to
1409                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1410                  * We then get retied later */
1411                 i=0;
1412                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1413                 if (i < 0)
1414                         {
1415                         s->rwstate=SSL_X509_LOOKUP;
1416                         return(-1);
1417                         }
1418                 s->rwstate=SSL_NOTHING;
1419                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1420                         {
1421                         s->state=SSL3_ST_CW_CERT_B;
1422                         if (    !SSL_use_certificate(s,x509) ||
1423                                 !SSL_use_PrivateKey(s,pkey))
1424                                 i=0;
1425                         }
1426                 else if (i == 1)
1427                         {
1428                         i=0;
1429                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1430                         }
1431
1432                 if (x509 != NULL) X509_free(x509);
1433                 if (pkey != NULL) EVP_PKEY_free(pkey);
1434                 if (i == 0)
1435                         {
1436                         if (s->version == SSL3_VERSION)
1437                                 {
1438                                 s->s3->tmp.cert_req=0;
1439                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1440                                 return(1);
1441                                 }
1442                         else
1443                                 {
1444                                 s->s3->tmp.cert_req=2;
1445                                 }
1446                         }
1447
1448                 /* Ok, we have a cert */
1449                 s->state=SSL3_ST_CW_CERT_C;
1450                 }
1451
1452         if (s->state == SSL3_ST_CW_CERT_C)
1453                 {
1454                 s->state=SSL3_ST_CW_CERT_D;
1455                 l=dtls1_output_cert_chain(s,
1456                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1457                 s->init_num=(int)l;
1458                 s->init_off=0;
1459
1460                 /* set header called by dtls1_output_cert_chain() */
1461
1462                 /* buffer the message to handle re-xmits */
1463                 dtls1_buffer_message(s, 0);
1464                 }
1465         /* SSL3_ST_CW_CERT_D */
1466         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1467         }
1468
1469