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