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