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