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