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