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