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