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