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