bb1fd6ac0a8682c26306f9cc3e492cdce2c77b17
[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 <openssl/crypto.h>
118 #include "ssl_locl.h"
119 #ifndef OPENSSL_NO_KRB5
120 #include "kssl_lcl.h"
121 #endif
122 #include <openssl/buffer.h>
123 #include <openssl/rand.h>
124 #include <openssl/objects.h>
125 #include <openssl/evp.h>
126 #include <openssl/md5.h>
127 #include <openssl/bn.h>
128 #ifndef OPENSSL_NO_DH
129 #include <openssl/dh.h>
130 #endif
131
132 static const SSL_METHOD *dtls1_get_client_method(int ver);
133 static int dtls1_get_hello_verify(SSL *s);
134
135 static const SSL_METHOD *dtls1_get_client_method(int ver)
136         {
137         if (ver == DTLS1_VERSION || ver == DTLS1_BAD_VER)
138                 return(DTLSv1_client_method());
139         else
140                 return(NULL);
141         }
142
143 IMPLEMENT_dtls1_meth_func(DTLSv1_client_method,
144                         ssl_undefined_function,
145                         dtls1_connect,
146                         dtls1_get_client_method)
147
148 int dtls1_connect(SSL *s)
149         {
150         BUF_MEM *buf=NULL;
151         unsigned long Time=(unsigned long)time(NULL);
152         void (*cb)(const SSL *ssl,int type,int val)=NULL;
153         int ret= -1;
154         int new_state,state,skip=0;
155 #ifndef OPENSSL_NO_SCTP
156         unsigned char sctpauthkey[64];
157         char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
158 #endif
159
160         RAND_add(&Time,sizeof(Time),0);
161         ERR_clear_error();
162         clear_sys_error();
163
164         if (s->info_callback != NULL)
165                 cb=s->info_callback;
166         else if (s->ctx->info_callback != NULL)
167                 cb=s->ctx->info_callback;
168         
169         s->in_handshake++;
170         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
171
172 #ifndef OPENSSL_NO_SCTP
173         /* Notify SCTP BIO socket to enter handshake
174          * mode and prevent stream identifier other
175          * than 0. Will be ignored if no SCTP is used.
176          */
177         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL);
178 #endif
179
180 #ifndef OPENSSL_NO_HEARTBEATS
181         /* If we're awaiting a HeartbeatResponse, pretend we
182          * already got and don't await it anymore, because
183          * Heartbeats don't make sense during handshakes anyway.
184          */
185         if (s->tlsext_hb_pending)
186                 {
187                 dtls1_stop_timer(s);
188                 s->tlsext_hb_pending = 0;
189                 s->tlsext_hb_seq++;
190                 }
191 #endif
192
193         for (;;)
194                 {
195                 state=s->state;
196
197                 switch(s->state)
198                         {
199                 case SSL_ST_RENEGOTIATE:
200                         s->renegotiate=1;
201                         s->state=SSL_ST_CONNECT;
202                         s->ctx->stats.sess_connect_renegotiate++;
203                         /* break */
204                 case SSL_ST_BEFORE:
205                 case SSL_ST_CONNECT:
206                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
207                 case SSL_ST_OK|SSL_ST_CONNECT:
208
209                         s->server=0;
210                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
211
212                         if ((s->version & 0xff00 ) != (DTLS1_VERSION & 0xff00) &&
213                             (s->version & 0xff00 ) != (DTLS1_BAD_VER & 0xff00))
214                                 {
215                                 SSLerr(SSL_F_DTLS1_CONNECT, ERR_R_INTERNAL_ERROR);
216                                 ret = -1;
217                                 goto end;
218                                 }
219                                 
220                         /* s->version=SSL3_VERSION; */
221                         s->type=SSL_ST_CONNECT;
222
223                         if (s->init_buf == NULL)
224                                 {
225                                 if ((buf=BUF_MEM_new()) == NULL)
226                                         {
227                                         ret= -1;
228                                         goto end;
229                                         }
230                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
231                                         {
232                                         ret= -1;
233                                         goto end;
234                                         }
235                                 s->init_buf=buf;
236                                 buf=NULL;
237                                 }
238
239                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
240
241                         /* setup buffing BIO */
242                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
243
244                         /* don't push the buffering BIO quite yet */
245
246                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
247                         s->ctx->stats.sess_connect++;
248                         s->init_num=0;
249                         /* mark client_random uninitialized */
250                         memset(s->s3->client_random,0,sizeof(s->s3->client_random));
251                         s->d1->send_cookie = 0;
252                         s->hit = 0;
253                         break;
254
255 #ifndef OPENSSL_NO_SCTP
256                 case DTLS1_SCTP_ST_CR_READ_SOCK:
257
258                         if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)))
259                         {
260                                 s->s3->in_read_app_data=2;
261                                 s->rwstate=SSL_READING;
262                                 BIO_clear_retry_flags(SSL_get_rbio(s));
263                                 BIO_set_retry_read(SSL_get_rbio(s));
264                                 ret = -1;
265                                 goto end;
266                         }
267
268                         s->state=s->s3->tmp.next_state;
269                         break;
270
271                 case DTLS1_SCTP_ST_CW_WRITE_SOCK:
272                         /* read app data until dry event */
273
274                         ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
275                         if (ret < 0) goto end;
276
277                         if (ret == 0)
278                         {
279                                 s->s3->in_read_app_data=2;
280                                 s->rwstate=SSL_READING;
281                                 BIO_clear_retry_flags(SSL_get_rbio(s));
282                                 BIO_set_retry_read(SSL_get_rbio(s));
283                                 ret = -1;
284                                 goto end;
285                         }
286
287                         s->state=s->d1->next_state;
288                         break;
289 #endif
290
291                 case SSL3_ST_CW_CLNT_HELLO_A:
292                 case SSL3_ST_CW_CLNT_HELLO_B:
293
294                         s->shutdown=0;
295
296                         /* every DTLS ClientHello resets Finished MAC */
297                         ssl3_init_finished_mac(s);
298
299                         dtls1_start_timer(s);
300                         ret=dtls1_client_hello(s);
301                         if (ret <= 0) goto end;
302
303                         if ( s->d1->send_cookie)
304                                 {
305                                 s->state=SSL3_ST_CW_FLUSH;
306                                 s->s3->tmp.next_state=SSL3_ST_CR_SRVR_HELLO_A;
307                                 }
308                         else
309                                 s->state=SSL3_ST_CR_SRVR_HELLO_A;
310
311                         s->init_num=0;
312
313 #ifndef OPENSSL_NO_SCTP
314                         /* Disable buffering for SCTP */
315                         if (!BIO_dgram_is_sctp(SSL_get_wbio(s)))
316                                 {
317 #endif
318                                 /* turn on buffering for the next lot of output */
319                                 if (s->bbio != s->wbio)
320                                         s->wbio=BIO_push(s->bbio,s->wbio);
321 #ifndef OPENSSL_NO_SCTP
322                                 }
323 #endif
324
325                         break;
326
327                 case SSL3_ST_CR_SRVR_HELLO_A:
328                 case SSL3_ST_CR_SRVR_HELLO_B:
329                         ret=ssl3_get_server_hello(s);
330                         if (ret <= 0) goto end;
331                         else
332                                 {
333                                 dtls1_stop_timer(s);
334                                 if (s->hit)
335                                         {
336 #ifndef OPENSSL_NO_SCTP
337                                         /* Add new shared key for SCTP-Auth,
338                                          * will be ignored if no SCTP used.
339                                          */
340                                         snprintf((char*) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
341                                                  DTLS1_SCTP_AUTH_LABEL);
342
343                                         SSL_export_keying_material(s, sctpauthkey,
344                                                                    sizeof(sctpauthkey), labelbuffer,
345                                                                    sizeof(labelbuffer), NULL, 0, 0);
346
347                                         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
348                                                          sizeof(sctpauthkey), sctpauthkey);
349 #endif
350
351                                         s->state=SSL3_ST_CR_FINISHED_A;
352                                         }
353                                 else
354                                         s->state=DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
355                                 }
356                         s->init_num=0;
357                         break;
358
359                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
360                 case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
361
362                         ret = dtls1_get_hello_verify(s);
363                         if ( ret <= 0)
364                                 goto end;
365                         dtls1_stop_timer(s);
366                         if ( s->d1->send_cookie) /* start again, with a cookie */
367                                 s->state=SSL3_ST_CW_CLNT_HELLO_A;
368                         else
369                                 s->state = SSL3_ST_CR_CERT_A;
370                         s->init_num = 0;
371                         break;
372
373                 case SSL3_ST_CR_CERT_A:
374                 case SSL3_ST_CR_CERT_B:
375 #ifndef OPENSSL_NO_TLSEXT
376                         ret=ssl3_check_finished(s);
377                         if (ret <= 0) goto end;
378                         if (ret == 2)
379                                 {
380                                 s->hit = 1;
381                                 if (s->tlsext_ticket_expected)
382                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
383                                 else
384                                         s->state=SSL3_ST_CR_FINISHED_A;
385                                 s->init_num=0;
386                                 break;
387                                 }
388 #endif
389                         /* Check if it is anon DH or PSK */
390                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
391                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
392                                 {
393                                 ret=ssl3_get_server_certificate(s);
394                                 if (ret <= 0) goto end;
395 #ifndef OPENSSL_NO_TLSEXT
396                                 if (s->tlsext_status_expected)
397                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
398                                 else
399                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
400                                 }
401                         else
402                                 {
403                                 skip = 1;
404                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
405                                 }
406 #else
407                                 }
408                         else
409                                 skip=1;
410
411                         s->state=SSL3_ST_CR_KEY_EXCH_A;
412 #endif
413                         s->init_num=0;
414                         break;
415
416                 case SSL3_ST_CR_KEY_EXCH_A:
417                 case SSL3_ST_CR_KEY_EXCH_B:
418                         ret=ssl3_get_key_exchange(s);
419                         if (ret <= 0) goto end;
420                         s->state=SSL3_ST_CR_CERT_REQ_A;
421                         s->init_num=0;
422
423                         /* at this point we check that we have the
424                          * required stuff from the server */
425                         if (!ssl3_check_cert_and_algorithm(s))
426                                 {
427                                 ret= -1;
428                                 goto end;
429                                 }
430                         break;
431
432                 case SSL3_ST_CR_CERT_REQ_A:
433                 case SSL3_ST_CR_CERT_REQ_B:
434                         ret=ssl3_get_certificate_request(s);
435                         if (ret <= 0) goto end;
436                         s->state=SSL3_ST_CR_SRVR_DONE_A;
437                         s->init_num=0;
438                         break;
439
440                 case SSL3_ST_CR_SRVR_DONE_A:
441                 case SSL3_ST_CR_SRVR_DONE_B:
442                         ret=ssl3_get_server_done(s);
443                         if (ret <= 0) goto end;
444                         if (s->s3->tmp.cert_req)
445                                 s->s3->tmp.next_state=SSL3_ST_CW_CERT_A;
446                         else
447                                 s->s3->tmp.next_state=SSL3_ST_CW_KEY_EXCH_A;
448                         s->init_num=0;
449
450 #ifndef OPENSSL_NO_SCTP                 
451                         if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
452                             state == SSL_ST_RENEGOTIATE)
453                                 s->state=DTLS1_SCTP_ST_CR_READ_SOCK;
454                         else
455 #endif                  
456                         s->state=s->s3->tmp.next_state;
457                         break;
458
459                 case SSL3_ST_CW_CERT_A:
460                 case SSL3_ST_CW_CERT_B:
461                 case SSL3_ST_CW_CERT_C:
462                 case SSL3_ST_CW_CERT_D:
463                         dtls1_start_timer(s);
464                         ret=dtls1_send_client_certificate(s);
465                         if (ret <= 0) goto end;
466                         s->state=SSL3_ST_CW_KEY_EXCH_A;
467                         s->init_num=0;
468                         break;
469
470                 case SSL3_ST_CW_KEY_EXCH_A:
471                 case SSL3_ST_CW_KEY_EXCH_B:
472                         dtls1_start_timer(s);
473                         ret=dtls1_send_client_key_exchange(s);
474                         if (ret <= 0) goto end;
475
476 #ifndef OPENSSL_NO_SCTP
477                         /* Add new shared key for SCTP-Auth,
478                          * will be ignored if no SCTP used.
479                          */
480                         snprintf((char*) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
481                                  DTLS1_SCTP_AUTH_LABEL);
482
483                         SSL_export_keying_material(s, sctpauthkey,
484                                                    sizeof(sctpauthkey), labelbuffer,
485                                                    sizeof(labelbuffer), NULL, 0, 0);
486
487                         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
488                                          sizeof(sctpauthkey), sctpauthkey);
489 #endif
490
491                         /* EAY EAY EAY need to check for DH fix cert
492                          * sent back */
493                         /* For TLS, cert_req is set to 2, so a cert chain
494                          * of nothing is sent, but no verify packet is sent */
495                         if (s->s3->tmp.cert_req == 1)
496                                 {
497                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
498                                 }
499                         else
500                                 {
501 #ifndef OPENSSL_NO_SCTP
502                                 if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
503                                         {
504                                         s->d1->next_state=SSL3_ST_CW_CHANGE_A;
505                                         s->state=DTLS1_SCTP_ST_CW_WRITE_SOCK;
506                                         }
507                                 else
508 #endif
509                                         s->state=SSL3_ST_CW_CHANGE_A;
510                                 s->s3->change_cipher_spec=0;
511                                 }
512
513                         s->init_num=0;
514                         break;
515
516                 case SSL3_ST_CW_CERT_VRFY_A:
517                 case SSL3_ST_CW_CERT_VRFY_B:
518                         dtls1_start_timer(s);
519                         ret=dtls1_send_client_verify(s);
520                         if (ret <= 0) goto end;
521 #ifndef OPENSSL_NO_SCTP
522                         if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
523                         {
524                                 s->d1->next_state=SSL3_ST_CW_CHANGE_A;
525                                 s->state=DTLS1_SCTP_ST_CW_WRITE_SOCK;
526                         }
527                         else
528 #endif
529                                 s->state=SSL3_ST_CW_CHANGE_A;
530                         s->init_num=0;
531                         s->s3->change_cipher_spec=0;
532                         break;
533
534                 case SSL3_ST_CW_CHANGE_A:
535                 case SSL3_ST_CW_CHANGE_B:
536                         if (!s->hit)
537                                 dtls1_start_timer(s);
538                         ret=dtls1_send_change_cipher_spec(s,
539                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
540                         if (ret <= 0) goto end;
541
542 #ifndef OPENSSL_NO_SCTP
543                         /* Change to new shared key of SCTP-Auth,
544                          * will be ignored if no SCTP used.
545                          */
546                         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL);
547 #endif
548
549                         s->state=SSL3_ST_CW_FINISHED_A;
550                         s->init_num=0;
551
552                         s->session->cipher=s->s3->tmp.new_cipher;
553 #ifdef OPENSSL_NO_COMP
554                         s->session->compress_meth=0;
555 #else
556                         if (s->s3->tmp.new_compression == NULL)
557                                 s->session->compress_meth=0;
558                         else
559                                 s->session->compress_meth=
560                                         s->s3->tmp.new_compression->id;
561 #endif
562                         if (!s->method->ssl3_enc->setup_key_block(s))
563                                 {
564                                 ret= -1;
565                                 goto end;
566                                 }
567
568                         if (!s->method->ssl3_enc->change_cipher_state(s,
569                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
570                                 {
571                                 ret= -1;
572                                 goto end;
573                                 }
574                         
575                         dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
576                         break;
577
578                 case SSL3_ST_CW_FINISHED_A:
579                 case SSL3_ST_CW_FINISHED_B:
580                         if (!s->hit)
581                                 dtls1_start_timer(s);
582                         ret=dtls1_send_finished(s,
583                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
584                                 s->method->ssl3_enc->client_finished_label,
585                                 s->method->ssl3_enc->client_finished_label_len);
586                         if (ret <= 0) goto end;
587                         s->state=SSL3_ST_CW_FLUSH;
588
589                         /* clear flags */
590                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
591                         if (s->hit)
592                                 {
593                                 s->s3->tmp.next_state=SSL_ST_OK;
594 #ifndef OPENSSL_NO_SCTP
595                                 if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
596                                         {
597                                                 s->d1->next_state = s->s3->tmp.next_state;
598                                                 s->s3->tmp.next_state=DTLS1_SCTP_ST_CW_WRITE_SOCK;
599                                         }
600 #endif
601                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
602                                         {
603                                         s->state=SSL_ST_OK;
604 #ifndef OPENSSL_NO_SCTP
605                                         if (BIO_dgram_is_sctp(SSL_get_wbio(s)))
606                                                 {
607                                                         s->d1->next_state = SSL_ST_OK;
608                                                         s->state=DTLS1_SCTP_ST_CW_WRITE_SOCK;
609                                                 }
610 #endif
611                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
612                                         s->s3->delay_buf_pop_ret=0;
613                                         }
614                                 }
615                         else
616                                 {
617 #ifndef OPENSSL_NO_TLSEXT
618                                 /* Allow NewSessionTicket if ticket expected */
619                                 if (s->tlsext_ticket_expected)
620                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
621                                 else
622 #endif
623                                 
624                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
625                                 }
626                         s->init_num=0;
627                         break;
628
629 #ifndef OPENSSL_NO_TLSEXT
630                 case SSL3_ST_CR_SESSION_TICKET_A:
631                 case SSL3_ST_CR_SESSION_TICKET_B:
632                         ret=ssl3_get_new_session_ticket(s);
633                         if (ret <= 0) goto end;
634                         s->state=SSL3_ST_CR_FINISHED_A;
635                         s->init_num=0;
636                 break;
637
638                 case SSL3_ST_CR_CERT_STATUS_A:
639                 case SSL3_ST_CR_CERT_STATUS_B:
640                         ret=ssl3_get_cert_status(s);
641                         if (ret <= 0) goto end;
642                         s->state=SSL3_ST_CR_KEY_EXCH_A;
643                         s->init_num=0;
644                 break;
645 #endif
646
647                 case SSL3_ST_CR_FINISHED_A:
648                 case SSL3_ST_CR_FINISHED_B:
649                         s->d1->change_cipher_spec_ok = 1;
650                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
651                                 SSL3_ST_CR_FINISHED_B);
652                         if (ret <= 0) goto end;
653                         dtls1_stop_timer(s);
654
655                         if (s->hit)
656                                 s->state=SSL3_ST_CW_CHANGE_A;
657                         else
658                                 s->state=SSL_ST_OK;
659
660 #ifndef OPENSSL_NO_SCTP
661                         if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
662                                 state == SSL_ST_RENEGOTIATE)
663                                 {
664                                 s->d1->next_state=s->state;
665                                 s->state=DTLS1_SCTP_ST_CW_WRITE_SOCK;
666                                 }
667 #endif
668
669                         s->init_num=0;
670                         break;
671
672                 case SSL3_ST_CW_FLUSH:
673                         s->rwstate=SSL_WRITING;
674                         if (BIO_flush(s->wbio) <= 0)
675                                 {
676                                 /* If the write error was fatal, stop trying */
677                                 if (!BIO_should_retry(s->wbio))
678                                         {
679                                         s->rwstate=SSL_NOTHING;
680                                         s->state=s->s3->tmp.next_state;
681                                         }
682                                 
683                                 ret= -1;
684                                 goto end;
685                                 }
686                         s->rwstate=SSL_NOTHING;
687                         s->state=s->s3->tmp.next_state;
688                         break;
689
690                 case SSL_ST_OK:
691                         /* clean a few things up */
692                         ssl3_cleanup_key_block(s);
693
694 #if 0
695                         if (s->init_buf != NULL)
696                                 {
697                                 BUF_MEM_free(s->init_buf);
698                                 s->init_buf=NULL;
699                                 }
700 #endif
701
702                         /* If we are not 'joining' the last two packets,
703                          * remove the buffering now */
704                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
705                                 ssl_free_wbio_buffer(s);
706                         /* else do it later in ssl3_write */
707
708                         s->init_num=0;
709                         s->renegotiate=0;
710                         s->new_session=0;
711
712                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
713                         if (s->hit) s->ctx->stats.sess_hit++;
714
715                         ret=1;
716                         /* s->server=0; */
717                         s->handshake_func=dtls1_connect;
718                         s->ctx->stats.sess_connect_good++;
719
720                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
721
722                         /* done with handshaking */
723                         s->d1->handshake_read_seq  = 0;
724                         s->d1->next_handshake_write_seq = 0;
725                         goto end;
726                         /* break; */
727                         
728                 default:
729                         SSLerr(SSL_F_DTLS1_CONNECT,SSL_R_UNKNOWN_STATE);
730                         ret= -1;
731                         goto end;
732                         /* break; */
733                         }
734
735                 /* did we do anything */
736                 if (!s->s3->tmp.reuse_message && !skip)
737                         {
738                         if (s->debug)
739                                 {
740                                 if ((ret=BIO_flush(s->wbio)) <= 0)
741                                         goto end;
742                                 }
743
744                         if ((cb != NULL) && (s->state != state))
745                                 {
746                                 new_state=s->state;
747                                 s->state=state;
748                                 cb(s,SSL_CB_CONNECT_LOOP,1);
749                                 s->state=new_state;
750                                 }
751                         }
752                 skip=0;
753                 }
754 end:
755         s->in_handshake--;
756         
757 #ifndef OPENSSL_NO_SCTP
758         /* Notify SCTP BIO socket to leave handshake
759          * mode and allow stream identifier other
760          * than 0. Will be ignored if no SCTP is used.
761          */
762         BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL);
763 #endif
764
765         if (buf != NULL)
766                 BUF_MEM_free(buf);
767         if (cb != NULL)
768                 cb(s,SSL_CB_CONNECT_EXIT,ret);
769         return(ret);
770         }
771
772 int dtls1_client_hello(SSL *s)
773         {
774         unsigned char *buf;
775         unsigned char *p,*d;
776         unsigned int i,j;
777         unsigned long Time,l;
778         SSL_COMP *comp;
779
780         buf=(unsigned char *)s->init_buf->data;
781         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
782                 {
783                 SSL_SESSION *sess = s->session;
784                 if ((s->session == NULL) ||
785                         (s->session->ssl_version != s->version) ||
786 #ifdef OPENSSL_NO_TLSEXT
787                         !sess->session_id_length ||
788 #else
789                         (!sess->session_id_length && !sess->tlsext_tick) ||
790 #endif
791                         (s->session->not_resumable))
792                         {
793                         if (!ssl_get_new_session(s,0))
794                                 goto err;
795                         }
796                 /* else use the pre-loaded session */
797
798                 p=s->s3->client_random;
799
800                 /* if client_random is initialized, reuse it, we are
801                  * required to use same upon reply to HelloVerify */
802                 for (i=0;p[i]=='\0' && i<sizeof(s->s3->client_random);i++) ;
803                 if (i==sizeof(s->s3->client_random))
804                         {
805                         Time=(unsigned long)time(NULL); /* Time */
806                         l2n(Time,p);
807                         RAND_pseudo_bytes(p,sizeof(s->s3->client_random)-4);
808                         }
809
810                 /* Do the message type and length last */
811                 d=p= &(buf[DTLS1_HM_HEADER_LENGTH]);
812
813                 *(p++)=s->version>>8;
814                 *(p++)=s->version&0xff;
815                 s->client_version=s->version;
816
817                 /* Random stuff */
818                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
819                 p+=SSL3_RANDOM_SIZE;
820
821                 /* Session ID */
822                 if (s->new_session)
823                         i=0;
824                 else
825                         i=s->session->session_id_length;
826                 *(p++)=i;
827                 if (i != 0)
828                         {
829                         if (i > sizeof s->session->session_id)
830                                 {
831                                 SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
832                                 goto err;
833                                 }
834                         memcpy(p,s->session->session_id,i);
835                         p+=i;
836                         }
837                 
838                 /* cookie stuff */
839                 if ( s->d1->cookie_len > sizeof(s->d1->cookie))
840                         {
841                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
842                         goto err;
843                         }
844                 *(p++) = s->d1->cookie_len;
845                 memcpy(p, s->d1->cookie, s->d1->cookie_len);
846                 p += s->d1->cookie_len;
847
848                 /* Ciphers supported */
849                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
850                 if (i == 0)
851                         {
852                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
853                         goto err;
854                         }
855                 s2n(i,p);
856                 p+=i;
857
858                 /* COMPRESSION */
859                 if (s->ctx->comp_methods == NULL)
860                         j=0;
861                 else
862                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
863                 *(p++)=1+j;
864                 for (i=0; i<j; i++)
865                         {
866                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
867                         *(p++)=comp->id;
868                         }
869                 *(p++)=0; /* Add the NULL method */
870
871 #ifndef OPENSSL_NO_TLSEXT
872                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
873                         {
874                         SSLerr(SSL_F_DTLS1_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
875                         goto err;
876                         }
877 #endif          
878
879                 l=(p-d);
880                 d=buf;
881
882                 d = dtls1_set_message_header(s, d, SSL3_MT_CLIENT_HELLO, l, 0, l);
883
884                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
885                 /* number of bytes to write */
886                 s->init_num=p-buf;
887                 s->init_off=0;
888
889                 /* buffer the message to handle re-xmits */
890                 dtls1_buffer_message(s, 0);
891                 }
892
893         /* SSL3_ST_CW_CLNT_HELLO_B */
894         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
895 err:
896         return(-1);
897         }
898
899 static int dtls1_get_hello_verify(SSL *s)
900         {
901         int n, al, ok = 0;
902         unsigned char *data;
903         unsigned int cookie_len;
904
905         n=s->method->ssl_get_message(s,
906                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
907                 DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B,
908                 -1,
909                 s->max_cert_list,
910                 &ok);
911
912         if (!ok) return((int)n);
913
914         if (s->s3->tmp.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST)
915                 {
916                 s->d1->send_cookie = 0;
917                 s->s3->tmp.reuse_message=1;
918                 return(1);
919                 }
920
921         data = (unsigned char *)s->init_msg;
922
923         if ((data[0] != (s->version>>8)) || (data[1] != (s->version&0xff)))
924                 {
925                 SSLerr(SSL_F_DTLS1_GET_HELLO_VERIFY,SSL_R_WRONG_SSL_VERSION);
926                 s->version=(s->version&0xff00)|data[1];
927                 al = SSL_AD_PROTOCOL_VERSION;
928                 goto f_err;
929                 }
930         data+=2;
931
932         cookie_len = *(data++);
933         if ( cookie_len > sizeof(s->d1->cookie))
934                 {
935                 al=SSL_AD_ILLEGAL_PARAMETER;
936                 goto f_err;
937                 }
938
939         memcpy(s->d1->cookie, data, cookie_len);
940         s->d1->cookie_len = cookie_len;
941
942         s->d1->send_cookie = 1;
943         return 1;
944
945 f_err:
946         ssl3_send_alert(s, SSL3_AL_FATAL, al);
947         return -1;
948         }
949
950 int dtls1_send_client_key_exchange(SSL *s)
951         {
952         unsigned char *p,*d;
953         int n;
954         unsigned long alg_k;
955 #ifndef OPENSSL_NO_RSA
956         unsigned char *q;
957         EVP_PKEY *pkey=NULL;
958 #endif
959 #ifndef OPENSSL_NO_KRB5
960         KSSL_ERR kssl_err;
961 #endif /* OPENSSL_NO_KRB5 */
962 #ifndef OPENSSL_NO_ECDH
963         EC_KEY *clnt_ecdh = NULL;
964         const EC_POINT *srvr_ecpoint = NULL;
965         EVP_PKEY *srvr_pub_pkey = NULL;
966         unsigned char *encodedPoint = NULL;
967         int encoded_pt_len = 0;
968         BN_CTX * bn_ctx = NULL;
969 #endif
970
971         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
972                 {
973                 d=(unsigned char *)s->init_buf->data;
974                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
975                 
976                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
977
978                 /* Fool emacs indentation */
979                 if (0) {}
980 #ifndef OPENSSL_NO_RSA
981                 else if (alg_k & SSL_kRSA)
982                         {
983                         RSA *rsa;
984                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
985
986                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
987                                 rsa=s->session->sess_cert->peer_rsa_tmp;
988                         else
989                                 {
990                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
991                                 if ((pkey == NULL) ||
992                                         (pkey->type != EVP_PKEY_RSA) ||
993                                         (pkey->pkey.rsa == NULL))
994                                         {
995                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
996                                         goto err;
997                                         }
998                                 rsa=pkey->pkey.rsa;
999                                 EVP_PKEY_free(pkey);
1000                                 }
1001                                 
1002                         tmp_buf[0]=s->client_version>>8;
1003                         tmp_buf[1]=s->client_version&0xff;
1004                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
1005                                         goto err;
1006
1007                         s->session->master_key_length=sizeof tmp_buf;
1008
1009                         q=p;
1010                         /* Fix buf for TLS and [incidentally] DTLS */
1011                         if (s->version > SSL3_VERSION)
1012                                 p+=2;
1013                         n=RSA_public_encrypt(sizeof tmp_buf,
1014                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1015 #ifdef PKCS1_CHECK
1016                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1017                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1018 #endif
1019                         if (n <= 0)
1020                                 {
1021                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1022                                 goto err;
1023                                 }
1024
1025                         /* Fix buf for TLS and [incidentally] DTLS */
1026                         if (s->version > SSL3_VERSION)
1027                                 {
1028                                 s2n(n,q);
1029                                 n+=2;
1030                                 }
1031
1032                         s->session->master_key_length=
1033                                 s->method->ssl3_enc->generate_master_secret(s,
1034                                         s->session->master_key,
1035                                         tmp_buf,sizeof tmp_buf);
1036                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
1037                         }
1038 #endif
1039 #ifndef OPENSSL_NO_KRB5
1040                 else if (alg_k & SSL_kKRB5)
1041                         {
1042                         krb5_error_code krb5rc;
1043                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
1044                         /*  krb5_data   krb5_ap_req;  */
1045                         krb5_data       *enc_ticket;
1046                         krb5_data       authenticator, *authp = NULL;
1047                         EVP_CIPHER_CTX  ciph_ctx;
1048                         const EVP_CIPHER *enc = NULL;
1049                         unsigned char   iv[EVP_MAX_IV_LENGTH];
1050                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1051                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
1052                                                 + EVP_MAX_IV_LENGTH];
1053                         int             padl, outl = sizeof(epms);
1054
1055                         EVP_CIPHER_CTX_init(&ciph_ctx);
1056
1057 #ifdef KSSL_DEBUG
1058                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
1059                                 alg_k, SSL_kKRB5);
1060 #endif  /* KSSL_DEBUG */
1061
1062                         authp = NULL;
1063 #ifdef KRB5SENDAUTH
1064                         if (KRB5SENDAUTH)  authp = &authenticator;
1065 #endif  /* KRB5SENDAUTH */
1066
1067                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
1068                                 &kssl_err);
1069                         enc = kssl_map_enc(kssl_ctx->enctype);
1070                         if (enc == NULL)
1071                             goto err;
1072 #ifdef KSSL_DEBUG
1073                         {
1074                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
1075                         if (krb5rc && kssl_err.text)
1076                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
1077                         }
1078 #endif  /* KSSL_DEBUG */
1079
1080                         if (krb5rc)
1081                                 {
1082                                 ssl3_send_alert(s,SSL3_AL_FATAL,
1083                                                 SSL_AD_HANDSHAKE_FAILURE);
1084                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1085                                                 kssl_err.reason);
1086                                 goto err;
1087                                 }
1088
1089                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
1090                         **  in place of RFC 2712 KerberosWrapper, as in:
1091                         **
1092                         **  Send ticket (copy to *p, set n = length)
1093                         **  n = krb5_ap_req.length;
1094                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
1095                         **  if (krb5_ap_req.data)  
1096                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
1097                         **
1098                         **  Now using real RFC 2712 KerberosWrapper
1099                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
1100                         **  Note: 2712 "opaque" types are here replaced
1101                         **  with a 2-byte length followed by the value.
1102                         **  Example:
1103                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
1104                         **  Where "xx xx" = length bytes.  Shown here with
1105                         **  optional authenticator omitted.
1106                         */
1107
1108                         /*  KerberosWrapper.Ticket              */
1109                         s2n(enc_ticket->length,p);
1110                         memcpy(p, enc_ticket->data, enc_ticket->length);
1111                         p+= enc_ticket->length;
1112                         n = enc_ticket->length + 2;
1113
1114                         /*  KerberosWrapper.Authenticator       */
1115                         if (authp  &&  authp->length)  
1116                                 {
1117                                 s2n(authp->length,p);
1118                                 memcpy(p, authp->data, authp->length);
1119                                 p+= authp->length;
1120                                 n+= authp->length + 2;
1121                                 
1122                                 free(authp->data);
1123                                 authp->data = NULL;
1124                                 authp->length = 0;
1125                                 }
1126                         else
1127                                 {
1128                                 s2n(0,p);/*  null authenticator length  */
1129                                 n+=2;
1130                                 }
1131  
1132                         if (RAND_bytes(tmp_buf,sizeof tmp_buf) <= 0)
1133                             goto err;
1134
1135                         /*  20010420 VRS.  Tried it this way; failed.
1136                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
1137                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
1138                         **                              kssl_ctx->length);
1139                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
1140                         */
1141
1142                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
1143                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
1144                                 kssl_ctx->key,iv);
1145                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
1146                                 sizeof tmp_buf);
1147                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
1148                         outl += padl;
1149                         if (outl > (int)sizeof epms)
1150                                 {
1151                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1152                                 goto err;
1153                                 }
1154                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1155
1156                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
1157                         s2n(outl,p);
1158                         memcpy(p, epms, outl);
1159                         p+=outl;
1160                         n+=outl + 2;
1161
1162                         s->session->master_key_length=
1163                                 s->method->ssl3_enc->generate_master_secret(s,
1164                                         s->session->master_key,
1165                                         tmp_buf, sizeof tmp_buf);
1166
1167                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
1168                         OPENSSL_cleanse(epms, outl);
1169                         }
1170 #endif
1171 #ifndef OPENSSL_NO_DH
1172                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1173                         {
1174                         DH *dh_srvr,*dh_clnt;
1175
1176                         if (s->session->sess_cert->peer_dh_tmp != NULL)
1177                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
1178                         else
1179                                 {
1180                                 /* we get them from the cert */
1181                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1182                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1183                                 goto err;
1184                                 }
1185                         
1186                         /* generate a new random key */
1187                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
1188                                 {
1189                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1190                                 goto err;
1191                                 }
1192                         if (!DH_generate_key(dh_clnt))
1193                                 {
1194                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1195                                 goto err;
1196                                 }
1197
1198                         /* use the 'p' output buffer for the DH key, but
1199                          * make sure to clear it out afterwards */
1200
1201                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
1202
1203                         if (n <= 0)
1204                                 {
1205                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1206                                 goto err;
1207                                 }
1208
1209                         /* generate master key from the result */
1210                         s->session->master_key_length=
1211                                 s->method->ssl3_enc->generate_master_secret(s,
1212                                         s->session->master_key,p,n);
1213                         /* clean up */
1214                         memset(p,0,n);
1215
1216                         /* send off the data */
1217                         n=BN_num_bytes(dh_clnt->pub_key);
1218                         s2n(n,p);
1219                         BN_bn2bin(dh_clnt->pub_key,p);
1220                         n+=2;
1221
1222                         DH_free(dh_clnt);
1223
1224                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
1225                         }
1226 #endif
1227 #ifndef OPENSSL_NO_ECDH 
1228                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
1229                         {
1230                         const EC_GROUP *srvr_group = NULL;
1231                         EC_KEY *tkey;
1232                         int ecdh_clnt_cert = 0;
1233                         int field_size = 0;
1234
1235                         /* Did we send out the client's
1236                          * ECDH share for use in premaster
1237                          * computation as part of client certificate?
1238                          * If so, set ecdh_clnt_cert to 1.
1239                          */
1240                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
1241                                 {
1242                                 /* XXX: For now, we do not support client
1243                                  * authentication using ECDH certificates.
1244                                  * To add such support, one needs to add
1245                                  * code that checks for appropriate 
1246                                  * conditions and sets ecdh_clnt_cert to 1.
1247                                  * For example, the cert have an ECC
1248                                  * key on the same curve as the server's
1249                                  * and the key should be authorized for
1250                                  * key agreement.
1251                                  *
1252                                  * One also needs to add code in ssl3_connect
1253                                  * to skip sending the certificate verify
1254                                  * message.
1255                                  *
1256                                  * if ((s->cert->key->privatekey != NULL) &&
1257                                  *     (s->cert->key->privatekey->type ==
1258                                  *      EVP_PKEY_EC) && ...)
1259                                  * ecdh_clnt_cert = 1;
1260                                  */
1261                                 }
1262
1263                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
1264                                 {
1265                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
1266                                 }
1267                         else
1268                                 {
1269                                 /* Get the Server Public Key from Cert */
1270                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
1271                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1272                                 if ((srvr_pub_pkey == NULL) ||
1273                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
1274                                     (srvr_pub_pkey->pkey.ec == NULL))
1275                                         {
1276                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1277                                             ERR_R_INTERNAL_ERROR);
1278                                         goto err;
1279                                         }
1280
1281                                 tkey = srvr_pub_pkey->pkey.ec;
1282                                 }
1283
1284                         srvr_group   = EC_KEY_get0_group(tkey);
1285                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
1286
1287                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
1288                                 {
1289                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1290                                     ERR_R_INTERNAL_ERROR);
1291                                 goto err;
1292                                 }
1293
1294                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
1295                                 {
1296                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1297                                 goto err;
1298                                 }
1299
1300                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
1301                                 {
1302                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1303                                 goto err;
1304                                 }
1305                         if (ecdh_clnt_cert) 
1306                                 { 
1307                                 /* Reuse key info from our certificate
1308                                  * We only need our private key to perform
1309                                  * the ECDH computation.
1310                                  */
1311                                 const BIGNUM *priv_key;
1312                                 tkey = s->cert->key->privatekey->pkey.ec;
1313                                 priv_key = EC_KEY_get0_private_key(tkey);
1314                                 if (priv_key == NULL)
1315                                         {
1316                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1317                                         goto err;
1318                                         }
1319                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
1320                                         {
1321                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
1322                                         goto err;
1323                                         }
1324                                 }
1325                         else 
1326                                 {
1327                                 /* Generate a new ECDH key pair */
1328                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
1329                                         {
1330                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1331                                         goto err;
1332                                         }
1333                                 }
1334
1335                         /* use the 'p' output buffer for the ECDH key, but
1336                          * make sure to clear it out afterwards
1337                          */
1338
1339                         field_size = EC_GROUP_get_degree(srvr_group);
1340                         if (field_size <= 0)
1341                                 {
1342                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1343                                        ERR_R_ECDH_LIB);
1344                                 goto err;
1345                                 }
1346                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
1347                         if (n <= 0)
1348                                 {
1349                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE, 
1350                                        ERR_R_ECDH_LIB);
1351                                 goto err;
1352                                 }
1353
1354                         /* generate master key from the result */
1355                         s->session->master_key_length = s->method->ssl3_enc \
1356                             -> generate_master_secret(s, 
1357                                 s->session->master_key,
1358                                 p, n);
1359
1360                         memset(p, 0, n); /* clean up */
1361
1362                         if (ecdh_clnt_cert) 
1363                                 {
1364                                 /* Send empty client key exch message */
1365                                 n = 0;
1366                                 }
1367                         else 
1368                                 {
1369                                 /* First check the size of encoding and
1370                                  * allocate memory accordingly.
1371                                  */
1372                                 encoded_pt_len = 
1373                                     EC_POINT_point2oct(srvr_group, 
1374                                         EC_KEY_get0_public_key(clnt_ecdh), 
1375                                         POINT_CONVERSION_UNCOMPRESSED, 
1376                                         NULL, 0, NULL);
1377
1378                                 encodedPoint = (unsigned char *) 
1379                                     OPENSSL_malloc(encoded_pt_len * 
1380                                         sizeof(unsigned char)); 
1381                                 bn_ctx = BN_CTX_new();
1382                                 if ((encodedPoint == NULL) || 
1383                                     (bn_ctx == NULL)) 
1384                                         {
1385                                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1386                                         goto err;
1387                                         }
1388
1389                                 /* Encode the public key */
1390                                 n = EC_POINT_point2oct(srvr_group, 
1391                                     EC_KEY_get0_public_key(clnt_ecdh), 
1392                                     POINT_CONVERSION_UNCOMPRESSED, 
1393                                     encodedPoint, encoded_pt_len, bn_ctx);
1394
1395                                 *p = n; /* length of encoded point */
1396                                 /* Encoded point will be copied here */
1397                                 p += 1; 
1398                                 /* copy the point */
1399                                 memcpy((unsigned char *)p, encodedPoint, n);
1400                                 /* increment n to account for length field */
1401                                 n += 1; 
1402                                 }
1403
1404                         /* Free allocated memory */
1405                         BN_CTX_free(bn_ctx);
1406                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1407                         if (clnt_ecdh != NULL) 
1408                                  EC_KEY_free(clnt_ecdh);
1409                         EVP_PKEY_free(srvr_pub_pkey);
1410                         }
1411 #endif /* !OPENSSL_NO_ECDH */
1412
1413 #ifndef OPENSSL_NO_PSK
1414                 else if (alg_k & SSL_kPSK)
1415                         {
1416                         char identity[PSK_MAX_IDENTITY_LEN];
1417                         unsigned char *t = NULL;
1418                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
1419                         unsigned int pre_ms_len = 0, psk_len = 0;
1420                         int psk_err = 1;
1421
1422                         n = 0;
1423                         if (s->psk_client_callback == NULL)
1424                                 {
1425                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1426                                         SSL_R_PSK_NO_CLIENT_CB);
1427                                 goto err;
1428                                 }
1429
1430                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
1431                                 identity, PSK_MAX_IDENTITY_LEN,
1432                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
1433                         if (psk_len > PSK_MAX_PSK_LEN)
1434                                 {
1435                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1436                                         ERR_R_INTERNAL_ERROR);
1437                                 goto psk_err;
1438                                 }
1439                         else if (psk_len == 0)
1440                                 {
1441                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1442                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
1443                                 goto psk_err;
1444                                 }
1445
1446                         /* create PSK pre_master_secret */
1447                         pre_ms_len = 2+psk_len+2+psk_len;
1448                         t = psk_or_pre_ms;
1449                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
1450                         s2n(psk_len, t);
1451                         memset(t, 0, psk_len);
1452                         t+=psk_len;
1453                         s2n(psk_len, t);
1454
1455                         if (s->session->psk_identity_hint != NULL)
1456                                 OPENSSL_free(s->session->psk_identity_hint);
1457                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
1458                         if (s->ctx->psk_identity_hint != NULL &&
1459                                 s->session->psk_identity_hint == NULL)
1460                                 {
1461                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1462                                         ERR_R_MALLOC_FAILURE);
1463                                 goto psk_err;
1464                                 }
1465
1466                         if (s->session->psk_identity != NULL)
1467                                 OPENSSL_free(s->session->psk_identity);
1468                         s->session->psk_identity = BUF_strdup(identity);
1469                         if (s->session->psk_identity == NULL)
1470                                 {
1471                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,
1472                                         ERR_R_MALLOC_FAILURE);
1473                                 goto psk_err;
1474                                 }
1475
1476                         s->session->master_key_length =
1477                                 s->method->ssl3_enc->generate_master_secret(s,
1478                                         s->session->master_key,
1479                                         psk_or_pre_ms, pre_ms_len); 
1480                         n = strlen(identity);
1481                         s2n(n, p);
1482                         memcpy(p, identity, n);
1483                         n+=2;
1484                         psk_err = 0;
1485                 psk_err:
1486                         OPENSSL_cleanse(identity, PSK_MAX_IDENTITY_LEN);
1487                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
1488                         if (psk_err != 0)
1489                                 {
1490                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1491                                 goto err;
1492                                 }
1493                         }
1494 #endif
1495                 else
1496                         {
1497                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1498                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1499                         goto err;
1500                         }
1501                 
1502                 d = dtls1_set_message_header(s, d,
1503                 SSL3_MT_CLIENT_KEY_EXCHANGE, n, 0, n);
1504                 /*
1505                  *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
1506                  l2n3(n,d);
1507                  l2n(s->d1->handshake_write_seq,d);
1508                  s->d1->handshake_write_seq++;
1509                 */
1510                 
1511                 s->state=SSL3_ST_CW_KEY_EXCH_B;
1512                 /* number of bytes to write */
1513                 s->init_num=n+DTLS1_HM_HEADER_LENGTH;
1514                 s->init_off=0;
1515
1516                 /* buffer the message to handle re-xmits */
1517                 dtls1_buffer_message(s, 0);
1518                 }
1519         
1520         /* SSL3_ST_CW_KEY_EXCH_B */
1521         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1522 err:
1523 #ifndef OPENSSL_NO_ECDH
1524         BN_CTX_free(bn_ctx);
1525         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1526         if (clnt_ecdh != NULL) 
1527                 EC_KEY_free(clnt_ecdh);
1528         EVP_PKEY_free(srvr_pub_pkey);
1529 #endif
1530         return(-1);
1531         }
1532
1533 int dtls1_send_client_verify(SSL *s)
1534         {
1535         unsigned char *p,*d;
1536         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1537         EVP_PKEY *pkey;
1538 #ifndef OPENSSL_NO_RSA
1539         unsigned u=0;
1540 #endif
1541         unsigned long n;
1542 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
1543         int j;
1544 #endif
1545
1546         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
1547                 {
1548                 d=(unsigned char *)s->init_buf->data;
1549                 p= &(d[DTLS1_HM_HEADER_LENGTH]);
1550                 pkey=s->cert->key->privatekey;
1551
1552                 s->method->ssl3_enc->cert_verify_mac(s,
1553                 NID_sha1,
1554                         &(data[MD5_DIGEST_LENGTH]));
1555
1556 #ifndef OPENSSL_NO_RSA
1557                 if (pkey->type == EVP_PKEY_RSA)
1558                         {
1559                         s->method->ssl3_enc->cert_verify_mac(s,
1560                                 NID_md5,
1561                                 &(data[0]));
1562                         if (RSA_sign(NID_md5_sha1, data,
1563                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
1564                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
1565                                 {
1566                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
1567                                 goto err;
1568                                 }
1569                         s2n(u,p);
1570                         n=u+2;
1571                         }
1572                 else
1573 #endif
1574 #ifndef OPENSSL_NO_DSA
1575                         if (pkey->type == EVP_PKEY_DSA)
1576                         {
1577                         if (!DSA_sign(pkey->save_type,
1578                                 &(data[MD5_DIGEST_LENGTH]),
1579                                 SHA_DIGEST_LENGTH,&(p[2]),
1580                                 (unsigned int *)&j,pkey->pkey.dsa))
1581                                 {
1582                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
1583                                 goto err;
1584                                 }
1585                         s2n(j,p);
1586                         n=j+2;
1587                         }
1588                 else
1589 #endif
1590 #ifndef OPENSSL_NO_ECDSA
1591                         if (pkey->type == EVP_PKEY_EC)
1592                         {
1593                         if (!ECDSA_sign(pkey->save_type,
1594                                 &(data[MD5_DIGEST_LENGTH]),
1595                                 SHA_DIGEST_LENGTH,&(p[2]),
1596                                 (unsigned int *)&j,pkey->pkey.ec))
1597                                 {
1598                                 SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,
1599                                     ERR_R_ECDSA_LIB);
1600                                 goto err;
1601                                 }
1602                         s2n(j,p);
1603                         n=j+2;
1604                         }
1605                 else
1606 #endif
1607                         {
1608                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
1609                         goto err;
1610                         }
1611
1612                 d = dtls1_set_message_header(s, d,
1613                         SSL3_MT_CERTIFICATE_VERIFY, n, 0, n) ;
1614
1615                 s->init_num=(int)n+DTLS1_HM_HEADER_LENGTH;
1616                 s->init_off=0;
1617
1618                 /* buffer the message to handle re-xmits */
1619                 dtls1_buffer_message(s, 0);
1620
1621                 s->state = SSL3_ST_CW_CERT_VRFY_B;
1622                 }
1623
1624         /* s->state = SSL3_ST_CW_CERT_VRFY_B */
1625         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1626 err:
1627         return(-1);
1628         }
1629
1630 int dtls1_send_client_certificate(SSL *s)
1631         {
1632         X509 *x509=NULL;
1633         EVP_PKEY *pkey=NULL;
1634         int i;
1635         unsigned long l;
1636
1637         if (s->state == SSL3_ST_CW_CERT_A)
1638                 {
1639                 if ((s->cert == NULL) ||
1640                         (s->cert->key->x509 == NULL) ||
1641                         (s->cert->key->privatekey == NULL))
1642                         s->state=SSL3_ST_CW_CERT_B;
1643                 else
1644                         s->state=SSL3_ST_CW_CERT_C;
1645                 }
1646
1647         /* We need to get a client cert */
1648         if (s->state == SSL3_ST_CW_CERT_B)
1649                 {
1650                 /* If we get an error, we need to
1651                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
1652                  * We then get retied later */
1653                 i=0;
1654                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
1655                 if (i < 0)
1656                         {
1657                         s->rwstate=SSL_X509_LOOKUP;
1658                         return(-1);
1659                         }
1660                 s->rwstate=SSL_NOTHING;
1661                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
1662                         {
1663                         s->state=SSL3_ST_CW_CERT_B;
1664                         if (    !SSL_use_certificate(s,x509) ||
1665                                 !SSL_use_PrivateKey(s,pkey))
1666                                 i=0;
1667                         }
1668                 else if (i == 1)
1669                         {
1670                         i=0;
1671                         SSLerr(SSL_F_DTLS1_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
1672                         }
1673
1674                 if (x509 != NULL) X509_free(x509);
1675                 if (pkey != NULL) EVP_PKEY_free(pkey);
1676                 if (i == 0)
1677                         {
1678                         if (s->version == SSL3_VERSION)
1679                                 {
1680                                 s->s3->tmp.cert_req=0;
1681                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
1682                                 return(1);
1683                                 }
1684                         else
1685                                 {
1686                                 s->s3->tmp.cert_req=2;
1687                                 }
1688                         }
1689
1690                 /* Ok, we have a cert */
1691                 s->state=SSL3_ST_CW_CERT_C;
1692                 }
1693
1694         if (s->state == SSL3_ST_CW_CERT_C)
1695                 {
1696                 s->state=SSL3_ST_CW_CERT_D;
1697                 l=dtls1_output_cert_chain(s,
1698                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
1699                 s->init_num=(int)l;
1700                 s->init_off=0;
1701
1702                 /* set header called by dtls1_output_cert_chain() */
1703
1704                 /* buffer the message to handle re-xmits */
1705                 dtls1_buffer_message(s, 0);
1706                 }
1707         /* SSL3_ST_CW_CERT_D */
1708         return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
1709         }
1710
1711