1/* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113 *
114 * Portions of the attached software ("Contribution") are developed by
115 * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116 *
117 * The Contribution is licensed pursuant to the OpenSSL open source
118 * license provided above.
119 *
120 * ECC cipher suite support in OpenSSL originally written by
121 * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122 *
123 */
124/* ====================================================================
125 * Copyright 2005 Nokia. All rights reserved.
126 *
127 * The portions of the attached software ("Contribution") is developed by
128 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129 * license.
130 *
131 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133 * support (see RFC 4279) to OpenSSL.
134 *
135 * No patent licenses or other rights except those expressly stated in
136 * the OpenSSL open source license shall be deemed granted or received
137 * expressly, by implication, estoppel, or otherwise.
138 *
139 * No assurances are provided by Nokia that the Contribution does not
140 * infringe the patent or other intellectual property rights of any third
141 * party or that the license provides you with all the necessary rights
142 * to make use of the Contribution.
143 *
144 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148 * OTHERWISE.
149 */
150
151#define REUSE_CIPHER_BUG
152#define NETSCAPE_HANG_BUG
153
154#include <stdio.h>
155#include "ssl_locl.h"
156#include "kssl_lcl.h"
157#include "../crypto/constant_time_locl.h"
158#include <openssl/buffer.h>
159#include <openssl/rand.h>
160#include <openssl/objects.h>
161#include <openssl/ec.h>
162#include <openssl/ecdsa.h>
163#include <openssl/evp.h>
164#include <openssl/hmac.h>
165#include <openssl/sha.h>
166#include <openssl/x509.h>
167#ifndef OPENSSL_NO_DH
168#include <openssl/dh.h>
169#endif
170#include <openssl/bn.h>
171#ifndef OPENSSL_NO_KRB5
172#include <openssl/krb5_asn.h>
173#endif
174#include <openssl/md5.h>
175
176static const SSL_METHOD *ssl3_get_server_method(int ver);
177
178static const SSL_METHOD *ssl3_get_server_method(int ver)
179	{
180	if (ver == SSL3_VERSION)
181		return(SSLv3_server_method());
182	else
183		return(NULL);
184	}
185
186#ifndef OPENSSL_NO_SRP
187static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
188	{
189	int ret = SSL_ERROR_NONE;
190
191	*al = SSL_AD_UNRECOGNIZED_NAME;
192
193	if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
194	    (s->srp_ctx.TLS_ext_srp_username_callback != NULL))
195		{
196		if(s->srp_ctx.login == NULL)
197			{
198			/* RFC 5054 says SHOULD reject,
199			   we do so if There is no srp login name */
200			ret = SSL3_AL_FATAL;
201			*al = SSL_AD_UNKNOWN_PSK_IDENTITY;
202			}
203		else
204			{
205			ret = SSL_srp_server_param_with_username(s,al);
206			}
207		}
208	return ret;
209	}
210#endif
211
212IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
213			ssl3_accept,
214			ssl_undefined_function,
215			ssl3_get_server_method)
216
217int ssl3_accept(SSL *s)
218	{
219	BUF_MEM *buf;
220	unsigned long alg_k,Time=(unsigned long)time(NULL);
221	unsigned long alg_a;
222	void (*cb)(const SSL *ssl,int type,int val)=NULL;
223	int ret= -1;
224	int new_state,state,skip=0;
225
226	RAND_add(&Time,sizeof(Time),0);
227	ERR_clear_error();
228	clear_sys_error();
229
230	if (s->info_callback != NULL)
231		cb=s->info_callback;
232	else if (s->ctx->info_callback != NULL)
233		cb=s->ctx->info_callback;
234
235	/* init things to blank */
236	s->in_handshake++;
237	if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
238
239	if (s->cert == NULL)
240		{
241		SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
242		return(-1);
243		}
244
245#ifndef OPENSSL_NO_HEARTBEATS
246	/* If we're awaiting a HeartbeatResponse, pretend we
247	 * already got and don't await it anymore, because
248	 * Heartbeats don't make sense during handshakes anyway.
249	 */
250	if (s->tlsext_hb_pending)
251		{
252		s->tlsext_hb_pending = 0;
253		s->tlsext_hb_seq++;
254		}
255#endif
256
257	for (;;)
258		{
259		state=s->state;
260
261		switch (s->state)
262			{
263		case SSL_ST_RENEGOTIATE:
264			s->renegotiate=1;
265			/* s->state=SSL_ST_ACCEPT; */
266
267		case SSL_ST_BEFORE:
268		case SSL_ST_ACCEPT:
269		case SSL_ST_BEFORE|SSL_ST_ACCEPT:
270		case SSL_ST_OK|SSL_ST_ACCEPT:
271
272			s->server=1;
273			if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
274
275			if ((s->version>>8) != 3)
276				{
277				SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
278				return -1;
279				}
280			s->type=SSL_ST_ACCEPT;
281
282			if (s->init_buf == NULL)
283				{
284				if ((buf=BUF_MEM_new()) == NULL)
285					{
286					ret= -1;
287					goto end;
288					}
289				if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
290					{
291					ret= -1;
292					goto end;
293					}
294				s->init_buf=buf;
295				}
296
297			if (!ssl3_setup_buffers(s))
298				{
299				ret= -1;
300				goto end;
301				}
302
303			s->init_num=0;
304			s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
305
306			if (s->state != SSL_ST_RENEGOTIATE)
307				{
308				/* Ok, we now need to push on a buffering BIO so that
309				 * the output is sent in a way that TCP likes :-)
310				 */
311				if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
312
313				ssl3_init_finished_mac(s);
314				s->state=SSL3_ST_SR_CLNT_HELLO_A;
315				s->ctx->stats.sess_accept++;
316				}
317			else if (!s->s3->send_connection_binding &&
318				!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
319				{
320				/* Server attempting to renegotiate with
321				 * client that doesn't support secure
322				 * renegotiation.
323				 */
324				SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
325				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
326				ret = -1;
327				goto end;
328				}
329			else
330				{
331				/* s->state == SSL_ST_RENEGOTIATE,
332				 * we will just send a HelloRequest */
333				s->ctx->stats.sess_accept_renegotiate++;
334				s->state=SSL3_ST_SW_HELLO_REQ_A;
335				}
336			break;
337
338		case SSL3_ST_SW_HELLO_REQ_A:
339		case SSL3_ST_SW_HELLO_REQ_B:
340
341			s->shutdown=0;
342			ret=ssl3_send_hello_request(s);
343			if (ret <= 0) goto end;
344			s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
345			s->state=SSL3_ST_SW_FLUSH;
346			s->init_num=0;
347
348			ssl3_init_finished_mac(s);
349			break;
350
351		case SSL3_ST_SW_HELLO_REQ_C:
352			s->state=SSL_ST_OK;
353			break;
354
355		case SSL3_ST_SR_CLNT_HELLO_A:
356		case SSL3_ST_SR_CLNT_HELLO_B:
357		case SSL3_ST_SR_CLNT_HELLO_C:
358
359			s->shutdown=0;
360			if (s->rwstate != SSL_X509_LOOKUP)
361			{
362				ret=ssl3_get_client_hello(s);
363				if (ret <= 0) goto end;
364			}
365#ifndef OPENSSL_NO_SRP
366			{
367			int al;
368			if ((ret = ssl_check_srp_ext_ClientHello(s,&al))  < 0)
369					{
370					/* callback indicates firther work to be done */
371					s->rwstate=SSL_X509_LOOKUP;
372					goto end;
373					}
374			if (ret != SSL_ERROR_NONE)
375				{
376				ssl3_send_alert(s,SSL3_AL_FATAL,al);
377				/* This is not really an error but the only means to
378                                   for a client to detect whether srp is supported. */
379 				   if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
380					SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
381				ret = SSL_TLSEXT_ERR_ALERT_FATAL;
382				ret= -1;
383				goto end;
384				}
385			}
386#endif
387
388			s->renegotiate = 2;
389			s->state=SSL3_ST_SW_SRVR_HELLO_A;
390			s->init_num=0;
391			break;
392
393		case SSL3_ST_SW_SRVR_HELLO_A:
394		case SSL3_ST_SW_SRVR_HELLO_B:
395			ret=ssl3_send_server_hello(s);
396			if (ret <= 0) goto end;
397#ifndef OPENSSL_NO_TLSEXT
398			if (s->hit)
399				{
400				if (s->tlsext_ticket_expected)
401					s->state=SSL3_ST_SW_SESSION_TICKET_A;
402				else
403					s->state=SSL3_ST_SW_CHANGE_A;
404				}
405#else
406			if (s->hit)
407					s->state=SSL3_ST_SW_CHANGE_A;
408#endif
409			else
410				s->state=SSL3_ST_SW_CERT_A;
411			s->init_num=0;
412			break;
413
414		case SSL3_ST_SW_CERT_A:
415		case SSL3_ST_SW_CERT_B:
416			/* Check if it is anon DH or anon ECDH, */
417			/* non-RSA PSK or KRB5 or SRP */
418			if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
419				/* Among PSK ciphersuites only RSA_PSK uses server certificate */
420				&& !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK &&
421					 !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kRSA)))
422				{
423				ret=ssl3_send_server_certificate(s);
424				if (ret <= 0) goto end;
425#ifndef OPENSSL_NO_TLSEXT
426				if (s->tlsext_status_expected)
427					s->state=SSL3_ST_SW_CERT_STATUS_A;
428				else
429					s->state=SSL3_ST_SW_KEY_EXCH_A;
430				}
431			else
432				{
433				skip = 1;
434				s->state=SSL3_ST_SW_KEY_EXCH_A;
435				}
436#else
437				}
438			else
439				skip=1;
440
441			s->state=SSL3_ST_SW_KEY_EXCH_A;
442#endif
443			s->init_num=0;
444			break;
445
446		case SSL3_ST_SW_KEY_EXCH_A:
447		case SSL3_ST_SW_KEY_EXCH_B:
448			alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
449			alg_a = s->s3->tmp.new_cipher->algorithm_auth;
450
451			/* clear this, it may get reset by
452			 * send_server_key_exchange */
453			if ((s->options & SSL_OP_EPHEMERAL_RSA)
454#ifndef OPENSSL_NO_KRB5
455				&& !(alg_k & SSL_kKRB5)
456#endif /* OPENSSL_NO_KRB5 */
457				)
458				/* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
459				 * even when forbidden by protocol specs
460				 * (handshake may fail as clients are not required to
461				 * be able to handle this) */
462				s->s3->tmp.use_rsa_tmp=1;
463			else
464				s->s3->tmp.use_rsa_tmp=0;
465
466
467			/* only send if a DH key exchange, fortezza or
468			 * RSA but we have a sign only certificate
469			 *
470			 * PSK: may send PSK identity hints
471			 *
472			 * For ECC ciphersuites, we send a serverKeyExchange
473			 * message only if the cipher suite is either
474			 * ECDH-anon or ECDHE. In other cases, the
475			 * server certificate contains the server's
476			 * public key for key exchange.
477			 */
478			if (s->s3->tmp.use_rsa_tmp
479			/* PSK: send ServerKeyExchange if either:
480			 *   - PSK identity hint is provided, or
481			 *   - the key exchange is kEECDH.
482			 */
483#ifndef OPENSSL_NO_PSK
484			    || ((alg_a & SSL_aPSK) && ((alg_k & SSL_kEECDH) || s->session->psk_identity_hint))
485#endif
486#ifndef OPENSSL_NO_SRP
487			    /* SRP: send ServerKeyExchange */
488			    || (alg_k & SSL_kSRP)
489#endif
490			    || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
491			    || (alg_k & SSL_kEECDH)
492			    || ((alg_k & SSL_kRSA)
493				&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
494				    || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
495					&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
496					)
497				    )
498				)
499			    )
500				{
501				ret=ssl3_send_server_key_exchange(s);
502				if (ret <= 0) goto end;
503				}
504			else
505				skip=1;
506
507			s->state=SSL3_ST_SW_CERT_REQ_A;
508			s->init_num=0;
509			break;
510
511		case SSL3_ST_SW_CERT_REQ_A:
512		case SSL3_ST_SW_CERT_REQ_B:
513			if (/* don't request cert unless asked for it: */
514				!(s->verify_mode & SSL_VERIFY_PEER) ||
515				/* if SSL_VERIFY_CLIENT_ONCE is set,
516				 * don't request cert during re-negotiation: */
517				((s->session->peer != NULL) &&
518				 (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
519				/* never request cert in anonymous ciphersuites
520				 * (see section "Certificate request" in SSL 3 drafts
521				 * and in RFC 2246): */
522				((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
523				 /* ... except when the application insists on verification
524				  * (against the specs, but s3_clnt.c accepts this for SSL 3) */
525				 !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
526				 /* never request cert in Kerberos ciphersuites */
527				(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
528				/* don't request certificate for SRP auth */
529				(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
530				/* With normal PSK Certificates and
531				 * Certificate Requests are omitted */
532				|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
533				{
534				/* no cert request */
535				skip=1;
536				s->s3->tmp.cert_request=0;
537				s->state=SSL3_ST_SW_SRVR_DONE_A;
538				if (s->s3->handshake_buffer)
539					if (!ssl3_digest_cached_records(s))
540						return -1;
541				}
542			else
543				{
544				s->s3->tmp.cert_request=1;
545				ret=ssl3_send_certificate_request(s);
546				if (ret <= 0) goto end;
547#ifndef NETSCAPE_HANG_BUG
548				s->state=SSL3_ST_SW_SRVR_DONE_A;
549#else
550				s->state=SSL3_ST_SW_FLUSH;
551				s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
552#endif
553				s->init_num=0;
554				}
555			break;
556
557		case SSL3_ST_SW_SRVR_DONE_A:
558		case SSL3_ST_SW_SRVR_DONE_B:
559			ret=ssl3_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
568			/* This code originally checked to see if
569			 * any data was pending using BIO_CTRL_INFO
570			 * and then flushed. This caused problems
571			 * as documented in PR#1939. The proposed
572			 * fix doesn't completely resolve this issue
573			 * as buggy implementations of BIO_CTRL_PENDING
574			 * still exist. So instead we just flush
575			 * unconditionally.
576			 */
577
578			s->rwstate=SSL_WRITING;
579			if (BIO_flush(s->wbio) <= 0)
580				{
581				ret= -1;
582				goto end;
583				}
584			s->rwstate=SSL_NOTHING;
585
586			s->state=s->s3->tmp.next_state;
587			break;
588
589		case SSL3_ST_SR_CERT_A:
590		case SSL3_ST_SR_CERT_B:
591			/* Check for second client hello (MS SGC) */
592			ret = ssl3_check_client_hello(s);
593			if (ret <= 0)
594				goto end;
595			if (ret == 2)
596				s->state = SSL3_ST_SR_CLNT_HELLO_C;
597			else {
598				if (s->s3->tmp.cert_request)
599					{
600					ret=ssl3_get_client_certificate(s);
601					if (ret <= 0) goto end;
602					}
603				s->init_num=0;
604				s->state=SSL3_ST_SR_KEY_EXCH_A;
605			}
606			break;
607
608		case SSL3_ST_SR_KEY_EXCH_A:
609		case SSL3_ST_SR_KEY_EXCH_B:
610			ret=ssl3_get_client_key_exchange(s);
611			if (ret <= 0)
612				goto end;
613			if (ret == 2)
614				{
615				/* For the ECDH ciphersuites when
616				 * the client sends its ECDH pub key in
617				 * a certificate, the CertificateVerify
618				 * message is not sent.
619				 * Also for GOST ciphersuites when
620				 * the client uses its key from the certificate
621				 * for key exchange.
622				 */
623				s->init_num = 0;
624				s->state=SSL3_ST_SR_POST_CLIENT_CERT;
625				}
626			else if (TLS1_get_version(s) >= TLS1_2_VERSION)
627				{
628				s->state=SSL3_ST_SR_CERT_VRFY_A;
629				s->init_num=0;
630				if (!s->session->peer)
631					break;
632				/* For TLS v1.2 freeze the handshake buffer
633				 * at this point and digest cached records.
634				 */
635				if (!s->s3->handshake_buffer)
636					{
637					SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
638					return -1;
639					}
640				s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
641				if (!ssl3_digest_cached_records(s))
642					return -1;
643				}
644			else
645				{
646				int offset=0;
647				int dgst_num;
648
649				s->state=SSL3_ST_SR_CERT_VRFY_A;
650				s->init_num=0;
651
652				/* We need to get hashes here so if there is
653				 * a client cert, it can be verified
654				 * FIXME - digest processing for CertificateVerify
655				 * should be generalized. But it is next step
656				 */
657				if (s->s3->handshake_buffer)
658					if (!ssl3_digest_cached_records(s))
659						return -1;
660				for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
661					if (s->s3->handshake_dgst[dgst_num])
662						{
663						int dgst_size;
664
665						s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
666						dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
667						if (dgst_size < 0)
668							{
669							ret = -1;
670							goto end;
671							}
672						offset+=dgst_size;
673						}
674				}
675			break;
676
677		case SSL3_ST_SR_CERT_VRFY_A:
678		case SSL3_ST_SR_CERT_VRFY_B:
679
680			s->s3->flags |= SSL3_FLAGS_CCS_OK;
681			/* we should decide if we expected this one */
682			ret=ssl3_get_cert_verify(s);
683			if (ret <= 0) goto end;
684
685			s->state=SSL3_ST_SR_POST_CLIENT_CERT;
686			s->init_num=0;
687			break;
688
689		case SSL3_ST_SR_POST_CLIENT_CERT: {
690			char next_proto_neg = 0;
691			char channel_id = 0;
692#if !defined(OPENSSL_NO_TLSEXT)
693# if !defined(OPENSSL_NO_NEXTPROTONEG)
694			next_proto_neg = s->s3->next_proto_neg_seen;
695# endif
696			channel_id = s->s3->tlsext_channel_id_valid;
697#endif
698
699			if (next_proto_neg)
700				s->state=SSL3_ST_SR_NEXT_PROTO_A;
701			else if (channel_id)
702				s->state=SSL3_ST_SR_CHANNEL_ID_A;
703			else
704				s->state=SSL3_ST_SR_FINISHED_A;
705			break;
706		}
707
708#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
709		case SSL3_ST_SR_NEXT_PROTO_A:
710		case SSL3_ST_SR_NEXT_PROTO_B:
711			ret=ssl3_get_next_proto(s);
712			if (ret <= 0) goto end;
713			s->init_num = 0;
714			if (s->s3->tlsext_channel_id_valid)
715				s->state=SSL3_ST_SR_CHANNEL_ID_A;
716			else
717				s->state=SSL3_ST_SR_FINISHED_A;
718			break;
719#endif
720
721#if !defined(OPENSSL_NO_TLSEXT)
722		case SSL3_ST_SR_CHANNEL_ID_A:
723		case SSL3_ST_SR_CHANNEL_ID_B:
724			ret=ssl3_get_channel_id(s);
725			if (ret <= 0) goto end;
726			s->init_num = 0;
727			s->state=SSL3_ST_SR_FINISHED_A;
728			break;
729#endif
730
731		case SSL3_ST_SR_FINISHED_A:
732		case SSL3_ST_SR_FINISHED_B:
733			s->s3->flags |= SSL3_FLAGS_CCS_OK;
734			ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
735				SSL3_ST_SR_FINISHED_B);
736			if (ret <= 0) goto end;
737			if (s->hit)
738				s->state=SSL_ST_OK;
739#ifndef OPENSSL_NO_TLSEXT
740			else if (s->tlsext_ticket_expected)
741				s->state=SSL3_ST_SW_SESSION_TICKET_A;
742#endif
743			else
744				s->state=SSL3_ST_SW_CHANGE_A;
745			/* If this is a full handshake with ChannelID then
746			 * record the hashshake hashes in |s->session| in case
747			 * we need them to verify a ChannelID signature on a
748			 * resumption of this session in the future. */
749			if (!s->hit && s->s3->tlsext_channel_id_new)
750				{
751				ret = tls1_record_handshake_hashes_for_channel_id(s);
752				if (ret <= 0) goto end;
753				}
754			s->init_num=0;
755			break;
756
757#ifndef OPENSSL_NO_TLSEXT
758		case SSL3_ST_SW_SESSION_TICKET_A:
759		case SSL3_ST_SW_SESSION_TICKET_B:
760			ret=ssl3_send_newsession_ticket(s);
761			if (ret <= 0) goto end;
762			s->state=SSL3_ST_SW_CHANGE_A;
763			s->init_num=0;
764			break;
765
766		case SSL3_ST_SW_CERT_STATUS_A:
767		case SSL3_ST_SW_CERT_STATUS_B:
768			ret=ssl3_send_cert_status(s);
769			if (ret <= 0) goto end;
770			s->state=SSL3_ST_SW_KEY_EXCH_A;
771			s->init_num=0;
772			break;
773
774#endif
775
776		case SSL3_ST_SW_CHANGE_A:
777		case SSL3_ST_SW_CHANGE_B:
778
779			s->session->cipher=s->s3->tmp.new_cipher;
780			if (!s->method->ssl3_enc->setup_key_block(s))
781				{ ret= -1; goto end; }
782
783			ret=ssl3_send_change_cipher_spec(s,
784				SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
785
786			if (ret <= 0) goto end;
787			s->state=SSL3_ST_SW_FINISHED_A;
788			s->init_num=0;
789
790			if (!s->method->ssl3_enc->change_cipher_state(s,
791				SSL3_CHANGE_CIPHER_SERVER_WRITE))
792				{
793				ret= -1;
794				goto end;
795				}
796
797			break;
798
799		case SSL3_ST_SW_FINISHED_A:
800		case SSL3_ST_SW_FINISHED_B:
801			ret=ssl3_send_finished(s,
802				SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
803				s->method->ssl3_enc->server_finished_label,
804				s->method->ssl3_enc->server_finished_label_len);
805			if (ret <= 0) goto end;
806			s->state=SSL3_ST_SW_FLUSH;
807			if (s->hit)
808				s->s3->tmp.next_state=SSL3_ST_SR_POST_CLIENT_CERT;
809			else
810				s->s3->tmp.next_state=SSL_ST_OK;
811			s->init_num=0;
812			break;
813
814		case SSL_ST_OK:
815			/* clean a few things up */
816			ssl3_cleanup_key_block(s);
817
818			BUF_MEM_free(s->init_buf);
819			s->init_buf=NULL;
820
821			/* remove buffering on output */
822			ssl_free_wbio_buffer(s);
823
824			s->init_num=0;
825
826			if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
827				{
828				s->renegotiate=0;
829				s->new_session=0;
830
831				ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
832
833				s->ctx->stats.sess_accept_good++;
834				/* s->server=1; */
835				s->handshake_func=ssl3_accept;
836
837				if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
838				}
839
840			ret = 1;
841			goto end;
842			/* break; */
843
844		default:
845			SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
846			ret= -1;
847			goto end;
848			/* break; */
849			}
850
851		if (!s->s3->tmp.reuse_message && !skip)
852			{
853			if (s->debug)
854				{
855				if ((ret=BIO_flush(s->wbio)) <= 0)
856					goto end;
857				}
858
859
860			if ((cb != NULL) && (s->state != state))
861				{
862				new_state=s->state;
863				s->state=state;
864				cb(s,SSL_CB_ACCEPT_LOOP,1);
865				s->state=new_state;
866				}
867			}
868		skip=0;
869		}
870end:
871	/* BIO_flush(s->wbio); */
872
873	s->in_handshake--;
874	if (cb != NULL)
875		cb(s,SSL_CB_ACCEPT_EXIT,ret);
876	return(ret);
877	}
878
879int ssl3_send_hello_request(SSL *s)
880	{
881	unsigned char *p;
882
883	if (s->state == SSL3_ST_SW_HELLO_REQ_A)
884		{
885		p=(unsigned char *)s->init_buf->data;
886		*(p++)=SSL3_MT_HELLO_REQUEST;
887		*(p++)=0;
888		*(p++)=0;
889		*(p++)=0;
890
891		s->state=SSL3_ST_SW_HELLO_REQ_B;
892		/* number of bytes to write */
893		s->init_num=4;
894		s->init_off=0;
895		}
896
897	/* SSL3_ST_SW_HELLO_REQ_B */
898	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
899	}
900
901int ssl3_check_client_hello(SSL *s)
902	{
903	int ok;
904	long n;
905
906	/* this function is called when we really expect a Certificate message,
907	 * so permit appropriate message length */
908	n=s->method->ssl_get_message(s,
909		SSL3_ST_SR_CERT_A,
910		SSL3_ST_SR_CERT_B,
911		-1,
912		s->max_cert_list,
913		&ok);
914	if (!ok) return((int)n);
915	s->s3->tmp.reuse_message = 1;
916	if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
917		{
918		/* We only allow the client to restart the handshake once per
919		 * negotiation. */
920		if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
921			{
922			SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
923			return -1;
924			}
925		/* Throw away what we have done so far in the current handshake,
926		 * which will now be aborted. (A full SSL_clear would be too much.) */
927#ifndef OPENSSL_NO_DH
928		if (s->s3->tmp.dh != NULL)
929			{
930			DH_free(s->s3->tmp.dh);
931			s->s3->tmp.dh = NULL;
932			}
933#endif
934#ifndef OPENSSL_NO_ECDH
935		if (s->s3->tmp.ecdh != NULL)
936			{
937			EC_KEY_free(s->s3->tmp.ecdh);
938			s->s3->tmp.ecdh = NULL;
939			}
940#endif
941		s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
942		return 2;
943		}
944	return 1;
945}
946
947int ssl3_get_client_hello(SSL *s)
948	{
949	int i,j,ok,al,ret= -1;
950	unsigned int cookie_len;
951	long n;
952	unsigned long id;
953	unsigned char *p,*d,*q;
954	SSL_CIPHER *c;
955#ifndef OPENSSL_NO_COMP
956	SSL_COMP *comp=NULL;
957#endif
958	STACK_OF(SSL_CIPHER) *ciphers=NULL;
959
960	/* We do this so that we will respond with our native type.
961	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
962	 * This down switching should be handled by a different method.
963	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
964	 * TLSv1.
965	 */
966	if (s->state == SSL3_ST_SR_CLNT_HELLO_A
967		)
968		{
969		s->state=SSL3_ST_SR_CLNT_HELLO_B;
970		}
971	s->first_packet=1;
972	n=s->method->ssl_get_message(s,
973		SSL3_ST_SR_CLNT_HELLO_B,
974		SSL3_ST_SR_CLNT_HELLO_C,
975		SSL3_MT_CLIENT_HELLO,
976		SSL3_RT_MAX_PLAIN_LENGTH,
977		&ok);
978
979	if (!ok) return((int)n);
980	s->first_packet=0;
981	d=p=(unsigned char *)s->init_msg;
982
983	/* use version from inside client hello, not from record header
984	 * (may differ: see RFC 2246, Appendix E, second paragraph) */
985	s->client_version=(((int)p[0])<<8)|(int)p[1];
986	p+=2;
987
988	if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
989	    (s->version != DTLS1_VERSION && s->client_version < s->version))
990		{
991		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
992		if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
993			!s->enc_write_ctx && !s->write_hash)
994			{
995			/* similar to ssl3_get_record, send alert using remote version number */
996			s->version = s->client_version;
997			}
998		al = SSL_AD_PROTOCOL_VERSION;
999		goto f_err;
1000		}
1001
1002	/* If we require cookies and this ClientHello doesn't
1003	 * contain one, just return since we do not want to
1004	 * allocate any memory yet. So check cookie length...
1005	 */
1006	if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1007		{
1008		unsigned int session_length, cookie_length;
1009
1010		session_length = *(p + SSL3_RANDOM_SIZE);
1011		cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1012
1013		if (cookie_length == 0)
1014			return 1;
1015		}
1016
1017	/* load the client random */
1018	memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1019	p+=SSL3_RANDOM_SIZE;
1020
1021	/* get the session-id */
1022	j= *(p++);
1023
1024	s->hit=0;
1025	/* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1026	 * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1027	 * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1028	 * than a change to default behavior so that applications relying on this for security
1029	 * won't even compile against older library versions).
1030	 *
1031	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1032	 * renegotiation but not a new session (s->new_session remains unset): for servers,
1033	 * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1034	 * setting will be ignored.
1035	 */
1036	if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1037		{
1038	        if (!s->session_creation_enabled)
1039			{
1040			ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1041			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
1042			goto err;
1043		}
1044		if (!ssl_get_new_session(s,1))
1045			goto err;
1046		}
1047	else
1048		{
1049		i=ssl_get_prev_session(s, p, j, d + n);
1050		if (i == 1)
1051			{ /* previous session */
1052			s->hit=1;
1053			}
1054		else if (i == -1)
1055			goto err;
1056		else /* i == 0 */
1057			{
1058		        if (!s->session_creation_enabled)
1059				{
1060				ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
1061				SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_SESSION_MAY_NOT_BE_CREATED);
1062				goto err;
1063				}
1064			if (!ssl_get_new_session(s,1))
1065				goto err;
1066			}
1067		}
1068
1069	p+=j;
1070
1071	if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1072		{
1073		/* cookie stuff */
1074		cookie_len = *(p++);
1075
1076		/*
1077		 * The ClientHello may contain a cookie even if the
1078		 * HelloVerify message has not been sent--make sure that it
1079		 * does not cause an overflow.
1080		 */
1081		if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1082			{
1083			/* too much data */
1084			al = SSL_AD_DECODE_ERROR;
1085			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1086			goto f_err;
1087			}
1088
1089		/* verify the cookie if appropriate option is set. */
1090		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1091			cookie_len > 0)
1092			{
1093			memcpy(s->d1->rcvd_cookie, p, cookie_len);
1094
1095			if ( s->ctx->app_verify_cookie_cb != NULL)
1096				{
1097				if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1098					cookie_len) == 0)
1099					{
1100					al=SSL_AD_HANDSHAKE_FAILURE;
1101					SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1102						SSL_R_COOKIE_MISMATCH);
1103					goto f_err;
1104					}
1105				/* else cookie verification succeeded */
1106				}
1107			else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1108						  s->d1->cookie_len) != 0) /* default verification */
1109				{
1110					al=SSL_AD_HANDSHAKE_FAILURE;
1111					SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1112						SSL_R_COOKIE_MISMATCH);
1113					goto f_err;
1114				}
1115
1116			ret = 2;
1117			}
1118
1119		p += cookie_len;
1120		}
1121
1122	n2s(p,i);
1123	if ((i == 0) && (j != 0))
1124		{
1125		/* we need a cipher if we are not resuming a session */
1126		al=SSL_AD_ILLEGAL_PARAMETER;
1127		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1128		goto f_err;
1129		}
1130	if ((p+i) >= (d+n))
1131		{
1132		/* not enough data */
1133		al=SSL_AD_DECODE_ERROR;
1134		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1135		goto f_err;
1136		}
1137	if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1138		== NULL))
1139		{
1140		goto err;
1141		}
1142	p+=i;
1143
1144	/* If it is a hit, check that the cipher is in the list */
1145	if ((s->hit) && (i > 0))
1146		{
1147		j=0;
1148		id=s->session->cipher->id;
1149
1150#ifdef CIPHER_DEBUG
1151		printf("client sent %d ciphers\n",sk_num(ciphers));
1152#endif
1153		for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1154			{
1155			c=sk_SSL_CIPHER_value(ciphers,i);
1156#ifdef CIPHER_DEBUG
1157			printf("client [%2d of %2d]:%s\n",
1158				i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1159#endif
1160			if (c->id == id)
1161				{
1162				j=1;
1163				break;
1164				}
1165			}
1166/* Disabled because it can be used in a ciphersuite downgrade
1167 * attack: CVE-2010-4180.
1168 */
1169#if 0
1170		if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1171			{
1172			/* Special case as client bug workaround: the previously used cipher may
1173			 * not be in the current list, the client instead might be trying to
1174			 * continue using a cipher that before wasn't chosen due to server
1175			 * preferences.  We'll have to reject the connection if the cipher is not
1176			 * enabled, though. */
1177			c = sk_SSL_CIPHER_value(ciphers, 0);
1178			if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1179				{
1180				s->session->cipher = c;
1181				j = 1;
1182				}
1183			}
1184#endif
1185		if (j == 0)
1186			{
1187			/* we need to have the cipher in the cipher
1188			 * list if we are asked to reuse it */
1189			al=SSL_AD_ILLEGAL_PARAMETER;
1190			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1191			goto f_err;
1192			}
1193		}
1194
1195	/* compression */
1196	i= *(p++);
1197	if ((p+i) > (d+n))
1198		{
1199		/* not enough data */
1200		al=SSL_AD_DECODE_ERROR;
1201		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1202		goto f_err;
1203		}
1204	q=p;
1205	for (j=0; j<i; j++)
1206		{
1207		if (p[j] == 0) break;
1208		}
1209
1210	p+=i;
1211	if (j >= i)
1212		{
1213		/* no compress */
1214		al=SSL_AD_DECODE_ERROR;
1215		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1216		goto f_err;
1217		}
1218
1219#ifndef OPENSSL_NO_TLSEXT
1220	/* TLS extensions*/
1221	if (s->version >= SSL3_VERSION)
1222		{
1223		if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
1224			{
1225			/* 'al' set by ssl_parse_clienthello_tlsext */
1226			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1227			goto f_err;
1228			}
1229		}
1230		if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1231			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
1232			goto err;
1233		}
1234
1235	/* Check if we want to use external pre-shared secret for this
1236	 * handshake for not reused session only. We need to generate
1237	 * server_random before calling tls_session_secret_cb in order to allow
1238	 * SessionTicket processing to use it in key derivation. */
1239	{
1240		unsigned char *pos;
1241		pos=s->s3->server_random;
1242		if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1243			{
1244			al=SSL_AD_INTERNAL_ERROR;
1245			goto f_err;
1246			}
1247	}
1248
1249	if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1250		{
1251		SSL_CIPHER *pref_cipher=NULL;
1252
1253		s->session->master_key_length=sizeof(s->session->master_key);
1254		if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1255			ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1256			{
1257			s->hit=1;
1258			s->session->ciphers=ciphers;
1259			s->session->verify_result=X509_V_OK;
1260
1261			ciphers=NULL;
1262
1263			/* check if some cipher was preferred by call back */
1264			pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1265			if (pref_cipher == NULL)
1266				{
1267				al=SSL_AD_HANDSHAKE_FAILURE;
1268				SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1269				goto f_err;
1270				}
1271
1272			s->session->cipher=pref_cipher;
1273
1274			if (s->cipher_list)
1275				sk_SSL_CIPHER_free(s->cipher_list);
1276
1277			if (s->cipher_list_by_id)
1278				sk_SSL_CIPHER_free(s->cipher_list_by_id);
1279
1280			s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1281			s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1282			}
1283		}
1284#endif
1285
1286	/* Worst case, we will use the NULL compression, but if we have other
1287	 * options, we will now look for them.  We have i-1 compression
1288	 * algorithms from the client, starting at q. */
1289	s->s3->tmp.new_compression=NULL;
1290#ifndef OPENSSL_NO_COMP
1291	/* This only happens if we have a cache hit */
1292	if (s->session->compress_meth != 0)
1293		{
1294		int m, comp_id = s->session->compress_meth;
1295		/* Perform sanity checks on resumed compression algorithm */
1296		/* Can't disable compression */
1297		if (s->options & SSL_OP_NO_COMPRESSION)
1298			{
1299			al=SSL_AD_INTERNAL_ERROR;
1300			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1301			goto f_err;
1302			}
1303		/* Look for resumed compression method */
1304		for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1305			{
1306			comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1307			if (comp_id == comp->id)
1308				{
1309				s->s3->tmp.new_compression=comp;
1310				break;
1311				}
1312			}
1313		if (s->s3->tmp.new_compression == NULL)
1314			{
1315			al=SSL_AD_INTERNAL_ERROR;
1316			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1317			goto f_err;
1318			}
1319		/* Look for resumed method in compression list */
1320		for (m = 0; m < i; m++)
1321			{
1322			if (q[m] == comp_id)
1323				break;
1324			}
1325		if (m >= i)
1326			{
1327			al=SSL_AD_ILLEGAL_PARAMETER;
1328			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1329			goto f_err;
1330			}
1331		}
1332	else if (s->hit)
1333		comp = NULL;
1334	else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1335		{ /* See if we have a match */
1336		int m,nn,o,v,done=0;
1337
1338		nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1339		for (m=0; m<nn; m++)
1340			{
1341			comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1342			v=comp->id;
1343			for (o=0; o<i; o++)
1344				{
1345				if (v == q[o])
1346					{
1347					done=1;
1348					break;
1349					}
1350				}
1351			if (done) break;
1352			}
1353		if (done)
1354			s->s3->tmp.new_compression=comp;
1355		else
1356			comp=NULL;
1357		}
1358#else
1359	/* If compression is disabled we'd better not try to resume a session
1360	 * using compression.
1361	 */
1362	if (s->session->compress_meth != 0)
1363		{
1364		al=SSL_AD_INTERNAL_ERROR;
1365		SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1366		goto f_err;
1367		}
1368#endif
1369
1370	/* Given s->session->ciphers and SSL_get_ciphers, we must
1371	 * pick a cipher */
1372
1373	if (!s->hit)
1374		{
1375#ifdef OPENSSL_NO_COMP
1376		s->session->compress_meth=0;
1377#else
1378		s->session->compress_meth=(comp == NULL)?0:comp->id;
1379#endif
1380		if (s->session->ciphers != NULL)
1381			sk_SSL_CIPHER_free(s->session->ciphers);
1382		s->session->ciphers=ciphers;
1383		if (ciphers == NULL)
1384			{
1385			al=SSL_AD_ILLEGAL_PARAMETER;
1386			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1387			goto f_err;
1388			}
1389		ciphers=NULL;
1390		c=ssl3_choose_cipher(s,s->session->ciphers,
1391				     SSL_get_ciphers(s));
1392
1393		if (c == NULL)
1394			{
1395			al=SSL_AD_HANDSHAKE_FAILURE;
1396			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1397			goto f_err;
1398			}
1399		s->s3->tmp.new_cipher=c;
1400		}
1401	else
1402		{
1403		/* Session-id reuse */
1404#ifdef REUSE_CIPHER_BUG
1405		STACK_OF(SSL_CIPHER) *sk;
1406		SSL_CIPHER *nc=NULL;
1407		SSL_CIPHER *ec=NULL;
1408
1409		if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1410			{
1411			sk=s->session->ciphers;
1412			for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1413				{
1414				c=sk_SSL_CIPHER_value(sk,i);
1415				if (c->algorithm_enc & SSL_eNULL)
1416					nc=c;
1417				if (SSL_C_IS_EXPORT(c))
1418					ec=c;
1419				}
1420			if (nc != NULL)
1421				s->s3->tmp.new_cipher=nc;
1422			else if (ec != NULL)
1423				s->s3->tmp.new_cipher=ec;
1424			else
1425				s->s3->tmp.new_cipher=s->session->cipher;
1426			}
1427		else
1428#endif
1429		s->s3->tmp.new_cipher=s->session->cipher;
1430		}
1431
1432	if (TLS1_get_version(s) < TLS1_2_VERSION || !(s->verify_mode & SSL_VERIFY_PEER))
1433		{
1434		if (!ssl3_digest_cached_records(s))
1435			{
1436			al = SSL_AD_INTERNAL_ERROR;
1437			goto f_err;
1438			}
1439		}
1440
1441	/* we now have the following setup.
1442	 * client_random
1443	 * cipher_list 		- our prefered list of ciphers
1444	 * ciphers 		- the clients prefered list of ciphers
1445	 * compression		- basically ignored right now
1446	 * ssl version is set	- sslv3
1447	 * s->session		- The ssl session has been setup.
1448	 * s->hit		- session reuse flag
1449	 * s->tmp.new_cipher	- the new cipher to use.
1450	 */
1451
1452	/* Handles TLS extensions that we couldn't check earlier */
1453	if (s->version >= SSL3_VERSION)
1454		{
1455		if (ssl_check_clienthello_tlsext_late(s) <= 0)
1456			{
1457			SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1458			goto err;
1459			}
1460		}
1461
1462	if (ret < 0) ret=1;
1463	if (0)
1464		{
1465f_err:
1466		ssl3_send_alert(s,SSL3_AL_FATAL,al);
1467		}
1468err:
1469	if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1470	return(ret);
1471	}
1472
1473int ssl3_send_server_hello(SSL *s)
1474	{
1475	unsigned char *buf;
1476	unsigned char *p,*d;
1477	int i,sl;
1478	unsigned long l;
1479
1480	if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1481		{
1482		/* We only accept ChannelIDs on connections with ECDHE in order
1483		 * to avoid a known attack while we fix ChannelID itself. */
1484		if (s->s3 &&
1485		    s->s3->tlsext_channel_id_valid &&
1486		    (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
1487			s->s3->tlsext_channel_id_valid = 0;
1488
1489		/* If this is a resumption and the original handshake didn't
1490		 * support ChannelID then we didn't record the original
1491		 * handshake hashes in the session and so cannot resume with
1492		 * ChannelIDs. */
1493		if (s->hit &&
1494		    s->s3->tlsext_channel_id_new &&
1495		    s->session->original_handshake_hash_len == 0)
1496			s->s3->tlsext_channel_id_valid = 0;
1497
1498		buf=(unsigned char *)s->init_buf->data;
1499#ifdef OPENSSL_NO_TLSEXT
1500		p=s->s3->server_random;
1501		if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1502			return -1;
1503#endif
1504		/* Do the message type and length last */
1505		d=p= &(buf[4]);
1506
1507		*(p++)=s->version>>8;
1508		*(p++)=s->version&0xff;
1509
1510		/* Random stuff */
1511		memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1512		p+=SSL3_RANDOM_SIZE;
1513
1514		/* There are several cases for the session ID to send
1515		 * back in the server hello:
1516		 * - For session reuse from the session cache,
1517		 *   we send back the old session ID.
1518		 * - If stateless session reuse (using a session ticket)
1519		 *   is successful, we send back the client's "session ID"
1520		 *   (which doesn't actually identify the session).
1521		 * - If it is a new session, we send back the new
1522		 *   session ID.
1523		 * - However, if we want the new session to be single-use,
1524		 *   we send back a 0-length session ID.
1525		 * s->hit is non-zero in either case of session reuse,
1526		 * so the following won't overwrite an ID that we're supposed
1527		 * to send back.
1528		 */
1529		if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1530			&& !s->hit)
1531			s->session->session_id_length=0;
1532
1533		sl=s->session->session_id_length;
1534		if (sl > (int)sizeof(s->session->session_id))
1535			{
1536			SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1537			return -1;
1538			}
1539		*(p++)=sl;
1540		memcpy(p,s->session->session_id,sl);
1541		p+=sl;
1542
1543		/* put the cipher */
1544		i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1545		p+=i;
1546
1547		/* put the compression method */
1548#ifdef OPENSSL_NO_COMP
1549			*(p++)=0;
1550#else
1551		if (s->s3->tmp.new_compression == NULL)
1552			*(p++)=0;
1553		else
1554			*(p++)=s->s3->tmp.new_compression->id;
1555#endif
1556#ifndef OPENSSL_NO_TLSEXT
1557		if (ssl_prepare_serverhello_tlsext(s) <= 0)
1558			{
1559			SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1560			return -1;
1561			}
1562		if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1563			{
1564			SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1565			return -1;
1566			}
1567#endif
1568		/* do the header */
1569		l=(p-d);
1570		d=buf;
1571		*(d++)=SSL3_MT_SERVER_HELLO;
1572		l2n3(l,d);
1573
1574		s->state=SSL3_ST_SW_SRVR_HELLO_B;
1575		/* number of bytes to write */
1576		s->init_num=p-buf;
1577		s->init_off=0;
1578		}
1579
1580	/* SSL3_ST_SW_SRVR_HELLO_B */
1581	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1582	}
1583
1584int ssl3_send_server_done(SSL *s)
1585	{
1586	unsigned char *p;
1587
1588	if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1589		{
1590		p=(unsigned char *)s->init_buf->data;
1591
1592		/* do the header */
1593		*(p++)=SSL3_MT_SERVER_DONE;
1594		*(p++)=0;
1595		*(p++)=0;
1596		*(p++)=0;
1597
1598		s->state=SSL3_ST_SW_SRVR_DONE_B;
1599		/* number of bytes to write */
1600		s->init_num=4;
1601		s->init_off=0;
1602		}
1603
1604	/* SSL3_ST_SW_SRVR_DONE_B */
1605	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1606	}
1607
1608int ssl3_send_server_key_exchange(SSL *s)
1609	{
1610#ifndef OPENSSL_NO_RSA
1611	unsigned char *q;
1612	int j,num;
1613	RSA *rsa;
1614	unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1615	unsigned int u;
1616#endif
1617#ifndef OPENSSL_NO_DH
1618	DH *dh=NULL,*dhp;
1619#endif
1620#ifndef OPENSSL_NO_ECDH
1621	EC_KEY *ecdh=NULL, *ecdhp;
1622	unsigned char *encodedPoint = NULL;
1623	int encodedlen = 0;
1624	int curve_id = 0;
1625	BN_CTX *bn_ctx = NULL;
1626#endif
1627#ifndef OPENSSL_NO_PSK
1628	const char* psk_identity_hint;
1629	size_t psk_identity_hint_len;
1630#endif
1631	EVP_PKEY *pkey;
1632	const EVP_MD *md = NULL;
1633	unsigned char *p,*d;
1634	int al,i;
1635	unsigned long alg_k;
1636	unsigned long alg_a;
1637	int n;
1638	CERT *cert;
1639	BIGNUM *r[4];
1640	int nr[4],kn;
1641	BUF_MEM *buf;
1642	EVP_MD_CTX md_ctx;
1643
1644	EVP_MD_CTX_init(&md_ctx);
1645	if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1646		{
1647		alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1648		alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1649		cert=s->cert;
1650
1651		buf=s->init_buf;
1652
1653		r[0]=r[1]=r[2]=r[3]=NULL;
1654		n=0;
1655#ifndef OPENSSL_NO_PSK
1656		if (alg_a & SSL_aPSK)
1657			{
1658			/* size for PSK identity hint */
1659			psk_identity_hint = s->session->psk_identity_hint;
1660			if (psk_identity_hint)
1661				psk_identity_hint_len = strlen(psk_identity_hint);
1662			else
1663				psk_identity_hint_len = 0;
1664			n+=2+psk_identity_hint_len;
1665			}
1666#endif /* !OPENSSL_NO_PSK */
1667#ifndef OPENSSL_NO_RSA
1668		if (alg_k & SSL_kRSA)
1669			{
1670			rsa=cert->rsa_tmp;
1671			if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1672				{
1673				rsa=s->cert->rsa_tmp_cb(s,
1674				      SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1675				      SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1676				if(rsa == NULL)
1677				{
1678					al=SSL_AD_HANDSHAKE_FAILURE;
1679					SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1680					goto f_err;
1681				}
1682				RSA_up_ref(rsa);
1683				cert->rsa_tmp=rsa;
1684				}
1685			if (rsa == NULL)
1686				{
1687				al=SSL_AD_HANDSHAKE_FAILURE;
1688				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1689				goto f_err;
1690				}
1691			r[0]=rsa->n;
1692			r[1]=rsa->e;
1693			s->s3->tmp.use_rsa_tmp=1;
1694			}
1695#endif
1696#ifndef OPENSSL_NO_DH
1697		else if (alg_k & SSL_kEDH)
1698			{
1699			dhp=cert->dh_tmp;
1700			if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1701				dhp=s->cert->dh_tmp_cb(s,
1702				      SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1703				      SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1704			if (dhp == NULL)
1705				{
1706				al=SSL_AD_HANDSHAKE_FAILURE;
1707				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1708				goto f_err;
1709				}
1710
1711			if (s->s3->tmp.dh != NULL)
1712				{
1713				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1714				goto err;
1715				}
1716
1717			if ((dh=DHparams_dup(dhp)) == NULL)
1718				{
1719				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1720				goto err;
1721				}
1722
1723			s->s3->tmp.dh=dh;
1724			if ((dhp->pub_key == NULL ||
1725			     dhp->priv_key == NULL ||
1726			     (s->options & SSL_OP_SINGLE_DH_USE)))
1727				{
1728				if(!DH_generate_key(dh))
1729				    {
1730				    SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1731					   ERR_R_DH_LIB);
1732				    goto err;
1733				    }
1734				}
1735			else
1736				{
1737				dh->pub_key=BN_dup(dhp->pub_key);
1738				dh->priv_key=BN_dup(dhp->priv_key);
1739				if ((dh->pub_key == NULL) ||
1740					(dh->priv_key == NULL))
1741					{
1742					SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1743					goto err;
1744					}
1745				}
1746			r[0]=dh->p;
1747			r[1]=dh->g;
1748			r[2]=dh->pub_key;
1749			}
1750#endif
1751#ifndef OPENSSL_NO_ECDH
1752		else if (alg_k & SSL_kEECDH)
1753			{
1754			const EC_GROUP *group;
1755
1756			ecdhp=cert->ecdh_tmp;
1757			if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1758				{
1759				ecdhp=s->cert->ecdh_tmp_cb(s,
1760				      SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1761				      SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1762				}
1763			if (ecdhp == NULL)
1764				{
1765				al=SSL_AD_HANDSHAKE_FAILURE;
1766				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1767				goto f_err;
1768				}
1769
1770			if (s->s3->tmp.ecdh != NULL)
1771				{
1772				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1773				goto err;
1774				}
1775
1776			/* Duplicate the ECDH structure. */
1777			if (ecdhp == NULL)
1778				{
1779				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1780				goto err;
1781				}
1782			if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1783				{
1784				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1785				goto err;
1786				}
1787
1788			s->s3->tmp.ecdh=ecdh;
1789			if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1790			    (EC_KEY_get0_private_key(ecdh) == NULL) ||
1791			    (s->options & SSL_OP_SINGLE_ECDH_USE))
1792				{
1793				if(!EC_KEY_generate_key(ecdh))
1794				    {
1795				    SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1796				    goto err;
1797				    }
1798				}
1799
1800			if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1801			    (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1802			    (EC_KEY_get0_private_key(ecdh) == NULL))
1803				{
1804				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1805				goto err;
1806				}
1807
1808			if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1809			    (EC_GROUP_get_degree(group) > 163))
1810				{
1811				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1812				goto err;
1813				}
1814
1815			/* XXX: For now, we only support ephemeral ECDH
1816			 * keys over named (not generic) curves. For
1817			 * supported named curves, curve_id is non-zero.
1818			 */
1819			if ((curve_id =
1820			    tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1821			    == 0)
1822				{
1823				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1824				goto err;
1825				}
1826
1827			/* Encode the public key.
1828			 * First check the size of encoding and
1829			 * allocate memory accordingly.
1830			 */
1831			encodedlen = EC_POINT_point2oct(group,
1832			    EC_KEY_get0_public_key(ecdh),
1833			    POINT_CONVERSION_UNCOMPRESSED,
1834			    NULL, 0, NULL);
1835
1836			encodedPoint = (unsigned char *)
1837			    OPENSSL_malloc(encodedlen*sizeof(unsigned char));
1838			bn_ctx = BN_CTX_new();
1839			if ((encodedPoint == NULL) || (bn_ctx == NULL))
1840				{
1841				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1842				goto err;
1843				}
1844
1845
1846			encodedlen = EC_POINT_point2oct(group,
1847			    EC_KEY_get0_public_key(ecdh),
1848			    POINT_CONVERSION_UNCOMPRESSED,
1849			    encodedPoint, encodedlen, bn_ctx);
1850
1851			if (encodedlen == 0)
1852				{
1853				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1854				goto err;
1855				}
1856
1857			BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1858
1859			/* XXX: For now, we only support named (not
1860			 * generic) curves in ECDH ephemeral key exchanges.
1861			 * In this situation, we need four additional bytes
1862			 * to encode the entire ServerECDHParams
1863			 * structure.
1864			 */
1865			n += 4 + encodedlen;
1866
1867			/* We'll generate the serverKeyExchange message
1868			 * explicitly so we can set these to NULLs
1869			 */
1870			r[0]=NULL;
1871			r[1]=NULL;
1872			r[2]=NULL;
1873			r[3]=NULL;
1874			}
1875#endif /* !OPENSSL_NO_ECDH */
1876#ifndef OPENSSL_NO_SRP
1877		else if (alg_k & SSL_kSRP)
1878			{
1879			if ((s->srp_ctx.N == NULL) ||
1880				(s->srp_ctx.g == NULL) ||
1881				(s->srp_ctx.s == NULL) ||
1882				(s->srp_ctx.B == NULL))
1883				{
1884				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1885				goto err;
1886				}
1887			r[0]=s->srp_ctx.N;
1888			r[1]=s->srp_ctx.g;
1889			r[2]=s->srp_ctx.s;
1890			r[3]=s->srp_ctx.B;
1891			}
1892#endif
1893		else if (!(alg_k & SSL_kPSK))
1894			{
1895			al=SSL_AD_HANDSHAKE_FAILURE;
1896			SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1897			goto f_err;
1898			}
1899		for (i=0; i < 4 && r[i] != NULL; i++)
1900			{
1901			nr[i]=BN_num_bytes(r[i]);
1902#ifndef OPENSSL_NO_SRP
1903			if ((i == 2) && (alg_k & SSL_kSRP))
1904				n+=1+nr[i];
1905			else
1906#endif
1907			n+=2+nr[i];
1908			}
1909
1910		if (!(alg_a & (SSL_aNULL|SSL_aSRP))
1911			/* Among PSK ciphersuites only RSA uses a certificate */
1912			&& !((alg_a & SSL_aPSK) && !(alg_k & SSL_kRSA)))
1913			{
1914			if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1915				== NULL)
1916				{
1917				al=SSL_AD_DECODE_ERROR;
1918				goto f_err;
1919				}
1920			kn=EVP_PKEY_size(pkey);
1921			}
1922		else
1923			{
1924			pkey=NULL;
1925			kn=0;
1926			}
1927
1928		if (!BUF_MEM_grow_clean(buf,n+4+kn))
1929			{
1930			SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1931			goto err;
1932			}
1933		d=(unsigned char *)s->init_buf->data;
1934		p= &(d[4]);
1935
1936		for (i=0; i < 4 && r[i] != NULL; i++)
1937			{
1938#ifndef OPENSSL_NO_SRP
1939			if ((i == 2) && (alg_k & SSL_kSRP))
1940				{
1941				*p = nr[i];
1942				p++;
1943				}
1944			else
1945#endif
1946			s2n(nr[i],p);
1947			BN_bn2bin(r[i],p);
1948			p+=nr[i];
1949			}
1950
1951/* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
1952 * When one of them is used, the server key exchange record needs to have both
1953 * the psk_identity_hint and the ServerECDHParams. */
1954#ifndef OPENSSL_NO_PSK
1955		if (alg_a & SSL_aPSK)
1956			{
1957			/* copy PSK identity hint (if provided) */
1958			s2n(psk_identity_hint_len, p);
1959			if (psk_identity_hint_len > 0)
1960				{
1961				memcpy(p, psk_identity_hint, psk_identity_hint_len);
1962				p+=psk_identity_hint_len;
1963				}
1964			}
1965#endif /* OPENSSL_NO_PSK */
1966
1967#ifndef OPENSSL_NO_ECDH
1968		if (alg_k & SSL_kEECDH)
1969			{
1970			/* XXX: For now, we only support named (not generic) curves.
1971			 * In this situation, the serverKeyExchange message has:
1972			 * [1 byte CurveType], [2 byte CurveName]
1973			 * [1 byte length of encoded point], followed by
1974			 * the actual encoded point itself
1975			 */
1976			*p = NAMED_CURVE_TYPE;
1977			p += 1;
1978			*p = 0;
1979			p += 1;
1980			*p = curve_id;
1981			p += 1;
1982			*p = encodedlen;
1983			p += 1;
1984			memcpy((unsigned char*)p,
1985			    (unsigned char *)encodedPoint,
1986			    encodedlen);
1987			OPENSSL_free(encodedPoint);
1988			encodedPoint = NULL;
1989			p += encodedlen;
1990			}
1991#endif /* OPENSSL_NO_ECDH */
1992
1993		/* not anonymous */
1994		if (pkey != NULL)
1995			{
1996			/* n is the length of the params, they start at &(d[4])
1997			 * and p points to the space at the end. */
1998#ifndef OPENSSL_NO_RSA
1999			if (pkey->type == EVP_PKEY_RSA
2000					&& TLS1_get_version(s) < TLS1_2_VERSION)
2001				{
2002				q=md_buf;
2003				j=0;
2004				for (num=2; num > 0; num--)
2005					{
2006					EVP_MD_CTX_set_flags(&md_ctx,
2007						EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2008					EVP_DigestInit_ex(&md_ctx,(num == 2)
2009						?s->ctx->md5:s->ctx->sha1, NULL);
2010					EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2011					EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2012					EVP_DigestUpdate(&md_ctx,&(d[4]),n);
2013					EVP_DigestFinal_ex(&md_ctx,q,
2014						(unsigned int *)&i);
2015					q+=i;
2016					j+=i;
2017					}
2018				if (RSA_sign(NID_md5_sha1, md_buf, j,
2019					&(p[2]), &u, pkey->pkey.rsa) <= 0)
2020					{
2021					SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2022					goto err;
2023					}
2024				s2n(u,p);
2025				n+=u+2;
2026				}
2027			else
2028#endif /* OPENSSL_NO_RSA */
2029			if (md)
2030				{
2031				/* For TLS1.2 and later send signature
2032				 * algorithm */
2033				if (TLS1_get_version(s) >= TLS1_2_VERSION)
2034					{
2035					if (!tls12_get_sigandhash(p, pkey, md))
2036						{
2037						/* Should never happen */
2038						al=SSL_AD_INTERNAL_ERROR;
2039						SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2040						goto f_err;
2041						}
2042					p+=2;
2043					}
2044#ifdef SSL_DEBUG
2045				fprintf(stderr, "Using hash %s\n",
2046							EVP_MD_name(md));
2047#endif
2048				EVP_SignInit_ex(&md_ctx, md, NULL);
2049				EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2050				EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2051				EVP_SignUpdate(&md_ctx,&(d[4]),n);
2052				if (!EVP_SignFinal(&md_ctx,&(p[2]),
2053					(unsigned int *)&i,pkey))
2054					{
2055					SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2056					goto err;
2057					}
2058				s2n(i,p);
2059				n+=i+2;
2060				if (TLS1_get_version(s) >= TLS1_2_VERSION)
2061					n+= 2;
2062				}
2063			else
2064				{
2065				/* Is this error check actually needed? */
2066				al=SSL_AD_HANDSHAKE_FAILURE;
2067				SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2068				goto f_err;
2069				}
2070			}
2071
2072		*(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
2073		l2n3(n,d);
2074
2075		/* we should now have things packed up, so lets send
2076		 * it off */
2077		s->init_num=n+4;
2078		s->init_off=0;
2079		}
2080
2081	s->state = SSL3_ST_SW_KEY_EXCH_B;
2082	EVP_MD_CTX_cleanup(&md_ctx);
2083	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2084f_err:
2085	ssl3_send_alert(s,SSL3_AL_FATAL,al);
2086err:
2087#ifndef OPENSSL_NO_ECDH
2088	if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2089	BN_CTX_free(bn_ctx);
2090#endif
2091	EVP_MD_CTX_cleanup(&md_ctx);
2092	return(-1);
2093	}
2094
2095int ssl3_send_certificate_request(SSL *s)
2096	{
2097	unsigned char *p,*d;
2098	int i,j,nl,off,n;
2099	STACK_OF(X509_NAME) *sk=NULL;
2100	X509_NAME *name;
2101	BUF_MEM *buf;
2102
2103	if (s->state == SSL3_ST_SW_CERT_REQ_A)
2104		{
2105		buf=s->init_buf;
2106
2107		d=p=(unsigned char *)&(buf->data[4]);
2108
2109		/* get the list of acceptable cert types */
2110		p++;
2111		n=ssl3_get_req_cert_type(s,p);
2112		d[0]=n;
2113		p+=n;
2114		n++;
2115
2116		if (TLS1_get_version(s) >= TLS1_2_VERSION)
2117			{
2118			nl = tls12_get_req_sig_algs(s, p + 2);
2119			s2n(nl, p);
2120			p += nl + 2;
2121			n += nl + 2;
2122			}
2123
2124		off=n;
2125		p+=2;
2126		n+=2;
2127
2128		sk=SSL_get_client_CA_list(s);
2129		nl=0;
2130		if (sk != NULL)
2131			{
2132			for (i=0; i<sk_X509_NAME_num(sk); i++)
2133				{
2134				name=sk_X509_NAME_value(sk,i);
2135				j=i2d_X509_NAME(name,NULL);
2136				if (!BUF_MEM_grow_clean(buf,4+n+j+2))
2137					{
2138					SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2139					goto err;
2140					}
2141				p=(unsigned char *)&(buf->data[4+n]);
2142				if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2143					{
2144					s2n(j,p);
2145					i2d_X509_NAME(name,&p);
2146					n+=2+j;
2147					nl+=2+j;
2148					}
2149				else
2150					{
2151					d=p;
2152					i2d_X509_NAME(name,&p);
2153					j-=2; s2n(j,d); j+=2;
2154					n+=j;
2155					nl+=j;
2156					}
2157				}
2158			}
2159		/* else no CA names */
2160		p=(unsigned char *)&(buf->data[4+off]);
2161		s2n(nl,p);
2162
2163		d=(unsigned char *)buf->data;
2164		*(d++)=SSL3_MT_CERTIFICATE_REQUEST;
2165		l2n3(n,d);
2166
2167		/* we should now have things packed up, so lets send
2168		 * it off */
2169
2170		s->init_num=n+4;
2171		s->init_off=0;
2172#ifdef NETSCAPE_HANG_BUG
2173		if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2174			{
2175			SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2176			goto err;
2177			}
2178		p=(unsigned char *)s->init_buf->data + s->init_num;
2179
2180		/* do the header */
2181		*(p++)=SSL3_MT_SERVER_DONE;
2182		*(p++)=0;
2183		*(p++)=0;
2184		*(p++)=0;
2185		s->init_num += 4;
2186#endif
2187
2188		s->state = SSL3_ST_SW_CERT_REQ_B;
2189		}
2190
2191	/* SSL3_ST_SW_CERT_REQ_B */
2192	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2193err:
2194	return(-1);
2195	}
2196
2197int ssl3_get_client_key_exchange(SSL *s)
2198	{
2199	int i,al,ok;
2200	long n;
2201	unsigned long alg_k;
2202	unsigned long alg_a;
2203	unsigned char *p;
2204#ifndef OPENSSL_NO_RSA
2205	RSA *rsa=NULL;
2206	EVP_PKEY *pkey=NULL;
2207#endif
2208#ifndef OPENSSL_NO_DH
2209	BIGNUM *pub=NULL;
2210	DH *dh_srvr;
2211#endif
2212#ifndef OPENSSL_NO_KRB5
2213	KSSL_ERR kssl_err;
2214#endif /* OPENSSL_NO_KRB5 */
2215
2216#ifndef OPENSSL_NO_ECDH
2217	EC_KEY *srvr_ecdh = NULL;
2218	EVP_PKEY *clnt_pub_pkey = NULL;
2219	EC_POINT *clnt_ecpoint = NULL;
2220	BN_CTX *bn_ctx = NULL;
2221#ifndef OPENSSL_NO_PSK
2222	unsigned int psk_len = 0;
2223	unsigned char psk[PSK_MAX_PSK_LEN];
2224#endif /* OPENSSL_NO_PSK */
2225#endif
2226
2227	n=s->method->ssl_get_message(s,
2228		SSL3_ST_SR_KEY_EXCH_A,
2229		SSL3_ST_SR_KEY_EXCH_B,
2230		SSL3_MT_CLIENT_KEY_EXCHANGE,
2231		2048, /* ??? */
2232		&ok);
2233
2234	if (!ok) return((int)n);
2235	p=(unsigned char *)s->init_msg;
2236
2237	alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2238	alg_a=s->s3->tmp.new_cipher->algorithm_auth;
2239
2240#ifndef OPENSSL_NO_PSK
2241	if (alg_a & SSL_aPSK)
2242		{
2243		unsigned char *t = NULL;
2244		unsigned char pre_ms[PSK_MAX_PSK_LEN*2+4];
2245		unsigned int pre_ms_len = 0;
2246		int psk_err = 1;
2247		char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2248
2249		al=SSL_AD_HANDSHAKE_FAILURE;
2250
2251		n2s(p, i);
2252		if (n != i+2 && !(alg_k & SSL_kEECDH))
2253			{
2254			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2255				SSL_R_LENGTH_MISMATCH);
2256			goto psk_err;
2257			}
2258		if (i > PSK_MAX_IDENTITY_LEN)
2259			{
2260			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2261				SSL_R_DATA_LENGTH_TOO_LONG);
2262			goto psk_err;
2263			}
2264		if (s->psk_server_callback == NULL)
2265			{
2266			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2267			       SSL_R_PSK_NO_SERVER_CB);
2268			goto psk_err;
2269			}
2270
2271		/* Create guaranteed NUL-terminated identity
2272		 * string for the callback */
2273		memcpy(tmp_id, p, i);
2274		memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2275		psk_len = s->psk_server_callback(s, tmp_id, psk, sizeof(psk));
2276
2277		if (psk_len > PSK_MAX_PSK_LEN)
2278			{
2279			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2280				ERR_R_INTERNAL_ERROR);
2281			goto psk_err;
2282			}
2283		else if (psk_len == 0)
2284			{
2285			/* PSK related to the given identity not found */
2286			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2287			       SSL_R_PSK_IDENTITY_NOT_FOUND);
2288			al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2289			goto psk_err;
2290			}
2291		if (!(alg_k & SSL_kEECDH))
2292			{
2293			/* Create the shared secret now if we're not using ECDHE-PSK.*/
2294			pre_ms_len=2+psk_len+2+psk_len;
2295			t = pre_ms;
2296			s2n(psk_len, t);
2297			memset(t, 0, psk_len);
2298			t+=psk_len;
2299			s2n(psk_len, t);
2300			memcpy(t, psk, psk_len);
2301
2302			s->session->master_key_length=
2303				s->method->ssl3_enc->generate_master_secret(s,
2304					s->session->master_key, pre_ms, pre_ms_len);
2305			}
2306		if (s->session->psk_identity != NULL)
2307			OPENSSL_free(s->session->psk_identity);
2308		s->session->psk_identity = BUF_strdup(tmp_id);
2309		OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2310		if (s->session->psk_identity == NULL)
2311			{
2312			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2313				ERR_R_MALLOC_FAILURE);
2314			goto psk_err;
2315			}
2316
2317		p += i;
2318		n -= (i + 2);
2319		psk_err = 0;
2320	psk_err:
2321		OPENSSL_cleanse(pre_ms, sizeof(pre_ms));
2322		if (psk_err != 0)
2323			goto f_err;
2324		}
2325#endif /* OPENSSL_NO_PSK */
2326	if (0) {}
2327#ifndef OPENSSL_NO_RSA
2328	if (alg_k & SSL_kRSA)
2329		{
2330		unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2331		int decrypt_len;
2332		unsigned char decrypt_good, version_good;
2333
2334		/* FIX THIS UP EAY EAY EAY EAY */
2335		if (s->s3->tmp.use_rsa_tmp)
2336			{
2337			if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2338				rsa=s->cert->rsa_tmp;
2339			/* Don't do a callback because rsa_tmp should
2340			 * be sent already */
2341			if (rsa == NULL)
2342				{
2343				al=SSL_AD_HANDSHAKE_FAILURE;
2344				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2345				goto f_err;
2346
2347				}
2348			}
2349		else
2350			{
2351			pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2352			if (	(pkey == NULL) ||
2353				(pkey->type != EVP_PKEY_RSA) ||
2354				(pkey->pkey.rsa == NULL))
2355				{
2356				al=SSL_AD_HANDSHAKE_FAILURE;
2357				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2358				goto f_err;
2359				}
2360			rsa=pkey->pkey.rsa;
2361			}
2362
2363		/* TLS and [incidentally] DTLS{0xFEFF} */
2364		if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2365			{
2366			n2s(p,i);
2367			if (n != i+2)
2368				{
2369				if (!(s->options & SSL_OP_TLS_D5_BUG))
2370					{
2371					SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2372					goto err;
2373					}
2374				else
2375					p-=2;
2376				}
2377			else
2378				n=i;
2379			}
2380
2381		/* We must not leak whether a decryption failure occurs because
2382		 * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2383		 * RFC 2246, section 7.4.7.1). The code follows that advice of
2384		 * the TLS RFC and generates a random premaster secret for the
2385		 * case that the decrypt fails. See
2386		 * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2387
2388		/* should be RAND_bytes, but we cannot work around a failure. */
2389		if (RAND_pseudo_bytes(rand_premaster_secret,
2390				      sizeof(rand_premaster_secret)) <= 0)
2391			goto err;
2392		decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2393		ERR_clear_error();
2394
2395		/* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2396		 * decrypt_good will be 0xff if so and zero otherwise. */
2397		decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2398
2399		/* If the version in the decrypted pre-master secret is correct
2400		 * then version_good will be 0xff, otherwise it'll be zero.
2401		 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2402		 * (http://eprint.iacr.org/2003/052/) exploits the version
2403		 * number check as a "bad version oracle". Thus version checks
2404		 * are done in constant time and are treated like any other
2405		 * decryption error. */
2406		version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2407		version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2408
2409		/* The premaster secret must contain the same version number as
2410		 * the ClientHello to detect version rollback attacks
2411		 * (strangely, the protocol does not offer such protection for
2412		 * DH ciphersuites). However, buggy clients exist that send the
2413		 * negotiated protocol version instead if the server does not
2414		 * support the requested protocol version. If
2415		 * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2416		if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2417			{
2418			unsigned char workaround_good;
2419			workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2420			workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2421			version_good |= workaround_good;
2422			}
2423
2424		/* Both decryption and version must be good for decrypt_good
2425		 * to remain non-zero (0xff). */
2426		decrypt_good &= version_good;
2427
2428		/* Now copy rand_premaster_secret over p using
2429		 * decrypt_good_mask. */
2430		for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2431			{
2432			p[i] = constant_time_select_8(decrypt_good, p[i],
2433						      rand_premaster_secret[i]);
2434			}
2435
2436		s->session->master_key_length=
2437			s->method->ssl3_enc->generate_master_secret(s,
2438				s->session->master_key,
2439				p,i);
2440		OPENSSL_cleanse(p,i);
2441		}
2442#endif
2443#ifndef OPENSSL_NO_DH
2444	else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2445		{
2446		n2s(p,i);
2447		if (n != i+2)
2448			{
2449			if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2450				{
2451				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2452				goto err;
2453				}
2454			else
2455				{
2456				p-=2;
2457				i=(int)n;
2458				}
2459			}
2460
2461		if (n == 0L) /* the parameters are in the cert */
2462			{
2463			al=SSL_AD_HANDSHAKE_FAILURE;
2464			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
2465			goto f_err;
2466			}
2467		else
2468			{
2469			if (s->s3->tmp.dh == NULL)
2470				{
2471				al=SSL_AD_HANDSHAKE_FAILURE;
2472				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2473				goto f_err;
2474				}
2475			else
2476				dh_srvr=s->s3->tmp.dh;
2477			}
2478
2479		pub=BN_bin2bn(p,i,NULL);
2480		if (pub == NULL)
2481			{
2482			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2483			goto err;
2484			}
2485
2486		i=DH_compute_key(p,pub,dh_srvr);
2487
2488		if (i <= 0)
2489			{
2490			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2491			BN_clear_free(pub);
2492			goto err;
2493			}
2494
2495		DH_free(s->s3->tmp.dh);
2496		s->s3->tmp.dh=NULL;
2497
2498		BN_clear_free(pub);
2499		pub=NULL;
2500		s->session->master_key_length=
2501			s->method->ssl3_enc->generate_master_secret(s,
2502				s->session->master_key,p,i);
2503		OPENSSL_cleanse(p,i);
2504		}
2505#endif
2506#ifndef OPENSSL_NO_KRB5
2507	else if (alg_k & SSL_kKRB5)
2508		{
2509		krb5_error_code		krb5rc;
2510		krb5_data		enc_ticket;
2511		krb5_data		authenticator;
2512		krb5_data		enc_pms;
2513		KSSL_CTX		*kssl_ctx = s->kssl_ctx;
2514		EVP_CIPHER_CTX		ciph_ctx;
2515		const EVP_CIPHER	*enc = NULL;
2516		unsigned char		iv[EVP_MAX_IV_LENGTH];
2517		unsigned char		pms[SSL_MAX_MASTER_KEY_LENGTH
2518					       + EVP_MAX_BLOCK_LENGTH];
2519		int		     padl, outl;
2520		krb5_timestamp		authtime = 0;
2521		krb5_ticket_times	ttimes;
2522
2523		EVP_CIPHER_CTX_init(&ciph_ctx);
2524
2525		if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2526
2527		n2s(p,i);
2528		enc_ticket.length = i;
2529
2530		if (n < (long)(enc_ticket.length + 6))
2531			{
2532			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2533				SSL_R_DATA_LENGTH_TOO_LONG);
2534			goto err;
2535			}
2536
2537		enc_ticket.data = (char *)p;
2538		p+=enc_ticket.length;
2539
2540		n2s(p,i);
2541		authenticator.length = i;
2542
2543		if (n < (long)(enc_ticket.length + authenticator.length + 6))
2544			{
2545			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2546				SSL_R_DATA_LENGTH_TOO_LONG);
2547			goto err;
2548			}
2549
2550		authenticator.data = (char *)p;
2551		p+=authenticator.length;
2552
2553		n2s(p,i);
2554		enc_pms.length = i;
2555		enc_pms.data = (char *)p;
2556		p+=enc_pms.length;
2557
2558		/* Note that the length is checked again below,
2559		** after decryption
2560		*/
2561		if(enc_pms.length > sizeof pms)
2562			{
2563			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2564			       SSL_R_DATA_LENGTH_TOO_LONG);
2565			goto err;
2566			}
2567
2568		if (n != (long)(enc_ticket.length + authenticator.length +
2569						enc_pms.length + 6))
2570			{
2571			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2572				SSL_R_DATA_LENGTH_TOO_LONG);
2573			goto err;
2574			}
2575
2576		if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2577					&kssl_err)) != 0)
2578			{
2579#ifdef KSSL_DEBUG
2580			printf("kssl_sget_tkt rtn %d [%d]\n",
2581				krb5rc, kssl_err.reason);
2582			if (kssl_err.text)
2583				printf("kssl_err text= %s\n", kssl_err.text);
2584#endif	/* KSSL_DEBUG */
2585			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2586				kssl_err.reason);
2587			goto err;
2588			}
2589
2590		/*  Note: no authenticator is not considered an error,
2591		**  but will return authtime == 0.
2592		*/
2593		if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2594					&authtime, &kssl_err)) != 0)
2595			{
2596#ifdef KSSL_DEBUG
2597			printf("kssl_check_authent rtn %d [%d]\n",
2598				krb5rc, kssl_err.reason);
2599			if (kssl_err.text)
2600				printf("kssl_err text= %s\n", kssl_err.text);
2601#endif	/* KSSL_DEBUG */
2602			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2603				kssl_err.reason);
2604			goto err;
2605			}
2606
2607		if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2608			{
2609			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2610			goto err;
2611			}
2612
2613#ifdef KSSL_DEBUG
2614		kssl_ctx_show(kssl_ctx);
2615#endif	/* KSSL_DEBUG */
2616
2617		enc = kssl_map_enc(kssl_ctx->enctype);
2618		if (enc == NULL)
2619		    goto err;
2620
2621		memset(iv, 0, sizeof iv);	/* per RFC 1510 */
2622
2623		if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2624			{
2625			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2626				SSL_R_DECRYPTION_FAILED);
2627			goto err;
2628			}
2629		if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2630					(unsigned char *)enc_pms.data, enc_pms.length))
2631			{
2632			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2633				SSL_R_DECRYPTION_FAILED);
2634			goto err;
2635			}
2636		if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2637			{
2638			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2639				SSL_R_DATA_LENGTH_TOO_LONG);
2640			goto err;
2641			}
2642		if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2643			{
2644			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2645				SSL_R_DECRYPTION_FAILED);
2646			goto err;
2647			}
2648		outl += padl;
2649		if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2650			{
2651			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2652				SSL_R_DATA_LENGTH_TOO_LONG);
2653			goto err;
2654			}
2655		if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2656		    {
2657		    /* The premaster secret must contain the same version number as the
2658		     * ClientHello to detect version rollback attacks (strangely, the
2659		     * protocol does not offer such protection for DH ciphersuites).
2660		     * However, buggy clients exist that send random bytes instead of
2661		     * the protocol version.
2662		     * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients.
2663		     * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2664		     */
2665		    if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2666			{
2667			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2668			       SSL_AD_DECODE_ERROR);
2669			goto err;
2670			}
2671		    }
2672
2673		EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2674
2675		s->session->master_key_length=
2676			s->method->ssl3_enc->generate_master_secret(s,
2677				s->session->master_key, pms, outl);
2678
2679		if (kssl_ctx->client_princ)
2680			{
2681			size_t len = strlen(kssl_ctx->client_princ);
2682			if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH )
2683				{
2684				s->session->krb5_client_princ_len = len;
2685				memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2686				}
2687			}
2688
2689
2690		/*  Was doing kssl_ctx_free() here,
2691		**  but it caused problems for apache.
2692		**  kssl_ctx = kssl_ctx_free(kssl_ctx);
2693		**  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2694		*/
2695		}
2696#endif	/* OPENSSL_NO_KRB5 */
2697#ifndef OPENSSL_NO_ECDH
2698	else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2699		{
2700		int ret = 1;
2701		int field_size = 0;
2702		const EC_KEY   *tkey;
2703		const EC_GROUP *group;
2704		const BIGNUM *priv_key;
2705#ifndef OPENSSL_NO_PSK
2706		unsigned char *pre_ms;
2707		unsigned int pre_ms_len;
2708		unsigned char *t;
2709#endif /* OPENSSL_NO_PSK */
2710
2711		/* initialize structures for server's ECDH key pair */
2712		if ((srvr_ecdh = EC_KEY_new()) == NULL)
2713			{
2714			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2715			    ERR_R_MALLOC_FAILURE);
2716			goto err;
2717			}
2718
2719		/* Let's get server private key and group information */
2720		if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2721			{
2722			/* use the certificate */
2723			tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2724			}
2725		else
2726			{
2727			/* use the ephermeral values we saved when
2728			 * generating the ServerKeyExchange msg.
2729			 */
2730			tkey = s->s3->tmp.ecdh;
2731			}
2732
2733		group    = EC_KEY_get0_group(tkey);
2734		priv_key = EC_KEY_get0_private_key(tkey);
2735
2736		if (!EC_KEY_set_group(srvr_ecdh, group) ||
2737		    !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2738			{
2739			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2740			       ERR_R_EC_LIB);
2741			goto err;
2742			}
2743
2744		/* Let's get client's public key */
2745		if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2746			{
2747			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2748			    ERR_R_MALLOC_FAILURE);
2749			goto err;
2750			}
2751
2752		if (n == 0L)
2753			{
2754			/* Client Publickey was in Client Certificate */
2755
2756			 if (alg_k & SSL_kEECDH)
2757				 {
2758				 al=SSL_AD_HANDSHAKE_FAILURE;
2759				 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2760				 goto f_err;
2761				 }
2762			if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2763			    == NULL) ||
2764			    (clnt_pub_pkey->type != EVP_PKEY_EC))
2765				{
2766				/* XXX: For now, we do not support client
2767				 * authentication using ECDH certificates
2768				 * so this branch (n == 0L) of the code is
2769				 * never executed. When that support is
2770				 * added, we ought to ensure the key
2771				 * received in the certificate is
2772				 * authorized for key agreement.
2773				 * ECDH_compute_key implicitly checks that
2774				 * the two ECDH shares are for the same
2775				 * group.
2776				 */
2777			   	al=SSL_AD_HANDSHAKE_FAILURE;
2778			   	SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2779				    SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2780			   	goto f_err;
2781			   	}
2782
2783			if (EC_POINT_copy(clnt_ecpoint,
2784			    EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2785				{
2786				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2787					ERR_R_EC_LIB);
2788				goto err;
2789				}
2790			ret = 2; /* Skip certificate verify processing */
2791			}
2792		else
2793			{
2794			/* Get client's public key from encoded point
2795			 * in the ClientKeyExchange message.
2796			 */
2797			if ((bn_ctx = BN_CTX_new()) == NULL)
2798				{
2799				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2800				    ERR_R_MALLOC_FAILURE);
2801				goto err;
2802				}
2803
2804			/* Get encoded point length */
2805			i = *p;
2806			p += 1;
2807			if (n != 1 + i)
2808				{
2809				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2810				    ERR_R_EC_LIB);
2811				goto err;
2812				}
2813			if (EC_POINT_oct2point(group,
2814			    clnt_ecpoint, p, i, bn_ctx) == 0)
2815				{
2816				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2817				    ERR_R_EC_LIB);
2818				goto err;
2819				}
2820			/* p is pointing to somewhere in the buffer
2821			 * currently, so set it to the start
2822			 */
2823			p=(unsigned char *)s->init_buf->data;
2824			}
2825
2826		/* Compute the shared pre-master secret */
2827		field_size = EC_GROUP_get_degree(group);
2828		if (field_size <= 0)
2829			{
2830			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2831			       ERR_R_ECDH_LIB);
2832			goto err;
2833			}
2834		i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2835		if (i <= 0)
2836			{
2837			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2838			    ERR_R_ECDH_LIB);
2839			goto err;
2840			}
2841
2842		EVP_PKEY_free(clnt_pub_pkey);
2843		EC_POINT_free(clnt_ecpoint);
2844		EC_KEY_free(srvr_ecdh);
2845		BN_CTX_free(bn_ctx);
2846		EC_KEY_free(s->s3->tmp.ecdh);
2847		s->s3->tmp.ecdh = NULL;
2848
2849#ifndef OPENSSL_NO_PSK
2850		/* ECDHE PSK ciphersuites from RFC 5489 */
2851	    if ((alg_a & SSL_aPSK) && psk_len != 0)
2852			{
2853			pre_ms_len = 2+i+2+psk_len;
2854			pre_ms = OPENSSL_malloc(pre_ms_len);
2855			if (pre_ms == NULL)
2856				{
2857				SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2858					ERR_R_MALLOC_FAILURE);
2859				goto err;
2860				}
2861			memset(pre_ms, 0, pre_ms_len);
2862			t = pre_ms;
2863			s2n(i, t);
2864			memcpy(t, p, i);
2865			t += i;
2866			s2n(psk_len, t);
2867			memcpy(t, psk, psk_len);
2868			s->session->master_key_length = s->method->ssl3_enc \
2869				-> generate_master_secret(s,
2870					s->session->master_key, pre_ms, pre_ms_len);
2871			OPENSSL_cleanse(pre_ms, pre_ms_len);
2872			OPENSSL_free(pre_ms);
2873			}
2874#endif /* OPENSSL_NO_PSK */
2875		if (!(alg_a & SSL_aPSK))
2876			{
2877			/* Compute the master secret */
2878			s->session->master_key_length = s->method->ssl3_enc \
2879				-> generate_master_secret(s,
2880					s->session->master_key, p, i);
2881			}
2882
2883		OPENSSL_cleanse(p, i);
2884		}
2885#endif
2886#ifndef OPENSSL_NO_SRP
2887	else if (alg_k & SSL_kSRP)
2888		{
2889		int param_len;
2890
2891		n2s(p,i);
2892		param_len=i+2;
2893		if (param_len > n)
2894			{
2895			al=SSL_AD_DECODE_ERROR;
2896			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2897			goto f_err;
2898			}
2899		if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2900			{
2901			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2902			goto err;
2903			}
2904		if (s->session->srp_username != NULL)
2905			OPENSSL_free(s->session->srp_username);
2906		s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2907		if (s->session->srp_username == NULL)
2908			{
2909			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2910				ERR_R_MALLOC_FAILURE);
2911			goto err;
2912			}
2913
2914		if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2915			{
2916			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2917			goto err;
2918			}
2919
2920		p+=i;
2921		}
2922#endif	/* OPENSSL_NO_SRP */
2923	else if (alg_k & SSL_kGOST)
2924		{
2925		int ret = 0;
2926		EVP_PKEY_CTX *pkey_ctx;
2927		EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2928		unsigned char premaster_secret[32], *start;
2929		size_t outlen=32, inlen;
2930		unsigned long alg_a;
2931		int Ttag, Tclass;
2932		long Tlen;
2933
2934		/* Get our certificate private key*/
2935		alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2936		if (alg_a & SSL_aGOST94)
2937			pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2938		else if (alg_a & SSL_aGOST01)
2939			pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2940
2941		pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2942		EVP_PKEY_decrypt_init(pkey_ctx);
2943		/* If client certificate is present and is of the same type, maybe
2944		 * use it for key exchange.  Don't mind errors from
2945		 * EVP_PKEY_derive_set_peer, because it is completely valid to use
2946		 * a client certificate for authorization only. */
2947		client_pub_pkey = X509_get_pubkey(s->session->peer);
2948		if (client_pub_pkey)
2949			{
2950			if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2951				ERR_clear_error();
2952			}
2953		/* Decrypt session key */
2954		if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED ||
2955			Ttag != V_ASN1_SEQUENCE ||
2956			Tclass != V_ASN1_UNIVERSAL)
2957			{
2958			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2959			goto gerr;
2960			}
2961		start = p;
2962		inlen = Tlen;
2963		if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0)
2964			{
2965			SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2966			goto gerr;
2967			}
2968		/* Generate master secret */
2969		s->session->master_key_length=
2970			s->method->ssl3_enc->generate_master_secret(s,
2971				s->session->master_key,premaster_secret,32);
2972		/* Check if pubkey from client certificate was used */
2973		if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2974			ret = 2;
2975		else
2976			ret = 1;
2977	gerr:
2978		EVP_PKEY_free(client_pub_pkey);
2979		EVP_PKEY_CTX_free(pkey_ctx);
2980		if (ret)
2981			return ret;
2982		else
2983			goto err;
2984		}
2985	else if (!(alg_k & SSL_kPSK))
2986		{
2987		al=SSL_AD_HANDSHAKE_FAILURE;
2988		SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2989				SSL_R_UNKNOWN_CIPHER_TYPE);
2990		goto f_err;
2991		}
2992
2993	return(1);
2994f_err:
2995	ssl3_send_alert(s,SSL3_AL_FATAL,al);
2996#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2997err:
2998#endif
2999#ifndef OPENSSL_NO_ECDH
3000	EVP_PKEY_free(clnt_pub_pkey);
3001	EC_POINT_free(clnt_ecpoint);
3002	if (srvr_ecdh != NULL)
3003		EC_KEY_free(srvr_ecdh);
3004	BN_CTX_free(bn_ctx);
3005#endif
3006	return(-1);
3007	}
3008
3009int ssl3_get_cert_verify(SSL *s)
3010	{
3011	EVP_PKEY *pkey=NULL;
3012	unsigned char *p;
3013	int al,ok,ret=0;
3014	long n;
3015	int type=0,i,j;
3016	X509 *peer;
3017	const EVP_MD *md = NULL;
3018	EVP_MD_CTX mctx;
3019	EVP_MD_CTX_init(&mctx);
3020
3021	n=s->method->ssl_get_message(s,
3022		SSL3_ST_SR_CERT_VRFY_A,
3023		SSL3_ST_SR_CERT_VRFY_B,
3024		-1,
3025		SSL3_RT_MAX_PLAIN_LENGTH,
3026		&ok);
3027
3028	if (!ok) return((int)n);
3029
3030	if (s->session->peer != NULL)
3031		{
3032		peer=s->session->peer;
3033		pkey=X509_get_pubkey(peer);
3034		type=X509_certificate_type(peer,pkey);
3035		}
3036	else
3037		{
3038		peer=NULL;
3039		pkey=NULL;
3040		}
3041
3042	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3043		{
3044		s->s3->tmp.reuse_message=1;
3045		if ((peer != NULL) && (type & EVP_PKT_SIGN))
3046			{
3047			al=SSL_AD_UNEXPECTED_MESSAGE;
3048			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3049			goto f_err;
3050			}
3051		ret=1;
3052		goto end;
3053		}
3054
3055	if (peer == NULL)
3056		{
3057		SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3058		al=SSL_AD_UNEXPECTED_MESSAGE;
3059		goto f_err;
3060		}
3061
3062	if (!(type & EVP_PKT_SIGN))
3063		{
3064		SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3065		al=SSL_AD_ILLEGAL_PARAMETER;
3066		goto f_err;
3067		}
3068
3069	if (s->s3->change_cipher_spec)
3070		{
3071		SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3072		al=SSL_AD_UNEXPECTED_MESSAGE;
3073		goto f_err;
3074		}
3075
3076	/* we now have a signature that we need to verify */
3077	p=(unsigned char *)s->init_msg;
3078	/* Check for broken implementations of GOST ciphersuites */
3079	/* If key is GOST and n is exactly 64, it is bare
3080	 * signature without length field */
3081	if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3082		pkey->type == NID_id_GostR3410_2001) )
3083		{
3084		i=64;
3085		}
3086	else
3087		{
3088		if (TLS1_get_version(s) >= TLS1_2_VERSION)
3089			{
3090			int sigalg = tls12_get_sigid(pkey);
3091			/* Should never happen */
3092			if (sigalg == -1)
3093				{
3094				SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3095				al=SSL_AD_INTERNAL_ERROR;
3096				goto f_err;
3097				}
3098			/* Check key type is consistent with signature */
3099			if (sigalg != (int)p[1])
3100				{
3101				SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_TYPE);
3102				al=SSL_AD_DECODE_ERROR;
3103				goto f_err;
3104				}
3105			md = tls12_get_hash(p[0]);
3106			if (md == NULL)
3107				{
3108				SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_UNKNOWN_DIGEST);
3109				al=SSL_AD_DECODE_ERROR;
3110				goto f_err;
3111				}
3112#ifdef SSL_DEBUG
3113fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3114#endif
3115			p += 2;
3116			n -= 2;
3117			}
3118		n2s(p,i);
3119		n-=2;
3120		if (i > n)
3121			{
3122			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3123			al=SSL_AD_DECODE_ERROR;
3124			goto f_err;
3125			}
3126    	}
3127	j=EVP_PKEY_size(pkey);
3128	if ((i > j) || (n > j) || (n <= 0))
3129		{
3130		SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3131		al=SSL_AD_DECODE_ERROR;
3132		goto f_err;
3133		}
3134
3135	if (TLS1_get_version(s) >= TLS1_2_VERSION)
3136		{
3137		long hdatalen = 0;
3138		void *hdata;
3139		hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3140		if (hdatalen <= 0)
3141			{
3142			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3143			al=SSL_AD_INTERNAL_ERROR;
3144			goto f_err;
3145			}
3146#ifdef SSL_DEBUG
3147		fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3148							EVP_MD_name(md));
3149#endif
3150		if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3151			|| !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3152			{
3153			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3154			al=SSL_AD_INTERNAL_ERROR;
3155			goto f_err;
3156			}
3157
3158		if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3159			{
3160			al=SSL_AD_DECRYPT_ERROR;
3161			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3162			goto f_err;
3163			}
3164		}
3165	else
3166#ifndef OPENSSL_NO_RSA
3167	if (pkey->type == EVP_PKEY_RSA)
3168		{
3169		i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3170			MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i,
3171							pkey->pkey.rsa);
3172		if (i < 0)
3173			{
3174			al=SSL_AD_DECRYPT_ERROR;
3175			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3176			goto f_err;
3177			}
3178		if (i == 0)
3179			{
3180			al=SSL_AD_DECRYPT_ERROR;
3181			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3182			goto f_err;
3183			}
3184		}
3185	else
3186#endif
3187#ifndef OPENSSL_NO_DSA
3188		if (pkey->type == EVP_PKEY_DSA)
3189		{
3190		j=DSA_verify(pkey->save_type,
3191			&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3192			SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3193		if (j <= 0)
3194			{
3195			/* bad signature */
3196			al=SSL_AD_DECRYPT_ERROR;
3197			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3198			goto f_err;
3199			}
3200		}
3201	else
3202#endif
3203#ifndef OPENSSL_NO_ECDSA
3204		if (pkey->type == EVP_PKEY_EC)
3205		{
3206		j=ECDSA_verify(pkey->save_type,
3207			&(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3208			SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3209		if (j <= 0)
3210			{
3211			/* bad signature */
3212			al=SSL_AD_DECRYPT_ERROR;
3213			SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3214			    SSL_R_BAD_ECDSA_SIGNATURE);
3215			goto f_err;
3216			}
3217		}
3218	else
3219#endif
3220	if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3221		{   unsigned char signature[64];
3222			int idx;
3223			EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3224			EVP_PKEY_verify_init(pctx);
3225			if (i!=64) {
3226				fprintf(stderr,"GOST signature length is %d",i);
3227			}
3228			for (idx=0;idx<64;idx++) {
3229				signature[63-idx]=p[idx];
3230			}
3231			j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3232			EVP_PKEY_CTX_free(pctx);
3233			if (j<=0)
3234				{
3235				al=SSL_AD_DECRYPT_ERROR;
3236				SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3237					SSL_R_BAD_ECDSA_SIGNATURE);
3238				goto f_err;
3239				}
3240		}
3241	else
3242		{
3243		SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3244		al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3245		goto f_err;
3246		}
3247
3248
3249	ret=1;
3250	if (0)
3251		{
3252f_err:
3253		ssl3_send_alert(s,SSL3_AL_FATAL,al);
3254		}
3255end:
3256	if (s->s3->handshake_buffer)
3257		{
3258		BIO_free(s->s3->handshake_buffer);
3259		s->s3->handshake_buffer = NULL;
3260		s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3261		}
3262	EVP_MD_CTX_cleanup(&mctx);
3263	EVP_PKEY_free(pkey);
3264	return(ret);
3265	}
3266
3267int ssl3_get_client_certificate(SSL *s)
3268	{
3269	int i,ok,al,ret= -1;
3270	X509 *x=NULL;
3271	unsigned long l,nc,llen,n;
3272	const unsigned char *p,*q;
3273	unsigned char *d;
3274	STACK_OF(X509) *sk=NULL;
3275
3276	n=s->method->ssl_get_message(s,
3277		SSL3_ST_SR_CERT_A,
3278		SSL3_ST_SR_CERT_B,
3279		-1,
3280		s->max_cert_list,
3281		&ok);
3282
3283	if (!ok) return((int)n);
3284
3285	if	(s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3286		{
3287		if (	(s->verify_mode & SSL_VERIFY_PEER) &&
3288			(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3289			{
3290			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3291			al=SSL_AD_HANDSHAKE_FAILURE;
3292			goto f_err;
3293			}
3294		/* If tls asked for a client cert, the client must return a 0 list */
3295		if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3296			{
3297			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3298			al=SSL_AD_UNEXPECTED_MESSAGE;
3299			goto f_err;
3300			}
3301		s->s3->tmp.reuse_message=1;
3302		return(1);
3303		}
3304
3305	if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3306		{
3307		al=SSL_AD_UNEXPECTED_MESSAGE;
3308		SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3309		goto f_err;
3310		}
3311	p=d=(unsigned char *)s->init_msg;
3312
3313	if ((sk=sk_X509_new_null()) == NULL)
3314		{
3315		SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3316		goto err;
3317		}
3318
3319	n2l3(p,llen);
3320	if (llen+3 != n)
3321		{
3322		al=SSL_AD_DECODE_ERROR;
3323		SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3324		goto f_err;
3325		}
3326	for (nc=0; nc<llen; )
3327		{
3328		n2l3(p,l);
3329		if ((l+nc+3) > llen)
3330			{
3331			al=SSL_AD_DECODE_ERROR;
3332			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3333			goto f_err;
3334			}
3335
3336		q=p;
3337		x=d2i_X509(NULL,&p,l);
3338		if (x == NULL)
3339			{
3340			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3341			goto err;
3342			}
3343		if (p != (q+l))
3344			{
3345			al=SSL_AD_DECODE_ERROR;
3346			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3347			goto f_err;
3348			}
3349		if (!sk_X509_push(sk,x))
3350			{
3351			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3352			goto err;
3353			}
3354		x=NULL;
3355		nc+=l+3;
3356		}
3357
3358	if (sk_X509_num(sk) <= 0)
3359		{
3360		/* TLS does not mind 0 certs returned */
3361		if (s->version == SSL3_VERSION)
3362			{
3363			al=SSL_AD_HANDSHAKE_FAILURE;
3364			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3365			goto f_err;
3366			}
3367		/* Fail for TLS only if we required a certificate */
3368		else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3369			 (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3370			{
3371			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3372			al=SSL_AD_HANDSHAKE_FAILURE;
3373			goto f_err;
3374			}
3375		/* No client certificate so digest cached records */
3376		if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3377			{
3378			al=SSL_AD_INTERNAL_ERROR;
3379			goto f_err;
3380			}
3381		}
3382	else
3383		{
3384		i=ssl_verify_cert_chain(s,sk);
3385		if (i <= 0)
3386			{
3387			al=ssl_verify_alarm_type(s->verify_result);
3388			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
3389			goto f_err;
3390			}
3391		}
3392
3393	if (s->session->peer != NULL) /* This should not be needed */
3394		X509_free(s->session->peer);
3395	s->session->peer=sk_X509_shift(sk);
3396	s->session->verify_result = s->verify_result;
3397
3398	/* With the current implementation, sess_cert will always be NULL
3399	 * when we arrive here. */
3400	if (s->session->sess_cert == NULL)
3401		{
3402		s->session->sess_cert = ssl_sess_cert_new();
3403		if (s->session->sess_cert == NULL)
3404			{
3405			SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3406			goto err;
3407			}
3408		}
3409	if (s->session->sess_cert->cert_chain != NULL)
3410		sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3411	s->session->sess_cert->cert_chain=sk;
3412	/* Inconsistency alert: cert_chain does *not* include the
3413	 * peer's own certificate, while we do include it in s3_clnt.c */
3414
3415	sk=NULL;
3416
3417	ret=1;
3418	if (0)
3419		{
3420f_err:
3421		ssl3_send_alert(s,SSL3_AL_FATAL,al);
3422		}
3423err:
3424	if (x != NULL) X509_free(x);
3425	if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3426	return(ret);
3427	}
3428
3429int ssl3_send_server_certificate(SSL *s)
3430	{
3431	unsigned long l;
3432	X509 *x;
3433
3434	if (s->state == SSL3_ST_SW_CERT_A)
3435		{
3436		x=ssl_get_server_send_cert(s);
3437		if (x == NULL)
3438			{
3439			/* VRS: allow null cert if auth == KRB5 */
3440			if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3441			    (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3442				{
3443				SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3444				return(0);
3445				}
3446			}
3447
3448		l=ssl3_output_cert_chain(s,x);
3449		s->state=SSL3_ST_SW_CERT_B;
3450		s->init_num=(int)l;
3451		s->init_off=0;
3452		}
3453
3454	/* SSL3_ST_SW_CERT_B */
3455	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3456	}
3457
3458#ifndef OPENSSL_NO_TLSEXT
3459/* send a new session ticket (not necessarily for a new session) */
3460int ssl3_send_newsession_ticket(SSL *s)
3461	{
3462	if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3463		{
3464		unsigned char *p, *senc, *macstart;
3465		const unsigned char *const_p;
3466		int len, slen_full, slen;
3467		SSL_SESSION *sess;
3468		unsigned int hlen;
3469		EVP_CIPHER_CTX ctx;
3470		HMAC_CTX hctx;
3471		SSL_CTX *tctx = s->initial_ctx;
3472		unsigned char iv[EVP_MAX_IV_LENGTH];
3473		unsigned char key_name[16];
3474
3475		/* get session encoding length */
3476		slen_full = i2d_SSL_SESSION(s->session, NULL);
3477		/* Some length values are 16 bits, so forget it if session is
3478 		 * too long
3479 		 */
3480		if (slen_full > 0xFF00)
3481			return -1;
3482		senc = OPENSSL_malloc(slen_full);
3483		if (!senc)
3484			return -1;
3485		p = senc;
3486		i2d_SSL_SESSION(s->session, &p);
3487
3488		/* create a fresh copy (not shared with other threads) to clean up */
3489		const_p = senc;
3490		sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3491		if (sess == NULL)
3492			{
3493			OPENSSL_free(senc);
3494			return -1;
3495			}
3496		sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3497
3498		slen = i2d_SSL_SESSION(sess, NULL);
3499		if (slen > slen_full) /* shouldn't ever happen */
3500			{
3501			OPENSSL_free(senc);
3502			return -1;
3503			}
3504		p = senc;
3505		i2d_SSL_SESSION(sess, &p);
3506		SSL_SESSION_free(sess);
3507
3508		/* Grow buffer if need be: the length calculation is as
3509 		 * follows 1 (size of message name) + 3 (message length
3510 		 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
3511 		 * 16 (key name) + max_iv_len (iv length) +
3512 		 * session_length + max_enc_block_size (max encrypted session
3513 		 * length) + max_md_size (HMAC).
3514 		 */
3515		if (!BUF_MEM_grow(s->init_buf,
3516			26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
3517			EVP_MAX_MD_SIZE + slen))
3518			return -1;
3519
3520		p=(unsigned char *)s->init_buf->data;
3521		/* do the header */
3522		*(p++)=SSL3_MT_NEWSESSION_TICKET;
3523		/* Skip message length for now */
3524		p += 3;
3525		EVP_CIPHER_CTX_init(&ctx);
3526		HMAC_CTX_init(&hctx);
3527		/* Initialize HMAC and cipher contexts. If callback present
3528		 * it does all the work otherwise use generated values
3529		 * from parent ctx.
3530		 */
3531		if (tctx->tlsext_ticket_key_cb)
3532			{
3533			if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3534							 &hctx, 1) < 0)
3535				{
3536				OPENSSL_free(senc);
3537				return -1;
3538				}
3539			}
3540		else
3541			{
3542			RAND_pseudo_bytes(iv, 16);
3543			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3544					tctx->tlsext_tick_aes_key, iv);
3545			HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3546					tlsext_tick_md(), NULL);
3547			memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3548			}
3549
3550		/* Ticket lifetime hint (advisory only):
3551		 * We leave this unspecified for resumed session (for simplicity),
3552		 * and guess that tickets for new sessions will live as long
3553		 * as their sessions. */
3554		l2n(s->hit ? 0 : s->session->timeout, p);
3555
3556		/* Skip ticket length for now */
3557		p += 2;
3558		/* Output key name */
3559		macstart = p;
3560		memcpy(p, key_name, 16);
3561		p += 16;
3562		/* output IV */
3563		memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3564		p += EVP_CIPHER_CTX_iv_length(&ctx);
3565		/* Encrypt session data */
3566		EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3567		p += len;
3568		EVP_EncryptFinal(&ctx, p, &len);
3569		p += len;
3570		EVP_CIPHER_CTX_cleanup(&ctx);
3571
3572		HMAC_Update(&hctx, macstart, p - macstart);
3573		HMAC_Final(&hctx, p, &hlen);
3574		HMAC_CTX_cleanup(&hctx);
3575
3576		p += hlen;
3577		/* Now write out lengths: p points to end of data written */
3578		/* Total length */
3579		len = p - (unsigned char *)s->init_buf->data;
3580		p=(unsigned char *)s->init_buf->data + 1;
3581		l2n3(len - 4, p); /* Message length */
3582		p += 4;
3583		s2n(len - 10, p);  /* Ticket length */
3584
3585		/* number of bytes to write */
3586		s->init_num= len;
3587		s->state=SSL3_ST_SW_SESSION_TICKET_B;
3588		s->init_off=0;
3589		OPENSSL_free(senc);
3590		}
3591
3592	/* SSL3_ST_SW_SESSION_TICKET_B */
3593	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3594	}
3595
3596int ssl3_send_cert_status(SSL *s)
3597	{
3598	if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3599		{
3600		unsigned char *p;
3601		/* Grow buffer if need be: the length calculation is as
3602 		 * follows 1 (message type) + 3 (message length) +
3603 		 * 1 (ocsp response type) + 3 (ocsp response length)
3604 		 * + (ocsp response)
3605 		 */
3606		if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3607			return -1;
3608
3609		p=(unsigned char *)s->init_buf->data;
3610
3611		/* do the header */
3612		*(p++)=SSL3_MT_CERTIFICATE_STATUS;
3613		/* message length */
3614		l2n3(s->tlsext_ocsp_resplen + 4, p);
3615		/* status type */
3616		*(p++)= s->tlsext_status_type;
3617		/* length of OCSP response */
3618		l2n3(s->tlsext_ocsp_resplen, p);
3619		/* actual response */
3620		memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3621		/* number of bytes to write */
3622		s->init_num = 8 + s->tlsext_ocsp_resplen;
3623		s->state=SSL3_ST_SW_CERT_STATUS_B;
3624		s->init_off = 0;
3625		}
3626
3627	/* SSL3_ST_SW_CERT_STATUS_B */
3628	return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3629	}
3630
3631# ifndef OPENSSL_NO_NEXTPROTONEG
3632/* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3633 * sets the next_proto member in s if found */
3634int ssl3_get_next_proto(SSL *s)
3635	{
3636	int ok;
3637	int proto_len, padding_len;
3638	long n;
3639	const unsigned char *p;
3640
3641	/* Clients cannot send a NextProtocol message if we didn't see the
3642	 * extension in their ClientHello */
3643	if (!s->s3->next_proto_neg_seen)
3644		{
3645		SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3646		return -1;
3647		}
3648
3649	n=s->method->ssl_get_message(s,
3650		SSL3_ST_SR_NEXT_PROTO_A,
3651		SSL3_ST_SR_NEXT_PROTO_B,
3652		SSL3_MT_NEXT_PROTO,
3653		514,  /* See the payload format below */
3654		&ok);
3655
3656	if (!ok)
3657		return((int)n);
3658
3659	/* s->state doesn't reflect whether ChangeCipherSpec has been received
3660	 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3661	 * by ssl3_get_finished). */
3662	if (!s->s3->change_cipher_spec)
3663		{
3664		SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3665		return -1;
3666		}
3667
3668	if (n < 2)
3669		return 0;  /* The body must be > 1 bytes long */
3670
3671	p=(unsigned char *)s->init_msg;
3672
3673	/* The payload looks like:
3674	 *   uint8 proto_len;
3675	 *   uint8 proto[proto_len];
3676	 *   uint8 padding_len;
3677	 *   uint8 padding[padding_len];
3678	 */
3679	proto_len = p[0];
3680	if (proto_len + 2 > s->init_num)
3681		return 0;
3682	padding_len = p[proto_len + 1];
3683	if (proto_len + padding_len + 2 != s->init_num)
3684		return 0;
3685
3686	s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3687	if (!s->next_proto_negotiated)
3688		{
3689		SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3690		return 0;
3691		}
3692	memcpy(s->next_proto_negotiated, p + 1, proto_len);
3693	s->next_proto_negotiated_len = proto_len;
3694
3695	return 1;
3696	}
3697# endif
3698
3699/* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
3700int ssl3_get_channel_id(SSL *s)
3701	{
3702	int ret = -1, ok;
3703	long n;
3704	const unsigned char *p;
3705	unsigned short extension_type, extension_len;
3706	EC_GROUP* p256 = NULL;
3707	EC_KEY* key = NULL;
3708	EC_POINT* point = NULL;
3709	ECDSA_SIG sig;
3710	BIGNUM x, y;
3711	unsigned short expected_extension_type;
3712
3713	if (s->state == SSL3_ST_SR_CHANNEL_ID_A && s->init_num == 0)
3714		{
3715		/* The first time that we're called we take the current
3716		 * handshake hash and store it. */
3717		EVP_MD_CTX md_ctx;
3718		unsigned int len;
3719
3720		EVP_MD_CTX_init(&md_ctx);
3721		EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL);
3722		if (!tls1_channel_id_hash(&md_ctx, s))
3723			return -1;
3724		len = sizeof(s->s3->tlsext_channel_id);
3725		EVP_DigestFinal(&md_ctx, s->s3->tlsext_channel_id, &len);
3726		EVP_MD_CTX_cleanup(&md_ctx);
3727		}
3728
3729	n = s->method->ssl_get_message(s,
3730		SSL3_ST_SR_CHANNEL_ID_A,
3731		SSL3_ST_SR_CHANNEL_ID_B,
3732		SSL3_MT_ENCRYPTED_EXTENSIONS,
3733		2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
3734		&ok);
3735
3736	if (!ok)
3737		return((int)n);
3738
3739	ssl3_finish_mac(s, (unsigned char*)s->init_buf->data, s->init_num + 4);
3740
3741	/* s->state doesn't reflect whether ChangeCipherSpec has been received
3742	 * in this handshake, but s->s3->change_cipher_spec does (will be reset
3743	 * by ssl3_get_finished). */
3744	if (!s->s3->change_cipher_spec)
3745		{
3746		SSLerr(SSL_F_SSL3_GET_CHANNEL_ID,SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
3747		return -1;
3748		}
3749
3750	if (n != 2 + 2 + TLSEXT_CHANNEL_ID_SIZE)
3751		{
3752		SSLerr(SSL_F_SSL3_GET_CHANNEL_ID,SSL_R_INVALID_MESSAGE);
3753		return -1;
3754		}
3755
3756	p = (unsigned char *)s->init_msg;
3757
3758	/* The payload looks like:
3759	 *   uint16 extension_type
3760	 *   uint16 extension_len;
3761	 *   uint8 x[32];
3762	 *   uint8 y[32];
3763	 *   uint8 r[32];
3764	 *   uint8 s[32];
3765	 */
3766	n2s(p, extension_type);
3767	n2s(p, extension_len);
3768
3769	expected_extension_type = TLSEXT_TYPE_channel_id;
3770	if (s->s3->tlsext_channel_id_new)
3771		expected_extension_type = TLSEXT_TYPE_channel_id_new;
3772
3773	if (extension_type != expected_extension_type ||
3774	    extension_len != TLSEXT_CHANNEL_ID_SIZE)
3775		{
3776		SSLerr(SSL_F_SSL3_GET_CHANNEL_ID,SSL_R_INVALID_MESSAGE);
3777		return -1;
3778		}
3779
3780	p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
3781	if (!p256)
3782		{
3783		SSLerr(SSL_F_SSL3_GET_CHANNEL_ID,SSL_R_NO_P256_SUPPORT);
3784		return -1;
3785		}
3786
3787	BN_init(&x);
3788	BN_init(&y);
3789	sig.r = BN_new();
3790	sig.s = BN_new();
3791
3792	if (BN_bin2bn(p +  0, 32, &x) == NULL ||
3793	    BN_bin2bn(p + 32, 32, &y) == NULL ||
3794	    BN_bin2bn(p + 64, 32, sig.r) == NULL ||
3795	    BN_bin2bn(p + 96, 32, sig.s) == NULL)
3796		goto err;
3797
3798	point = EC_POINT_new(p256);
3799	if (!point ||
3800	    !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
3801		goto err;
3802
3803	key = EC_KEY_new();
3804	if (!key ||
3805	    !EC_KEY_set_group(key, p256) ||
3806	    !EC_KEY_set_public_key(key, point))
3807		goto err;
3808
3809	/* We stored the handshake hash in |tlsext_channel_id| the first time
3810	 * that we were called. */
3811	switch (ECDSA_do_verify(s->s3->tlsext_channel_id, SHA256_DIGEST_LENGTH, &sig, key)) {
3812	case 1:
3813		break;
3814	case 0:
3815		SSLerr(SSL_F_SSL3_GET_CHANNEL_ID,SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
3816		s->s3->tlsext_channel_id_valid = 0;
3817		goto err;
3818	default:
3819		s->s3->tlsext_channel_id_valid = 0;
3820		goto err;
3821	}
3822
3823	memcpy(s->s3->tlsext_channel_id, p, 64);
3824	ret = 1;
3825
3826err:
3827	BN_free(&x);
3828	BN_free(&y);
3829	BN_free(sig.r);
3830	BN_free(sig.s);
3831	if (key)
3832		EC_KEY_free(key);
3833	if (point)
3834		EC_POINT_free(point);
3835	if (p256)
3836		EC_GROUP_free(p256);
3837	return ret;
3838	}
3839#endif
3840