Fix unsigned/signed warnings
[openssl.git] / ssl / d1_srvr.c
1 /* ssl/d1_srvr.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 #include <openssl/buffer.h>
119 #include <openssl/rand.h>
120 #include <openssl/objects.h>
121 #include <openssl/evp.h>
122 #include <openssl/x509.h>
123 #include <openssl/md5.h>
124 #include <openssl/bn.h>
125 #ifndef OPENSSL_NO_DH
126 # include <openssl/dh.h>
127 #endif
128
129 static const SSL_METHOD *dtls1_get_server_method(int ver);
130 static int dtls1_send_hello_verify_request(SSL *s);
131
132 static const SSL_METHOD *dtls1_get_server_method(int ver)
133 {
134     if (ver == DTLS1_VERSION)
135         return (DTLSv1_server_method());
136     else
137         return (NULL);
138 }
139
140 IMPLEMENT_dtls1_meth_func(DTLSv1_server_method,
141                           dtls1_accept,
142                           ssl_undefined_function, dtls1_get_server_method)
143
144 int dtls1_accept(SSL *s)
145 {
146     BUF_MEM *buf;
147     unsigned long Time = (unsigned long)time(NULL);
148     void (*cb) (const SSL *ssl, int type, int val) = NULL;
149     unsigned long alg_k;
150     int ret = -1;
151     int new_state, state, skip = 0;
152     int listen;
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     listen = s->d1->listen;
168
169     /* init things to blank */
170     s->in_handshake++;
171     if (!SSL_in_init(s) || SSL_in_before(s))
172         SSL_clear(s);
173
174     s->d1->listen = listen;
175 #ifndef OPENSSL_NO_SCTP
176     /*
177      * Notify SCTP BIO socket to enter handshake mode and prevent stream
178      * identifier other than 0. Will be ignored if no SCTP is used.
179      */
180     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
181              s->in_handshake, NULL);
182 #endif
183
184     if (s->cert == NULL) {
185         SSLerr(SSL_F_DTLS1_ACCEPT, SSL_R_NO_CERTIFICATE_SET);
186         return (-1);
187     }
188 #ifndef OPENSSL_NO_HEARTBEATS
189     /*
190      * If we're awaiting a HeartbeatResponse, pretend we already got and
191      * don't await it anymore, because Heartbeats don't make sense during
192      * handshakes anyway.
193      */
194     if (s->tlsext_hb_pending) {
195         dtls1_stop_timer(s);
196         s->tlsext_hb_pending = 0;
197         s->tlsext_hb_seq++;
198     }
199 #endif
200
201     for (;;) {
202         state = s->state;
203
204         switch (s->state) {
205         case SSL_ST_RENEGOTIATE:
206             s->renegotiate = 1;
207             /* s->state=SSL_ST_ACCEPT; */
208
209         case SSL_ST_BEFORE:
210         case SSL_ST_ACCEPT:
211         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
212         case SSL_ST_OK | SSL_ST_ACCEPT:
213
214             s->server = 1;
215             if (cb != NULL)
216                 cb(s, SSL_CB_HANDSHAKE_START, 1);
217
218             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
219                 SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR);
220                 return -1;
221             }
222             s->type = SSL_ST_ACCEPT;
223
224             if (s->init_buf == NULL) {
225                 if ((buf = BUF_MEM_new()) == NULL) {
226                     ret = -1;
227                     goto end;
228                 }
229                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
230                     BUF_MEM_free(buf);
231                     ret = -1;
232                     goto end;
233                 }
234                 s->init_buf = buf;
235             }
236
237             if (!ssl3_setup_buffers(s)) {
238                 ret = -1;
239                 goto end;
240             }
241
242             s->init_num = 0;
243             s->d1->change_cipher_spec_ok = 0;
244             /*
245              * Should have been reset by ssl3_get_finished, too.
246              */
247             s->s3->change_cipher_spec = 0;
248
249             if (s->state != SSL_ST_RENEGOTIATE) {
250                 /*
251                  * Ok, we now need to push on a buffering BIO so that the
252                  * output is sent in a way that TCP likes :-) ...but not with
253                  * SCTP :-)
254                  */
255 #ifndef OPENSSL_NO_SCTP
256                 if (!BIO_dgram_is_sctp(SSL_get_wbio(s)))
257 #endif
258                     if (!ssl_init_wbio_buffer(s, 1)) {
259                         ret = -1;
260                         goto end;
261                     }
262
263                 ssl3_init_finished_mac(s);
264                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
265                 s->ctx->stats.sess_accept++;
266             } else {
267                 /*
268                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
269                  * HelloRequest
270                  */
271                 s->ctx->stats.sess_accept_renegotiate++;
272                 s->state = SSL3_ST_SW_HELLO_REQ_A;
273             }
274
275             break;
276
277         case SSL3_ST_SW_HELLO_REQ_A:
278         case SSL3_ST_SW_HELLO_REQ_B:
279
280             s->shutdown = 0;
281             dtls1_clear_record_buffer(s);
282             dtls1_start_timer(s);
283             ret = dtls1_send_hello_request(s);
284             if (ret <= 0)
285                 goto end;
286             s->s3->tmp.next_state = SSL3_ST_SR_CLNT_HELLO_A;
287             s->state = SSL3_ST_SW_FLUSH;
288             s->init_num = 0;
289
290             ssl3_init_finished_mac(s);
291             break;
292
293         case SSL3_ST_SW_HELLO_REQ_C:
294             s->state = SSL_ST_OK;
295             break;
296
297         case SSL3_ST_SR_CLNT_HELLO_A:
298         case SSL3_ST_SR_CLNT_HELLO_B:
299         case SSL3_ST_SR_CLNT_HELLO_C:
300
301             s->shutdown = 0;
302             ret = ssl3_get_client_hello(s);
303             if (ret <= 0)
304                 goto end;
305             dtls1_stop_timer(s);
306
307             if (ret == 1 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
308                 s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A;
309             else
310                 s->state = SSL3_ST_SW_SRVR_HELLO_A;
311
312             s->init_num = 0;
313
314             /*
315              * Reflect ClientHello sequence to remain stateless while
316              * listening
317              */
318             if (listen) {
319                 memcpy(s->s3->write_sequence, s->s3->read_sequence,
320                        sizeof(s->s3->write_sequence));
321             }
322
323             /* If we're just listening, stop here */
324             if (listen && s->state == SSL3_ST_SW_SRVR_HELLO_A) {
325                 ret = 2;
326                 s->d1->listen = 0;
327                 /*
328                  * Set expected sequence numbers to continue the handshake.
329                  */
330                 s->d1->handshake_read_seq = 2;
331                 s->d1->handshake_write_seq = 1;
332                 s->d1->next_handshake_write_seq = 1;
333                 goto end;
334             }
335
336             break;
337
338         case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A:
339         case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B:
340
341             ret = dtls1_send_hello_verify_request(s);
342             if (ret <= 0)
343                 goto end;
344             s->state = SSL3_ST_SW_FLUSH;
345             s->s3->tmp.next_state = SSL3_ST_SR_CLNT_HELLO_A;
346
347             /* HelloVerifyRequest resets Finished MAC */
348             if (s->version != DTLS1_BAD_VER)
349                 ssl3_init_finished_mac(s);
350             break;
351
352 #ifndef OPENSSL_NO_SCTP
353         case DTLS1_SCTP_ST_SR_READ_SOCK:
354
355             if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
356                 s->s3->in_read_app_data = 2;
357                 s->rwstate = SSL_READING;
358                 BIO_clear_retry_flags(SSL_get_rbio(s));
359                 BIO_set_retry_read(SSL_get_rbio(s));
360                 ret = -1;
361                 goto end;
362             }
363
364             s->state = SSL3_ST_SR_FINISHED_A;
365             break;
366
367         case DTLS1_SCTP_ST_SW_WRITE_SOCK:
368             ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
369             if (ret < 0)
370                 goto end;
371
372             if (ret == 0) {
373                 if (s->d1->next_state != SSL_ST_OK) {
374                     s->s3->in_read_app_data = 2;
375                     s->rwstate = SSL_READING;
376                     BIO_clear_retry_flags(SSL_get_rbio(s));
377                     BIO_set_retry_read(SSL_get_rbio(s));
378                     ret = -1;
379                     goto end;
380                 }
381             }
382
383             s->state = s->d1->next_state;
384             break;
385 #endif
386
387         case SSL3_ST_SW_SRVR_HELLO_A:
388         case SSL3_ST_SW_SRVR_HELLO_B:
389             s->renegotiate = 2;
390             dtls1_start_timer(s);
391             ret = dtls1_send_server_hello(s);
392             if (ret <= 0)
393                 goto end;
394
395             if (s->hit) {
396 #ifndef OPENSSL_NO_SCTP
397                 /*
398                  * Add new shared key for SCTP-Auth, will be ignored if no
399                  * SCTP used.
400                  */
401                 snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
402                          DTLS1_SCTP_AUTH_LABEL);
403
404                 SSL_export_keying_material(s, sctpauthkey,
405                                            sizeof(sctpauthkey), labelbuffer,
406                                            sizeof(labelbuffer), NULL, 0, 0);
407
408                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
409                          sizeof(sctpauthkey), sctpauthkey);
410 #endif
411 #ifndef OPENSSL_NO_TLSEXT
412                 if (s->tlsext_ticket_expected)
413                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
414                 else
415                     s->state = SSL3_ST_SW_CHANGE_A;
416 #else
417                 s->state = SSL3_ST_SW_CHANGE_A;
418 #endif
419             } else
420                 s->state = SSL3_ST_SW_CERT_A;
421             s->init_num = 0;
422             break;
423
424         case SSL3_ST_SW_CERT_A:
425         case SSL3_ST_SW_CERT_B:
426             /* Check if it is anon DH or normal PSK */
427             if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
428                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
429                 dtls1_start_timer(s);
430                 ret = dtls1_send_server_certificate(s);
431                 if (ret <= 0)
432                     goto end;
433 #ifndef OPENSSL_NO_TLSEXT
434                 if (s->tlsext_status_expected)
435                     s->state = SSL3_ST_SW_CERT_STATUS_A;
436                 else
437                     s->state = SSL3_ST_SW_KEY_EXCH_A;
438             } else {
439                 skip = 1;
440                 s->state = SSL3_ST_SW_KEY_EXCH_A;
441             }
442 #else
443             } else
444                 skip = 1;
445
446             s->state = SSL3_ST_SW_KEY_EXCH_A;
447 #endif
448             s->init_num = 0;
449             break;
450
451         case SSL3_ST_SW_KEY_EXCH_A:
452         case SSL3_ST_SW_KEY_EXCH_B:
453             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
454
455             /*
456              * clear this, it may get reset by
457              * send_server_key_exchange
458              */
459             s->s3->tmp.use_rsa_tmp = 0;
460
461             /*
462              * only send if a DH key exchange or RSA but we have a sign only
463              * certificate
464              */
465             if (0
466                 /*
467                  * PSK: send ServerKeyExchange if PSK identity hint if
468                  * provided
469                  */
470 #ifndef OPENSSL_NO_PSK
471                 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
472 #endif
473                 || (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd))
474                 || (alg_k & SSL_kEECDH)
475                 || ((alg_k & SSL_kRSA)
476                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
477                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
478                             && EVP_PKEY_size(s->cert->pkeys
479                                              [SSL_PKEY_RSA_ENC].privatekey) *
480                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
481                         )
482                     )
483                 )
484                 ) {
485                 dtls1_start_timer(s);
486                 ret = dtls1_send_server_key_exchange(s);
487                 if (ret <= 0)
488                     goto end;
489             } else
490                 skip = 1;
491
492             s->state = SSL3_ST_SW_CERT_REQ_A;
493             s->init_num = 0;
494             break;
495
496         case SSL3_ST_SW_CERT_REQ_A:
497         case SSL3_ST_SW_CERT_REQ_B:
498             if (                /* don't request cert unless asked for it: */
499                    !(s->verify_mode & SSL_VERIFY_PEER) ||
500                    /*
501                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
502                     * during re-negotiation:
503                     */
504                    ((s->session->peer != NULL) &&
505                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
506                    /*
507                     * never request cert in anonymous ciphersuites (see
508                     * section "Certificate request" in SSL 3 drafts and in
509                     * RFC 2246):
510                     */
511                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
512                     /*
513                      * ... except when the application insists on
514                      * verification (against the specs, but s3_clnt.c accepts
515                      * this for SSL 3)
516                      */
517                     !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
518                    /*
519                     * never request cert in Kerberos ciphersuites
520                     */
521                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
522                    /*
523                     * With normal PSK Certificates and Certificate Requests
524                     * are omitted
525                     */
526                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
527                 /* no cert request */
528                 skip = 1;
529                 s->s3->tmp.cert_request = 0;
530                 s->state = SSL3_ST_SW_SRVR_DONE_A;
531 #ifndef OPENSSL_NO_SCTP
532                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
533                     s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A;
534                     s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
535                 }
536 #endif
537             } else {
538                 s->s3->tmp.cert_request = 1;
539                 dtls1_start_timer(s);
540                 ret = dtls1_send_certificate_request(s);
541                 if (ret <= 0)
542                     goto end;
543 #ifndef NETSCAPE_HANG_BUG
544                 s->state = SSL3_ST_SW_SRVR_DONE_A;
545 # ifndef OPENSSL_NO_SCTP
546                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
547                     s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A;
548                     s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
549                 }
550 # endif
551 #else
552                 s->state = SSL3_ST_SW_FLUSH;
553                 s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
554 # ifndef OPENSSL_NO_SCTP
555                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
556                     s->d1->next_state = s->s3->tmp.next_state;
557                     s->s3->tmp.next_state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
558                 }
559 # endif
560 #endif
561                 s->init_num = 0;
562             }
563             break;
564
565         case SSL3_ST_SW_SRVR_DONE_A:
566         case SSL3_ST_SW_SRVR_DONE_B:
567             dtls1_start_timer(s);
568             ret = dtls1_send_server_done(s);
569             if (ret <= 0)
570                 goto end;
571             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
572             s->state = SSL3_ST_SW_FLUSH;
573             s->init_num = 0;
574             break;
575
576         case SSL3_ST_SW_FLUSH:
577             s->rwstate = SSL_WRITING;
578             if (BIO_flush(s->wbio) <= 0) {
579                 /*
580                  * If the write error was fatal, stop trying
581                  */
582                 if (!BIO_should_retry(s->wbio)) {
583                     s->rwstate = SSL_NOTHING;
584                     s->state = s->s3->tmp.next_state;
585                 }
586
587                 ret = -1;
588                 goto end;
589             }
590             s->rwstate = SSL_NOTHING;
591             s->state = s->s3->tmp.next_state;
592             break;
593
594         case SSL3_ST_SR_CERT_A:
595         case SSL3_ST_SR_CERT_B:
596             /* Check for second client hello (MS SGC) */
597             ret = ssl3_check_client_hello(s);
598             if (ret <= 0)
599                 goto end;
600             if (ret == 2) {
601                 dtls1_stop_timer(s);
602                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
603             } else {
604                 if (s->s3->tmp.cert_request) {
605                     ret = ssl3_get_client_certificate(s);
606                     if (ret <= 0)
607                         goto end;
608                 }
609                 s->init_num = 0;
610                 s->state = SSL3_ST_SR_KEY_EXCH_A;
611             }
612             break;
613
614         case SSL3_ST_SR_KEY_EXCH_A:
615         case SSL3_ST_SR_KEY_EXCH_B:
616             ret = ssl3_get_client_key_exchange(s);
617             if (ret <= 0)
618                 goto end;
619 #ifndef OPENSSL_NO_SCTP
620             /*
621              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
622              * used.
623              */
624             snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
625                      DTLS1_SCTP_AUTH_LABEL);
626
627             SSL_export_keying_material(s, sctpauthkey,
628                                        sizeof(sctpauthkey), labelbuffer,
629                                        sizeof(labelbuffer), NULL, 0, 0);
630
631             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
632                      sizeof(sctpauthkey), sctpauthkey);
633 #endif
634
635             s->state = SSL3_ST_SR_CERT_VRFY_A;
636             s->init_num = 0;
637
638             if (ret == 2) {
639                 /*
640                  * For the ECDH ciphersuites when the client sends its ECDH
641                  * pub key in a certificate, the CertificateVerify message is
642                  * not sent.
643                  */
644                 s->state = SSL3_ST_SR_FINISHED_A;
645                 s->init_num = 0;
646             } else {
647                 s->state = SSL3_ST_SR_CERT_VRFY_A;
648                 s->init_num = 0;
649
650                 /*
651                  * We need to get hashes here so if there is a client cert,
652                  * it can be verified
653                  */
654                 s->method->ssl3_enc->cert_verify_mac(s,
655                                                      NID_md5,
656                                                      &(s->s3->
657                                                        tmp.cert_verify_md
658                                                        [0]));
659                 s->method->ssl3_enc->cert_verify_mac(s, NID_sha1,
660                                                      &(s->s3->
661                                                        tmp.cert_verify_md
662                                                        [MD5_DIGEST_LENGTH]));
663             }
664             break;
665
666         case SSL3_ST_SR_CERT_VRFY_A:
667         case SSL3_ST_SR_CERT_VRFY_B:
668             /*
669              * This *should* be the first time we enable CCS, but be
670              * extra careful about surrounding code changes. We need
671              * to set this here because we don't know if we're
672              * expecting a CertificateVerify or not.
673              */
674             if (!s->s3->change_cipher_spec)
675                 s->d1->change_cipher_spec_ok = 1;
676             /* we should decide if we expected this one */
677             ret = ssl3_get_cert_verify(s);
678             if (ret <= 0)
679                 goto end;
680 #ifndef OPENSSL_NO_SCTP
681             if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
682                 state == SSL_ST_RENEGOTIATE)
683                 s->state = DTLS1_SCTP_ST_SR_READ_SOCK;
684             else
685 #endif
686                 s->state = SSL3_ST_SR_FINISHED_A;
687             s->init_num = 0;
688             break;
689
690         case SSL3_ST_SR_FINISHED_A:
691         case SSL3_ST_SR_FINISHED_B:
692             /*
693              * Enable CCS for resumed handshakes.
694              * In a full handshake, we end up here through
695              * SSL3_ST_SR_CERT_VRFY_B, so change_cipher_spec_ok was
696              * already set. Receiving a CCS clears the flag, so make
697              * sure not to re-enable it to ban duplicates.
698              * s->s3->change_cipher_spec is set when a CCS is
699              * processed in d1_pkt.c, and remains set until
700              * the client's Finished message is read.
701              */
702             if (!s->s3->change_cipher_spec)
703                 s->d1->change_cipher_spec_ok = 1;
704             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
705                                     SSL3_ST_SR_FINISHED_B);
706             if (ret <= 0)
707                 goto end;
708             dtls1_stop_timer(s);
709             if (s->hit)
710                 s->state = SSL_ST_OK;
711 #ifndef OPENSSL_NO_TLSEXT
712             else if (s->tlsext_ticket_expected)
713                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
714 #endif
715             else
716                 s->state = SSL3_ST_SW_CHANGE_A;
717             s->init_num = 0;
718             break;
719
720 #ifndef OPENSSL_NO_TLSEXT
721         case SSL3_ST_SW_SESSION_TICKET_A:
722         case SSL3_ST_SW_SESSION_TICKET_B:
723             ret = dtls1_send_newsession_ticket(s);
724             if (ret <= 0)
725                 goto end;
726             s->state = SSL3_ST_SW_CHANGE_A;
727             s->init_num = 0;
728             break;
729
730         case SSL3_ST_SW_CERT_STATUS_A:
731         case SSL3_ST_SW_CERT_STATUS_B:
732             ret = ssl3_send_cert_status(s);
733             if (ret <= 0)
734                 goto end;
735             s->state = SSL3_ST_SW_KEY_EXCH_A;
736             s->init_num = 0;
737             break;
738
739 #endif
740
741         case SSL3_ST_SW_CHANGE_A:
742         case SSL3_ST_SW_CHANGE_B:
743
744             s->session->cipher = s->s3->tmp.new_cipher;
745             if (!s->method->ssl3_enc->setup_key_block(s)) {
746                 ret = -1;
747                 goto end;
748             }
749
750             ret = dtls1_send_change_cipher_spec(s,
751                                                 SSL3_ST_SW_CHANGE_A,
752                                                 SSL3_ST_SW_CHANGE_B);
753
754             if (ret <= 0)
755                 goto end;
756
757 #ifndef OPENSSL_NO_SCTP
758             if (!s->hit) {
759                 /*
760                  * Change to new shared key of SCTP-Auth, will be ignored if
761                  * no SCTP used.
762                  */
763                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
764                          0, NULL);
765             }
766 #endif
767
768             s->state = SSL3_ST_SW_FINISHED_A;
769             s->init_num = 0;
770
771             if (!s->method->ssl3_enc->change_cipher_state(s,
772                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
773             {
774                 ret = -1;
775                 goto end;
776             }
777
778             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
779             break;
780
781         case SSL3_ST_SW_FINISHED_A:
782         case SSL3_ST_SW_FINISHED_B:
783             ret = dtls1_send_finished(s,
784                                       SSL3_ST_SW_FINISHED_A,
785                                       SSL3_ST_SW_FINISHED_B,
786                                       s->method->
787                                       ssl3_enc->server_finished_label,
788                                       s->method->
789                                       ssl3_enc->server_finished_label_len);
790             if (ret <= 0)
791                 goto end;
792             s->state = SSL3_ST_SW_FLUSH;
793             if (s->hit) {
794                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
795
796 #ifndef OPENSSL_NO_SCTP
797                 /*
798                  * Change to new shared key of SCTP-Auth, will be ignored if
799                  * no SCTP used.
800                  */
801                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
802                          0, NULL);
803 #endif
804             } else {
805                 s->s3->tmp.next_state = SSL_ST_OK;
806 #ifndef OPENSSL_NO_SCTP
807                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
808                     s->d1->next_state = s->s3->tmp.next_state;
809                     s->s3->tmp.next_state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
810                 }
811 #endif
812             }
813             s->init_num = 0;
814             break;
815
816         case SSL_ST_OK:
817             /* clean a few things up */
818             ssl3_cleanup_key_block(s);
819
820 #if 0
821             BUF_MEM_free(s->init_buf);
822             s->init_buf = NULL;
823 #endif
824
825             /* remove buffering on output */
826             ssl_free_wbio_buffer(s);
827
828             s->init_num = 0;
829
830             if (s->renegotiate == 2) { /* skipped if we just sent a
831                                         * HelloRequest */
832                 s->renegotiate = 0;
833                 s->new_session = 0;
834
835                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
836
837                 s->ctx->stats.sess_accept_good++;
838                 /* s->server=1; */
839                 s->handshake_func = dtls1_accept;
840
841                 if (cb != NULL)
842                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
843             }
844
845             ret = 1;
846
847             /* done handshaking, next message is client hello */
848             s->d1->handshake_read_seq = 0;
849             /* next message is server hello */
850             s->d1->handshake_write_seq = 0;
851             s->d1->next_handshake_write_seq = 0;
852             goto end;
853             /* break; */
854
855         default:
856             SSLerr(SSL_F_DTLS1_ACCEPT, SSL_R_UNKNOWN_STATE);
857             ret = -1;
858             goto end;
859             /* break; */
860         }
861
862         if (!s->s3->tmp.reuse_message && !skip) {
863             if (s->debug) {
864                 if ((ret = BIO_flush(s->wbio)) <= 0)
865                     goto end;
866             }
867
868             if ((cb != NULL) && (s->state != state)) {
869                 new_state = s->state;
870                 s->state = state;
871                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
872                 s->state = new_state;
873             }
874         }
875         skip = 0;
876     }
877  end:
878     /* BIO_flush(s->wbio); */
879
880     s->in_handshake--;
881 #ifndef OPENSSL_NO_SCTP
882     /*
883      * Notify SCTP BIO socket to leave handshake mode and prevent stream
884      * identifier other than 0. Will be ignored if no SCTP is used.
885      */
886     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
887              s->in_handshake, NULL);
888 #endif
889
890     if (cb != NULL)
891         cb(s, SSL_CB_ACCEPT_EXIT, ret);
892     return (ret);
893 }
894
895 int dtls1_send_hello_request(SSL *s)
896 {
897     unsigned char *p;
898
899     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
900         p = (unsigned char *)s->init_buf->data;
901         p = dtls1_set_message_header(s, p, SSL3_MT_HELLO_REQUEST, 0, 0, 0);
902
903         s->state = SSL3_ST_SW_HELLO_REQ_B;
904         /* number of bytes to write */
905         s->init_num = DTLS1_HM_HEADER_LENGTH;
906         s->init_off = 0;
907
908         /*
909          * no need to buffer this message, since there are no retransmit
910          * requests for it
911          */
912     }
913
914     /* SSL3_ST_SW_HELLO_REQ_B */
915     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
916 }
917
918 int dtls1_send_hello_verify_request(SSL *s)
919 {
920     unsigned int msg_len;
921     unsigned char *msg, *buf, *p;
922
923     if (s->state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) {
924         buf = (unsigned char *)s->init_buf->data;
925
926         msg = p = &(buf[DTLS1_HM_HEADER_LENGTH]);
927         *(p++) = s->version >> 8;
928         *(p++) = s->version & 0xFF;
929
930         if (s->ctx->app_gen_cookie_cb == NULL ||
931             s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
932                                       &(s->d1->cookie_len)) == 0) {
933             SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,
934                    ERR_R_INTERNAL_ERROR);
935             return 0;
936         }
937
938         *(p++) = (unsigned char)s->d1->cookie_len;
939         memcpy(p, s->d1->cookie, s->d1->cookie_len);
940         p += s->d1->cookie_len;
941         msg_len = p - msg;
942
943         dtls1_set_message_header(s, buf,
944                                  DTLS1_MT_HELLO_VERIFY_REQUEST, msg_len, 0,
945                                  msg_len);
946
947         s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B;
948         /* number of bytes to write */
949         s->init_num = p - buf;
950         s->init_off = 0;
951     }
952
953     /* s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */
954     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
955 }
956
957 int dtls1_send_server_hello(SSL *s)
958 {
959     unsigned char *buf;
960     unsigned char *p, *d;
961     int i;
962     unsigned int sl;
963     unsigned long l;
964
965     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
966         buf = (unsigned char *)s->init_buf->data;
967         p = s->s3->server_random;
968         ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE);
969         /* Do the message type and length last */
970         d = p = &(buf[DTLS1_HM_HEADER_LENGTH]);
971
972         *(p++) = s->version >> 8;
973         *(p++) = s->version & 0xff;
974
975         /* Random stuff */
976         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
977         p += SSL3_RANDOM_SIZE;
978
979         /*
980          * now in theory we have 3 options to sending back the session id.
981          * If it is a re-use, we send back the old session-id, if it is a new
982          * session, we send back the new session-id or we send back a 0
983          * length session-id if we want it to be single use. Currently I will
984          * not implement the '0' length session-id 12-Jan-98 - I'll now
985          * support the '0' length stuff.
986          */
987         if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER))
988             s->session->session_id_length = 0;
989
990         sl = s->session->session_id_length;
991         if (sl > sizeof s->session->session_id) {
992             SSLerr(SSL_F_DTLS1_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
993             return -1;
994         }
995         *(p++) = sl;
996         memcpy(p, s->session->session_id, sl);
997         p += sl;
998
999         /* put the cipher */
1000         if (s->s3->tmp.new_cipher == NULL)
1001             return -1;
1002         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1003         p += i;
1004
1005         /* put the compression method */
1006 #ifdef OPENSSL_NO_COMP
1007         *(p++) = 0;
1008 #else
1009         if (s->s3->tmp.new_compression == NULL)
1010             *(p++) = 0;
1011         else
1012             *(p++) = s->s3->tmp.new_compression->id;
1013 #endif
1014
1015 #ifndef OPENSSL_NO_TLSEXT
1016         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1017             SSLerr(SSL_F_DTLS1_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1018             return -1;
1019         }
1020         if ((p =
1021              ssl_add_serverhello_tlsext(s, p,
1022                                         buf + SSL3_RT_MAX_PLAIN_LENGTH)) ==
1023             NULL) {
1024             SSLerr(SSL_F_DTLS1_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1025             return -1;
1026         }
1027 #endif
1028
1029         /* do the header */
1030         l = (p - d);
1031         d = buf;
1032
1033         d = dtls1_set_message_header(s, d, SSL3_MT_SERVER_HELLO, l, 0, l);
1034
1035         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1036         /* number of bytes to write */
1037         s->init_num = p - buf;
1038         s->init_off = 0;
1039
1040         /* buffer the message to handle re-xmits */
1041         dtls1_buffer_message(s, 0);
1042     }
1043
1044     /* SSL3_ST_SW_SRVR_HELLO_B */
1045     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1046 }
1047
1048 int dtls1_send_server_done(SSL *s)
1049 {
1050     unsigned char *p;
1051
1052     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1053         p = (unsigned char *)s->init_buf->data;
1054
1055         /* do the header */
1056         p = dtls1_set_message_header(s, p, SSL3_MT_SERVER_DONE, 0, 0, 0);
1057
1058         s->state = SSL3_ST_SW_SRVR_DONE_B;
1059         /* number of bytes to write */
1060         s->init_num = DTLS1_HM_HEADER_LENGTH;
1061         s->init_off = 0;
1062
1063         /* buffer the message to handle re-xmits */
1064         dtls1_buffer_message(s, 0);
1065     }
1066
1067     /* SSL3_ST_SW_SRVR_DONE_B */
1068     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1069 }
1070
1071 int dtls1_send_server_key_exchange(SSL *s)
1072 {
1073 #ifndef OPENSSL_NO_RSA
1074     unsigned char *q;
1075     int j, num;
1076     RSA *rsa;
1077     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1078     unsigned int u;
1079 #endif
1080 #ifndef OPENSSL_NO_DH
1081     DH *dh = NULL, *dhp;
1082 #endif
1083 #ifndef OPENSSL_NO_ECDH
1084     EC_KEY *ecdh = NULL, *ecdhp;
1085     unsigned char *encodedPoint = NULL;
1086     int encodedlen = 0;
1087     int curve_id = 0;
1088     BN_CTX *bn_ctx = NULL;
1089 #endif
1090     EVP_PKEY *pkey;
1091     unsigned char *p, *d;
1092     int al, i;
1093     unsigned long type;
1094     int n;
1095     CERT *cert;
1096     BIGNUM *r[4];
1097     int nr[4], kn;
1098     BUF_MEM *buf;
1099     EVP_MD_CTX md_ctx;
1100
1101     EVP_MD_CTX_init(&md_ctx);
1102     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1103         type = s->s3->tmp.new_cipher->algorithm_mkey;
1104         cert = s->cert;
1105
1106         buf = s->init_buf;
1107
1108         r[0] = r[1] = r[2] = r[3] = NULL;
1109         n = 0;
1110 #ifndef OPENSSL_NO_RSA
1111         if (type & SSL_kRSA) {
1112             rsa = cert->rsa_tmp;
1113             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1114                 rsa = s->cert->rsa_tmp_cb(s,
1115                                           SSL_C_IS_EXPORT(s->s3->
1116                                                           tmp.new_cipher),
1117                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1118                                                                   tmp.new_cipher));
1119                 if (rsa == NULL) {
1120                     al = SSL_AD_HANDSHAKE_FAILURE;
1121                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1122                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1123                     goto f_err;
1124                 }
1125                 RSA_up_ref(rsa);
1126                 cert->rsa_tmp = rsa;
1127             }
1128             if (rsa == NULL) {
1129                 al = SSL_AD_HANDSHAKE_FAILURE;
1130                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1131                        SSL_R_MISSING_TMP_RSA_KEY);
1132                 goto f_err;
1133             }
1134             r[0] = rsa->n;
1135             r[1] = rsa->e;
1136             s->s3->tmp.use_rsa_tmp = 1;
1137         } else
1138 #endif
1139 #ifndef OPENSSL_NO_DH
1140         if (type & SSL_kEDH) {
1141             dhp = cert->dh_tmp;
1142             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1143                 dhp = s->cert->dh_tmp_cb(s,
1144                                          SSL_C_IS_EXPORT(s->s3->
1145                                                          tmp.new_cipher),
1146                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1147                                                                  tmp.new_cipher));
1148             if (dhp == NULL) {
1149                 al = SSL_AD_HANDSHAKE_FAILURE;
1150                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1151                        SSL_R_MISSING_TMP_DH_KEY);
1152                 goto f_err;
1153             }
1154
1155             if (s->s3->tmp.dh != NULL) {
1156                 DH_free(dh);
1157                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1158                        ERR_R_INTERNAL_ERROR);
1159                 goto err;
1160             }
1161
1162             if ((dh = DHparams_dup(dhp)) == NULL) {
1163                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1164                 goto err;
1165             }
1166
1167             s->s3->tmp.dh = dh;
1168             if ((dhp->pub_key == NULL ||
1169                  dhp->priv_key == NULL ||
1170                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1171                 if (!DH_generate_key(dh)) {
1172                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1173                            ERR_R_DH_LIB);
1174                     goto err;
1175                 }
1176             } else {
1177                 dh->pub_key = BN_dup(dhp->pub_key);
1178                 dh->priv_key = BN_dup(dhp->priv_key);
1179                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1180                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1181                            ERR_R_DH_LIB);
1182                     goto err;
1183                 }
1184             }
1185             r[0] = dh->p;
1186             r[1] = dh->g;
1187             r[2] = dh->pub_key;
1188         } else
1189 #endif
1190 #ifndef OPENSSL_NO_ECDH
1191         if (type & SSL_kEECDH) {
1192             const EC_GROUP *group;
1193
1194             ecdhp = cert->ecdh_tmp;
1195             if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL)) {
1196                 ecdhp = s->cert->ecdh_tmp_cb(s,
1197                                              SSL_C_IS_EXPORT(s->s3->
1198                                                              tmp.new_cipher),
1199                                              SSL_C_EXPORT_PKEYLENGTH(s->
1200                                                                      s3->tmp.new_cipher));
1201             }
1202             if (ecdhp == NULL) {
1203                 al = SSL_AD_HANDSHAKE_FAILURE;
1204                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1205                        SSL_R_MISSING_TMP_ECDH_KEY);
1206                 goto f_err;
1207             }
1208
1209             if (s->s3->tmp.ecdh != NULL) {
1210                 EC_KEY_free(s->s3->tmp.ecdh);
1211                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1212                        ERR_R_INTERNAL_ERROR);
1213                 goto err;
1214             }
1215
1216             /* Duplicate the ECDH structure. */
1217             if (ecdhp == NULL) {
1218                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1219                 goto err;
1220             }
1221             if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1222                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1223                 goto err;
1224             }
1225
1226             s->s3->tmp.ecdh = ecdh;
1227             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1228                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1229                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1230                 if (!EC_KEY_generate_key(ecdh)) {
1231                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1232                            ERR_R_ECDH_LIB);
1233                     goto err;
1234                 }
1235             }
1236
1237             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1238                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1239                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1240                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1241                 goto err;
1242             }
1243
1244             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1245                 (EC_GROUP_get_degree(group) > 163)) {
1246                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1247                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1248                 goto err;
1249             }
1250
1251             /*
1252              * XXX: For now, we only support ephemeral ECDH keys over named
1253              * (not generic) curves. For supported named curves, curve_id is
1254              * non-zero.
1255              */
1256             if ((curve_id =
1257                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1258                 == 0) {
1259                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1260                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1261                 goto err;
1262             }
1263
1264             /*
1265              * Encode the public key. First check the size of encoding and
1266              * allocate memory accordingly.
1267              */
1268             encodedlen = EC_POINT_point2oct(group,
1269                                             EC_KEY_get0_public_key(ecdh),
1270                                             POINT_CONVERSION_UNCOMPRESSED,
1271                                             NULL, 0, NULL);
1272
1273             encodedPoint = (unsigned char *)
1274                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1275             bn_ctx = BN_CTX_new();
1276             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1277                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1278                        ERR_R_MALLOC_FAILURE);
1279                 goto err;
1280             }
1281
1282             encodedlen = EC_POINT_point2oct(group,
1283                                             EC_KEY_get0_public_key(ecdh),
1284                                             POINT_CONVERSION_UNCOMPRESSED,
1285                                             encodedPoint, encodedlen, bn_ctx);
1286
1287             if (encodedlen == 0) {
1288                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1289                 goto err;
1290             }
1291
1292             BN_CTX_free(bn_ctx);
1293             bn_ctx = NULL;
1294
1295             /*
1296              * XXX: For now, we only support named (not generic) curves in
1297              * ECDH ephemeral key exchanges. In this situation, we need four
1298              * additional bytes to encode the entire ServerECDHParams
1299              * structure.
1300              */
1301             n = 4 + encodedlen;
1302
1303             /*
1304              * We'll generate the serverKeyExchange message explicitly so we
1305              * can set these to NULLs
1306              */
1307             r[0] = NULL;
1308             r[1] = NULL;
1309             r[2] = NULL;
1310             r[3] = NULL;
1311         } else
1312 #endif                          /* !OPENSSL_NO_ECDH */
1313 #ifndef OPENSSL_NO_PSK
1314         if (type & SSL_kPSK) {
1315             /*
1316              * reserve size for record length and PSK identity hint
1317              */
1318             n += 2 + strlen(s->ctx->psk_identity_hint);
1319         } else
1320 #endif                          /* !OPENSSL_NO_PSK */
1321         {
1322             al = SSL_AD_HANDSHAKE_FAILURE;
1323             SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1324                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1325             goto f_err;
1326         }
1327         for (i = 0; r[i] != NULL; i++) {
1328             nr[i] = BN_num_bytes(r[i]);
1329             n += 2 + nr[i];
1330         }
1331
1332         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1333             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
1334             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, NULL))
1335                 == NULL) {
1336                 al = SSL_AD_DECODE_ERROR;
1337                 goto f_err;
1338             }
1339             kn = EVP_PKEY_size(pkey);
1340         } else {
1341             pkey = NULL;
1342             kn = 0;
1343         }
1344
1345         if (!BUF_MEM_grow_clean(buf, n + DTLS1_HM_HEADER_LENGTH + kn)) {
1346             SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
1347             goto err;
1348         }
1349         d = (unsigned char *)s->init_buf->data;
1350         p = &(d[DTLS1_HM_HEADER_LENGTH]);
1351
1352         for (i = 0; r[i] != NULL; i++) {
1353             s2n(nr[i], p);
1354             BN_bn2bin(r[i], p);
1355             p += nr[i];
1356         }
1357
1358 #ifndef OPENSSL_NO_ECDH
1359         if (type & SSL_kEECDH) {
1360             /*
1361              * XXX: For now, we only support named (not generic) curves. In
1362              * this situation, the serverKeyExchange message has: [1 byte
1363              * CurveType], [2 byte CurveName] [1 byte length of encoded
1364              * point], followed by the actual encoded point itself
1365              */
1366             *p = NAMED_CURVE_TYPE;
1367             p += 1;
1368             *p = 0;
1369             p += 1;
1370             *p = curve_id;
1371             p += 1;
1372             *p = encodedlen;
1373             p += 1;
1374             memcpy((unsigned char *)p,
1375                    (unsigned char *)encodedPoint, encodedlen);
1376             OPENSSL_free(encodedPoint);
1377             encodedPoint = NULL;
1378             p += encodedlen;
1379         }
1380 #endif
1381
1382 #ifndef OPENSSL_NO_PSK
1383         if (type & SSL_kPSK) {
1384             /* copy PSK identity hint */
1385             s2n(strlen(s->ctx->psk_identity_hint), p);
1386             strncpy((char *)p, s->ctx->psk_identity_hint,
1387                     strlen(s->ctx->psk_identity_hint));
1388             p += strlen(s->ctx->psk_identity_hint);
1389         }
1390 #endif
1391
1392         /* not anonymous */
1393         if (pkey != NULL) {
1394             /*
1395              * n is the length of the params, they start at
1396              * &(d[DTLS1_HM_HEADER_LENGTH]) and p points to the space at the
1397              * end.
1398              */
1399 #ifndef OPENSSL_NO_RSA
1400             if (pkey->type == EVP_PKEY_RSA) {
1401                 q = md_buf;
1402                 j = 0;
1403                 for (num = 2; num > 0; num--) {
1404                     EVP_DigestInit_ex(&md_ctx, (num == 2)
1405                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
1406                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
1407                                      SSL3_RANDOM_SIZE);
1408                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
1409                                      SSL3_RANDOM_SIZE);
1410                     EVP_DigestUpdate(&md_ctx, &(d[DTLS1_HM_HEADER_LENGTH]),
1411                                      n);
1412                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1413                     q += i;
1414                     j += i;
1415                 }
1416                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1417                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1418                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
1419                     goto err;
1420                 }
1421                 s2n(u, p);
1422                 n += u + 2;
1423             } else
1424 #endif
1425 #if !defined(OPENSSL_NO_DSA)
1426             if (pkey->type == EVP_PKEY_DSA) {
1427                 /* lets do DSS */
1428                 EVP_SignInit_ex(&md_ctx, EVP_dss1(), NULL);
1429                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1430                                SSL3_RANDOM_SIZE);
1431                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1432                                SSL3_RANDOM_SIZE);
1433                 EVP_SignUpdate(&md_ctx, &(d[DTLS1_HM_HEADER_LENGTH]), n);
1434                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1435                                    (unsigned int *)&i, pkey)) {
1436                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_DSA);
1437                     goto err;
1438                 }
1439                 s2n(i, p);
1440                 n += i + 2;
1441             } else
1442 #endif
1443 #if !defined(OPENSSL_NO_ECDSA)
1444             if (pkey->type == EVP_PKEY_EC) {
1445                 /* let's do ECDSA */
1446                 EVP_SignInit_ex(&md_ctx, EVP_ecdsa(), NULL);
1447                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
1448                                SSL3_RANDOM_SIZE);
1449                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
1450                                SSL3_RANDOM_SIZE);
1451                 EVP_SignUpdate(&md_ctx, &(d[DTLS1_HM_HEADER_LENGTH]), n);
1452                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
1453                                    (unsigned int *)&i, pkey)) {
1454                     SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1455                            ERR_LIB_ECDSA);
1456                     goto err;
1457                 }
1458                 s2n(i, p);
1459                 n += i + 2;
1460             } else
1461 #endif
1462             {
1463                 /* Is this error check actually needed? */
1464                 al = SSL_AD_HANDSHAKE_FAILURE;
1465                 SSLerr(SSL_F_DTLS1_SEND_SERVER_KEY_EXCHANGE,
1466                        SSL_R_UNKNOWN_PKEY_TYPE);
1467                 goto f_err;
1468             }
1469         }
1470
1471         d = dtls1_set_message_header(s, d,
1472                                      SSL3_MT_SERVER_KEY_EXCHANGE, n, 0, n);
1473
1474         /*
1475          * we should now have things packed up, so lets send it off
1476          */
1477         s->init_num = n + DTLS1_HM_HEADER_LENGTH;
1478         s->init_off = 0;
1479
1480         /* buffer the message to handle re-xmits */
1481         dtls1_buffer_message(s, 0);
1482     }
1483
1484     s->state = SSL3_ST_SW_KEY_EXCH_B;
1485     EVP_MD_CTX_cleanup(&md_ctx);
1486     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1487  f_err:
1488     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1489  err:
1490 #ifndef OPENSSL_NO_ECDH
1491     if (encodedPoint != NULL)
1492         OPENSSL_free(encodedPoint);
1493     BN_CTX_free(bn_ctx);
1494 #endif
1495     EVP_MD_CTX_cleanup(&md_ctx);
1496     return (-1);
1497 }
1498
1499 int dtls1_send_certificate_request(SSL *s)
1500 {
1501     unsigned char *p, *d;
1502     int i, j, nl, off, n;
1503     STACK_OF(X509_NAME) *sk = NULL;
1504     X509_NAME *name;
1505     BUF_MEM *buf;
1506     unsigned int msg_len;
1507
1508     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
1509         buf = s->init_buf;
1510
1511         d = p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
1512
1513         /* get the list of acceptable cert types */
1514         p++;
1515         n = ssl3_get_req_cert_type(s, p);
1516         d[0] = n;
1517         p += n;
1518         n++;
1519
1520         off = n;
1521         p += 2;
1522         n += 2;
1523
1524         sk = SSL_get_client_CA_list(s);
1525         nl = 0;
1526         if (sk != NULL) {
1527             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1528                 name = sk_X509_NAME_value(sk, i);
1529                 j = i2d_X509_NAME(name, NULL);
1530                 if (!BUF_MEM_grow_clean
1531                     (buf, DTLS1_HM_HEADER_LENGTH + n + j + 2)) {
1532                     SSLerr(SSL_F_DTLS1_SEND_CERTIFICATE_REQUEST,
1533                            ERR_R_BUF_LIB);
1534                     goto err;
1535                 }
1536                 p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH + n]);
1537                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) {
1538                     s2n(j, p);
1539                     i2d_X509_NAME(name, &p);
1540                     n += 2 + j;
1541                     nl += 2 + j;
1542                 } else {
1543                     d = p;
1544                     i2d_X509_NAME(name, &p);
1545                     j -= 2;
1546                     s2n(j, d);
1547                     j += 2;
1548                     n += j;
1549                     nl += j;
1550                 }
1551             }
1552         }
1553         /* else no CA names */
1554         p = (unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH + off]);
1555         s2n(nl, p);
1556
1557         d = (unsigned char *)buf->data;
1558         *(d++) = SSL3_MT_CERTIFICATE_REQUEST;
1559         l2n3(n, d);
1560         s2n(s->d1->handshake_write_seq, d);
1561         s->d1->handshake_write_seq++;
1562
1563         /*
1564          * we should now have things packed up, so lets send it off
1565          */
1566
1567         s->init_num = n + DTLS1_HM_HEADER_LENGTH;
1568         s->init_off = 0;
1569 #ifdef NETSCAPE_HANG_BUG
1570 /* XXX: what to do about this? */
1571         p = (unsigned char *)s->init_buf->data + s->init_num;
1572
1573         /* do the header */
1574         *(p++) = SSL3_MT_SERVER_DONE;
1575         *(p++) = 0;
1576         *(p++) = 0;
1577         *(p++) = 0;
1578         s->init_num += 4;
1579 #endif
1580
1581         /* XDTLS:  set message header ? */
1582         msg_len = s->init_num - DTLS1_HM_HEADER_LENGTH;
1583         dtls1_set_message_header(s, (void *)s->init_buf->data,
1584                                  SSL3_MT_CERTIFICATE_REQUEST, msg_len, 0,
1585                                  msg_len);
1586
1587         /* buffer the message to handle re-xmits */
1588         dtls1_buffer_message(s, 0);
1589
1590         s->state = SSL3_ST_SW_CERT_REQ_B;
1591     }
1592
1593     /* SSL3_ST_SW_CERT_REQ_B */
1594     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1595  err:
1596     return (-1);
1597 }
1598
1599 int dtls1_send_server_certificate(SSL *s)
1600 {
1601     unsigned long l;
1602     X509 *x;
1603
1604     if (s->state == SSL3_ST_SW_CERT_A) {
1605         x = ssl_get_server_send_cert(s);
1606         if (x == NULL) {
1607             /* VRS: allow null cert if auth == KRB5 */
1608             if ((s->s3->tmp.new_cipher->algorithm_mkey != SSL_kKRB5) ||
1609                 (s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5)) {
1610                 SSLerr(SSL_F_DTLS1_SEND_SERVER_CERTIFICATE,
1611                        ERR_R_INTERNAL_ERROR);
1612                 return (0);
1613             }
1614         }
1615
1616         l = dtls1_output_cert_chain(s, x);
1617         if (!l) {
1618             SSLerr(SSL_F_DTLS1_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
1619             return (0);
1620         }
1621         s->state = SSL3_ST_SW_CERT_B;
1622         s->init_num = (int)l;
1623         s->init_off = 0;
1624
1625         /* buffer the message to handle re-xmits */
1626         dtls1_buffer_message(s, 0);
1627     }
1628
1629     /* SSL3_ST_SW_CERT_B */
1630     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1631 }
1632
1633 #ifndef OPENSSL_NO_TLSEXT
1634 int dtls1_send_newsession_ticket(SSL *s)
1635 {
1636     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
1637         unsigned char *p, *senc, *macstart;
1638         int len, slen;
1639         unsigned int hlen, msg_len;
1640         EVP_CIPHER_CTX ctx;
1641         HMAC_CTX hctx;
1642         SSL_CTX *tctx = s->initial_ctx;
1643         unsigned char iv[EVP_MAX_IV_LENGTH];
1644         unsigned char key_name[16];
1645
1646         /* get session encoding length */
1647         slen = i2d_SSL_SESSION(s->session, NULL);
1648         /*
1649          * Some length values are 16 bits, so forget it if session is too
1650          * long
1651          */
1652         if (slen > 0xFF00)
1653             return -1;
1654         /*
1655          * Grow buffer if need be: the length calculation is as follows 12
1656          * (DTLS handshake message header) + 4 (ticket lifetime hint) + 2
1657          * (ticket length) + 16 (key name) + max_iv_len (iv length) +
1658          * session_length + max_enc_block_size (max encrypted session length)
1659          * + max_md_size (HMAC).
1660          */
1661         if (!BUF_MEM_grow(s->init_buf,
1662                           DTLS1_HM_HEADER_LENGTH + 22 + EVP_MAX_IV_LENGTH +
1663                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
1664             return -1;
1665         senc = OPENSSL_malloc(slen);
1666         if (!senc)
1667             return -1;
1668         p = senc;
1669         i2d_SSL_SESSION(s->session, &p);
1670
1671         p = (unsigned char *)&(s->init_buf->data[DTLS1_HM_HEADER_LENGTH]);
1672         EVP_CIPHER_CTX_init(&ctx);
1673         HMAC_CTX_init(&hctx);
1674         /*
1675          * Initialize HMAC and cipher contexts. If callback present it does
1676          * all the work otherwise use generated values from parent ctx.
1677          */
1678         if (tctx->tlsext_ticket_key_cb) {
1679             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
1680                                            &hctx, 1) < 0) {
1681                 OPENSSL_free(senc);
1682                 return -1;
1683             }
1684         } else {
1685             RAND_pseudo_bytes(iv, 16);
1686             EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
1687                                tctx->tlsext_tick_aes_key, iv);
1688             HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
1689                          tlsext_tick_md(), NULL);
1690             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
1691         }
1692         l2n(s->session->tlsext_tick_lifetime_hint, p);
1693         /* Skip ticket length for now */
1694         p += 2;
1695         /* Output key name */
1696         macstart = p;
1697         memcpy(p, key_name, 16);
1698         p += 16;
1699         /* output IV */
1700         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
1701         p += EVP_CIPHER_CTX_iv_length(&ctx);
1702         /* Encrypt session data */
1703         EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
1704         p += len;
1705         EVP_EncryptFinal(&ctx, p, &len);
1706         p += len;
1707         EVP_CIPHER_CTX_cleanup(&ctx);
1708
1709         HMAC_Update(&hctx, macstart, p - macstart);
1710         HMAC_Final(&hctx, p, &hlen);
1711         HMAC_CTX_cleanup(&hctx);
1712
1713         p += hlen;
1714         /* Now write out lengths: p points to end of data written */
1715         /* Total length */
1716         len = p - (unsigned char *)(s->init_buf->data);
1717         /* Ticket length */
1718         p = (unsigned char *)&(s->init_buf->data[DTLS1_HM_HEADER_LENGTH]) + 4;
1719         s2n(len - DTLS1_HM_HEADER_LENGTH - 6, p);
1720
1721         /* number of bytes to write */
1722         s->init_num = len;
1723         s->state = SSL3_ST_SW_SESSION_TICKET_B;
1724         s->init_off = 0;
1725         OPENSSL_free(senc);
1726
1727         /* XDTLS:  set message header ? */
1728         msg_len = s->init_num - DTLS1_HM_HEADER_LENGTH;
1729         dtls1_set_message_header(s, (void *)s->init_buf->data,
1730                                  SSL3_MT_NEWSESSION_TICKET, msg_len, 0,
1731                                  msg_len);
1732
1733         /* buffer the message to handle re-xmits */
1734         dtls1_buffer_message(s, 0);
1735     }
1736
1737     /* SSL3_ST_SW_SESSION_TICKET_B */
1738     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
1739 }
1740 #endif