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