Split TLS server functions
[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 if (ver == DTLS1_2_VERSION)
137         return (DTLSv1_2_server_method());
138     else
139         return (NULL);
140 }
141
142 IMPLEMENT_dtls1_meth_func(DTLS1_VERSION,
143                           DTLSv1_server_method,
144                           dtls1_accept,
145                           ssl_undefined_function,
146                           dtls1_get_server_method, DTLSv1_enc_data)
147
148     IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION,
149                           DTLSv1_2_server_method,
150                           dtls1_accept,
151                           ssl_undefined_function,
152                           dtls1_get_server_method, DTLSv1_2_enc_data)
153
154     IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION,
155                           DTLS_server_method,
156                           dtls1_accept,
157                           ssl_undefined_function,
158                           dtls1_get_server_method, DTLSv1_2_enc_data)
159
160 int dtls1_accept(SSL *s)
161 {
162     BUF_MEM *buf;
163     unsigned long Time = (unsigned long)time(NULL);
164     void (*cb) (const SSL *ssl, int type, int val) = NULL;
165     unsigned long alg_k;
166     int ret = -1;
167     int new_state, state, skip = 0;
168 #ifndef OPENSSL_NO_SCTP
169     unsigned char sctpauthkey[64];
170     char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
171 #endif
172
173     RAND_add(&Time, sizeof(Time), 0);
174     ERR_clear_error();
175     clear_sys_error();
176
177     if (s->info_callback != NULL)
178         cb = s->info_callback;
179     else if (s->ctx->info_callback != NULL)
180         cb = s->ctx->info_callback;
181
182     /* init things to blank */
183     s->in_handshake++;
184     if (!SSL_in_init(s) || SSL_in_before(s)) {
185         if (!SSL_clear(s))
186             return -1;
187     }
188
189 #ifndef OPENSSL_NO_SCTP
190     /*
191      * Notify SCTP BIO socket to enter handshake mode and prevent stream
192      * identifier other than 0. Will be ignored if no SCTP is used.
193      */
194     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
195              s->in_handshake, NULL);
196 #endif
197
198 #ifndef OPENSSL_NO_HEARTBEATS
199     /*
200      * If we're awaiting a HeartbeatResponse, pretend we already got and
201      * don't await it anymore, because Heartbeats don't make sense during
202      * handshakes anyway.
203      */
204     if (s->tlsext_hb_pending) {
205         dtls1_stop_timer(s);
206         s->tlsext_hb_pending = 0;
207         s->tlsext_hb_seq++;
208     }
209 #endif
210
211     for (;;) {
212         state = s->state;
213
214         switch (s->state) {
215         case SSL_ST_RENEGOTIATE:
216             s->renegotiate = 1;
217             /* s->state=SSL_ST_ACCEPT; */
218
219         case SSL_ST_BEFORE:
220         case SSL_ST_ACCEPT:
221         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
222         case SSL_ST_OK | SSL_ST_ACCEPT:
223
224             s->server = 1;
225             if (cb != NULL)
226                 cb(s, SSL_CB_HANDSHAKE_START, 1);
227
228             if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
229                 SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR);
230                 return -1;
231             }
232             s->type = SSL_ST_ACCEPT;
233
234             if (s->init_buf == NULL) {
235                 if ((buf = BUF_MEM_new()) == NULL) {
236                     ret = -1;
237                     s->state = SSL_ST_ERR;
238                     goto end;
239                 }
240                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
241                     BUF_MEM_free(buf);
242                     ret = -1;
243                     s->state = SSL_ST_ERR;
244                     goto end;
245                 }
246                 s->init_buf = buf;
247             }
248
249             if (!ssl3_setup_buffers(s)) {
250                 ret = -1;
251                 s->state = SSL_ST_ERR;
252                 goto end;
253             }
254
255             s->init_num = 0;
256             /*
257              * Should have been reset by ssl3_get_finished, too.
258              */
259             s->s3->change_cipher_spec = 0;
260
261             if (s->state != SSL_ST_RENEGOTIATE) {
262                 /*
263                  * Ok, we now need to push on a buffering BIO so that the
264                  * output is sent in a way that TCP likes :-) ...but not with
265                  * SCTP :-)
266                  */
267 #ifndef OPENSSL_NO_SCTP
268                 if (!BIO_dgram_is_sctp(SSL_get_wbio(s)))
269 #endif
270                     if (!ssl_init_wbio_buffer(s, 1)) {
271                         ret = -1;
272                         s->state = SSL_ST_ERR;
273                         goto end;
274                     }
275
276                 ssl3_init_finished_mac(s);
277                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
278                 s->ctx->stats.sess_accept++;
279             } else {
280                 /*
281                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
282                  * HelloRequest
283                  */
284                 s->ctx->stats.sess_accept_renegotiate++;
285                 s->state = SSL3_ST_SW_HELLO_REQ_A;
286             }
287
288             break;
289
290         case SSL3_ST_SW_HELLO_REQ_A:
291         case SSL3_ST_SW_HELLO_REQ_B:
292
293             s->shutdown = 0;
294             dtls1_clear_record_buffer(s);
295             dtls1_start_timer(s);
296             ret = ssl3_send_hello_request(s);
297             if (ret <= 0)
298                 goto end;
299             s->s3->tmp.next_state = SSL3_ST_SR_CLNT_HELLO_A;
300             s->state = SSL3_ST_SW_FLUSH;
301             s->init_num = 0;
302
303             ssl3_init_finished_mac(s);
304             break;
305
306         case SSL3_ST_SW_HELLO_REQ_C:
307             s->state = SSL_ST_OK;
308             break;
309
310         case SSL3_ST_SR_CLNT_HELLO_A:
311         case SSL3_ST_SR_CLNT_HELLO_B:
312         case SSL3_ST_SR_CLNT_HELLO_C:
313
314             s->shutdown = 0;
315             ret = ssl3_get_client_hello(s);
316             if (ret <= 0)
317                 goto end;
318             dtls1_stop_timer(s);
319
320             if (!s->d1->cookie_verified
321                     && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
322                 s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A;
323             else
324                 s->state = SSL3_ST_SW_SRVR_HELLO_A;
325
326             s->init_num = 0;
327             break;
328
329         case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A:
330         case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B:
331
332             ret = dtls1_send_hello_verify_request(s);
333             if (ret <= 0)
334                 goto end;
335             s->state = SSL3_ST_SW_FLUSH;
336             s->s3->tmp.next_state = SSL3_ST_SR_CLNT_HELLO_A;
337
338             /* HelloVerifyRequest resets Finished MAC */
339             if (s->version != DTLS1_BAD_VER)
340                 ssl3_init_finished_mac(s);
341             break;
342
343 #ifndef OPENSSL_NO_SCTP
344         case DTLS1_SCTP_ST_SR_READ_SOCK:
345
346             if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
347                 s->s3->in_read_app_data = 2;
348                 s->rwstate = SSL_READING;
349                 BIO_clear_retry_flags(SSL_get_rbio(s));
350                 BIO_set_retry_read(SSL_get_rbio(s));
351                 ret = -1;
352                 goto end;
353             }
354
355             s->state = SSL3_ST_SR_CHANGE_A;
356             break;
357
358         case DTLS1_SCTP_ST_SW_WRITE_SOCK:
359             ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
360             if (ret < 0)
361                 goto end;
362
363             if (ret == 0) {
364                 if (s->d1->next_state != SSL_ST_OK) {
365                     s->s3->in_read_app_data = 2;
366                     s->rwstate = SSL_READING;
367                     BIO_clear_retry_flags(SSL_get_rbio(s));
368                     BIO_set_retry_read(SSL_get_rbio(s));
369                     ret = -1;
370                     goto end;
371                 }
372             }
373
374             s->state = s->d1->next_state;
375             break;
376 #endif
377
378         case SSL3_ST_SW_SRVR_HELLO_A:
379         case SSL3_ST_SW_SRVR_HELLO_B:
380             s->renegotiate = 2;
381             dtls1_start_timer(s);
382             ret = ssl3_send_server_hello(s);
383             if (ret <= 0)
384                 goto end;
385
386             if (s->hit) {
387 #ifndef OPENSSL_NO_SCTP
388                 /*
389                  * Add new shared key for SCTP-Auth, will be ignored if no
390                  * SCTP used.
391                  */
392                 snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
393                          DTLS1_SCTP_AUTH_LABEL);
394
395                 if (SSL_export_keying_material(s, sctpauthkey,
396                         sizeof(sctpauthkey), labelbuffer,
397                         sizeof(labelbuffer), NULL, 0, 0) <= 0) {
398                     ret = -1;
399                     s->state = SSL_ST_ERR;
400                     goto end;
401                 }
402
403                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
404                          sizeof(sctpauthkey), sctpauthkey);
405 #endif
406                 if (s->tlsext_ticket_expected)
407                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
408                 else
409                     s->state = SSL3_ST_SW_CHANGE_A;
410             } else
411                 s->state = SSL3_ST_SW_CERT_A;
412             s->init_num = 0;
413             break;
414
415         case SSL3_ST_SW_CERT_A:
416         case SSL3_ST_SW_CERT_B:
417             /* Check if it is anon DH or normal PSK */
418             if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
419                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
420                 dtls1_start_timer(s);
421                 ret = ssl3_send_server_certificate(s);
422                 if (ret <= 0)
423                     goto end;
424
425                 if (s->tlsext_status_expected)
426                     s->state = SSL3_ST_SW_CERT_STATUS_A;
427                 else
428                     s->state = SSL3_ST_SW_KEY_EXCH_A;
429             } else {
430                 skip = 1;
431                 s->state = SSL3_ST_SW_KEY_EXCH_A;
432             }
433             s->init_num = 0;
434             break;
435
436         case SSL3_ST_SW_KEY_EXCH_A:
437         case SSL3_ST_SW_KEY_EXCH_B:
438             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
439
440             /*
441              * clear this, it may get reset by
442              * send_server_key_exchange
443              */
444             s->s3->tmp.use_rsa_tmp = 0;
445
446             /*
447              * only send if a DH key exchange or RSA but we have a sign only
448              * certificate
449              */
450             if (0
451                 /*
452                  * PSK: send ServerKeyExchange if PSK identity hint if
453                  * provided
454                  */
455 #ifndef OPENSSL_NO_PSK
456                 || ((alg_k & SSL_kPSK) && s->cert->psk_identity_hint)
457 #endif
458                 || (alg_k & SSL_kDHE)
459                 || (alg_k & SSL_kECDHE)
460                 || ((alg_k & SSL_kRSA)
461                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
462                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
463                             && EVP_PKEY_size(s->cert->pkeys
464                                              [SSL_PKEY_RSA_ENC].privatekey) *
465                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
466                         )
467                     )
468                 )
469                 ) {
470                 dtls1_start_timer(s);
471                 ret = ssl3_send_server_key_exchange(s);
472                 if (ret <= 0)
473                     goto end;
474             } else
475                 skip = 1;
476
477             s->state = SSL3_ST_SW_CERT_REQ_A;
478             s->init_num = 0;
479             break;
480
481         case SSL3_ST_SW_CERT_REQ_A:
482         case SSL3_ST_SW_CERT_REQ_B:
483             if (                /* don't request cert unless asked for it: */
484                    !(s->verify_mode & SSL_VERIFY_PEER) ||
485                    /*
486                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
487                     * during re-negotiation:
488                     */
489                    ((s->session->peer != NULL) &&
490                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
491                    /*
492                     * never request cert in anonymous ciphersuites (see
493                     * section "Certificate request" in SSL 3 drafts and in
494                     * RFC 2246):
495                     */
496                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
497                    /*
498                     * ... except when the application insists on
499                     * verification (against the specs, but s3_clnt.c accepts
500                     * this for SSL 3)
501                     */
502                    !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
503                    /*
504                     * With normal PSK Certificates and Certificate Requests
505                     * are omitted
506                     */
507                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
508                 /* no cert request */
509                 skip = 1;
510                 s->s3->tmp.cert_request = 0;
511                 s->state = SSL3_ST_SW_SRVR_DONE_A;
512 #ifndef OPENSSL_NO_SCTP
513                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
514                     s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A;
515                     s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
516                 }
517 #endif
518             } else {
519                 s->s3->tmp.cert_request = 1;
520                 dtls1_start_timer(s);
521                 ret = ssl3_send_certificate_request(s);
522                 if (ret <= 0)
523                     goto end;
524                 s->state = SSL3_ST_SW_SRVR_DONE_A;
525 # ifndef OPENSSL_NO_SCTP
526                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
527                     s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A;
528                     s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
529                 }
530 # endif
531                 s->init_num = 0;
532             }
533             break;
534
535         case SSL3_ST_SW_SRVR_DONE_A:
536         case SSL3_ST_SW_SRVR_DONE_B:
537             dtls1_start_timer(s);
538             ret = ssl3_send_server_done(s);
539             if (ret <= 0)
540                 goto end;
541             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
542             s->state = SSL3_ST_SW_FLUSH;
543             s->init_num = 0;
544             break;
545
546         case SSL3_ST_SW_FLUSH:
547             s->rwstate = SSL_WRITING;
548             if (BIO_flush(s->wbio) <= 0) {
549                 /*
550                  * If the write error was fatal, stop trying
551                  */
552                 if (!BIO_should_retry(s->wbio)) {
553                     s->rwstate = SSL_NOTHING;
554                     s->state = s->s3->tmp.next_state;
555                 }
556
557                 ret = -1;
558                 goto end;
559             }
560             s->rwstate = SSL_NOTHING;
561             s->state = s->s3->tmp.next_state;
562             break;
563
564         case SSL3_ST_SR_CERT_A:
565         case SSL3_ST_SR_CERT_B:
566             if (s->s3->tmp.cert_request) {
567                 ret = ssl3_get_client_certificate(s);
568                 if (ret <= 0)
569                     goto end;
570             }
571             s->init_num = 0;
572             s->state = SSL3_ST_SR_KEY_EXCH_A;
573             break;
574
575         case SSL3_ST_SR_KEY_EXCH_A:
576         case SSL3_ST_SR_KEY_EXCH_B:
577             ret = ssl3_get_client_key_exchange(s);
578             if (ret <= 0)
579                 goto end;
580 #ifndef OPENSSL_NO_SCTP
581             /*
582              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
583              * used.
584              */
585             snprintf((char *)labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL),
586                      DTLS1_SCTP_AUTH_LABEL);
587
588             if (SSL_export_keying_material(s, sctpauthkey,
589                                        sizeof(sctpauthkey), labelbuffer,
590                                        sizeof(labelbuffer), NULL, 0, 0) <= 0) {
591                 ret = -1;
592                 s->state = SSL_ST_ERR;
593                 goto end;
594             }
595
596             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
597                      sizeof(sctpauthkey), sctpauthkey);
598 #endif
599
600             s->state = SSL3_ST_SR_CERT_VRFY_A;
601             s->init_num = 0;
602
603             if (s->no_cert_verify) {
604                 /*
605                  * For the ECDH ciphersuites when the client sends its ECDH
606                  * pub key in a certificate, the CertificateVerify message is
607                  * not sent.
608                  */
609                 s->state = SSL3_ST_SR_CHANGE_A;
610                 s->init_num = 0;
611             } else if (SSL_USE_SIGALGS(s)) {
612                 s->state = SSL3_ST_SR_CERT_VRFY_A;
613                 s->init_num = 0;
614                 if (!s->session->peer)
615                     break;
616                 if (!s->s3->handshake_buffer) {
617                     SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR);
618                     s->state = SSL_ST_ERR;
619                     return -1;
620                 }
621                 /*
622                  * For sigalgs freeze the handshake buffer. If we support
623                  * extms we've done this already.
624                  */
625                 if (!ssl3_digest_cached_records(s, 1)) {
626                     s->state = SSL_ST_ERR;
627                     return -1;
628                 }
629             } else {
630                 s->state = SSL3_ST_SR_CERT_VRFY_A;
631                 s->init_num = 0;
632
633                 /*
634                  * We need to get hashes here so if there is a client cert,
635                  * it can be verified
636                  */
637                 s->method->ssl3_enc->cert_verify_mac(s,
638                                                      NID_md5,
639                                                      &(s->s3->
640                                                        tmp.cert_verify_md
641                                                        [0]));
642                 s->method->ssl3_enc->cert_verify_mac(s, NID_sha1,
643                                                      &(s->s3->
644                                                        tmp.cert_verify_md
645                                                        [MD5_DIGEST_LENGTH]));
646             }
647             break;
648
649         case SSL3_ST_SR_CERT_VRFY_A:
650         case SSL3_ST_SR_CERT_VRFY_B:
651             ret = ssl3_get_cert_verify(s);
652             if (ret <= 0)
653                 goto end;
654 #ifndef OPENSSL_NO_SCTP
655             if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
656                 state == SSL_ST_RENEGOTIATE)
657                 s->state = DTLS1_SCTP_ST_SR_READ_SOCK;
658             else
659 #endif
660                 s->state = SSL3_ST_SR_CHANGE_A;
661             s->init_num = 0;
662             break;
663
664         case SSL3_ST_SR_CHANGE_A:
665         case SSL3_ST_SR_CHANGE_B:
666             ret = ssl3_get_change_cipher_spec(s, SSL3_ST_SR_CHANGE_A,
667                                               SSL3_ST_SR_CHANGE_B);
668             if (ret <= 0)
669                 goto end;
670
671             s->state = SSL3_ST_SR_FINISHED_A;
672             s->init_num = 0;
673             break;
674
675         case SSL3_ST_SR_FINISHED_A:
676         case SSL3_ST_SR_FINISHED_B:
677             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
678                                     SSL3_ST_SR_FINISHED_B);
679             if (ret <= 0)
680                 goto end;
681             dtls1_stop_timer(s);
682             if (s->hit)
683                 s->state = SSL_ST_OK;
684             else if (s->tlsext_ticket_expected)
685                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
686             else
687                 s->state = SSL3_ST_SW_CHANGE_A;
688             s->init_num = 0;
689             break;
690
691         case SSL3_ST_SW_SESSION_TICKET_A:
692         case SSL3_ST_SW_SESSION_TICKET_B:
693             ret = ssl3_send_newsession_ticket(s);
694             if (ret <= 0)
695                 goto end;
696             s->state = SSL3_ST_SW_CHANGE_A;
697             s->init_num = 0;
698             break;
699
700         case SSL3_ST_SW_CERT_STATUS_A:
701         case SSL3_ST_SW_CERT_STATUS_B:
702             ret = ssl3_send_cert_status(s);
703             if (ret <= 0)
704                 goto end;
705             s->state = SSL3_ST_SW_KEY_EXCH_A;
706             s->init_num = 0;
707             break;
708
709         case SSL3_ST_SW_CHANGE_A:
710         case SSL3_ST_SW_CHANGE_B:
711
712             s->session->cipher = s->s3->tmp.new_cipher;
713             if (!s->method->ssl3_enc->setup_key_block(s)) {
714                 ret = -1;
715                 s->state = SSL_ST_ERR;
716                 goto end;
717             }
718
719             ret = dtls1_send_change_cipher_spec(s,
720                                                 SSL3_ST_SW_CHANGE_A,
721                                                 SSL3_ST_SW_CHANGE_B);
722
723             if (ret <= 0)
724                 goto end;
725
726 #ifndef OPENSSL_NO_SCTP
727             if (!s->hit) {
728                 /*
729                  * Change to new shared key of SCTP-Auth, will be ignored if
730                  * no SCTP used.
731                  */
732                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
733                          0, NULL);
734             }
735 #endif
736
737             s->state = SSL3_ST_SW_FINISHED_A;
738             s->init_num = 0;
739
740             if (!s->method->ssl3_enc->change_cipher_state(s,
741                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
742             {
743                 ret = -1;
744                 s->state = SSL_ST_ERR;
745                 goto end;
746             }
747
748             dtls1_reset_seq_numbers(s, SSL3_CC_WRITE);
749             break;
750
751         case SSL3_ST_SW_FINISHED_A:
752         case SSL3_ST_SW_FINISHED_B:
753             ret = ssl3_send_finished(s,
754                                      SSL3_ST_SW_FINISHED_A,
755                                      SSL3_ST_SW_FINISHED_B,
756                                      s->method->
757                                      ssl3_enc->server_finished_label,
758                                      s->method->
759                                      ssl3_enc->server_finished_label_len);
760             if (ret <= 0)
761                 goto end;
762             s->state = SSL3_ST_SW_FLUSH;
763             if (s->hit) {
764                 s->s3->tmp.next_state = SSL3_ST_SR_CHANGE_A;
765
766 #ifndef OPENSSL_NO_SCTP
767                 /*
768                  * Change to new shared key of SCTP-Auth, will be ignored if
769                  * no SCTP used.
770                  */
771                 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
772                          0, NULL);
773 #endif
774             } else {
775                 s->s3->tmp.next_state = SSL_ST_OK;
776 #ifndef OPENSSL_NO_SCTP
777                 if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
778                     s->d1->next_state = s->s3->tmp.next_state;
779                     s->s3->tmp.next_state = DTLS1_SCTP_ST_SW_WRITE_SOCK;
780                 }
781 #endif
782             }
783             s->init_num = 0;
784             break;
785
786         case SSL_ST_OK:
787             /* clean a few things up */
788             ssl3_cleanup_key_block(s);
789
790             /* remove buffering on output */
791             ssl_free_wbio_buffer(s);
792
793             s->init_num = 0;
794
795             if (s->renegotiate == 2) { /* skipped if we just sent a
796                                         * HelloRequest */
797                 s->renegotiate = 0;
798                 s->new_session = 0;
799
800                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
801
802                 s->ctx->stats.sess_accept_good++;
803                 /* s->server=1; */
804                 s->handshake_func = dtls1_accept;
805
806                 if (cb != NULL)
807                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
808             }
809
810             ret = 1;
811
812             /* done handshaking, next message is client hello */
813             s->d1->handshake_read_seq = 0;
814             /* next message is server hello */
815             s->d1->handshake_write_seq = 0;
816             s->d1->next_handshake_write_seq = 0;
817             goto end;
818             /* break; */
819
820         case SSL_ST_ERR:
821         default:
822             SSLerr(SSL_F_DTLS1_ACCEPT, SSL_R_UNKNOWN_STATE);
823             ret = -1;
824             goto end;
825             /* break; */
826         }
827
828         if (!s->s3->tmp.reuse_message && !skip) {
829             if (s->debug) {
830                 if ((ret = BIO_flush(s->wbio)) <= 0)
831                     goto end;
832             }
833
834             if ((cb != NULL) && (s->state != state)) {
835                 new_state = s->state;
836                 s->state = state;
837                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
838                 s->state = new_state;
839             }
840         }
841         skip = 0;
842     }
843  end:
844     /* BIO_flush(s->wbio); */
845
846     s->in_handshake--;
847 #ifndef OPENSSL_NO_SCTP
848     /*
849      * Notify SCTP BIO socket to leave handshake mode and prevent stream
850      * identifier other than 0. Will be ignored if no SCTP is used.
851      */
852     BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE,
853              s->in_handshake, NULL);
854 #endif
855
856     if (cb != NULL)
857         cb(s, SSL_CB_ACCEPT_EXIT, ret);
858     return (ret);
859 }
860
861 unsigned int dtls1_raw_hello_verify_request(unsigned char *buf,
862                                             unsigned char *cookie,
863                                             unsigned char cookie_len)
864 {
865     unsigned int msg_len;
866     unsigned char *p;
867
868     p = buf;
869     /* Always use DTLS 1.0 version: see RFC 6347 */
870     *(p++) = DTLS1_VERSION >> 8;
871     *(p++) = DTLS1_VERSION & 0xFF;
872
873     *(p++) = (unsigned char)cookie_len;
874     memcpy(p, cookie, cookie_len);
875     p += cookie_len;
876     msg_len = p - buf;
877
878     return msg_len;
879 }
880
881
882 int dtls1_send_hello_verify_request(SSL *s)
883 {
884     unsigned int len;
885     unsigned char *buf;
886
887     if (s->state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) {
888         buf = (unsigned char *)s->init_buf->data;
889
890         if (s->ctx->app_gen_cookie_cb == NULL ||
891             s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
892                                       &(s->d1->cookie_len)) == 0 ||
893             s->d1->cookie_len > 255) {
894             SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,
895                    SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
896             s->state = SSL_ST_ERR;
897             return 0;
898         }
899
900         len = dtls1_raw_hello_verify_request(&buf[DTLS1_HM_HEADER_LENGTH],
901                                              s->d1->cookie, s->d1->cookie_len);
902
903         dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, len, 0,
904                                  len);
905         len += DTLS1_HM_HEADER_LENGTH;
906
907         s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B;
908         /* number of bytes to write */
909         s->init_num = len;
910         s->init_off = 0;
911     }
912
913     /* s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */
914     return (dtls1_do_write(s, SSL3_RT_HANDSHAKE));
915 }