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