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