xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision d59bb9942320b767f2a19aaa7690c8c6e30b724c)
1 /* $OpenBSD: ssl_srvr.c,v 1.8 2017/03/01 14:01:24 jsing Exp $ */
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 #include <stdio.h>
152 
153 #include "ssl_locl.h"
154 
155 #include <openssl/bn.h>
156 #include <openssl/buffer.h>
157 #include <openssl/curve25519.h>
158 #include <openssl/evp.h>
159 #include <openssl/dh.h>
160 #ifndef OPENSSL_NO_GOST
161 #include <openssl/gost.h>
162 #endif
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/objects.h>
166 #include <openssl/x509.h>
167 
168 #include "bytestring.h"
169 
170 int
171 ssl3_accept(SSL *s)
172 {
173 	unsigned long alg_k;
174 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
175 	int ret = -1;
176 	int new_state, state, skip = 0;
177 
178 	ERR_clear_error();
179 	errno = 0;
180 
181 	if (s->internal->info_callback != NULL)
182 		cb = s->internal->info_callback;
183 	else if (s->ctx->internal->info_callback != NULL)
184 		cb = s->ctx->internal->info_callback;
185 
186 	/* init things to blank */
187 	s->internal->in_handshake++;
188 	if (!SSL_in_init(s) || SSL_in_before(s))
189 		SSL_clear(s);
190 
191 	if (s->cert == NULL) {
192 		SSLerror(s, SSL_R_NO_CERTIFICATE_SET);
193 		ret = -1;
194 		goto end;
195 	}
196 
197 	for (;;) {
198 		state = s->internal->state;
199 
200 		switch (s->internal->state) {
201 		case SSL_ST_RENEGOTIATE:
202 			s->internal->renegotiate = 1;
203 			/* s->internal->state=SSL_ST_ACCEPT; */
204 
205 		case SSL_ST_BEFORE:
206 		case SSL_ST_ACCEPT:
207 		case SSL_ST_BEFORE|SSL_ST_ACCEPT:
208 		case SSL_ST_OK|SSL_ST_ACCEPT:
209 
210 			s->server = 1;
211 			if (cb != NULL)
212 				cb(s, SSL_CB_HANDSHAKE_START, 1);
213 
214 			if ((s->version >> 8) != 3) {
215 				SSLerror(s, ERR_R_INTERNAL_ERROR);
216 				ret = -1;
217 				goto end;
218 			}
219 			s->internal->type = SSL_ST_ACCEPT;
220 
221 			if (!ssl3_setup_init_buffer(s)) {
222 				ret = -1;
223 				goto end;
224 			}
225 			if (!ssl3_setup_buffers(s)) {
226 				ret = -1;
227 				goto end;
228 			}
229 
230 			s->internal->init_num = 0;
231 
232 			if (s->internal->state != SSL_ST_RENEGOTIATE) {
233 				/*
234 				 * Ok, we now need to push on a buffering BIO
235 				 * so that the output is sent in a way that
236 				 * TCP likes :-)
237 				 */
238 				if (!ssl_init_wbio_buffer(s, 1)) {
239 					ret = -1;
240 					goto end;
241 				}
242 
243 				if (!tls1_init_finished_mac(s)) {
244 					ret = -1;
245 					goto end;
246 				}
247 
248 				s->internal->state = SSL3_ST_SR_CLNT_HELLO_A;
249 				s->ctx->internal->stats.sess_accept++;
250 			} else if (!S3I(s)->send_connection_binding) {
251 				/*
252 				 * Server attempting to renegotiate with
253 				 * client that doesn't support secure
254 				 * renegotiation.
255 				 */
256 				SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
257 				ssl3_send_alert(s, SSL3_AL_FATAL,
258 				    SSL_AD_HANDSHAKE_FAILURE);
259 				ret = -1;
260 				goto end;
261 			} else {
262 				/*
263 				 * s->internal->state == SSL_ST_RENEGOTIATE,
264 				 * we will just send a HelloRequest
265 				 */
266 				s->ctx->internal->stats.sess_accept_renegotiate++;
267 				s->internal->state = SSL3_ST_SW_HELLO_REQ_A;
268 			}
269 			break;
270 
271 		case SSL3_ST_SW_HELLO_REQ_A:
272 		case SSL3_ST_SW_HELLO_REQ_B:
273 
274 			s->internal->shutdown = 0;
275 			ret = ssl3_send_hello_request(s);
276 			if (ret <= 0)
277 				goto end;
278 			S3I(s)->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
279 			s->internal->state = SSL3_ST_SW_FLUSH;
280 			s->internal->init_num = 0;
281 
282 			if (!tls1_init_finished_mac(s)) {
283 				ret = -1;
284 				goto end;
285 			}
286 			break;
287 
288 		case SSL3_ST_SW_HELLO_REQ_C:
289 			s->internal->state = SSL_ST_OK;
290 			break;
291 
292 		case SSL3_ST_SR_CLNT_HELLO_A:
293 		case SSL3_ST_SR_CLNT_HELLO_B:
294 		case SSL3_ST_SR_CLNT_HELLO_C:
295 
296 			s->internal->shutdown = 0;
297 			if (s->internal->rwstate != SSL_X509_LOOKUP) {
298 				ret = ssl3_get_client_hello(s);
299 				if (ret <= 0)
300 					goto end;
301 			}
302 
303 			s->internal->renegotiate = 2;
304 			s->internal->state = SSL3_ST_SW_SRVR_HELLO_A;
305 			s->internal->init_num = 0;
306 			break;
307 
308 		case SSL3_ST_SW_SRVR_HELLO_A:
309 		case SSL3_ST_SW_SRVR_HELLO_B:
310 			ret = ssl3_send_server_hello(s);
311 			if (ret <= 0)
312 				goto end;
313 			if (s->internal->hit) {
314 				if (s->internal->tlsext_ticket_expected)
315 					s->internal->state = SSL3_ST_SW_SESSION_TICKET_A;
316 				else
317 					s->internal->state = SSL3_ST_SW_CHANGE_A;
318 			}
319 			else
320 				s->internal->state = SSL3_ST_SW_CERT_A;
321 			s->internal->init_num = 0;
322 			break;
323 
324 		case SSL3_ST_SW_CERT_A:
325 		case SSL3_ST_SW_CERT_B:
326 			/* Check if it is anon DH or anon ECDH. */
327 			if (!(S3I(s)->tmp.new_cipher->algorithm_auth &
328 			    SSL_aNULL)) {
329 				ret = ssl3_send_server_certificate(s);
330 				if (ret <= 0)
331 					goto end;
332 				if (s->internal->tlsext_status_expected)
333 					s->internal->state = SSL3_ST_SW_CERT_STATUS_A;
334 				else
335 					s->internal->state = SSL3_ST_SW_KEY_EXCH_A;
336 			} else {
337 				skip = 1;
338 				s->internal->state = SSL3_ST_SW_KEY_EXCH_A;
339 			}
340 			s->internal->init_num = 0;
341 			break;
342 
343 		case SSL3_ST_SW_KEY_EXCH_A:
344 		case SSL3_ST_SW_KEY_EXCH_B:
345 			alg_k = S3I(s)->tmp.new_cipher->algorithm_mkey;
346 
347 			/*
348 			 * Only send if using a DH key exchange.
349 			 *
350 			 * For ECC ciphersuites, we send a ServerKeyExchange
351 			 * message only if the cipher suite is ECDHE. In other
352 			 * cases, the server certificate contains the server's
353 			 * public key for key exchange.
354 			 */
355 			if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
356 				ret = ssl3_send_server_key_exchange(s);
357 				if (ret <= 0)
358 					goto end;
359 			} else
360 				skip = 1;
361 
362 			s->internal->state = SSL3_ST_SW_CERT_REQ_A;
363 			s->internal->init_num = 0;
364 			break;
365 
366 		case SSL3_ST_SW_CERT_REQ_A:
367 		case SSL3_ST_SW_CERT_REQ_B:
368 			/*
369 			 * Determine whether or not we need to request a
370 			 * certificate.
371 			 *
372 			 * Do not request a certificate if:
373 			 *
374 			 * - We did not ask for it (SSL_VERIFY_PEER is unset).
375 			 *
376 			 * - SSL_VERIFY_CLIENT_ONCE is set and we are
377 			 *   renegotiating.
378 			 *
379 			 * - We are using an anonymous ciphersuites
380 			 *   (see section "Certificate request" in SSL 3 drafts
381 			 *   and in RFC 2246) ... except when the application
382 			 *   insists on verification (against the specs, but
383 			 *   s3_clnt.c accepts this for SSL 3).
384 			 */
385 			if (!(s->verify_mode & SSL_VERIFY_PEER) ||
386 			    ((s->session->peer != NULL) &&
387 			     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
388 			    ((S3I(s)->tmp.new_cipher->algorithm_auth &
389 			     SSL_aNULL) && !(s->verify_mode &
390 			     SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
391 				/* No cert request */
392 				skip = 1;
393 				S3I(s)->tmp.cert_request = 0;
394 				s->internal->state = SSL3_ST_SW_SRVR_DONE_A;
395 				if (S3I(s)->handshake_buffer) {
396 					if (!tls1_digest_cached_records(s)) {
397 						ret = -1;
398 						goto end;
399 					}
400 				}
401 			} else {
402 				S3I(s)->tmp.cert_request = 1;
403 				ret = ssl3_send_certificate_request(s);
404 				if (ret <= 0)
405 					goto end;
406 				s->internal->state = SSL3_ST_SW_SRVR_DONE_A;
407 				s->internal->init_num = 0;
408 			}
409 			break;
410 
411 		case SSL3_ST_SW_SRVR_DONE_A:
412 		case SSL3_ST_SW_SRVR_DONE_B:
413 			ret = ssl3_send_server_done(s);
414 			if (ret <= 0)
415 				goto end;
416 			S3I(s)->tmp.next_state = SSL3_ST_SR_CERT_A;
417 			s->internal->state = SSL3_ST_SW_FLUSH;
418 			s->internal->init_num = 0;
419 			break;
420 
421 		case SSL3_ST_SW_FLUSH:
422 
423 			/*
424 			 * This code originally checked to see if
425 			 * any data was pending using BIO_CTRL_INFO
426 			 * and then flushed. This caused problems
427 			 * as documented in PR#1939. The proposed
428 			 * fix doesn't completely resolve this issue
429 			 * as buggy implementations of BIO_CTRL_PENDING
430 			 * still exist. So instead we just flush
431 			 * unconditionally.
432 			 */
433 
434 			s->internal->rwstate = SSL_WRITING;
435 			if (BIO_flush(s->wbio) <= 0) {
436 				ret = -1;
437 				goto end;
438 			}
439 			s->internal->rwstate = SSL_NOTHING;
440 
441 			s->internal->state = S3I(s)->tmp.next_state;
442 			break;
443 
444 		case SSL3_ST_SR_CERT_A:
445 		case SSL3_ST_SR_CERT_B:
446 			if (S3I(s)->tmp.cert_request) {
447 				ret = ssl3_get_client_certificate(s);
448 				if (ret <= 0)
449 					goto end;
450 			}
451 			s->internal->init_num = 0;
452 			s->internal->state = SSL3_ST_SR_KEY_EXCH_A;
453 			break;
454 
455 		case SSL3_ST_SR_KEY_EXCH_A:
456 		case SSL3_ST_SR_KEY_EXCH_B:
457 			ret = ssl3_get_client_key_exchange(s);
458 			if (ret <= 0)
459 				goto end;
460 			alg_k = S3I(s)->tmp.new_cipher->algorithm_mkey;
461 			if (ret == 2) {
462 				/*
463 				 * For the ECDH ciphersuites when
464 				 * the client sends its ECDH pub key in
465 				 * a certificate, the CertificateVerify
466 				 * message is not sent.
467 				 * Also for GOST ciphersuites when
468 				 * the client uses its key from the certificate
469 				 * for key exchange.
470 				 */
471 				if (S3I(s)->next_proto_neg_seen)
472 					s->internal->state = SSL3_ST_SR_NEXT_PROTO_A;
473 				else
474 					s->internal->state = SSL3_ST_SR_FINISHED_A;
475 				s->internal->init_num = 0;
476 			} else if (SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) {
477 				s->internal->state = SSL3_ST_SR_CERT_VRFY_A;
478 				s->internal->init_num = 0;
479 				if (!s->session->peer)
480 					break;
481 				/*
482 				 * For sigalgs freeze the handshake buffer
483 				 * at this point and digest cached records.
484 				 */
485 				if (!S3I(s)->handshake_buffer) {
486 					SSLerror(s, ERR_R_INTERNAL_ERROR);
487 					ret = -1;
488 					goto end;
489 				}
490 				s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
491 				if (!tls1_digest_cached_records(s)) {
492 					ret = -1;
493 					goto end;
494 				}
495 			} else {
496 				int offset = 0;
497 				int dgst_num;
498 
499 				s->internal->state = SSL3_ST_SR_CERT_VRFY_A;
500 				s->internal->init_num = 0;
501 
502 				/*
503 				 * We need to get hashes here so if there is
504 				 * a client cert, it can be verified
505 				 * FIXME - digest processing for
506 				 * CertificateVerify should be generalized.
507 				 * But it is next step
508 				 */
509 				if (S3I(s)->handshake_buffer) {
510 					if (!tls1_digest_cached_records(s)) {
511 						ret = -1;
512 						goto end;
513 					}
514 				}
515 				for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST;
516 				    dgst_num++)
517 					if (S3I(s)->handshake_dgst[dgst_num]) {
518 					int dgst_size;
519 
520 					tls1_cert_verify_mac(s,
521 					    EVP_MD_CTX_type(
522 					    S3I(s)->handshake_dgst[dgst_num]),
523 					    &(S3I(s)->tmp.cert_verify_md[offset]));
524 					dgst_size = EVP_MD_CTX_size(
525 					    S3I(s)->handshake_dgst[dgst_num]);
526 					if (dgst_size < 0) {
527 						ret = -1;
528 						goto end;
529 					}
530 					offset += dgst_size;
531 				}
532 			}
533 			break;
534 
535 		case SSL3_ST_SR_CERT_VRFY_A:
536 		case SSL3_ST_SR_CERT_VRFY_B:
537 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
538 
539 			/* we should decide if we expected this one */
540 			ret = ssl3_get_cert_verify(s);
541 			if (ret <= 0)
542 				goto end;
543 
544 			if (S3I(s)->next_proto_neg_seen)
545 				s->internal->state = SSL3_ST_SR_NEXT_PROTO_A;
546 			else
547 				s->internal->state = SSL3_ST_SR_FINISHED_A;
548 			s->internal->init_num = 0;
549 			break;
550 
551 		case SSL3_ST_SR_NEXT_PROTO_A:
552 		case SSL3_ST_SR_NEXT_PROTO_B:
553 			ret = ssl3_get_next_proto(s);
554 			if (ret <= 0)
555 				goto end;
556 			s->internal->init_num = 0;
557 			s->internal->state = SSL3_ST_SR_FINISHED_A;
558 			break;
559 
560 		case SSL3_ST_SR_FINISHED_A:
561 		case SSL3_ST_SR_FINISHED_B:
562 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
563 			ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
564 			    SSL3_ST_SR_FINISHED_B);
565 			if (ret <= 0)
566 				goto end;
567 			if (s->internal->hit)
568 				s->internal->state = SSL_ST_OK;
569 			else if (s->internal->tlsext_ticket_expected)
570 				s->internal->state = SSL3_ST_SW_SESSION_TICKET_A;
571 			else
572 				s->internal->state = SSL3_ST_SW_CHANGE_A;
573 			s->internal->init_num = 0;
574 			break;
575 
576 		case SSL3_ST_SW_SESSION_TICKET_A:
577 		case SSL3_ST_SW_SESSION_TICKET_B:
578 			ret = ssl3_send_newsession_ticket(s);
579 			if (ret <= 0)
580 				goto end;
581 			s->internal->state = SSL3_ST_SW_CHANGE_A;
582 			s->internal->init_num = 0;
583 			break;
584 
585 		case SSL3_ST_SW_CERT_STATUS_A:
586 		case SSL3_ST_SW_CERT_STATUS_B:
587 			ret = ssl3_send_cert_status(s);
588 			if (ret <= 0)
589 				goto end;
590 			s->internal->state = SSL3_ST_SW_KEY_EXCH_A;
591 			s->internal->init_num = 0;
592 			break;
593 
594 
595 		case SSL3_ST_SW_CHANGE_A:
596 		case SSL3_ST_SW_CHANGE_B:
597 
598 			s->session->cipher = S3I(s)->tmp.new_cipher;
599 			if (!tls1_setup_key_block(s)) {
600 				ret = -1;
601 				goto end;
602 			}
603 
604 			ret = ssl3_send_change_cipher_spec(s,
605 			    SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B);
606 
607 			if (ret <= 0)
608 				goto end;
609 			s->internal->state = SSL3_ST_SW_FINISHED_A;
610 			s->internal->init_num = 0;
611 
612 			if (!tls1_change_cipher_state(
613 			    s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
614 				ret = -1;
615 				goto end;
616 			}
617 
618 			break;
619 
620 		case SSL3_ST_SW_FINISHED_A:
621 		case SSL3_ST_SW_FINISHED_B:
622 			ret = ssl3_send_finished(s,
623 			SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
624 			TLS_MD_SERVER_FINISH_CONST,
625 			TLS_MD_SERVER_FINISH_CONST_SIZE);
626 			if (ret <= 0)
627 				goto end;
628 			s->internal->state = SSL3_ST_SW_FLUSH;
629 			if (s->internal->hit) {
630 				if (S3I(s)->next_proto_neg_seen) {
631 					s->s3->flags |= SSL3_FLAGS_CCS_OK;
632 					S3I(s)->tmp.next_state =
633 					    SSL3_ST_SR_NEXT_PROTO_A;
634 				} else
635 					S3I(s)->tmp.next_state =
636 					    SSL3_ST_SR_FINISHED_A;
637 			} else
638 				S3I(s)->tmp.next_state = SSL_ST_OK;
639 			s->internal->init_num = 0;
640 			break;
641 
642 		case SSL_ST_OK:
643 			/* clean a few things up */
644 			tls1_cleanup_key_block(s);
645 
646 			BUF_MEM_free(s->internal->init_buf);
647 			s->internal->init_buf = NULL;
648 
649 			/* remove buffering on output */
650 			ssl_free_wbio_buffer(s);
651 
652 			s->internal->init_num = 0;
653 
654 			/* skipped if we just sent a HelloRequest */
655 			if (s->internal->renegotiate == 2) {
656 				s->internal->renegotiate = 0;
657 				s->internal->new_session = 0;
658 
659 				ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
660 
661 				s->ctx->internal->stats.sess_accept_good++;
662 				/* s->server=1; */
663 				s->internal->handshake_func = ssl3_accept;
664 
665 				if (cb != NULL)
666 					cb(s, SSL_CB_HANDSHAKE_DONE, 1);
667 			}
668 
669 			ret = 1;
670 			goto end;
671 			/* break; */
672 
673 		default:
674 			SSLerror(s, SSL_R_UNKNOWN_STATE);
675 			ret = -1;
676 			goto end;
677 			/* break; */
678 		}
679 
680 		if (!S3I(s)->tmp.reuse_message && !skip) {
681 			if (s->internal->debug) {
682 				if ((ret = BIO_flush(s->wbio)) <= 0)
683 					goto end;
684 			}
685 
686 
687 			if ((cb != NULL) && (s->internal->state != state)) {
688 				new_state = s->internal->state;
689 				s->internal->state = state;
690 				cb(s, SSL_CB_ACCEPT_LOOP, 1);
691 				s->internal->state = new_state;
692 			}
693 		}
694 		skip = 0;
695 	}
696 end:
697 	/* BIO_flush(s->wbio); */
698 
699 	s->internal->in_handshake--;
700 	if (cb != NULL)
701 		cb(s, SSL_CB_ACCEPT_EXIT, ret);
702 	return (ret);
703 }
704 
705 int
706 ssl3_send_hello_request(SSL *s)
707 {
708 	if (s->internal->state == SSL3_ST_SW_HELLO_REQ_A) {
709 		ssl3_handshake_msg_start(s, SSL3_MT_HELLO_REQUEST);
710 		ssl3_handshake_msg_finish(s, 0);
711 
712 		s->internal->state = SSL3_ST_SW_HELLO_REQ_B;
713 	}
714 
715 	/* SSL3_ST_SW_HELLO_REQ_B */
716 	return (ssl3_handshake_write(s));
717 }
718 
719 int
720 ssl3_get_client_hello(SSL *s)
721 {
722 	CBS cbs, client_random, session_id, cookie, cipher_suites;
723 	CBS compression_methods;
724 	uint16_t client_version;
725 	uint8_t comp_method;
726 	int comp_null;
727 	int i, j, ok, al, ret = -1;
728 	long n;
729 	unsigned long id;
730 	unsigned char *p, *d;
731 	SSL_CIPHER *c;
732 	STACK_OF(SSL_CIPHER) *ciphers = NULL;
733 	unsigned long alg_k;
734 	const SSL_METHOD *method;
735 	uint16_t shared_version;
736 	unsigned char *end;
737 
738 	/*
739 	 * We do this so that we will respond with our native type.
740 	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
741 	 * This down switching should be handled by a different method.
742 	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
743 	 * TLSv1.
744 	 */
745 	if (s->internal->state == SSL3_ST_SR_CLNT_HELLO_A) {
746 		s->internal->state = SSL3_ST_SR_CLNT_HELLO_B;
747 	}
748 
749 	s->internal->first_packet = 1;
750 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
751 	    SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
752 	    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
753 	if (!ok)
754 		return ((int)n);
755 	s->internal->first_packet = 0;
756 
757 	if (n < 0)
758 		goto err;
759 
760 	d = p = (unsigned char *)s->internal->init_msg;
761 	end = d + n;
762 
763 	CBS_init(&cbs, s->internal->init_msg, n);
764 
765 	/*
766 	 * Use version from inside client hello, not from record header.
767 	 * (may differ: see RFC 2246, Appendix E, second paragraph)
768 	 */
769 	if (!CBS_get_u16(&cbs, &client_version))
770 		goto truncated;
771 
772 	if (ssl_max_shared_version(s, client_version, &shared_version) != 1) {
773 		SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
774 		if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
775 		    !s->internal->enc_write_ctx && !s->internal->write_hash) {
776 			/*
777 			 * Similar to ssl3_get_record, send alert using remote
778 			 * version number.
779 			 */
780 			s->version = s->client_version;
781 		}
782 		al = SSL_AD_PROTOCOL_VERSION;
783 		goto f_err;
784 	}
785 	s->client_version = client_version;
786 	s->version = shared_version;
787 
788 	if ((method = tls1_get_server_method(shared_version)) == NULL)
789 		method = dtls1_get_server_method(shared_version);
790 	if (method == NULL) {
791 		SSLerror(s, ERR_R_INTERNAL_ERROR);
792 		goto err;
793 	}
794 	s->method = method;
795 
796 	if (!CBS_get_bytes(&cbs, &client_random, SSL3_RANDOM_SIZE))
797 		goto truncated;
798 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
799 		goto truncated;
800 
801 	/*
802 	 * If we require cookies (DTLS) and this ClientHello doesn't
803 	 * contain one, just return since we do not want to
804 	 * allocate any memory yet. So check cookie length...
805 	 */
806 	if (SSL_IS_DTLS(s)) {
807 		if (!CBS_get_u8_length_prefixed(&cbs, &cookie))
808 			goto truncated;
809 		if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
810 			if (CBS_len(&cookie) == 0)
811 				return (1);
812 		}
813 	}
814 
815 	if (!CBS_write_bytes(&client_random, s->s3->client_random,
816 	    sizeof(s->s3->client_random), NULL))
817 		goto err;
818 
819 	s->internal->hit = 0;
820 
821 	/*
822 	 * Versions before 0.9.7 always allow clients to resume sessions in
823 	 * renegotiation. 0.9.7 and later allow this by default, but optionally
824 	 * ignore resumption requests with flag
825 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
826 	 * rather than a change to default behavior so that applications
827 	 * relying on this for security won't even compile against older
828 	 * library versions).
829 	 *
830 	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
831 	 * to request renegotiation but not a new session (s->internal->new_session
832 	 * remains unset): for servers, this essentially just means that the
833 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
834 	 * ignored.
835 	 */
836 	if ((s->internal->new_session && (s->internal->options &
837 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
838 		if (!ssl_get_new_session(s, 1))
839 			goto err;
840 	} else {
841 		/* XXX - pass CBS through instead... */
842 		i = ssl_get_prev_session(s,
843 		    (unsigned char *)CBS_data(&session_id),
844 		    CBS_len(&session_id), end);
845 		if (i == 1) { /* previous session */
846 			s->internal->hit = 1;
847 		} else if (i == -1)
848 			goto err;
849 		else {
850 			/* i == 0 */
851 			if (!ssl_get_new_session(s, 1))
852 				goto err;
853 		}
854 	}
855 
856 	if (SSL_IS_DTLS(s)) {
857 		/*
858 		 * The ClientHello may contain a cookie even if the HelloVerify
859 		 * message has not been sent - make sure that it does not cause
860 		 * an overflow.
861 		 */
862 		if (CBS_len(&cookie) > sizeof(D1I(s)->rcvd_cookie)) {
863 			al = SSL_AD_DECODE_ERROR;
864 			SSLerror(s, SSL_R_COOKIE_MISMATCH);
865 			goto f_err;
866 		}
867 
868 		/* Verify the cookie if appropriate option is set. */
869 		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
870 		    CBS_len(&cookie) > 0) {
871 			size_t cookie_len;
872 
873 			/* XXX - rcvd_cookie seems to only be used here... */
874 			if (!CBS_write_bytes(&cookie, D1I(s)->rcvd_cookie,
875 			    sizeof(D1I(s)->rcvd_cookie), &cookie_len))
876 				goto err;
877 
878 			if (s->ctx->internal->app_verify_cookie_cb != NULL) {
879 				if (s->ctx->internal->app_verify_cookie_cb(s,
880 				    D1I(s)->rcvd_cookie, cookie_len) == 0) {
881 					al = SSL_AD_HANDSHAKE_FAILURE;
882 					SSLerror(s, SSL_R_COOKIE_MISMATCH);
883 					goto f_err;
884 				}
885 				/* else cookie verification succeeded */
886 			/* XXX - can d1->cookie_len > sizeof(rcvd_cookie) ? */
887 			} else if (timingsafe_memcmp(D1I(s)->rcvd_cookie,
888 			    D1I(s)->cookie, D1I(s)->cookie_len) != 0) {
889 				/* default verification */
890 				al = SSL_AD_HANDSHAKE_FAILURE;
891 				SSLerror(s, SSL_R_COOKIE_MISMATCH);
892 				goto f_err;
893 			}
894 			ret = 2;
895 		}
896 	}
897 
898 	if (!CBS_get_u16_length_prefixed(&cbs, &cipher_suites))
899 		goto truncated;
900 
901 	/* XXX - This logic seems wrong... */
902 	if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
903 		/* we need a cipher if we are not resuming a session */
904 		al = SSL_AD_ILLEGAL_PARAMETER;
905 		SSLerror(s, SSL_R_NO_CIPHERS_SPECIFIED);
906 		goto f_err;
907 	}
908 
909 	if (CBS_len(&cipher_suites) > 0) {
910 		if ((ciphers = ssl_bytes_to_cipher_list(s,
911 		    CBS_data(&cipher_suites), CBS_len(&cipher_suites))) == NULL)
912 			goto err;
913 	}
914 
915 	/* If it is a hit, check that the cipher is in the list */
916 	if (s->internal->hit && CBS_len(&cipher_suites) > 0) {
917 		j = 0;
918 		id = s->session->cipher->id;
919 
920 		for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
921 			c = sk_SSL_CIPHER_value(ciphers, i);
922 			if (c->id == id) {
923 				j = 1;
924 				break;
925 			}
926 		}
927 		if (j == 0) {
928 			/*
929 			 * We need to have the cipher in the cipher
930 			 * list if we are asked to reuse it
931 			 */
932 			al = SSL_AD_ILLEGAL_PARAMETER;
933 			SSLerror(s, SSL_R_REQUIRED_CIPHER_MISSING);
934 			goto f_err;
935 		}
936 	}
937 
938 	if (!CBS_get_u8_length_prefixed(&cbs, &compression_methods))
939 		goto truncated;
940 
941 	comp_null = 0;
942 	while (CBS_len(&compression_methods) > 0) {
943 		if (!CBS_get_u8(&compression_methods, &comp_method))
944 			goto truncated;
945 		if (comp_method == 0)
946 			comp_null = 1;
947 	}
948 	if (comp_null == 0) {
949 		al = SSL_AD_DECODE_ERROR;
950 		SSLerror(s, SSL_R_NO_COMPRESSION_SPECIFIED);
951 		goto f_err;
952 	}
953 
954 	p = (unsigned char *)CBS_data(&cbs);
955 
956 	/* TLS extensions*/
957 	if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
958 		/* 'al' set by ssl_parse_clienthello_tlsext */
959 		SSLerror(s, SSL_R_PARSE_TLSEXT);
960 		goto f_err;
961 	}
962 	if (ssl_check_clienthello_tlsext_early(s) <= 0) {
963 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
964 		goto err;
965 	}
966 
967 	/*
968 	 * Check if we want to use external pre-shared secret for this
969 	 * handshake for not reused session only. We need to generate
970 	 * server_random before calling tls_session_secret_cb in order to allow
971 	 * SessionTicket processing to use it in key derivation.
972 	 */
973 	arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
974 
975 	if (!s->internal->hit && s->internal->tls_session_secret_cb) {
976 		SSL_CIPHER *pref_cipher = NULL;
977 
978 		s->session->master_key_length = sizeof(s->session->master_key);
979 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
980 		    &s->session->master_key_length, ciphers, &pref_cipher,
981 		    s->internal->tls_session_secret_cb_arg)) {
982 			s->internal->hit = 1;
983 			s->session->ciphers = ciphers;
984 			s->session->verify_result = X509_V_OK;
985 
986 			ciphers = NULL;
987 
988 			/* check if some cipher was preferred by call back */
989 			pref_cipher = pref_cipher ? pref_cipher :
990 			    ssl3_choose_cipher(s, s->session->ciphers,
991 			    SSL_get_ciphers(s));
992 			if (pref_cipher == NULL) {
993 				al = SSL_AD_HANDSHAKE_FAILURE;
994 				SSLerror(s, SSL_R_NO_SHARED_CIPHER);
995 				goto f_err;
996 			}
997 
998 			s->session->cipher = pref_cipher;
999 
1000 			sk_SSL_CIPHER_free(s->cipher_list);
1001 			sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
1002 
1003 			s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1004 			s->internal->cipher_list_by_id =
1005 			    sk_SSL_CIPHER_dup(s->session->ciphers);
1006 		}
1007 	}
1008 
1009 	/*
1010 	 * Given s->session->ciphers and SSL_get_ciphers, we must
1011 	 * pick a cipher
1012 	 */
1013 
1014 	if (!s->internal->hit) {
1015 		sk_SSL_CIPHER_free(s->session->ciphers);
1016 		s->session->ciphers = ciphers;
1017 		if (ciphers == NULL) {
1018 			al = SSL_AD_ILLEGAL_PARAMETER;
1019 			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
1020 			goto f_err;
1021 		}
1022 		ciphers = NULL;
1023 		c = ssl3_choose_cipher(s, s->session->ciphers,
1024 		SSL_get_ciphers(s));
1025 
1026 		if (c == NULL) {
1027 			al = SSL_AD_HANDSHAKE_FAILURE;
1028 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1029 			goto f_err;
1030 		}
1031 		S3I(s)->tmp.new_cipher = c;
1032 	} else {
1033 		S3I(s)->tmp.new_cipher = s->session->cipher;
1034 	}
1035 
1036 	alg_k = S3I(s)->tmp.new_cipher->algorithm_mkey;
1037 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1038 	    !(s->verify_mode & SSL_VERIFY_PEER)) {
1039 		if (!tls1_digest_cached_records(s)) {
1040 			al = SSL_AD_INTERNAL_ERROR;
1041 			goto f_err;
1042 		}
1043 	}
1044 
1045 	/*
1046 	 * We now have the following setup.
1047 	 * client_random
1048 	 * cipher_list 		- our prefered list of ciphers
1049 	 * ciphers 		- the clients prefered list of ciphers
1050 	 * compression		- basically ignored right now
1051 	 * ssl version is set	- sslv3
1052 	 * s->session		- The ssl session has been setup.
1053 	 * s->internal->hit		- session reuse flag
1054 	 * s->tmp.new_cipher	- the new cipher to use.
1055 	 */
1056 
1057 	/* Handles TLS extensions that we couldn't check earlier */
1058 	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1059 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1060 		goto err;
1061 	}
1062 
1063 	if (ret < 0)
1064 		ret = 1;
1065 	if (0) {
1066 truncated:
1067 		al = SSL_AD_DECODE_ERROR;
1068 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1069 f_err:
1070 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1071 	}
1072 err:
1073 	sk_SSL_CIPHER_free(ciphers);
1074 
1075 	return (ret);
1076 }
1077 
1078 int
1079 ssl3_send_server_hello(SSL *s)
1080 {
1081 	unsigned char *bufend;
1082 	unsigned char *p, *d;
1083 	CBB cbb, session_id;
1084 	size_t outlen;
1085 	int sl;
1086 
1087 	memset(&cbb, 0, sizeof(cbb));
1088 
1089 	bufend = (unsigned char *)s->internal->init_buf->data + SSL3_RT_MAX_PLAIN_LENGTH;
1090 
1091 	if (s->internal->state == SSL3_ST_SW_SRVR_HELLO_A) {
1092 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_SERVER_HELLO);
1093 
1094 		if (!CBB_init_fixed(&cbb, p, bufend - p))
1095 			goto err;
1096 
1097 		if (!CBB_add_u16(&cbb, s->version))
1098 			goto err;
1099 		if (!CBB_add_bytes(&cbb, s->s3->server_random,
1100 		    sizeof(s->s3->server_random)))
1101 			goto err;
1102 
1103 		/*
1104 		 * There are several cases for the session ID to send
1105 		 * back in the server hello:
1106 		 *
1107 		 * - For session reuse from the session cache,
1108 		 *   we send back the old session ID.
1109 		 * - If stateless session reuse (using a session ticket)
1110 		 *   is successful, we send back the client's "session ID"
1111 		 *   (which doesn't actually identify the session).
1112 		 * - If it is a new session, we send back the new
1113 		 *   session ID.
1114 		 * - However, if we want the new session to be single-use,
1115 		 *   we send back a 0-length session ID.
1116 		 *
1117 		 * s->internal->hit is non-zero in either case of session reuse,
1118 		 * so the following won't overwrite an ID that we're supposed
1119 		 * to send back.
1120 		 */
1121 		if (!(s->ctx->internal->session_cache_mode & SSL_SESS_CACHE_SERVER)
1122 		    && !s->internal->hit)
1123 			s->session->session_id_length = 0;
1124 
1125 		sl = s->session->session_id_length;
1126 		if (sl > (int)sizeof(s->session->session_id)) {
1127 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1128 			goto err;
1129 		}
1130 
1131 		if (!CBB_add_u8_length_prefixed(&cbb, &session_id))
1132 			goto err;
1133 		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1134 			goto err;
1135 
1136 		/* Cipher suite. */
1137 		if (!CBB_add_u16(&cbb,
1138 		    ssl3_cipher_get_value(S3I(s)->tmp.new_cipher)))
1139 			goto err;
1140 
1141 		/* Compression method. */
1142 		if (!CBB_add_u8(&cbb, 0))
1143 			goto err;
1144 
1145 		if (!CBB_finish(&cbb, NULL, &outlen))
1146 			goto err;
1147 
1148 		if ((p = ssl_add_serverhello_tlsext(s, p + outlen,
1149 		    bufend)) == NULL) {
1150 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1151 			goto err;
1152 		}
1153 
1154 		ssl3_handshake_msg_finish(s, p - d);
1155 	}
1156 
1157 	/* SSL3_ST_SW_SRVR_HELLO_B */
1158 	return (ssl3_handshake_write(s));
1159 
1160  err:
1161 	CBB_cleanup(&cbb);
1162 
1163 	return (-1);
1164 }
1165 
1166 int
1167 ssl3_send_server_done(SSL *s)
1168 {
1169 	if (s->internal->state == SSL3_ST_SW_SRVR_DONE_A) {
1170 		ssl3_handshake_msg_start(s, SSL3_MT_SERVER_DONE);
1171 		ssl3_handshake_msg_finish(s, 0);
1172 
1173 		s->internal->state = SSL3_ST_SW_SRVR_DONE_B;
1174 	}
1175 
1176 	/* SSL3_ST_SW_SRVR_DONE_B */
1177 	return (ssl3_handshake_write(s));
1178 }
1179 
1180 int
1181 ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1182 {
1183 	CBB dh_p, dh_g, dh_Ys;
1184 	DH *dh = NULL, *dhp;
1185 	unsigned char *data;
1186 	int al;
1187 
1188 	if (s->cert->dh_tmp_auto != 0) {
1189 		if ((dhp = ssl_get_auto_dh(s)) == NULL) {
1190 			al = SSL_AD_INTERNAL_ERROR;
1191 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1192 			goto f_err;
1193 		}
1194 	} else
1195 		dhp = s->cert->dh_tmp;
1196 
1197 	if (dhp == NULL && s->cert->dh_tmp_cb != NULL)
1198 		dhp = s->cert->dh_tmp_cb(s, 0,
1199 		    SSL_C_PKEYLENGTH(S3I(s)->tmp.new_cipher));
1200 
1201 	if (dhp == NULL) {
1202 		al = SSL_AD_HANDSHAKE_FAILURE;
1203 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1204 		goto f_err;
1205 	}
1206 
1207 	if (S3I(s)->tmp.dh != NULL) {
1208 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1209 		goto err;
1210 	}
1211 
1212 	if (s->cert->dh_tmp_auto != 0) {
1213 		dh = dhp;
1214 	} else if ((dh = DHparams_dup(dhp)) == NULL) {
1215 		SSLerror(s, ERR_R_DH_LIB);
1216 		goto err;
1217 	}
1218 	S3I(s)->tmp.dh = dh;
1219 	if (!DH_generate_key(dh)) {
1220 		SSLerror(s, ERR_R_DH_LIB);
1221 		goto err;
1222 	}
1223 
1224 	/*
1225 	 * Serialize the DH parameters and public key.
1226 	 */
1227 	if (!CBB_add_u16_length_prefixed(cbb, &dh_p))
1228 		goto err;
1229 	if (!CBB_add_space(&dh_p, &data, BN_num_bytes(dh->p)))
1230 		goto err;
1231 	BN_bn2bin(dh->p, data);
1232 
1233 	if (!CBB_add_u16_length_prefixed(cbb, &dh_g))
1234 		goto err;
1235 	if (!CBB_add_space(&dh_g, &data, BN_num_bytes(dh->g)))
1236 		goto err;
1237 	BN_bn2bin(dh->g, data);
1238 
1239 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Ys))
1240 		goto err;
1241 	if (!CBB_add_space(&dh_Ys, &data, BN_num_bytes(dh->pub_key)))
1242 		goto err;
1243 	BN_bn2bin(dh->pub_key, data);
1244 
1245 	if (!CBB_flush(cbb))
1246 		goto err;
1247 
1248 	return (1);
1249 
1250  f_err:
1251 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1252  err:
1253 	return (-1);
1254 }
1255 
1256 static int
1257 ssl3_send_server_kex_ecdhe_ecp(SSL *s, int nid, CBB *cbb)
1258 {
1259 	CBB ecpoint;
1260 	unsigned char *data;
1261 	EC_KEY *ecdh = NULL, *ecdhp;
1262 	const EC_GROUP *group;
1263 	unsigned char *encodedPoint = NULL;
1264 	int encodedlen = 0;
1265 	int curve_id = 0;
1266 	BN_CTX *bn_ctx = NULL;
1267 	int al;
1268 
1269 	ecdhp = s->cert->ecdh_tmp;
1270 	if (s->cert->ecdh_tmp_auto != 0) {
1271 		if (nid != NID_undef)
1272 			ecdhp = EC_KEY_new_by_curve_name(nid);
1273 	} else if (ecdhp == NULL && s->cert->ecdh_tmp_cb != NULL) {
1274 		ecdhp = s->cert->ecdh_tmp_cb(s, 0,
1275 		    SSL_C_PKEYLENGTH(S3I(s)->tmp.new_cipher));
1276 	}
1277 	if (ecdhp == NULL) {
1278 		al = SSL_AD_HANDSHAKE_FAILURE;
1279 		SSLerror(s, SSL_R_MISSING_TMP_ECDH_KEY);
1280 		goto f_err;
1281 	}
1282 
1283 	if (S3I(s)->tmp.ecdh != NULL) {
1284 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1285 		goto err;
1286 	}
1287 
1288 	/* Duplicate the ECDH structure. */
1289 	if (s->cert->ecdh_tmp_auto != 0) {
1290 		ecdh = ecdhp;
1291 	} else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1292 		SSLerror(s, ERR_R_ECDH_LIB);
1293 		goto err;
1294 	}
1295 	S3I(s)->tmp.ecdh = ecdh;
1296 
1297 	if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1298 	    (EC_KEY_get0_private_key(ecdh) == NULL) ||
1299 	    (s->internal->options & SSL_OP_SINGLE_ECDH_USE)) {
1300 		if (!EC_KEY_generate_key(ecdh)) {
1301 			SSLerror(s, ERR_R_ECDH_LIB);
1302 			goto err;
1303 		}
1304 	}
1305 
1306 	if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1307 	    (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1308 	    (EC_KEY_get0_private_key(ecdh) == NULL)) {
1309 		SSLerror(s, ERR_R_ECDH_LIB);
1310 		goto err;
1311 	}
1312 
1313 	/*
1314 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1315 	 * For supported named curves, curve_id is non-zero.
1316 	 */
1317 	if ((curve_id = tls1_ec_nid2curve_id(
1318 	    EC_GROUP_get_curve_name(group))) == 0) {
1319 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1320 		goto err;
1321 	}
1322 
1323 	/*
1324 	 * Encode the public key. First check the size of encoding and
1325 	 * allocate memory accordingly.
1326 	 */
1327 	encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1328 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
1329 
1330 	encodedPoint = malloc(encodedlen);
1331 
1332 	bn_ctx = BN_CTX_new();
1333 	if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1334 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1335 		goto err;
1336 	}
1337 
1338 	encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1339 	    POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encodedlen, bn_ctx);
1340 
1341 	if (encodedlen == 0) {
1342 		SSLerror(s, ERR_R_ECDH_LIB);
1343 		goto err;
1344 	}
1345 
1346 	BN_CTX_free(bn_ctx);
1347 	bn_ctx = NULL;
1348 
1349 	/*
1350 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1351 	 * In this case the ServerKeyExchange message has:
1352 	 * [1 byte CurveType], [2 byte CurveName]
1353 	 * [1 byte length of encoded point], followed by
1354 	 * the actual encoded point itself.
1355 	 */
1356 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1357 		goto err;
1358 	if (!CBB_add_u16(cbb, curve_id))
1359 		goto err;
1360 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1361 		goto err;
1362 	if (!CBB_add_space(&ecpoint, &data, encodedlen))
1363 		goto err;
1364 
1365 	memcpy(data, encodedPoint, encodedlen);
1366 
1367 	free(encodedPoint);
1368 	encodedPoint = NULL;
1369 
1370 	if (!CBB_flush(cbb))
1371 		goto err;
1372 
1373 	return (1);
1374 
1375  f_err:
1376 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1377  err:
1378 	free(encodedPoint);
1379 	BN_CTX_free(bn_ctx);
1380 
1381 	return (-1);
1382 }
1383 
1384 static int
1385 ssl3_send_server_kex_ecdhe_ecx(SSL *s, int nid, CBB *cbb)
1386 {
1387 	uint8_t *public_key = NULL;
1388 	int curve_id;
1389 	CBB ecpoint;
1390 	int ret = -1;
1391 
1392 	/* Generate an X25519 key pair. */
1393 	if (S3I(s)->tmp.x25519 != NULL) {
1394 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1395 		goto err;
1396 	}
1397 	if ((S3I(s)->tmp.x25519 = malloc(X25519_KEY_LENGTH)) == NULL)
1398 		goto err;
1399 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
1400 		goto err;
1401 	X25519_keypair(public_key, S3I(s)->tmp.x25519);
1402 
1403 	/* Serialize public key. */
1404 	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1405 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1406 		goto err;
1407 	}
1408 
1409 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1410 		goto err;
1411 	if (!CBB_add_u16(cbb, curve_id))
1412 		goto err;
1413 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1414 		goto err;
1415 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
1416 		goto err;
1417 	if (!CBB_flush(cbb))
1418 		goto err;
1419 
1420 	ret = 1;
1421 
1422  err:
1423 	free(public_key);
1424 
1425 	return (ret);
1426 }
1427 
1428 static int
1429 ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1430 {
1431 	int nid;
1432 
1433 	nid = tls1_get_shared_curve(s);
1434 
1435 	if (s->cert->ecdh_tmp_auto != 0 && nid == NID_X25519)
1436 		return ssl3_send_server_kex_ecdhe_ecx(s, nid, cbb);
1437 
1438 	return ssl3_send_server_kex_ecdhe_ecp(s, nid, cbb);
1439 }
1440 
1441 int
1442 ssl3_send_server_key_exchange(SSL *s)
1443 {
1444 	CBB cbb;
1445 	unsigned char *params = NULL;
1446 	size_t params_len;
1447 	unsigned char *q;
1448 	unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1449 	unsigned int u;
1450 	EVP_PKEY *pkey;
1451 	const EVP_MD *md = NULL;
1452 	unsigned char *p, *d;
1453 	int al, i, j, n, kn;
1454 	unsigned long type;
1455 	BUF_MEM *buf;
1456 	EVP_MD_CTX md_ctx;
1457 
1458 	memset(&cbb, 0, sizeof(cbb));
1459 
1460 	EVP_MD_CTX_init(&md_ctx);
1461 	if (s->internal->state == SSL3_ST_SW_KEY_EXCH_A) {
1462 		type = S3I(s)->tmp.new_cipher->algorithm_mkey;
1463 
1464 		buf = s->internal->init_buf;
1465 
1466 		if (!CBB_init(&cbb, 0))
1467 			goto err;
1468 
1469 		if (type & SSL_kDHE) {
1470 			if (ssl3_send_server_kex_dhe(s, &cbb) != 1)
1471 				goto err;
1472 		} else if (type & SSL_kECDHE) {
1473 			if (ssl3_send_server_kex_ecdhe(s, &cbb) != 1)
1474 				goto err;
1475 		} else {
1476 			al = SSL_AD_HANDSHAKE_FAILURE;
1477 			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1478 			goto f_err;
1479 		}
1480 
1481 		if (!CBB_finish(&cbb, &params, &params_len))
1482 			goto err;
1483 
1484 		if (!(S3I(s)->tmp.new_cipher->algorithm_auth & SSL_aNULL)) {
1485 			if ((pkey = ssl_get_sign_pkey(
1486 			    s, S3I(s)->tmp.new_cipher, &md)) == NULL) {
1487 				al = SSL_AD_DECODE_ERROR;
1488 				goto f_err;
1489 			}
1490 			kn = EVP_PKEY_size(pkey);
1491 		} else {
1492 			pkey = NULL;
1493 			kn = 0;
1494 		}
1495 
1496 		if (!BUF_MEM_grow_clean(buf, ssl3_handshake_msg_hdr_len(s) +
1497 		    params_len + kn)) {
1498 			SSLerror(s, ERR_LIB_BUF);
1499 			goto err;
1500 		}
1501 
1502 		d = p = ssl3_handshake_msg_start(s,
1503 		    SSL3_MT_SERVER_KEY_EXCHANGE);
1504 
1505 		memcpy(p, params, params_len);
1506 
1507 		free(params);
1508 		params = NULL;
1509 
1510 		n = params_len;
1511 		p += params_len;
1512 
1513 		/* not anonymous */
1514 		if (pkey != NULL) {
1515 			/*
1516 			 * n is the length of the params, they start at &(d[4])
1517 			 * and p points to the space at the end.
1518 			 */
1519 			if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1520 				q = md_buf;
1521 				j = 0;
1522 				if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(),
1523 				    NULL))
1524 					goto err;
1525 				EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1526 				    SSL3_RANDOM_SIZE);
1527 				EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1528 				    SSL3_RANDOM_SIZE);
1529 				EVP_DigestUpdate(&md_ctx, d, n);
1530 				EVP_DigestFinal_ex(&md_ctx, q,
1531 				    (unsigned int *)&i);
1532 				q += i;
1533 				j += i;
1534 				if (RSA_sign(NID_md5_sha1, md_buf, j,
1535 				    &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1536 					SSLerror(s, ERR_R_RSA_LIB);
1537 					goto err;
1538 				}
1539 				s2n(u, p);
1540 				n += u + 2;
1541 			} else if (md) {
1542 				/* Send signature algorithm. */
1543 				if (SSL_USE_SIGALGS(s)) {
1544 					if (!tls12_get_sigandhash(p, pkey, md)) {
1545 						/* Should never happen */
1546 						al = SSL_AD_INTERNAL_ERROR;
1547 						SSLerror(s, ERR_R_INTERNAL_ERROR);
1548 						goto f_err;
1549 					}
1550 					p += 2;
1551 				}
1552 				EVP_SignInit_ex(&md_ctx, md, NULL);
1553 				EVP_SignUpdate(&md_ctx,
1554 				    s->s3->client_random,
1555 				    SSL3_RANDOM_SIZE);
1556 				EVP_SignUpdate(&md_ctx,
1557 				    s->s3->server_random,
1558 				    SSL3_RANDOM_SIZE);
1559 				EVP_SignUpdate(&md_ctx, d, n);
1560 				if (!EVP_SignFinal(&md_ctx, &p[2],
1561 					(unsigned int *)&i, pkey)) {
1562 					SSLerror(s, ERR_R_EVP_LIB);
1563 					goto err;
1564 				}
1565 				s2n(i, p);
1566 				n += i + 2;
1567 				if (SSL_USE_SIGALGS(s))
1568 					n += 2;
1569 			} else {
1570 				/* Is this error check actually needed? */
1571 				al = SSL_AD_HANDSHAKE_FAILURE;
1572 				SSLerror(s, SSL_R_UNKNOWN_PKEY_TYPE);
1573 				goto f_err;
1574 			}
1575 		}
1576 
1577 		ssl3_handshake_msg_finish(s, n);
1578 	}
1579 
1580 	s->internal->state = SSL3_ST_SW_KEY_EXCH_B;
1581 
1582 	EVP_MD_CTX_cleanup(&md_ctx);
1583 
1584 	return (ssl3_handshake_write(s));
1585 
1586  f_err:
1587 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1588  err:
1589 	free(params);
1590 	EVP_MD_CTX_cleanup(&md_ctx);
1591 	CBB_cleanup(&cbb);
1592 
1593 	return (-1);
1594 }
1595 
1596 int
1597 ssl3_send_certificate_request(SSL *s)
1598 {
1599 	unsigned char *p, *d;
1600 	int i, j, nl, off, n;
1601 	STACK_OF(X509_NAME) *sk = NULL;
1602 	X509_NAME *name;
1603 	BUF_MEM *buf;
1604 
1605 	if (s->internal->state == SSL3_ST_SW_CERT_REQ_A) {
1606 		buf = s->internal->init_buf;
1607 
1608 		d = p = ssl3_handshake_msg_start(s,
1609 		    SSL3_MT_CERTIFICATE_REQUEST);
1610 
1611 		/* get the list of acceptable cert types */
1612 		p++;
1613 		n = ssl3_get_req_cert_type(s, p);
1614 		d[0] = n;
1615 		p += n;
1616 		n++;
1617 
1618 		if (SSL_USE_SIGALGS(s)) {
1619 			nl = tls12_get_req_sig_algs(s, p + 2);
1620 			s2n(nl, p);
1621 			p += nl + 2;
1622 			n += nl + 2;
1623 		}
1624 
1625 		off = n;
1626 		p += 2;
1627 		n += 2;
1628 
1629 		sk = SSL_get_client_CA_list(s);
1630 		nl = 0;
1631 		if (sk != NULL) {
1632 			for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1633 				name = sk_X509_NAME_value(sk, i);
1634 				j = i2d_X509_NAME(name, NULL);
1635 				if (!BUF_MEM_grow_clean(buf,
1636 				    ssl3_handshake_msg_hdr_len(s) + n + j
1637 				    + 2)) {
1638 					SSLerror(s, ERR_R_BUF_LIB);
1639 					goto err;
1640 				}
1641 				p = ssl3_handshake_msg_start(s,
1642 				    SSL3_MT_CERTIFICATE_REQUEST) + n;
1643 				s2n(j, p);
1644 				i2d_X509_NAME(name, &p);
1645 				n += 2 + j;
1646 				nl += 2 + j;
1647 			}
1648 		}
1649 		/* else no CA names */
1650 		p = ssl3_handshake_msg_start(s,
1651 		    SSL3_MT_CERTIFICATE_REQUEST) + off;
1652 		s2n(nl, p);
1653 
1654 		ssl3_handshake_msg_finish(s, n);
1655 
1656 		s->internal->state = SSL3_ST_SW_CERT_REQ_B;
1657 	}
1658 
1659 	/* SSL3_ST_SW_CERT_REQ_B */
1660 	return (ssl3_handshake_write(s));
1661 err:
1662 	return (-1);
1663 }
1664 
1665 static int
1666 ssl3_get_client_kex_rsa(SSL *s, unsigned char *p, long n)
1667 {
1668 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1669 	unsigned char *d;
1670 	RSA *rsa = NULL;
1671 	EVP_PKEY *pkey = NULL;
1672 	int i, al;
1673 
1674 	d = p;
1675 
1676 	arc4random_buf(fakekey, sizeof(fakekey));
1677 	fakekey[0] = s->client_version >> 8;
1678 	fakekey[1] = s->client_version & 0xff;
1679 
1680 	pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1681 	if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1682 	    (pkey->pkey.rsa == NULL)) {
1683 		al = SSL_AD_HANDSHAKE_FAILURE;
1684 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1685 		goto f_err;
1686 	}
1687 	rsa = pkey->pkey.rsa;
1688 
1689 	if (2 > n)
1690 		goto truncated;
1691 	n2s(p, i);
1692 	if (n != i + 2) {
1693 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1694 		goto err;
1695 	} else
1696 		n = i;
1697 
1698 	i = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1699 
1700 	ERR_clear_error();
1701 
1702 	al = -1;
1703 
1704 	if (i != SSL_MAX_MASTER_KEY_LENGTH) {
1705 		al = SSL_AD_DECODE_ERROR;
1706 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1707 	}
1708 
1709 	if (p - d + 2 > n)	/* needed in the SSL3 case */
1710 		goto truncated;
1711 	if ((al == -1) && !((p[0] == (s->client_version >> 8)) &&
1712 	    (p[1] == (s->client_version & 0xff)))) {
1713 		/*
1714 		 * The premaster secret must contain the same version
1715 		 * number as the ClientHello to detect version rollback
1716 		 * attacks (strangely, the protocol does not offer such
1717 		 * protection for DH ciphersuites).
1718 		 * However, buggy clients exist that send the negotiated
1719 		 * protocol version instead if the server does not
1720 		 * support the requested protocol version.
1721 		 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1722 		 * clients.
1723 		 */
1724 		if (!((s->internal->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1725 		    (p[0] == (s->version >> 8)) &&
1726 		    (p[1] == (s->version & 0xff)))) {
1727 			al = SSL_AD_DECODE_ERROR;
1728 			/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1729 
1730 			/*
1731 			 * The Klima-Pokorny-Rosa extension of
1732 			 * Bleichenbacher's attack
1733 			 * (http://eprint.iacr.org/2003/052/) exploits
1734 			 * the version number check as a "bad version
1735 			 * oracle" -- an alert would reveal that the
1736 			 * plaintext corresponding to some ciphertext
1737 			 * made up by the adversary is properly
1738 			 * formatted except that the version number is
1739 			 * wrong.
1740 			 * To avoid such attacks, we should treat this
1741 			 * just like any other decryption error.
1742 			 */
1743 		}
1744 	}
1745 
1746 	if (al != -1) {
1747 		/*
1748 		 * Some decryption failure -- use random value instead
1749 		 * as countermeasure against Bleichenbacher's attack
1750 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1751 		 * section 7.4.7.1).
1752 		 */
1753 		i = SSL_MAX_MASTER_KEY_LENGTH;
1754 		p = fakekey;
1755 	}
1756 
1757 	s->session->master_key_length =
1758 	    tls1_generate_master_secret(s,
1759 	        s->session->master_key, p, i);
1760 
1761 	explicit_bzero(p, i);
1762 
1763 	return (1);
1764 truncated:
1765 	al = SSL_AD_DECODE_ERROR;
1766 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1767 f_err:
1768 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1769 err:
1770 	return (-1);
1771 }
1772 
1773 static int
1774 ssl3_get_client_kex_dhe(SSL *s, unsigned char *p, long n)
1775 {
1776 	BIGNUM *bn = NULL;
1777 	int key_size, al;
1778 	CBS cbs, dh_Yc;
1779 	DH *dh;
1780 
1781 	if (n < 0)
1782 		goto err;
1783 
1784 	CBS_init(&cbs, p, n);
1785 
1786 	if (!CBS_get_u16_length_prefixed(&cbs, &dh_Yc))
1787 		goto truncated;
1788 
1789 	if (CBS_len(&cbs) != 0)
1790 		goto truncated;
1791 
1792 	if (S3I(s)->tmp.dh == NULL) {
1793 		al = SSL_AD_HANDSHAKE_FAILURE;
1794 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1795 		goto f_err;
1796 	}
1797 	dh = S3I(s)->tmp.dh;
1798 
1799 	if ((bn = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL)) == NULL) {
1800 		SSLerror(s, SSL_R_BN_LIB);
1801 		goto err;
1802 	}
1803 
1804 	key_size = DH_compute_key(p, bn, dh);
1805 	if (key_size <= 0) {
1806 		SSLerror(s, ERR_R_DH_LIB);
1807 		BN_clear_free(bn);
1808 		goto err;
1809 	}
1810 
1811 	s->session->master_key_length =
1812 	    tls1_generate_master_secret(
1813 	        s, s->session->master_key, p, key_size);
1814 
1815 	explicit_bzero(p, key_size);
1816 
1817 	DH_free(S3I(s)->tmp.dh);
1818 	S3I(s)->tmp.dh = NULL;
1819 
1820 	BN_clear_free(bn);
1821 
1822 	return (1);
1823 
1824  truncated:
1825 	al = SSL_AD_DECODE_ERROR;
1826 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1827  f_err:
1828 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1829  err:
1830 	return (-1);
1831 }
1832 
1833 static int
1834 ssl3_get_client_kex_ecdhe_ecp(SSL *s, unsigned char *p, long n)
1835 {
1836 	EC_KEY *srvr_ecdh = NULL;
1837 	EVP_PKEY *clnt_pub_pkey = NULL;
1838 	EC_POINT *clnt_ecpoint = NULL;
1839 	BN_CTX *bn_ctx = NULL;
1840 	int i, al;
1841 
1842 	int ret = 1;
1843 	int key_size;
1844 	const EC_KEY   *tkey;
1845 	const EC_GROUP *group;
1846 	const BIGNUM *priv_key;
1847 
1848 	/* Initialize structures for server's ECDH key pair. */
1849 	if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1850 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1851 		goto err;
1852 	}
1853 
1854 	/*
1855 	 * Use the ephemeral values we saved when
1856 	 * generating the ServerKeyExchange message.
1857 	 */
1858 	tkey = S3I(s)->tmp.ecdh;
1859 
1860 	group = EC_KEY_get0_group(tkey);
1861 	priv_key = EC_KEY_get0_private_key(tkey);
1862 
1863 	if (!EC_KEY_set_group(srvr_ecdh, group) ||
1864 	    !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1865 		SSLerror(s, ERR_R_EC_LIB);
1866 		goto err;
1867 	}
1868 
1869 	/* Let's get client's public key */
1870 	if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1871 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1872 		goto err;
1873 	}
1874 
1875 	if (n == 0L) {
1876 		/* Client Publickey was in Client Certificate */
1877 		if (((clnt_pub_pkey = X509_get_pubkey(
1878 		    s->session->peer)) == NULL) ||
1879 		    (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1880 			/*
1881 			 * XXX: For now, we do not support client
1882 			 * authentication using ECDH certificates
1883 			 * so this branch (n == 0L) of the code is
1884 			 * never executed. When that support is
1885 			 * added, we ought to ensure the key
1886 			 * received in the certificate is
1887 			 * authorized for key agreement.
1888 			 * ECDH_compute_key implicitly checks that
1889 			 * the two ECDH shares are for the same
1890 			 * group.
1891 			 */
1892 			al = SSL_AD_HANDSHAKE_FAILURE;
1893 			SSLerror(s, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1894 			goto f_err;
1895 		}
1896 
1897 		if (EC_POINT_copy(clnt_ecpoint,
1898 		    EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec))
1899 		    == 0) {
1900 			SSLerror(s, ERR_R_EC_LIB);
1901 			goto err;
1902 		}
1903 		ret = 2; /* Skip certificate verify processing */
1904 	} else {
1905 		/*
1906 		 * Get client's public key from encoded point
1907 		 * in the ClientKeyExchange message.
1908 		 */
1909 		if ((bn_ctx = BN_CTX_new()) == NULL) {
1910 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1911 			goto err;
1912 		}
1913 
1914 		/* Get encoded point length */
1915 		i = *p;
1916 
1917 		p += 1;
1918 		if (n != 1 + i) {
1919 			SSLerror(s, ERR_R_EC_LIB);
1920 			goto err;
1921 		}
1922 		if (EC_POINT_oct2point(group,
1923 			clnt_ecpoint, p, i, bn_ctx) == 0) {
1924 			SSLerror(s, ERR_R_EC_LIB);
1925 			goto err;
1926 		}
1927 		/*
1928 		 * p is pointing to somewhere in the buffer
1929 		 * currently, so set it to the start.
1930 		 */
1931 		p = (unsigned char *)s->internal->init_buf->data;
1932 	}
1933 
1934 	/* Compute the shared pre-master secret */
1935 	key_size = ECDH_size(srvr_ecdh);
1936 	if (key_size <= 0) {
1937 		SSLerror(s, ERR_R_ECDH_LIB);
1938 		goto err;
1939 	}
1940 	i = ECDH_compute_key(p, key_size, clnt_ecpoint, srvr_ecdh,
1941 	    NULL);
1942 	if (i <= 0) {
1943 		SSLerror(s, ERR_R_ECDH_LIB);
1944 		goto err;
1945 	}
1946 
1947 	EVP_PKEY_free(clnt_pub_pkey);
1948 	EC_POINT_free(clnt_ecpoint);
1949 	EC_KEY_free(srvr_ecdh);
1950 	BN_CTX_free(bn_ctx);
1951 	EC_KEY_free(S3I(s)->tmp.ecdh);
1952 	S3I(s)->tmp.ecdh = NULL;
1953 
1954 	/* Compute the master secret */
1955 	s->session->master_key_length =
1956 	    tls1_generate_master_secret(
1957 		s, s->session->master_key, p, i);
1958 
1959 	explicit_bzero(p, i);
1960 	return (ret);
1961 
1962  f_err:
1963 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1964  err:
1965 	EVP_PKEY_free(clnt_pub_pkey);
1966 	EC_POINT_free(clnt_ecpoint);
1967 	EC_KEY_free(srvr_ecdh);
1968 	BN_CTX_free(bn_ctx);
1969 	return (-1);
1970 }
1971 
1972 static int
1973 ssl3_get_client_kex_ecdhe_ecx(SSL *s, unsigned char *p, long n)
1974 {
1975 	uint8_t *shared_key = NULL;
1976 	CBS cbs, ecpoint;
1977 	int ret = -1;
1978 
1979 	if (n < 0)
1980 		goto err;
1981 
1982 	CBS_init(&cbs, p, n);
1983 	if (!CBS_get_u8_length_prefixed(&cbs, &ecpoint))
1984 		goto err;
1985 	if (CBS_len(&ecpoint) != X25519_KEY_LENGTH)
1986 		goto err;
1987 
1988 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
1989 		goto err;
1990 	if (!X25519(shared_key, S3I(s)->tmp.x25519, CBS_data(&ecpoint)))
1991 		goto err;
1992 
1993 	explicit_bzero(S3I(s)->tmp.x25519, X25519_KEY_LENGTH);
1994 	free(S3I(s)->tmp.x25519);
1995 	S3I(s)->tmp.x25519 = NULL;
1996 
1997 	s->session->master_key_length =
1998 	    tls1_generate_master_secret(
1999 		s, s->session->master_key, shared_key, X25519_KEY_LENGTH);
2000 
2001 	ret = 1;
2002 
2003  err:
2004 	if (shared_key != NULL)
2005 		explicit_bzero(shared_key, X25519_KEY_LENGTH);
2006 	free(shared_key);
2007 
2008 	return (ret);
2009 }
2010 
2011 static int
2012 ssl3_get_client_kex_ecdhe(SSL *s, unsigned char *p, long n)
2013 {
2014         if (S3I(s)->tmp.x25519 != NULL)
2015 		return ssl3_get_client_kex_ecdhe_ecx(s, p, n);
2016 
2017 	return ssl3_get_client_kex_ecdhe_ecp(s, p, n);
2018 }
2019 
2020 static int
2021 ssl3_get_client_kex_gost(SSL *s, unsigned char *p, long n)
2022 {
2023 
2024 	EVP_PKEY_CTX *pkey_ctx;
2025 	EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2026 	unsigned char premaster_secret[32], *start;
2027 	size_t outlen = 32, inlen;
2028 	unsigned long alg_a;
2029 	int Ttag, Tclass;
2030 	long Tlen;
2031 	int al;
2032 	int ret = 0;
2033 
2034 	/* Get our certificate private key*/
2035 	alg_a = S3I(s)->tmp.new_cipher->algorithm_auth;
2036 	if (alg_a & SSL_aGOST01)
2037 		pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2038 
2039 	pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2040 	EVP_PKEY_decrypt_init(pkey_ctx);
2041 	/*
2042 	 * If client certificate is present and is of the same type,
2043 	 * maybe use it for key exchange.
2044 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
2045 	 * it is completely valid to use a client certificate for
2046 	 * authorization only.
2047 	 */
2048 	client_pub_pkey = X509_get_pubkey(s->session->peer);
2049 	if (client_pub_pkey) {
2050 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2051 		    client_pub_pkey) <= 0)
2052 			ERR_clear_error();
2053 	}
2054 	if (2 > n)
2055 		goto truncated;
2056 	/* Decrypt session key */
2057 	if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag,
2058 	    &Tclass, n) != V_ASN1_CONSTRUCTED ||
2059 	    Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
2060 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2061 		goto gerr;
2062 	}
2063 	start = p;
2064 	inlen = Tlen;
2065 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
2066 	    start, inlen) <=0) {
2067 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2068 		goto gerr;
2069 	}
2070 	/* Generate master secret */
2071 	s->session->master_key_length =
2072 	    tls1_generate_master_secret(
2073 		s, s->session->master_key, premaster_secret, 32);
2074 	/* Check if pubkey from client certificate was used */
2075 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
2076 	    EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2077 		ret = 2;
2078 	else
2079 		ret = 1;
2080  gerr:
2081 	EVP_PKEY_free(client_pub_pkey);
2082 	EVP_PKEY_CTX_free(pkey_ctx);
2083 	if (ret)
2084 		return (ret);
2085 	else
2086 		goto err;
2087 
2088  truncated:
2089 	al = SSL_AD_DECODE_ERROR;
2090 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2091 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2092  err:
2093 	return (-1);
2094 }
2095 
2096 int
2097 ssl3_get_client_key_exchange(SSL *s)
2098 {
2099 	unsigned long alg_k;
2100 	unsigned char *p;
2101 	int al, ok;
2102 	long n;
2103 
2104 	/* 2048 maxlen is a guess.  How long a key does that permit? */
2105 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
2106 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2107 	if (!ok)
2108 		return ((int)n);
2109 
2110 	p = (unsigned char *)s->internal->init_msg;
2111 
2112 	alg_k = S3I(s)->tmp.new_cipher->algorithm_mkey;
2113 
2114 	if (alg_k & SSL_kRSA) {
2115 		if (ssl3_get_client_kex_rsa(s, p, n) != 1)
2116 			goto err;
2117 	} else if (alg_k & SSL_kDHE) {
2118 		if (ssl3_get_client_kex_dhe(s, p, n) != 1)
2119 			goto err;
2120 	} else if (alg_k & SSL_kECDHE) {
2121 		if (ssl3_get_client_kex_ecdhe(s, p, n) != 1)
2122 			goto err;
2123 	} else if (alg_k & SSL_kGOST) {
2124 		if (ssl3_get_client_kex_gost(s, p, n) != 1)
2125 			goto err;
2126 	} else {
2127 		al = SSL_AD_HANDSHAKE_FAILURE;
2128 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
2129 		goto f_err;
2130 	}
2131 
2132 	return (1);
2133 
2134  f_err:
2135 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2136  err:
2137 	return (-1);
2138 }
2139 
2140 int
2141 ssl3_get_cert_verify(SSL *s)
2142 {
2143 	EVP_PKEY *pkey = NULL;
2144 	unsigned char *p;
2145 	int al, ok, ret = 0;
2146 	long n;
2147 	int type = 0, i, j;
2148 	X509 *peer;
2149 	const EVP_MD *md = NULL;
2150 	EVP_MD_CTX mctx;
2151 	EVP_MD_CTX_init(&mctx);
2152 
2153 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2154 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2155 	if (!ok)
2156 		return ((int)n);
2157 
2158 	if (s->session->peer != NULL) {
2159 		peer = s->session->peer;
2160 		pkey = X509_get_pubkey(peer);
2161 		type = X509_certificate_type(peer, pkey);
2162 	} else {
2163 		peer = NULL;
2164 		pkey = NULL;
2165 	}
2166 
2167 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2168 		S3I(s)->tmp.reuse_message = 1;
2169 		if (peer != NULL) {
2170 			al = SSL_AD_UNEXPECTED_MESSAGE;
2171 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
2172 			goto f_err;
2173 		}
2174 		ret = 1;
2175 		goto end;
2176 	}
2177 
2178 	if (peer == NULL) {
2179 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
2180 		al = SSL_AD_UNEXPECTED_MESSAGE;
2181 		goto f_err;
2182 	}
2183 
2184 	if (!(type & EVP_PKT_SIGN)) {
2185 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2186 		al = SSL_AD_ILLEGAL_PARAMETER;
2187 		goto f_err;
2188 	}
2189 
2190 	if (S3I(s)->change_cipher_spec) {
2191 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2192 		al = SSL_AD_UNEXPECTED_MESSAGE;
2193 		goto f_err;
2194 	}
2195 
2196 	/* we now have a signature that we need to verify */
2197 	p = (unsigned char *)s->internal->init_msg;
2198 	/*
2199 	 * Check for broken implementations of GOST ciphersuites.
2200 	 *
2201 	 * If key is GOST and n is exactly 64, it is a bare
2202 	 * signature without length field.
2203 	 */
2204 	if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2205 	    pkey->type == NID_id_GostR3410_2001) ) {
2206 		i = 64;
2207 	} else {
2208 		if (SSL_USE_SIGALGS(s)) {
2209 			int sigalg = tls12_get_sigid(pkey);
2210 			/* Should never happen */
2211 			if (sigalg == -1) {
2212 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2213 				al = SSL_AD_INTERNAL_ERROR;
2214 				goto f_err;
2215 			}
2216 			if (2 > n)
2217 				goto truncated;
2218 			/* Check key type is consistent with signature */
2219 			if (sigalg != (int)p[1]) {
2220 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
2221 				al = SSL_AD_DECODE_ERROR;
2222 				goto f_err;
2223 			}
2224 			md = tls12_get_hash(p[0]);
2225 			if (md == NULL) {
2226 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
2227 				al = SSL_AD_DECODE_ERROR;
2228 				goto f_err;
2229 			}
2230 			p += 2;
2231 			n -= 2;
2232 		}
2233 		if (2 > n)
2234 			goto truncated;
2235 		n2s(p, i);
2236 		n -= 2;
2237 		if (i > n)
2238 			goto truncated;
2239 	}
2240 	j = EVP_PKEY_size(pkey);
2241 	if ((i > j) || (n > j) || (n <= 0)) {
2242 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2243 		al = SSL_AD_DECODE_ERROR;
2244 		goto f_err;
2245 	}
2246 
2247 	if (SSL_USE_SIGALGS(s)) {
2248 		long hdatalen = 0;
2249 		void *hdata;
2250 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2251 		if (hdatalen <= 0) {
2252 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2253 			al = SSL_AD_INTERNAL_ERROR;
2254 			goto f_err;
2255 		}
2256 		if (!EVP_VerifyInit_ex(&mctx, md, NULL) ||
2257 		    !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2258 			SSLerror(s, ERR_R_EVP_LIB);
2259 			al = SSL_AD_INTERNAL_ERROR;
2260 			goto f_err;
2261 		}
2262 
2263 		if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2264 			al = SSL_AD_DECRYPT_ERROR;
2265 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2266 			goto f_err;
2267 		}
2268 	} else
2269 	if (pkey->type == EVP_PKEY_RSA) {
2270 		i = RSA_verify(NID_md5_sha1, S3I(s)->tmp.cert_verify_md,
2271 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2272 		    pkey->pkey.rsa);
2273 		if (i < 0) {
2274 			al = SSL_AD_DECRYPT_ERROR;
2275 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2276 			goto f_err;
2277 		}
2278 		if (i == 0) {
2279 			al = SSL_AD_DECRYPT_ERROR;
2280 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2281 			goto f_err;
2282 		}
2283 	} else
2284 	if (pkey->type == EVP_PKEY_DSA) {
2285 		j = DSA_verify(pkey->save_type,
2286 		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2287 		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2288 		if (j <= 0) {
2289 			/* bad signature */
2290 			al = SSL_AD_DECRYPT_ERROR;
2291 			SSLerror(s, SSL_R_BAD_DSA_SIGNATURE);
2292 			goto f_err;
2293 		}
2294 	} else
2295 	if (pkey->type == EVP_PKEY_EC) {
2296 		j = ECDSA_verify(pkey->save_type,
2297 		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2298 		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2299 		if (j <= 0) {
2300 			/* bad signature */
2301 			al = SSL_AD_DECRYPT_ERROR;
2302 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2303 			goto f_err;
2304 		}
2305 	} else
2306 #ifndef OPENSSL_NO_GOST
2307 	if (pkey->type == NID_id_GostR3410_94 ||
2308 	    pkey->type == NID_id_GostR3410_2001) {
2309 		long hdatalen = 0;
2310 		void *hdata;
2311 		unsigned char signature[128];
2312 		unsigned int siglen = sizeof(signature);
2313 		int nid;
2314 		EVP_PKEY_CTX *pctx;
2315 
2316 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2317 		if (hdatalen <= 0) {
2318 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2319 			al = SSL_AD_INTERNAL_ERROR;
2320 			goto f_err;
2321 		}
2322 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2323 				!(md = EVP_get_digestbynid(nid))) {
2324 			SSLerror(s, ERR_R_EVP_LIB);
2325 			al = SSL_AD_INTERNAL_ERROR;
2326 			goto f_err;
2327 		}
2328 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2329 		if (!pctx) {
2330 			SSLerror(s, ERR_R_EVP_LIB);
2331 			al = SSL_AD_INTERNAL_ERROR;
2332 			goto f_err;
2333 		}
2334 		if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2335 		    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2336 		    !EVP_DigestFinal(&mctx, signature, &siglen) ||
2337 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2338 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2339 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2340 				       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2341 				       GOST_SIG_FORMAT_RS_LE,
2342 				       NULL) <= 0)) {
2343 			SSLerror(s, ERR_R_EVP_LIB);
2344 			al = SSL_AD_INTERNAL_ERROR;
2345 			EVP_PKEY_CTX_free(pctx);
2346 			goto f_err;
2347 		}
2348 
2349 		if (EVP_PKEY_verify(pctx, p, i, signature, siglen) <= 0) {
2350 			al = SSL_AD_DECRYPT_ERROR;
2351 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2352 			EVP_PKEY_CTX_free(pctx);
2353 			goto f_err;
2354 		}
2355 
2356 		EVP_PKEY_CTX_free(pctx);
2357 	} else
2358 #endif
2359 	{
2360 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2361 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2362 		goto f_err;
2363 	}
2364 
2365 
2366 	ret = 1;
2367 	if (0) {
2368 truncated:
2369 		al = SSL_AD_DECODE_ERROR;
2370 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2371 f_err:
2372 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2373 	}
2374 end:
2375 	if (S3I(s)->handshake_buffer) {
2376 		BIO_free(S3I(s)->handshake_buffer);
2377 		S3I(s)->handshake_buffer = NULL;
2378 		s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2379 	}
2380 	EVP_MD_CTX_cleanup(&mctx);
2381 	EVP_PKEY_free(pkey);
2382 	return (ret);
2383 }
2384 
2385 int
2386 ssl3_get_client_certificate(SSL *s)
2387 {
2388 	CBS cbs, client_certs;
2389 	int i, ok, al, ret = -1;
2390 	X509 *x = NULL;
2391 	long n;
2392 	const unsigned char *q;
2393 	STACK_OF(X509) *sk = NULL;
2394 
2395 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2396 	    -1, s->internal->max_cert_list, &ok);
2397 
2398 	if (!ok)
2399 		return ((int)n);
2400 
2401 	if (S3I(s)->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2402 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2403 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2404 		    	SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2405 			al = SSL_AD_HANDSHAKE_FAILURE;
2406 			goto f_err;
2407 		}
2408 		/*
2409 		 * If tls asked for a client cert,
2410 		 * the client must return a 0 list.
2411 		 */
2412 		if (S3I(s)->tmp.cert_request) {
2413 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2414 			    );
2415 			al = SSL_AD_UNEXPECTED_MESSAGE;
2416 			goto f_err;
2417 		}
2418 		S3I(s)->tmp.reuse_message = 1;
2419 		return (1);
2420 	}
2421 
2422 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
2423 		al = SSL_AD_UNEXPECTED_MESSAGE;
2424 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2425 		goto f_err;
2426 	}
2427 
2428 	if (n < 0)
2429 		goto truncated;
2430 
2431 	CBS_init(&cbs, s->internal->init_msg, n);
2432 
2433 	if ((sk = sk_X509_new_null()) == NULL) {
2434 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2435 		goto err;
2436 	}
2437 
2438 	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2439 	    CBS_len(&cbs) != 0)
2440 		goto truncated;
2441 
2442 	while (CBS_len(&client_certs) > 0) {
2443 		CBS cert;
2444 
2445 		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2446 			al = SSL_AD_DECODE_ERROR;
2447 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2448 			goto f_err;
2449 		}
2450 
2451 		q = CBS_data(&cert);
2452 		x = d2i_X509(NULL, &q, CBS_len(&cert));
2453 		if (x == NULL) {
2454 			SSLerror(s, ERR_R_ASN1_LIB);
2455 			goto err;
2456 		}
2457 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2458 			al = SSL_AD_DECODE_ERROR;
2459 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2460 			goto f_err;
2461 		}
2462 		if (!sk_X509_push(sk, x)) {
2463 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2464 			goto err;
2465 		}
2466 		x = NULL;
2467 	}
2468 
2469 	if (sk_X509_num(sk) <= 0) {
2470 		/*
2471 		 * TLS does not mind 0 certs returned.
2472 		 * Fail for TLS only if we required a certificate.
2473 		 */
2474 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2475 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2476 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2477 			al = SSL_AD_HANDSHAKE_FAILURE;
2478 			goto f_err;
2479 		}
2480 		/* No client certificate so digest cached records */
2481 		if (S3I(s)->handshake_buffer && !tls1_digest_cached_records(s)) {
2482 			al = SSL_AD_INTERNAL_ERROR;
2483 			goto f_err;
2484 		}
2485 	} else {
2486 		i = ssl_verify_cert_chain(s, sk);
2487 		if (i <= 0) {
2488 			al = ssl_verify_alarm_type(s->verify_result);
2489 			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2490 			goto f_err;
2491 		}
2492 	}
2493 
2494 	X509_free(s->session->peer);
2495 	s->session->peer = sk_X509_shift(sk);
2496 	s->session->verify_result = s->verify_result;
2497 
2498 	/*
2499 	 * With the current implementation, sess_cert will always be NULL
2500 	 * when we arrive here
2501 	 */
2502 	if (SSI(s)->sess_cert == NULL) {
2503 		SSI(s)->sess_cert = ssl_sess_cert_new();
2504 		if (SSI(s)->sess_cert == NULL) {
2505 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2506 			goto err;
2507 		}
2508 	}
2509 	sk_X509_pop_free(SSI(s)->sess_cert->cert_chain, X509_free);
2510 	SSI(s)->sess_cert->cert_chain = sk;
2511 
2512 	/*
2513 	 * Inconsistency alert: cert_chain does *not* include the
2514 	 * peer's own certificate, while we do include it in s3_clnt.c
2515 	 */
2516 
2517 	sk = NULL;
2518 
2519 	ret = 1;
2520 	if (0) {
2521 truncated:
2522 		al = SSL_AD_DECODE_ERROR;
2523 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2524 f_err:
2525 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2526 	}
2527 err:
2528 	X509_free(x);
2529 	sk_X509_pop_free(sk, X509_free);
2530 
2531 	return (ret);
2532 }
2533 
2534 int
2535 ssl3_send_server_certificate(SSL *s)
2536 {
2537 	CBB cbb, server_cert;
2538 	X509 *x;
2539 
2540 	/*
2541 	 * Server Certificate - RFC 5246, section 7.4.2.
2542 	 */
2543 
2544 	memset(&cbb, 0, sizeof(cbb));
2545 
2546 	if (s->internal->state == SSL3_ST_SW_CERT_A) {
2547 		if ((x = ssl_get_server_send_cert(s)) == NULL) {
2548 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2549 			return (0);
2550 		}
2551 
2552 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &server_cert,
2553 		    SSL3_MT_CERTIFICATE))
2554 			goto err;
2555 		if (!ssl3_output_cert_chain(s, &server_cert, x))
2556 			goto err;
2557 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2558 			goto err;
2559 
2560 		s->internal->state = SSL3_ST_SW_CERT_B;
2561 	}
2562 
2563 	/* SSL3_ST_SW_CERT_B */
2564 	return (ssl3_handshake_write(s));
2565 
2566  err:
2567 	CBB_cleanup(&cbb);
2568 
2569 	return (0);
2570 }
2571 
2572 /* send a new session ticket (not necessarily for a new session) */
2573 int
2574 ssl3_send_newsession_ticket(SSL *s)
2575 {
2576 	unsigned char *d, *p, *macstart;
2577 	unsigned char *senc = NULL;
2578 	const unsigned char *const_p;
2579 	int len, slen_full, slen;
2580 	SSL_SESSION *sess;
2581 	unsigned int hlen;
2582 	EVP_CIPHER_CTX ctx;
2583 	HMAC_CTX hctx;
2584 	SSL_CTX *tctx = s->initial_ctx;
2585 	unsigned char iv[EVP_MAX_IV_LENGTH];
2586 	unsigned char key_name[16];
2587 
2588 	if (s->internal->state == SSL3_ST_SW_SESSION_TICKET_A) {
2589 		/* get session encoding length */
2590 		slen_full = i2d_SSL_SESSION(s->session, NULL);
2591 		/*
2592 		 * Some length values are 16 bits, so forget it if session is
2593  		 * too long
2594  		 */
2595 		if (slen_full > 0xFF00)
2596 			goto err;
2597 		senc = malloc(slen_full);
2598 		if (!senc)
2599 			goto err;
2600 		p = senc;
2601 		i2d_SSL_SESSION(s->session, &p);
2602 
2603 		/*
2604 		 * Create a fresh copy (not shared with other threads) to
2605 		 * clean up
2606 		 */
2607 		const_p = senc;
2608 		sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2609 		if (sess == NULL)
2610 			goto err;
2611 
2612 		/* ID is irrelevant for the ticket */
2613 		sess->session_id_length = 0;
2614 
2615 		slen = i2d_SSL_SESSION(sess, NULL);
2616 		if (slen > slen_full) {
2617 			/* shouldn't ever happen */
2618 			goto err;
2619 		}
2620 		p = senc;
2621 		i2d_SSL_SESSION(sess, &p);
2622 		SSL_SESSION_free(sess);
2623 
2624 		/*
2625 		 * Grow buffer if need be: the length calculation is as
2626  		 * follows 1 (size of message name) + 3 (message length
2627  		 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2628  		 * 16 (key name) + max_iv_len (iv length) +
2629  		 * session_length + max_enc_block_size (max encrypted session
2630  		 * length) + max_md_size (HMAC).
2631  		 */
2632 		if (!BUF_MEM_grow(s->internal->init_buf, ssl3_handshake_msg_hdr_len(s) +
2633 		    22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2634 		    EVP_MAX_MD_SIZE + slen))
2635 			goto err;
2636 
2637 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_NEWSESSION_TICKET);
2638 
2639 		EVP_CIPHER_CTX_init(&ctx);
2640 		HMAC_CTX_init(&hctx);
2641 
2642 		/*
2643 		 * Initialize HMAC and cipher contexts. If callback present
2644 		 * it does all the work otherwise use generated values
2645 		 * from parent ctx.
2646 		 */
2647 		if (tctx->internal->tlsext_ticket_key_cb) {
2648 			if (tctx->internal->tlsext_ticket_key_cb(s,
2649 			    key_name, iv, &ctx, &hctx, 1) < 0) {
2650 				EVP_CIPHER_CTX_cleanup(&ctx);
2651 				goto err;
2652 			}
2653 		} else {
2654 			arc4random_buf(iv, 16);
2655 			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2656 			    tctx->internal->tlsext_tick_aes_key, iv);
2657 			HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
2658 			    16, tlsext_tick_md(), NULL);
2659 			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2660 		}
2661 
2662 		/*
2663 		 * Ticket lifetime hint (advisory only):
2664 		 * We leave this unspecified for resumed session
2665 		 * (for simplicity), and guess that tickets for new
2666 		 * sessions will live as long as their sessions.
2667 		 */
2668 		l2n(s->internal->hit ? 0 : s->session->timeout, p);
2669 
2670 		/* Skip ticket length for now */
2671 		p += 2;
2672 		/* Output key name */
2673 		macstart = p;
2674 		memcpy(p, key_name, 16);
2675 		p += 16;
2676 		/* output IV */
2677 		memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2678 		p += EVP_CIPHER_CTX_iv_length(&ctx);
2679 		/* Encrypt session data */
2680 		EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2681 		p += len;
2682 		EVP_EncryptFinal_ex(&ctx, p, &len);
2683 		p += len;
2684 		EVP_CIPHER_CTX_cleanup(&ctx);
2685 
2686 		HMAC_Update(&hctx, macstart, p - macstart);
2687 		HMAC_Final(&hctx, p, &hlen);
2688 		HMAC_CTX_cleanup(&hctx);
2689 		p += hlen;
2690 
2691 		/* Now write out lengths: p points to end of data written */
2692 		/* Total length */
2693 		len = p - d;
2694 
2695 		/* Skip ticket lifetime hint. */
2696 		p = d + 4;
2697 		s2n(len - 6, p); /* Message length */
2698 
2699 		ssl3_handshake_msg_finish(s, len);
2700 
2701 		s->internal->state = SSL3_ST_SW_SESSION_TICKET_B;
2702 
2703 		explicit_bzero(senc, slen_full);
2704 		free(senc);
2705 	}
2706 
2707 	/* SSL3_ST_SW_SESSION_TICKET_B */
2708 	return (ssl3_handshake_write(s));
2709 
2710  err:
2711 	if (senc != NULL)
2712 		explicit_bzero(senc, slen_full);
2713 	free(senc);
2714 
2715 	return (-1);
2716 }
2717 
2718 int
2719 ssl3_send_cert_status(SSL *s)
2720 {
2721 	unsigned char *p;
2722 
2723 	if (s->internal->state == SSL3_ST_SW_CERT_STATUS_A) {
2724 		/*
2725 		 * Grow buffer if need be: the length calculation is as
2726  		 * follows 1 (message type) + 3 (message length) +
2727  		 * 1 (ocsp response type) + 3 (ocsp response length)
2728  		 * + (ocsp response)
2729  		 */
2730 		if (!BUF_MEM_grow(s->internal->init_buf, SSL3_HM_HEADER_LENGTH + 4 +
2731 		    s->internal->tlsext_ocsp_resplen))
2732 			return (-1);
2733 
2734 		p = ssl3_handshake_msg_start(s, SSL3_MT_CERTIFICATE_STATUS);
2735 
2736 		*(p++) = s->tlsext_status_type;
2737 		l2n3(s->internal->tlsext_ocsp_resplen, p);
2738 		memcpy(p, s->internal->tlsext_ocsp_resp, s->internal->tlsext_ocsp_resplen);
2739 
2740 		ssl3_handshake_msg_finish(s, s->internal->tlsext_ocsp_resplen + 4);
2741 
2742 		s->internal->state = SSL3_ST_SW_CERT_STATUS_B;
2743 	}
2744 
2745 	/* SSL3_ST_SW_CERT_STATUS_B */
2746 	return (ssl3_handshake_write(s));
2747 }
2748 
2749 /*
2750  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
2751  * It sets the next_proto member in s if found
2752  */
2753 int
2754 ssl3_get_next_proto(SSL *s)
2755 {
2756 	CBS cbs, proto, padding;
2757 	int ok;
2758 	long n;
2759 	size_t len;
2760 
2761 	/*
2762 	 * Clients cannot send a NextProtocol message if we didn't see the
2763 	 * extension in their ClientHello
2764 	 */
2765 	if (!S3I(s)->next_proto_neg_seen) {
2766 		SSLerror(s, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2767 		return (-1);
2768 	}
2769 
2770 	/* 514 maxlen is enough for the payload format below */
2771 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A,
2772 	    SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO, 514, &ok);
2773 	if (!ok)
2774 		return ((int)n);
2775 
2776 	/*
2777 	 * s->internal->state doesn't reflect whether ChangeCipherSpec has been received
2778 	 * in this handshake, but S3I(s)->change_cipher_spec does (will be reset
2779 	 * by ssl3_get_finished).
2780 	 */
2781 	if (!S3I(s)->change_cipher_spec) {
2782 		SSLerror(s, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2783 		return (-1);
2784 	}
2785 
2786 	if (n < 2)
2787 		return (0);
2788 	/* The body must be > 1 bytes long */
2789 
2790 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
2791 
2792 	/*
2793 	 * The payload looks like:
2794 	 *   uint8 proto_len;
2795 	 *   uint8 proto[proto_len];
2796 	 *   uint8 padding_len;
2797 	 *   uint8 padding[padding_len];
2798 	 */
2799 	if (!CBS_get_u8_length_prefixed(&cbs, &proto) ||
2800 	    !CBS_get_u8_length_prefixed(&cbs, &padding) ||
2801 	    CBS_len(&cbs) != 0)
2802 		return 0;
2803 
2804 	/*
2805 	 * XXX We should not NULL it, but this matches old behavior of not
2806 	 * freeing before malloc.
2807 	 */
2808 	s->internal->next_proto_negotiated = NULL;
2809 	s->internal->next_proto_negotiated_len = 0;
2810 
2811 	if (!CBS_stow(&proto, &s->internal->next_proto_negotiated, &len)) {
2812 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2813 		return (0);
2814 	}
2815 	s->internal->next_proto_negotiated_len = (uint8_t)len;
2816 
2817 	return (1);
2818 }
2819