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