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