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