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