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