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