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