xref: /openbsd/lib/libssl/ssl_srvr.c (revision 510d2225)
1 /* $OpenBSD: ssl_srvr.c,v 1.157 2023/11/18 10:51:09 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->debug) {
744 				if ((ret = BIO_flush(s->wbio)) <= 0)
745 					goto end;
746 			}
747 
748 
749 			if (s->s3->hs.state != state) {
750 				new_state = s->s3->hs.state;
751 				s->s3->hs.state = state;
752 				ssl_info_callback(s, SSL_CB_ACCEPT_LOOP, 1);
753 				s->s3->hs.state = new_state;
754 			}
755 		}
756 		skip = 0;
757 	}
758  end:
759 	/* BIO_flush(s->wbio); */
760 	s->in_handshake--;
761 	ssl_info_callback(s, SSL_CB_ACCEPT_EXIT, ret);
762 
763 	return (ret);
764 }
765 
766 static int
767 ssl3_send_hello_request(SSL *s)
768 {
769 	CBB cbb, hello;
770 
771 	memset(&cbb, 0, sizeof(cbb));
772 
773 	if (s->s3->hs.state == SSL3_ST_SW_HELLO_REQ_A) {
774 		if (!ssl3_handshake_msg_start(s, &cbb, &hello,
775 		    SSL3_MT_HELLO_REQUEST))
776 			goto err;
777 		if (!ssl3_handshake_msg_finish(s, &cbb))
778 			goto err;
779 
780 		s->s3->hs.state = SSL3_ST_SW_HELLO_REQ_B;
781 	}
782 
783 	/* SSL3_ST_SW_HELLO_REQ_B */
784 	return (ssl3_handshake_write(s));
785 
786  err:
787 	CBB_cleanup(&cbb);
788 
789 	return (-1);
790 }
791 
792 static int
793 ssl3_get_client_hello(SSL *s)
794 {
795 	CBS cbs, client_random, session_id, cookie, cipher_suites;
796 	CBS compression_methods;
797 	uint16_t client_version;
798 	uint8_t comp_method;
799 	int comp_null;
800 	int i, j, al, ret, cookie_valid = 0;
801 	unsigned long id;
802 	SSL_CIPHER *c;
803 	STACK_OF(SSL_CIPHER) *ciphers = NULL;
804 	unsigned long alg_k;
805 	const SSL_METHOD *method;
806 	uint16_t shared_version;
807 
808 	/*
809 	 * We do this so that we will respond with our native type.
810 	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
811 	 * This down switching should be handled by a different method.
812 	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
813 	 * TLSv1.
814 	 */
815 	if (s->s3->hs.state == SSL3_ST_SR_CLNT_HELLO_A)
816 		s->s3->hs.state = SSL3_ST_SR_CLNT_HELLO_B;
817 
818 	s->first_packet = 1;
819 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
820 	    SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
821 	    SSL3_RT_MAX_PLAIN_LENGTH)) <= 0)
822 		return ret;
823 	s->first_packet = 0;
824 
825 	ret = -1;
826 
827 	if (s->init_num < 0)
828 		goto err;
829 
830 	CBS_init(&cbs, s->init_msg, s->init_num);
831 
832 	/* Parse client hello up until the extensions (if any). */
833 	if (!CBS_get_u16(&cbs, &client_version))
834 		goto decode_err;
835 	if (!CBS_get_bytes(&cbs, &client_random, SSL3_RANDOM_SIZE))
836 		goto decode_err;
837 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
838 		goto decode_err;
839 	if (CBS_len(&session_id) > SSL3_SESSION_ID_SIZE) {
840 		al = SSL_AD_ILLEGAL_PARAMETER;
841 		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
842 		goto fatal_err;
843 	}
844 	if (SSL_is_dtls(s)) {
845 		if (!CBS_get_u8_length_prefixed(&cbs, &cookie))
846 			goto decode_err;
847 	}
848 	if (!CBS_get_u16_length_prefixed(&cbs, &cipher_suites))
849 		goto decode_err;
850 	if (!CBS_get_u8_length_prefixed(&cbs, &compression_methods))
851 		goto decode_err;
852 
853 	/*
854 	 * Use version from inside client hello, not from record header.
855 	 * (may differ: see RFC 2246, Appendix E, second paragraph)
856 	 */
857 	if (!ssl_max_shared_version(s, client_version, &shared_version)) {
858 		if ((client_version >> 8) == SSL3_VERSION_MAJOR &&
859 		    !tls12_record_layer_write_protected(s->rl)) {
860 			/*
861 			 * Similar to ssl3_get_record, send alert using remote
862 			 * version number.
863 			 */
864 			s->version = client_version;
865 		}
866 		SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
867 		al = SSL_AD_PROTOCOL_VERSION;
868 		goto fatal_err;
869 	}
870 	s->s3->hs.peer_legacy_version = client_version;
871 	s->version = shared_version;
872 
873 	s->s3->hs.negotiated_tls_version = ssl_tls_version(shared_version);
874 	if (s->s3->hs.negotiated_tls_version == 0) {
875 		SSLerror(s, ERR_R_INTERNAL_ERROR);
876 		goto err;
877 	}
878 
879 	if ((method = ssl_get_method(shared_version)) == NULL) {
880 		SSLerror(s, ERR_R_INTERNAL_ERROR);
881 		goto err;
882 	}
883 	s->method = method;
884 
885 	/*
886 	 * If we require cookies (DTLS) and this ClientHello does not contain
887 	 * one, just return since we do not want to allocate any memory yet.
888 	 * So check cookie length...
889 	 */
890 	if (SSL_is_dtls(s)) {
891 		if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
892 			if (CBS_len(&cookie) == 0)
893 				return (1);
894 		}
895 	}
896 
897 	if (!CBS_write_bytes(&client_random, s->s3->client_random,
898 	    sizeof(s->s3->client_random), NULL))
899 		goto err;
900 
901 	s->hit = 0;
902 
903 	/*
904 	 * Versions before 0.9.7 always allow clients to resume sessions in
905 	 * renegotiation. 0.9.7 and later allow this by default, but optionally
906 	 * ignore resumption requests with flag
907 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
908 	 * rather than a change to default behavior so that applications
909 	 * relying on this for security won't even compile against older
910 	 * library versions).
911 	 *
912 	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
913 	 * to request renegotiation but not a new session (s->new_session
914 	 * remains unset): for servers, this essentially just means that the
915 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
916 	 * ignored.
917 	 */
918 	if ((s->new_session && (s->options &
919 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
920 		if (!ssl_get_new_session(s, 1))
921 			goto err;
922 	} else {
923 		CBS ext_block;
924 
925 		CBS_dup(&cbs, &ext_block);
926 
927 		i = ssl_get_prev_session(s, &session_id, &ext_block, &al);
928 		if (i == 1) { /* previous session */
929 			s->hit = 1;
930 		} else if (i == -1)
931 			goto fatal_err;
932 		else {
933 			/* i == 0 */
934 			if (!ssl_get_new_session(s, 1))
935 				goto err;
936 		}
937 	}
938 
939 	if (SSL_is_dtls(s)) {
940 		/*
941 		 * The ClientHello may contain a cookie even if the HelloVerify
942 		 * message has not been sent - make sure that it does not cause
943 		 * an overflow.
944 		 */
945 		if (CBS_len(&cookie) > sizeof(s->d1->rcvd_cookie)) {
946 			al = SSL_AD_DECODE_ERROR;
947 			SSLerror(s, SSL_R_COOKIE_MISMATCH);
948 			goto fatal_err;
949 		}
950 
951 		/* Verify the cookie if appropriate option is set. */
952 		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
953 		    CBS_len(&cookie) > 0) {
954 			size_t cookie_len;
955 
956 			/* XXX - rcvd_cookie seems to only be used here... */
957 			if (!CBS_write_bytes(&cookie, s->d1->rcvd_cookie,
958 			    sizeof(s->d1->rcvd_cookie), &cookie_len))
959 				goto err;
960 
961 			if (s->ctx->app_verify_cookie_cb != NULL) {
962 				if (s->ctx->app_verify_cookie_cb(s,
963 				    s->d1->rcvd_cookie, cookie_len) == 0) {
964 					al = SSL_AD_HANDSHAKE_FAILURE;
965 					SSLerror(s, SSL_R_COOKIE_MISMATCH);
966 					goto fatal_err;
967 				}
968 				/* else cookie verification succeeded */
969 			/* XXX - can d1->cookie_len > sizeof(rcvd_cookie) ? */
970 			} else if (timingsafe_memcmp(s->d1->rcvd_cookie,
971 			    s->d1->cookie, s->d1->cookie_len) != 0) {
972 				/* default verification */
973 				al = SSL_AD_HANDSHAKE_FAILURE;
974 				SSLerror(s, SSL_R_COOKIE_MISMATCH);
975 				goto fatal_err;
976 			}
977 			cookie_valid = 1;
978 		}
979 	}
980 
981 	/* XXX - This logic seems wrong... */
982 	if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
983 		/* we need a cipher if we are not resuming a session */
984 		al = SSL_AD_ILLEGAL_PARAMETER;
985 		SSLerror(s, SSL_R_NO_CIPHERS_SPECIFIED);
986 		goto fatal_err;
987 	}
988 
989 	if (CBS_len(&cipher_suites) > 0) {
990 		if ((ciphers = ssl_bytes_to_cipher_list(s,
991 		    &cipher_suites)) == NULL)
992 			goto err;
993 	}
994 
995 	/* If it is a hit, check that the cipher is in the list */
996 	/* XXX - CBS_len(&cipher_suites) will always be zero here... */
997 	if (s->hit && CBS_len(&cipher_suites) > 0) {
998 		j = 0;
999 		id = s->session->cipher->id;
1000 
1001 		for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1002 			c = sk_SSL_CIPHER_value(ciphers, i);
1003 			if (c->id == id) {
1004 				j = 1;
1005 				break;
1006 			}
1007 		}
1008 		if (j == 0) {
1009 			/*
1010 			 * We need to have the cipher in the cipher
1011 			 * list if we are asked to reuse it
1012 			 */
1013 			al = SSL_AD_ILLEGAL_PARAMETER;
1014 			SSLerror(s, SSL_R_REQUIRED_CIPHER_MISSING);
1015 			goto fatal_err;
1016 		}
1017 	}
1018 
1019 	comp_null = 0;
1020 	while (CBS_len(&compression_methods) > 0) {
1021 		if (!CBS_get_u8(&compression_methods, &comp_method))
1022 			goto decode_err;
1023 		if (comp_method == 0)
1024 			comp_null = 1;
1025 	}
1026 	if (comp_null == 0) {
1027 		al = SSL_AD_DECODE_ERROR;
1028 		SSLerror(s, SSL_R_NO_COMPRESSION_SPECIFIED);
1029 		goto fatal_err;
1030 	}
1031 
1032 	if (!tlsext_server_parse(s, SSL_TLSEXT_MSG_CH, &cbs, &al)) {
1033 		SSLerror(s, SSL_R_PARSE_TLSEXT);
1034 		goto fatal_err;
1035 	}
1036 
1037 	if (CBS_len(&cbs) != 0)
1038 		goto decode_err;
1039 
1040 	if (!s->s3->renegotiate_seen && s->renegotiate) {
1041 		al = SSL_AD_HANDSHAKE_FAILURE;
1042 		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1043 		goto fatal_err;
1044 	}
1045 
1046 	if (ssl_check_clienthello_tlsext_early(s) <= 0) {
1047 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1048 		goto err;
1049 	}
1050 
1051 	/*
1052 	 * Check if we want to use external pre-shared secret for this
1053 	 * handshake for not reused session only. We need to generate
1054 	 * server_random before calling tls_session_secret_cb in order to allow
1055 	 * SessionTicket processing to use it in key derivation.
1056 	 */
1057 	arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
1058 
1059 	if (s->s3->hs.our_max_tls_version >= TLS1_2_VERSION &&
1060 	    s->s3->hs.negotiated_tls_version < s->s3->hs.our_max_tls_version) {
1061 		/*
1062 		 * RFC 8446 section 4.1.3. If we are downgrading from TLS 1.3
1063 		 * we must set the last 8 bytes of the server random to magical
1064 		 * values to indicate we meant to downgrade.  For TLS 1.2 it is
1065 		 * recommended that we do the same.
1066 		 */
1067 		size_t index = SSL3_RANDOM_SIZE - sizeof(tls13_downgrade_12);
1068 		uint8_t *magic = &s->s3->server_random[index];
1069 		if (s->s3->hs.negotiated_tls_version == TLS1_2_VERSION) {
1070 			/* Indicate we chose to downgrade to 1.2. */
1071 			memcpy(magic, tls13_downgrade_12,
1072 			    sizeof(tls13_downgrade_12));
1073 		} else {
1074 			/* Indicate we chose to downgrade to 1.1 or lower */
1075 			memcpy(magic, tls13_downgrade_11,
1076 			    sizeof(tls13_downgrade_11));
1077 		}
1078 	}
1079 
1080 	if (!s->hit && s->tls_session_secret_cb != NULL) {
1081 		SSL_CIPHER *pref_cipher = NULL;
1082 		int master_key_length = sizeof(s->session->master_key);
1083 
1084 		if (!s->tls_session_secret_cb(s,
1085 		    s->session->master_key, &master_key_length, ciphers,
1086 		    &pref_cipher, s->tls_session_secret_cb_arg)) {
1087 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1088 			goto err;
1089 		}
1090 		if (master_key_length <= 0) {
1091 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1092 			goto err;
1093 		}
1094 		s->session->master_key_length = master_key_length;
1095 
1096 		s->hit = 1;
1097 		s->session->verify_result = X509_V_OK;
1098 
1099 		sk_SSL_CIPHER_free(s->session->ciphers);
1100 		s->session->ciphers = ciphers;
1101 		ciphers = NULL;
1102 
1103 		/* Check if some cipher was preferred by the callback. */
1104 		if (pref_cipher == NULL)
1105 			pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1106 			    SSL_get_ciphers(s));
1107 		if (pref_cipher == NULL) {
1108 			al = SSL_AD_HANDSHAKE_FAILURE;
1109 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1110 			goto fatal_err;
1111 		}
1112 		s->session->cipher = pref_cipher;
1113 
1114 		sk_SSL_CIPHER_free(s->cipher_list);
1115 		s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1116 	}
1117 
1118 	/*
1119 	 * Given s->session->ciphers and SSL_get_ciphers, we must
1120 	 * pick a cipher
1121 	 */
1122 
1123 	if (!s->hit) {
1124 		if (ciphers == NULL) {
1125 			al = SSL_AD_ILLEGAL_PARAMETER;
1126 			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
1127 			goto fatal_err;
1128 		}
1129 		sk_SSL_CIPHER_free(s->session->ciphers);
1130 		s->session->ciphers = ciphers;
1131 		ciphers = NULL;
1132 
1133 		if ((c = ssl3_choose_cipher(s, s->session->ciphers,
1134 		    SSL_get_ciphers(s))) == NULL) {
1135 			al = SSL_AD_HANDSHAKE_FAILURE;
1136 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1137 			goto fatal_err;
1138 		}
1139 		s->s3->hs.cipher = c;
1140 	} else {
1141 		s->s3->hs.cipher = s->session->cipher;
1142 	}
1143 
1144 	if (!tls1_transcript_hash_init(s))
1145 		goto err;
1146 
1147 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1148 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1149 	    !(s->verify_mode & SSL_VERIFY_PEER))
1150 		tls1_transcript_free(s);
1151 
1152 	/*
1153 	 * We now have the following setup.
1154 	 * client_random
1155 	 * cipher_list		- our preferred list of ciphers
1156 	 * ciphers		- the clients preferred list of ciphers
1157 	 * compression		- basically ignored right now
1158 	 * ssl version is set	- sslv3
1159 	 * s->session		- The ssl session has been setup.
1160 	 * s->hit		- session reuse flag
1161 	 * s->hs.cipher	- the new cipher to use.
1162 	 */
1163 
1164 	/* Handles TLS extensions that we couldn't check earlier */
1165 	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1166 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1167 		goto err;
1168 	}
1169 
1170 	ret = cookie_valid ? 2 : 1;
1171 
1172 	if (0) {
1173  decode_err:
1174 		al = SSL_AD_DECODE_ERROR;
1175 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1176  fatal_err:
1177 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1178 	}
1179  err:
1180 	sk_SSL_CIPHER_free(ciphers);
1181 
1182 	return (ret);
1183 }
1184 
1185 static int
1186 ssl3_send_dtls_hello_verify_request(SSL *s)
1187 {
1188 	CBB cbb, verify, cookie;
1189 
1190 	memset(&cbb, 0, sizeof(cbb));
1191 
1192 	if (s->s3->hs.state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) {
1193 		if (s->ctx->app_gen_cookie_cb == NULL ||
1194 		    s->ctx->app_gen_cookie_cb(s, s->d1->cookie,
1195 			&(s->d1->cookie_len)) == 0) {
1196 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1197 			return 0;
1198 		}
1199 
1200 		/*
1201 		 * Per RFC 6347 section 4.2.1, the HelloVerifyRequest should
1202 		 * always contain DTLSv1.0 regardless of the version that is
1203 		 * going to be negotiated.
1204 		 */
1205 		if (!ssl3_handshake_msg_start(s, &cbb, &verify,
1206 		    DTLS1_MT_HELLO_VERIFY_REQUEST))
1207 			goto err;
1208 		if (!CBB_add_u16(&verify, DTLS1_VERSION))
1209 			goto err;
1210 		if (!CBB_add_u8_length_prefixed(&verify, &cookie))
1211 			goto err;
1212 		if (!CBB_add_bytes(&cookie, s->d1->cookie, s->d1->cookie_len))
1213 			goto err;
1214 		if (!ssl3_handshake_msg_finish(s, &cbb))
1215 			goto err;
1216 
1217 		s->s3->hs.state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B;
1218 	}
1219 
1220 	/* s->s3->hs.state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */
1221 	return (ssl3_handshake_write(s));
1222 
1223  err:
1224 	CBB_cleanup(&cbb);
1225 
1226 	return (-1);
1227 }
1228 
1229 static int
1230 ssl3_send_server_hello(SSL *s)
1231 {
1232 	CBB cbb, server_hello, session_id;
1233 	size_t sl;
1234 
1235 	memset(&cbb, 0, sizeof(cbb));
1236 
1237 	if (s->s3->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
1238 		if (!ssl3_handshake_msg_start(s, &cbb, &server_hello,
1239 		    SSL3_MT_SERVER_HELLO))
1240 			goto err;
1241 
1242 		if (!CBB_add_u16(&server_hello, s->version))
1243 			goto err;
1244 		if (!CBB_add_bytes(&server_hello, s->s3->server_random,
1245 		    sizeof(s->s3->server_random)))
1246 			goto err;
1247 
1248 		/*
1249 		 * There are several cases for the session ID to send
1250 		 * back in the server hello:
1251 		 *
1252 		 * - For session reuse from the session cache,
1253 		 *   we send back the old session ID.
1254 		 * - If stateless session reuse (using a session ticket)
1255 		 *   is successful, we send back the client's "session ID"
1256 		 *   (which doesn't actually identify the session).
1257 		 * - If it is a new session, we send back the new
1258 		 *   session ID.
1259 		 * - However, if we want the new session to be single-use,
1260 		 *   we send back a 0-length session ID.
1261 		 *
1262 		 * s->hit is non-zero in either case of session reuse,
1263 		 * so the following won't overwrite an ID that we're supposed
1264 		 * to send back.
1265 		 */
1266 		if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1267 		    && !s->hit)
1268 			s->session->session_id_length = 0;
1269 
1270 		sl = s->session->session_id_length;
1271 		if (sl > sizeof(s->session->session_id)) {
1272 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1273 			goto err;
1274 		}
1275 		if (!CBB_add_u8_length_prefixed(&server_hello, &session_id))
1276 			goto err;
1277 		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1278 			goto err;
1279 
1280 		/* Cipher suite. */
1281 		if (!CBB_add_u16(&server_hello,
1282 		    ssl3_cipher_get_value(s->s3->hs.cipher)))
1283 			goto err;
1284 
1285 		/* Compression method (null). */
1286 		if (!CBB_add_u8(&server_hello, 0))
1287 			goto err;
1288 
1289 		/* TLS extensions */
1290 		if (!tlsext_server_build(s, SSL_TLSEXT_MSG_SH, &server_hello)) {
1291 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1292 			goto err;
1293 		}
1294 
1295 		if (!ssl3_handshake_msg_finish(s, &cbb))
1296 			goto err;
1297 	}
1298 
1299 	/* SSL3_ST_SW_SRVR_HELLO_B */
1300 	return (ssl3_handshake_write(s));
1301 
1302  err:
1303 	CBB_cleanup(&cbb);
1304 
1305 	return (-1);
1306 }
1307 
1308 static int
1309 ssl3_send_server_done(SSL *s)
1310 {
1311 	CBB cbb, done;
1312 
1313 	memset(&cbb, 0, sizeof(cbb));
1314 
1315 	if (s->s3->hs.state == SSL3_ST_SW_SRVR_DONE_A) {
1316 		if (!ssl3_handshake_msg_start(s, &cbb, &done,
1317 		    SSL3_MT_SERVER_DONE))
1318 			goto err;
1319 		if (!ssl3_handshake_msg_finish(s, &cbb))
1320 			goto err;
1321 
1322 		s->s3->hs.state = SSL3_ST_SW_SRVR_DONE_B;
1323 	}
1324 
1325 	/* SSL3_ST_SW_SRVR_DONE_B */
1326 	return (ssl3_handshake_write(s));
1327 
1328  err:
1329 	CBB_cleanup(&cbb);
1330 
1331 	return (-1);
1332 }
1333 
1334 static int
1335 ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1336 {
1337 	int nid = NID_dhKeyAgreement;
1338 
1339 	tls_key_share_free(s->s3->hs.key_share);
1340 	if ((s->s3->hs.key_share = tls_key_share_new_nid(nid)) == NULL)
1341 		goto err;
1342 
1343 	if (s->cert->dhe_params_auto != 0) {
1344 		size_t key_bits;
1345 
1346 		if ((key_bits = ssl_dhe_params_auto_key_bits(s)) == 0) {
1347 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1348 			ssl3_send_alert(s, SSL3_AL_FATAL,
1349 			    SSL_AD_INTERNAL_ERROR);
1350 			goto err;
1351 		}
1352 		tls_key_share_set_key_bits(s->s3->hs.key_share,
1353 		    key_bits);
1354 	} else {
1355 		DH *dh_params = s->cert->dhe_params;
1356 
1357 		if (dh_params == NULL && s->cert->dhe_params_cb != NULL)
1358 			dh_params = s->cert->dhe_params_cb(s, 0,
1359 			    SSL_C_PKEYLENGTH(s->s3->hs.cipher));
1360 
1361 		if (dh_params == NULL) {
1362 			SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1363 			ssl3_send_alert(s, SSL3_AL_FATAL,
1364 			    SSL_AD_HANDSHAKE_FAILURE);
1365 			goto err;
1366 		}
1367 
1368 		if (!tls_key_share_set_dh_params(s->s3->hs.key_share, dh_params))
1369 			goto err;
1370 	}
1371 
1372 	if (!tls_key_share_generate(s->s3->hs.key_share))
1373 		goto err;
1374 
1375 	if (!tls_key_share_params(s->s3->hs.key_share, cbb))
1376 		goto err;
1377 	if (!tls_key_share_public(s->s3->hs.key_share, cbb))
1378 		goto err;
1379 
1380 	if (!tls_key_share_peer_security(s, s->s3->hs.key_share)) {
1381 		SSLerror(s, SSL_R_DH_KEY_TOO_SMALL);
1382 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1383 		return 0;
1384 	}
1385 
1386 	return 1;
1387 
1388  err:
1389 	return 0;
1390 }
1391 
1392 static int
1393 ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1394 {
1395 	CBB public;
1396 	int nid;
1397 
1398 	if (!tls1_get_supported_group(s, &nid)) {
1399 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1400 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1401 		goto err;
1402 	}
1403 
1404 	tls_key_share_free(s->s3->hs.key_share);
1405 	if ((s->s3->hs.key_share = tls_key_share_new_nid(nid)) == NULL)
1406 		goto err;
1407 
1408 	if (!tls_key_share_generate(s->s3->hs.key_share))
1409 		goto err;
1410 
1411 	/*
1412 	 * ECC key exchange - see RFC 8422, section 5.4.
1413 	 */
1414 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1415 		goto err;
1416 	if (!CBB_add_u16(cbb, tls_key_share_group(s->s3->hs.key_share)))
1417 		goto err;
1418 	if (!CBB_add_u8_length_prefixed(cbb, &public))
1419 		goto err;
1420 	if (!tls_key_share_public(s->s3->hs.key_share, &public))
1421 		goto err;
1422 	if (!CBB_flush(cbb))
1423 		goto err;
1424 
1425 	return 1;
1426 
1427  err:
1428 	return 0;
1429 }
1430 
1431 static int
1432 ssl3_send_server_key_exchange(SSL *s)
1433 {
1434 	CBB cbb, cbb_signature, cbb_signed_params, server_kex;
1435 	CBS params;
1436 	const struct ssl_sigalg *sigalg = NULL;
1437 	unsigned char *signed_params = NULL;
1438 	size_t signed_params_len;
1439 	unsigned char *signature = NULL;
1440 	size_t signature_len = 0;
1441 	const EVP_MD *md = NULL;
1442 	unsigned long type;
1443 	EVP_MD_CTX *md_ctx = NULL;
1444 	EVP_PKEY_CTX *pctx;
1445 	EVP_PKEY *pkey;
1446 	int al;
1447 
1448 	memset(&cbb, 0, sizeof(cbb));
1449 	memset(&cbb_signed_params, 0, sizeof(cbb_signed_params));
1450 
1451 	if ((md_ctx = EVP_MD_CTX_new()) == NULL)
1452 		goto err;
1453 
1454 	if (s->s3->hs.state == SSL3_ST_SW_KEY_EXCH_A) {
1455 
1456 		if (!ssl3_handshake_msg_start(s, &cbb, &server_kex,
1457 		    SSL3_MT_SERVER_KEY_EXCHANGE))
1458 			goto err;
1459 
1460 		if (!CBB_init(&cbb_signed_params, 0))
1461 			goto err;
1462 
1463 		if (!CBB_add_bytes(&cbb_signed_params, s->s3->client_random,
1464 		    SSL3_RANDOM_SIZE)) {
1465 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1466 			goto err;
1467 		}
1468 		if (!CBB_add_bytes(&cbb_signed_params, s->s3->server_random,
1469 		    SSL3_RANDOM_SIZE)) {
1470 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1471 			goto err;
1472 		}
1473 
1474 		type = s->s3->hs.cipher->algorithm_mkey;
1475 		if (type & SSL_kDHE) {
1476 			if (!ssl3_send_server_kex_dhe(s, &cbb_signed_params))
1477 				goto err;
1478 		} else if (type & SSL_kECDHE) {
1479 			if (!ssl3_send_server_kex_ecdhe(s, &cbb_signed_params))
1480 				goto err;
1481 		} else {
1482 			al = SSL_AD_HANDSHAKE_FAILURE;
1483 			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1484 			goto fatal_err;
1485 		}
1486 
1487 		if (!CBB_finish(&cbb_signed_params, &signed_params,
1488 		    &signed_params_len))
1489 			goto err;
1490 
1491 		CBS_init(&params, signed_params, signed_params_len);
1492 		if (!CBS_skip(&params, 2 * SSL3_RANDOM_SIZE))
1493 			goto err;
1494 
1495 		if (!CBB_add_bytes(&server_kex, CBS_data(&params),
1496 		    CBS_len(&params)))
1497 			goto err;
1498 
1499 		/* Add signature unless anonymous. */
1500 		if (!(s->s3->hs.cipher->algorithm_auth & SSL_aNULL)) {
1501 			if ((pkey = ssl_get_sign_pkey(s, s->s3->hs.cipher,
1502 			    &md, &sigalg)) == NULL) {
1503 				al = SSL_AD_DECODE_ERROR;
1504 				goto fatal_err;
1505 			}
1506 			s->s3->hs.our_sigalg = sigalg;
1507 
1508 			/* Send signature algorithm. */
1509 			if (SSL_USE_SIGALGS(s)) {
1510 				if (!CBB_add_u16(&server_kex, sigalg->value)) {
1511 					al = SSL_AD_INTERNAL_ERROR;
1512 					SSLerror(s, ERR_R_INTERNAL_ERROR);
1513 					goto fatal_err;
1514 				}
1515 			}
1516 
1517 			if (!EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey)) {
1518 				SSLerror(s, ERR_R_EVP_LIB);
1519 				goto err;
1520 			}
1521 			if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1522 			    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1523 			    RSA_PKCS1_PSS_PADDING) ||
1524 			    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
1525 				SSLerror(s, ERR_R_EVP_LIB);
1526 				goto err;
1527 			}
1528 			if (!EVP_DigestSign(md_ctx, NULL, &signature_len,
1529 			    signed_params, signed_params_len)) {
1530 				SSLerror(s, ERR_R_EVP_LIB);
1531 				goto err;
1532 			}
1533 			if ((signature = calloc(1, signature_len)) == NULL) {
1534 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1535 				goto err;
1536 			}
1537 			if (!EVP_DigestSign(md_ctx, signature, &signature_len,
1538 			    signed_params, signed_params_len)) {
1539 				SSLerror(s, ERR_R_EVP_LIB);
1540 				goto err;
1541 			}
1542 
1543 			if (!CBB_add_u16_length_prefixed(&server_kex,
1544 			    &cbb_signature))
1545 				goto err;
1546 			if (!CBB_add_bytes(&cbb_signature, signature,
1547 			    signature_len))
1548 				goto err;
1549 		}
1550 
1551 		if (!ssl3_handshake_msg_finish(s, &cbb))
1552 			goto err;
1553 
1554 		s->s3->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1555 	}
1556 
1557 	EVP_MD_CTX_free(md_ctx);
1558 	free(signature);
1559 	free(signed_params);
1560 
1561 	return (ssl3_handshake_write(s));
1562 
1563  fatal_err:
1564 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1565  err:
1566 	CBB_cleanup(&cbb_signed_params);
1567 	CBB_cleanup(&cbb);
1568 	EVP_MD_CTX_free(md_ctx);
1569 	free(signature);
1570 	free(signed_params);
1571 
1572 	return (-1);
1573 }
1574 
1575 static int
1576 ssl3_send_certificate_request(SSL *s)
1577 {
1578 	CBB cbb, cert_request, cert_types, sigalgs, cert_auth, dn;
1579 	STACK_OF(X509_NAME) *sk = NULL;
1580 	X509_NAME *name;
1581 	int i;
1582 
1583 	/*
1584 	 * Certificate Request - RFC 5246 section 7.4.4.
1585 	 */
1586 
1587 	memset(&cbb, 0, sizeof(cbb));
1588 
1589 	if (s->s3->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1590 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_request,
1591 		    SSL3_MT_CERTIFICATE_REQUEST))
1592 			goto err;
1593 
1594 		if (!CBB_add_u8_length_prefixed(&cert_request, &cert_types))
1595 			goto err;
1596 		if (!ssl3_get_req_cert_types(s, &cert_types))
1597 			goto err;
1598 
1599 		if (SSL_USE_SIGALGS(s)) {
1600 			if (!CBB_add_u16_length_prefixed(&cert_request,
1601 			    &sigalgs))
1602 				goto err;
1603 			if (!ssl_sigalgs_build(s->s3->hs.negotiated_tls_version,
1604 			    &sigalgs, SSL_get_security_level(s)))
1605 				goto err;
1606 		}
1607 
1608 		if (!CBB_add_u16_length_prefixed(&cert_request, &cert_auth))
1609 			goto err;
1610 
1611 		sk = SSL_get_client_CA_list(s);
1612 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1613 			unsigned char *name_data;
1614 			size_t name_len;
1615 
1616 			name = sk_X509_NAME_value(sk, i);
1617 			name_len = i2d_X509_NAME(name, NULL);
1618 
1619 			if (!CBB_add_u16_length_prefixed(&cert_auth, &dn))
1620 				goto err;
1621 			if (!CBB_add_space(&dn, &name_data, name_len))
1622 				goto err;
1623 			if (i2d_X509_NAME(name, &name_data) != name_len)
1624 				goto err;
1625 		}
1626 
1627 		if (!ssl3_handshake_msg_finish(s, &cbb))
1628 			goto err;
1629 
1630 		s->s3->hs.state = SSL3_ST_SW_CERT_REQ_B;
1631 	}
1632 
1633 	/* SSL3_ST_SW_CERT_REQ_B */
1634 	return (ssl3_handshake_write(s));
1635 
1636  err:
1637 	CBB_cleanup(&cbb);
1638 
1639 	return (-1);
1640 }
1641 
1642 static int
1643 ssl3_get_client_kex_rsa(SSL *s, CBS *cbs)
1644 {
1645 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1646 	unsigned char *pms = NULL;
1647 	unsigned char *p;
1648 	size_t pms_len = 0;
1649 	EVP_PKEY *pkey = NULL;
1650 	RSA *rsa = NULL;
1651 	CBS enc_pms;
1652 	int decrypt_len;
1653 	int al = -1;
1654 
1655 	arc4random_buf(fakekey, sizeof(fakekey));
1656 
1657 	fakekey[0] = s->s3->hs.peer_legacy_version >> 8;
1658 	fakekey[1] = s->s3->hs.peer_legacy_version & 0xff;
1659 
1660 	pkey = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
1661 	if (pkey == NULL || (rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
1662 		al = SSL_AD_HANDSHAKE_FAILURE;
1663 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1664 		goto fatal_err;
1665 	}
1666 
1667 	pms_len = RSA_size(rsa);
1668 	if (pms_len < SSL_MAX_MASTER_KEY_LENGTH)
1669 		goto err;
1670 	if ((pms = malloc(pms_len)) == NULL)
1671 		goto err;
1672 	p = pms;
1673 
1674 	if (!CBS_get_u16_length_prefixed(cbs, &enc_pms))
1675 		goto decode_err;
1676 	if (CBS_len(cbs) != 0 || CBS_len(&enc_pms) != RSA_size(rsa)) {
1677 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1678 		goto err;
1679 	}
1680 
1681 	decrypt_len = RSA_private_decrypt(CBS_len(&enc_pms), CBS_data(&enc_pms),
1682 	    pms, rsa, RSA_PKCS1_PADDING);
1683 
1684 	ERR_clear_error();
1685 
1686 	if (decrypt_len != SSL_MAX_MASTER_KEY_LENGTH) {
1687 		al = SSL_AD_DECODE_ERROR;
1688 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1689 	}
1690 
1691 	if ((al == -1) && !((pms[0] == (s->s3->hs.peer_legacy_version >> 8)) &&
1692 	    (pms[1] == (s->s3->hs.peer_legacy_version & 0xff)))) {
1693 		/*
1694 		 * The premaster secret must contain the same version number
1695 		 * as the ClientHello to detect version rollback attacks
1696 		 * (strangely, the protocol does not offer such protection for
1697 		 * DH ciphersuites).
1698 		 *
1699 		 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1700 		 * (http://eprint.iacr.org/2003/052/) exploits the version
1701 		 * number check as a "bad version oracle" -- an alert would
1702 		 * reveal that the plaintext corresponding to some ciphertext
1703 		 * made up by the adversary is properly formatted except that
1704 		 * the version number is wrong. To avoid such attacks, we should
1705 		 * treat this just like any other decryption error.
1706 		 */
1707 		al = SSL_AD_DECODE_ERROR;
1708 		/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1709 	}
1710 
1711 	if (al != -1) {
1712 		/*
1713 		 * Some decryption failure -- use random value instead
1714 		 * as countermeasure against Bleichenbacher's attack
1715 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1716 		 * section 7.4.7.1).
1717 		 */
1718 		p = fakekey;
1719 	}
1720 
1721 	if (!tls12_derive_master_secret(s, p, SSL_MAX_MASTER_KEY_LENGTH))
1722 		goto err;
1723 
1724 	freezero(pms, pms_len);
1725 
1726 	return 1;
1727 
1728  decode_err:
1729 	al = SSL_AD_DECODE_ERROR;
1730 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1731  fatal_err:
1732 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1733  err:
1734 	freezero(pms, pms_len);
1735 
1736 	return 0;
1737 }
1738 
1739 static int
1740 ssl3_get_client_kex_dhe(SSL *s, CBS *cbs)
1741 {
1742 	uint8_t *key = NULL;
1743 	size_t key_len = 0;
1744 	int decode_error, invalid_key;
1745 	int ret = 0;
1746 
1747 	if (s->s3->hs.key_share == NULL) {
1748 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1749 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1750 		goto err;
1751 	}
1752 
1753 	if (!tls_key_share_peer_public(s->s3->hs.key_share, cbs,
1754 	    &decode_error, &invalid_key)) {
1755 		if (decode_error) {
1756 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1757 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1758 		}
1759 		goto err;
1760 	}
1761 	if (invalid_key) {
1762 		SSLerror(s, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1763 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1764 		goto err;
1765 	}
1766 
1767 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1768 		goto err;
1769 
1770 	if (!tls12_derive_master_secret(s, key, key_len))
1771 		goto err;
1772 
1773 	ret = 1;
1774 
1775  err:
1776 	freezero(key, key_len);
1777 
1778 	return ret;
1779 }
1780 
1781 static int
1782 ssl3_get_client_kex_ecdhe(SSL *s, CBS *cbs)
1783 {
1784 	uint8_t *key = NULL;
1785 	size_t key_len = 0;
1786 	int decode_error;
1787 	CBS public;
1788 	int ret = 0;
1789 
1790 	if (s->s3->hs.key_share == NULL) {
1791 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1792 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1793 		goto err;
1794 	}
1795 
1796 	if (!CBS_get_u8_length_prefixed(cbs, &public)) {
1797 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1798 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1799 		goto err;
1800 	}
1801 	if (!tls_key_share_peer_public(s->s3->hs.key_share, &public,
1802 	    &decode_error, NULL)) {
1803 		if (decode_error) {
1804 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1805 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1806 		}
1807 		goto err;
1808 	}
1809 
1810 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1811 		goto err;
1812 
1813 	if (!tls12_derive_master_secret(s, key, key_len))
1814 		goto err;
1815 
1816 	ret = 1;
1817 
1818  err:
1819 	freezero(key, key_len);
1820 
1821 	return ret;
1822 }
1823 
1824 static int
1825 ssl3_get_client_kex_gost(SSL *s, CBS *cbs)
1826 {
1827 	unsigned char premaster_secret[32];
1828 	EVP_PKEY_CTX *pkey_ctx = NULL;
1829 	EVP_PKEY *client_pubkey;
1830 	EVP_PKEY *pkey = NULL;
1831 	size_t outlen;
1832 	CBS gostblob;
1833 
1834 	/* Get our certificate private key*/
1835 #ifndef OPENSSL_NO_GOST
1836 	if ((s->s3->hs.cipher->algorithm_auth & SSL_aGOST01) != 0)
1837 		pkey = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
1838 #endif
1839 
1840 	if ((pkey_ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL)
1841 		goto err;
1842 	if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0)
1843 		goto err;
1844 
1845 	/*
1846 	 * If client certificate is present and is of the same type,
1847 	 * maybe use it for key exchange.
1848 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
1849 	 * it is completely valid to use a client certificate for
1850 	 * authorization only.
1851 	 */
1852 	if ((client_pubkey = X509_get0_pubkey(s->session->peer_cert)) != NULL) {
1853 		if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pubkey) <= 0)
1854 			ERR_clear_error();
1855 	}
1856 
1857 	/* Decrypt session key */
1858 	if (!CBS_get_asn1(cbs, &gostblob, CBS_ASN1_SEQUENCE))
1859 		goto decode_err;
1860 	if (CBS_len(cbs) != 0)
1861 		goto decode_err;
1862 	outlen = sizeof(premaster_secret);
1863 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
1864 	    CBS_data(&gostblob), CBS_len(&gostblob)) <= 0) {
1865 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
1866 		goto err;
1867 	}
1868 
1869 	if (!tls12_derive_master_secret(s, premaster_secret,
1870 	    sizeof(premaster_secret)))
1871 		goto err;
1872 
1873 	/* Check if pubkey from client certificate was used */
1874 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY,
1875 	    2, NULL) > 0)
1876 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
1877 
1878 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1879 	EVP_PKEY_CTX_free(pkey_ctx);
1880 
1881 	return 1;
1882 
1883  decode_err:
1884 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1885 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1886  err:
1887 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1888 	EVP_PKEY_CTX_free(pkey_ctx);
1889 
1890 	return 0;
1891 }
1892 
1893 static int
1894 ssl3_get_client_key_exchange(SSL *s)
1895 {
1896 	unsigned long alg_k;
1897 	int al, ret;
1898 	CBS cbs;
1899 
1900 	/* 2048 maxlen is a guess.  How long a key does that permit? */
1901 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
1902 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048)) <= 0)
1903 		return ret;
1904 
1905 	if (s->init_num < 0)
1906 		goto err;
1907 
1908 	CBS_init(&cbs, s->init_msg, s->init_num);
1909 
1910 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1911 
1912 	if (alg_k & SSL_kRSA) {
1913 		if (!ssl3_get_client_kex_rsa(s, &cbs))
1914 			goto err;
1915 	} else if (alg_k & SSL_kDHE) {
1916 		if (!ssl3_get_client_kex_dhe(s, &cbs))
1917 			goto err;
1918 	} else if (alg_k & SSL_kECDHE) {
1919 		if (!ssl3_get_client_kex_ecdhe(s, &cbs))
1920 			goto err;
1921 	} else if (alg_k & SSL_kGOST) {
1922 		if (!ssl3_get_client_kex_gost(s, &cbs))
1923 			goto err;
1924 	} else {
1925 		al = SSL_AD_HANDSHAKE_FAILURE;
1926 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
1927 		goto fatal_err;
1928 	}
1929 
1930 	if (CBS_len(&cbs) != 0) {
1931 		al = SSL_AD_DECODE_ERROR;
1932 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1933 		goto fatal_err;
1934 	}
1935 
1936 	return (1);
1937 
1938  fatal_err:
1939 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1940  err:
1941 	return (-1);
1942 }
1943 
1944 static int
1945 ssl3_get_cert_verify(SSL *s)
1946 {
1947 	CBS cbs, signature;
1948 	const struct ssl_sigalg *sigalg = NULL;
1949 	uint16_t sigalg_value = SIGALG_NONE;
1950 	EVP_PKEY *pkey;
1951 	X509 *peer_cert = NULL;
1952 	EVP_MD_CTX *mctx = NULL;
1953 	int al, verify;
1954 	const unsigned char *hdata;
1955 	size_t hdatalen;
1956 	int type = 0;
1957 	int ret;
1958 
1959 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
1960 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH)) <= 0)
1961 		return ret;
1962 
1963 	ret = 0;
1964 
1965 	if (s->init_num < 0)
1966 		goto err;
1967 
1968 	if ((mctx = EVP_MD_CTX_new()) == NULL)
1969 		goto err;
1970 
1971 	CBS_init(&cbs, s->init_msg, s->init_num);
1972 
1973 	peer_cert = s->session->peer_cert;
1974 	pkey = X509_get0_pubkey(peer_cert);
1975 	type = X509_certificate_type(peer_cert, pkey);
1976 
1977 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
1978 		s->s3->hs.tls12.reuse_message = 1;
1979 		if (peer_cert != NULL) {
1980 			al = SSL_AD_UNEXPECTED_MESSAGE;
1981 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
1982 			goto fatal_err;
1983 		}
1984 		ret = 1;
1985 		goto end;
1986 	}
1987 
1988 	if (peer_cert == NULL) {
1989 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
1990 		al = SSL_AD_UNEXPECTED_MESSAGE;
1991 		goto fatal_err;
1992 	}
1993 
1994 	if (!(type & EVP_PKT_SIGN)) {
1995 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1996 		al = SSL_AD_ILLEGAL_PARAMETER;
1997 		goto fatal_err;
1998 	}
1999 
2000 	if (s->s3->change_cipher_spec) {
2001 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2002 		al = SSL_AD_UNEXPECTED_MESSAGE;
2003 		goto fatal_err;
2004 	}
2005 
2006 	if (SSL_USE_SIGALGS(s)) {
2007 		if (!CBS_get_u16(&cbs, &sigalg_value))
2008 			goto decode_err;
2009 	}
2010 	if (!CBS_get_u16_length_prefixed(&cbs, &signature))
2011 		goto err;
2012 	if (CBS_len(&cbs) != 0) {
2013 		al = SSL_AD_DECODE_ERROR;
2014 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
2015 		goto fatal_err;
2016 	}
2017 
2018 	if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
2019 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2020 		al = SSL_AD_DECODE_ERROR;
2021 		goto fatal_err;
2022 	}
2023 
2024 	if ((sigalg = ssl_sigalg_for_peer(s, pkey,
2025 	    sigalg_value)) == NULL) {
2026 		al = SSL_AD_DECODE_ERROR;
2027 		goto fatal_err;
2028 	}
2029 	s->s3->hs.peer_sigalg = sigalg;
2030 
2031 	if (SSL_USE_SIGALGS(s)) {
2032 		EVP_PKEY_CTX *pctx;
2033 
2034 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2035 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2036 			al = SSL_AD_INTERNAL_ERROR;
2037 			goto fatal_err;
2038 		}
2039 		if (!EVP_DigestVerifyInit(mctx, &pctx, sigalg->md(),
2040 		    NULL, pkey)) {
2041 			SSLerror(s, ERR_R_EVP_LIB);
2042 			al = SSL_AD_INTERNAL_ERROR;
2043 			goto fatal_err;
2044 		}
2045 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2046 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
2047 			RSA_PKCS1_PSS_PADDING) ||
2048 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2049 			al = SSL_AD_INTERNAL_ERROR;
2050 			goto fatal_err;
2051 		}
2052 #ifndef OPENSSL_NO_GOST
2053 		if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2054 		    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2055 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE,
2056 		    NULL) <= 0) {
2057 			al = SSL_AD_INTERNAL_ERROR;
2058 			goto fatal_err;
2059 		}
2060 #endif
2061 		if (EVP_DigestVerify(mctx, CBS_data(&signature),
2062 		    CBS_len(&signature), hdata, hdatalen) <= 0) {
2063 			SSLerror(s, ERR_R_EVP_LIB);
2064 			al = SSL_AD_INTERNAL_ERROR;
2065 			goto fatal_err;
2066 		}
2067 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
2068 		RSA *rsa;
2069 
2070 		if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
2071 			al = SSL_AD_INTERNAL_ERROR;
2072 			SSLerror(s, ERR_R_EVP_LIB);
2073 			goto fatal_err;
2074 		}
2075 		verify = RSA_verify(NID_md5_sha1, s->s3->hs.tls12.cert_verify,
2076 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, CBS_data(&signature),
2077 		    CBS_len(&signature), rsa);
2078 		if (verify < 0) {
2079 			al = SSL_AD_DECRYPT_ERROR;
2080 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2081 			goto fatal_err;
2082 		}
2083 		if (verify == 0) {
2084 			al = SSL_AD_DECRYPT_ERROR;
2085 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2086 			goto fatal_err;
2087 		}
2088 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
2089 		EC_KEY *eckey;
2090 
2091 		if ((eckey = EVP_PKEY_get0_EC_KEY(pkey)) == NULL) {
2092 			al = SSL_AD_INTERNAL_ERROR;
2093 			SSLerror(s, ERR_R_EVP_LIB);
2094 			goto fatal_err;
2095 		}
2096 		verify = ECDSA_verify(0,
2097 		    &(s->s3->hs.tls12.cert_verify[MD5_DIGEST_LENGTH]),
2098 		    SHA_DIGEST_LENGTH, CBS_data(&signature),
2099 		    CBS_len(&signature), eckey);
2100 		if (verify <= 0) {
2101 			al = SSL_AD_DECRYPT_ERROR;
2102 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2103 			goto fatal_err;
2104 		}
2105 #ifndef OPENSSL_NO_GOST
2106 	} else if (EVP_PKEY_id(pkey) == NID_id_GostR3410_94 ||
2107 	    EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2108 		unsigned char sigbuf[128];
2109 		unsigned int siglen = sizeof(sigbuf);
2110 		EVP_PKEY_CTX *pctx;
2111 		const EVP_MD *md;
2112 		int nid;
2113 
2114 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2115 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2116 			al = SSL_AD_INTERNAL_ERROR;
2117 			goto fatal_err;
2118 		}
2119 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2120 		    !(md = EVP_get_digestbynid(nid))) {
2121 			SSLerror(s, ERR_R_EVP_LIB);
2122 			al = SSL_AD_INTERNAL_ERROR;
2123 			goto fatal_err;
2124 		}
2125 		if ((pctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
2126 			SSLerror(s, ERR_R_EVP_LIB);
2127 			al = SSL_AD_INTERNAL_ERROR;
2128 			goto fatal_err;
2129 		}
2130 		if (!EVP_DigestInit_ex(mctx, md, NULL) ||
2131 		    !EVP_DigestUpdate(mctx, hdata, hdatalen) ||
2132 		    !EVP_DigestFinal(mctx, sigbuf, &siglen) ||
2133 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2134 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2135 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2136 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2137 		    GOST_SIG_FORMAT_RS_LE, NULL) <= 0)) {
2138 			SSLerror(s, ERR_R_EVP_LIB);
2139 			al = SSL_AD_INTERNAL_ERROR;
2140 			EVP_PKEY_CTX_free(pctx);
2141 			goto fatal_err;
2142 		}
2143 		if (EVP_PKEY_verify(pctx, CBS_data(&signature),
2144 		    CBS_len(&signature), sigbuf, siglen) <= 0) {
2145 			al = SSL_AD_DECRYPT_ERROR;
2146 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2147 			EVP_PKEY_CTX_free(pctx);
2148 			goto fatal_err;
2149 		}
2150 
2151 		EVP_PKEY_CTX_free(pctx);
2152 #endif
2153 	} else {
2154 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2155 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2156 		goto fatal_err;
2157 	}
2158 
2159 	ret = 1;
2160 	if (0) {
2161  decode_err:
2162 		al = SSL_AD_DECODE_ERROR;
2163 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2164  fatal_err:
2165 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2166 	}
2167  end:
2168 	tls1_transcript_free(s);
2169  err:
2170 	EVP_MD_CTX_free(mctx);
2171 
2172 	return (ret);
2173 }
2174 
2175 static int
2176 ssl3_get_client_certificate(SSL *s)
2177 {
2178 	CBS cbs, cert_list, cert_data;
2179 	STACK_OF(X509) *certs = NULL;
2180 	X509 *cert = NULL;
2181 	const uint8_t *p;
2182 	int al, ret;
2183 
2184 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2185 	    -1, s->max_cert_list)) <= 0)
2186 		return ret;
2187 
2188 	ret = -1;
2189 
2190 	if (s->s3->hs.tls12.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2191 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2192 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2193 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2194 			al = SSL_AD_HANDSHAKE_FAILURE;
2195 			goto fatal_err;
2196 		}
2197 
2198 		/*
2199 		 * If we asked for a client certificate and the client has none,
2200 		 * it must respond with a certificate list of length zero.
2201 		 */
2202 		if (s->s3->hs.tls12.cert_request != 0) {
2203 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2204 			al = SSL_AD_UNEXPECTED_MESSAGE;
2205 			goto fatal_err;
2206 		}
2207 		s->s3->hs.tls12.reuse_message = 1;
2208 		return (1);
2209 	}
2210 
2211 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
2212 		al = SSL_AD_UNEXPECTED_MESSAGE;
2213 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2214 		goto fatal_err;
2215 	}
2216 
2217 	if (s->init_num < 0)
2218 		goto decode_err;
2219 
2220 	CBS_init(&cbs, s->init_msg, s->init_num);
2221 
2222 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list))
2223 		goto decode_err;
2224 	if (CBS_len(&cbs) != 0)
2225 		goto decode_err;
2226 
2227 	/*
2228 	 * A TLS client must send an empty certificate list, if no suitable
2229 	 * certificate is available (rather than omitting the Certificate
2230 	 * handshake message) - see RFC 5246 section 7.4.6.
2231 	 */
2232 	if (CBS_len(&cert_list) == 0) {
2233 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2234 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2235 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2236 			al = SSL_AD_HANDSHAKE_FAILURE;
2237 			goto fatal_err;
2238 		}
2239 		/* No client certificate so free transcript. */
2240 		tls1_transcript_free(s);
2241 		goto done;
2242 	}
2243 
2244 	if ((certs = sk_X509_new_null()) == NULL) {
2245 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2246 		goto err;
2247 	}
2248 
2249 	while (CBS_len(&cert_list) > 0) {
2250 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert_data))
2251 			goto decode_err;
2252 		p = CBS_data(&cert_data);
2253 		if ((cert = d2i_X509(NULL, &p, CBS_len(&cert_data))) == NULL) {
2254 			SSLerror(s, ERR_R_ASN1_LIB);
2255 			goto err;
2256 		}
2257 		if (p != CBS_data(&cert_data) + CBS_len(&cert_data))
2258 			goto decode_err;
2259 		if (!sk_X509_push(certs, cert)) {
2260 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2261 			goto err;
2262 		}
2263 		cert = NULL;
2264 	}
2265 
2266 	if (ssl_verify_cert_chain(s, certs) <= 0) {
2267 		al = ssl_verify_alarm_type(s->verify_result);
2268 		SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2269 		goto fatal_err;
2270 	}
2271 	s->session->verify_result = s->verify_result;
2272 	ERR_clear_error();
2273 
2274 	if (!tls_process_peer_certs(s, certs))
2275 		goto err;
2276 
2277  done:
2278 	ret = 1;
2279 	if (0) {
2280  decode_err:
2281 		al = SSL_AD_DECODE_ERROR;
2282 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2283  fatal_err:
2284 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2285 	}
2286  err:
2287 	sk_X509_pop_free(certs, X509_free);
2288 	X509_free(cert);
2289 
2290 	return (ret);
2291 }
2292 
2293 static int
2294 ssl3_send_server_certificate(SSL *s)
2295 {
2296 	CBB cbb, server_cert;
2297 	SSL_CERT_PKEY *cpk;
2298 
2299 	/*
2300 	 * Server Certificate - RFC 5246, section 7.4.2.
2301 	 */
2302 
2303 	memset(&cbb, 0, sizeof(cbb));
2304 
2305 	if (s->s3->hs.state == SSL3_ST_SW_CERT_A) {
2306 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL) {
2307 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2308 			return (0);
2309 		}
2310 
2311 		if (!ssl3_handshake_msg_start(s, &cbb, &server_cert,
2312 		    SSL3_MT_CERTIFICATE))
2313 			goto err;
2314 		if (!ssl3_output_cert_chain(s, &server_cert, cpk))
2315 			goto err;
2316 		if (!ssl3_handshake_msg_finish(s, &cbb))
2317 			goto err;
2318 
2319 		s->s3->hs.state = SSL3_ST_SW_CERT_B;
2320 	}
2321 
2322 	/* SSL3_ST_SW_CERT_B */
2323 	return (ssl3_handshake_write(s));
2324 
2325  err:
2326 	CBB_cleanup(&cbb);
2327 
2328 	return (0);
2329 }
2330 
2331 /* send a new session ticket (not necessarily for a new session) */
2332 static int
2333 ssl3_send_newsession_ticket(SSL *s)
2334 {
2335 	CBB cbb, session_ticket, ticket;
2336 	SSL_CTX *tctx = s->initial_ctx;
2337 	size_t enc_session_len, enc_session_max_len, hmac_len;
2338 	size_t session_len = 0;
2339 	unsigned char *enc_session = NULL, *session = NULL;
2340 	unsigned char iv[EVP_MAX_IV_LENGTH];
2341 	unsigned char key_name[16];
2342 	unsigned char *hmac;
2343 	unsigned int hlen;
2344 	EVP_CIPHER_CTX *ctx = NULL;
2345 	HMAC_CTX *hctx = NULL;
2346 	int iv_len, len;
2347 
2348 	/*
2349 	 * New Session Ticket - RFC 5077, section 3.3.
2350 	 */
2351 
2352 	memset(&cbb, 0, sizeof(cbb));
2353 
2354 	if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
2355 		goto err;
2356 	if ((hctx = HMAC_CTX_new()) == NULL)
2357 		goto err;
2358 
2359 	if (s->s3->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2360 		if (!ssl3_handshake_msg_start(s, &cbb, &session_ticket,
2361 		    SSL3_MT_NEWSESSION_TICKET))
2362 			goto err;
2363 
2364 		if (!SSL_SESSION_ticket(s->session, &session, &session_len))
2365 			goto err;
2366 		if (session_len > 0xffff)
2367 			goto err;
2368 
2369 		/*
2370 		 * Initialize HMAC and cipher contexts. If callback is present
2371 		 * it does all the work, otherwise use generated values from
2372 		 * parent context.
2373 		 */
2374 		if (tctx->tlsext_ticket_key_cb != NULL) {
2375 			if (tctx->tlsext_ticket_key_cb(s,
2376 			    key_name, iv, ctx, hctx, 1) < 0)
2377 				goto err;
2378 		} else {
2379 			arc4random_buf(iv, 16);
2380 			EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL,
2381 			    tctx->tlsext_tick_aes_key, iv);
2382 			HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
2383 			    16, EVP_sha256(), NULL);
2384 			memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2385 		}
2386 
2387 		/* Encrypt the session state. */
2388 		enc_session_max_len = session_len + EVP_MAX_BLOCK_LENGTH;
2389 		if ((enc_session = calloc(1, enc_session_max_len)) == NULL)
2390 			goto err;
2391 		enc_session_len = 0;
2392 		if (!EVP_EncryptUpdate(ctx, enc_session, &len, session,
2393 		    session_len))
2394 			goto err;
2395 		enc_session_len += len;
2396 		if (!EVP_EncryptFinal_ex(ctx, enc_session + enc_session_len,
2397 		    &len))
2398 			goto err;
2399 		enc_session_len += len;
2400 
2401 		if (enc_session_len > enc_session_max_len)
2402 			goto err;
2403 
2404 		/* Generate the HMAC. */
2405 		if (!HMAC_Update(hctx, key_name, sizeof(key_name)))
2406 			goto err;
2407 		if (!HMAC_Update(hctx, iv, EVP_CIPHER_CTX_iv_length(ctx)))
2408 			goto err;
2409 		if (!HMAC_Update(hctx, enc_session, enc_session_len))
2410 			goto err;
2411 
2412 		if ((hmac_len = HMAC_size(hctx)) <= 0)
2413 			goto err;
2414 
2415 		/*
2416 		 * Ticket lifetime hint (advisory only):
2417 		 * We leave this unspecified for resumed session
2418 		 * (for simplicity), and guess that tickets for new
2419 		 * sessions will live as long as their sessions.
2420 		 */
2421 		if (!CBB_add_u32(&session_ticket,
2422 		    s->hit ? 0 : s->session->timeout))
2423 			goto err;
2424 
2425 		if (!CBB_add_u16_length_prefixed(&session_ticket, &ticket))
2426 			goto err;
2427 		if (!CBB_add_bytes(&ticket, key_name, sizeof(key_name)))
2428 			goto err;
2429 		if ((iv_len = EVP_CIPHER_CTX_iv_length(ctx)) < 0)
2430 			goto err;
2431 		if (!CBB_add_bytes(&ticket, iv, iv_len))
2432 			goto err;
2433 		if (!CBB_add_bytes(&ticket, enc_session, enc_session_len))
2434 			goto err;
2435 		if (!CBB_add_space(&ticket, &hmac, hmac_len))
2436 			goto err;
2437 
2438 		if (!HMAC_Final(hctx, hmac, &hlen))
2439 			goto err;
2440 		if (hlen != hmac_len)
2441 			goto err;
2442 
2443 		if (!ssl3_handshake_msg_finish(s, &cbb))
2444 			goto err;
2445 
2446 		s->s3->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2447 	}
2448 
2449 	EVP_CIPHER_CTX_free(ctx);
2450 	HMAC_CTX_free(hctx);
2451 	freezero(session, session_len);
2452 	free(enc_session);
2453 
2454 	/* SSL3_ST_SW_SESSION_TICKET_B */
2455 	return (ssl3_handshake_write(s));
2456 
2457  err:
2458 	CBB_cleanup(&cbb);
2459 	EVP_CIPHER_CTX_free(ctx);
2460 	HMAC_CTX_free(hctx);
2461 	freezero(session, session_len);
2462 	free(enc_session);
2463 
2464 	return (-1);
2465 }
2466 
2467 static int
2468 ssl3_send_cert_status(SSL *s)
2469 {
2470 	CBB cbb, certstatus, ocspresp;
2471 
2472 	memset(&cbb, 0, sizeof(cbb));
2473 
2474 	if (s->s3->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2475 		if (!ssl3_handshake_msg_start(s, &cbb, &certstatus,
2476 		    SSL3_MT_CERTIFICATE_STATUS))
2477 			goto err;
2478 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2479 			goto err;
2480 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2481 			goto err;
2482 		if (!CBB_add_bytes(&ocspresp, s->tlsext_ocsp_resp,
2483 		    s->tlsext_ocsp_resp_len))
2484 			goto err;
2485 		if (!ssl3_handshake_msg_finish(s, &cbb))
2486 			goto err;
2487 
2488 		s->s3->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2489 	}
2490 
2491 	/* SSL3_ST_SW_CERT_STATUS_B */
2492 	return (ssl3_handshake_write(s));
2493 
2494  err:
2495 	CBB_cleanup(&cbb);
2496 
2497 	return (-1);
2498 }
2499 
2500 static int
2501 ssl3_send_server_change_cipher_spec(SSL *s)
2502 {
2503 	size_t outlen;
2504 	CBB cbb;
2505 
2506 	memset(&cbb, 0, sizeof(cbb));
2507 
2508 	if (s->s3->hs.state == SSL3_ST_SW_CHANGE_A) {
2509 		if (!CBB_init_fixed(&cbb, s->init_buf->data,
2510 		    s->init_buf->length))
2511 			goto err;
2512 		if (!CBB_add_u8(&cbb, SSL3_MT_CCS))
2513 			goto err;
2514 		if (!CBB_finish(&cbb, NULL, &outlen))
2515 			goto err;
2516 
2517 		if (outlen > INT_MAX)
2518 			goto err;
2519 
2520 		s->init_num = (int)outlen;
2521 		s->init_off = 0;
2522 
2523 		if (SSL_is_dtls(s)) {
2524 			s->d1->handshake_write_seq =
2525 			    s->d1->next_handshake_write_seq;
2526 			dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
2527 			    s->d1->handshake_write_seq, 0, 0);
2528 			dtls1_buffer_message(s, 1);
2529 		}
2530 
2531 		s->s3->hs.state = SSL3_ST_SW_CHANGE_B;
2532 	}
2533 
2534 	/* SSL3_ST_SW_CHANGE_B */
2535 	return ssl3_record_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
2536 
2537  err:
2538 	CBB_cleanup(&cbb);
2539 
2540 	return -1;
2541 }
2542 
2543 static int
2544 ssl3_get_client_finished(SSL *s)
2545 {
2546 	int al, md_len, ret;
2547 	CBS cbs;
2548 
2549 	/* should actually be 36+4 :-) */
2550 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_FINISHED_A,
2551 	    SSL3_ST_SR_FINISHED_B, SSL3_MT_FINISHED, 64)) <= 0)
2552 		return ret;
2553 
2554 	/* If this occurs, we have missed a message */
2555 	if (!s->s3->change_cipher_spec) {
2556 		al = SSL_AD_UNEXPECTED_MESSAGE;
2557 		SSLerror(s, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
2558 		goto fatal_err;
2559 	}
2560 	s->s3->change_cipher_spec = 0;
2561 
2562 	md_len = TLS1_FINISH_MAC_LENGTH;
2563 
2564 	if (s->init_num < 0) {
2565 		al = SSL_AD_DECODE_ERROR;
2566 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2567 		goto fatal_err;
2568 	}
2569 
2570 	CBS_init(&cbs, s->init_msg, s->init_num);
2571 
2572 	if (s->s3->hs.peer_finished_len != md_len ||
2573 	    CBS_len(&cbs) != md_len) {
2574 		al = SSL_AD_DECODE_ERROR;
2575 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2576 		goto fatal_err;
2577 	}
2578 
2579 	if (!CBS_mem_equal(&cbs, s->s3->hs.peer_finished, CBS_len(&cbs))) {
2580 		al = SSL_AD_DECRYPT_ERROR;
2581 		SSLerror(s, SSL_R_DIGEST_CHECK_FAILED);
2582 		goto fatal_err;
2583 	}
2584 
2585 	/* Copy finished so we can use it for renegotiation checks. */
2586 	OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
2587 	memcpy(s->s3->previous_client_finished,
2588 	    s->s3->hs.peer_finished, md_len);
2589 	s->s3->previous_client_finished_len = md_len;
2590 
2591 	return (1);
2592  fatal_err:
2593 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2594 	return (0);
2595 }
2596 
2597 static int
2598 ssl3_send_server_finished(SSL *s)
2599 {
2600 	CBB cbb, finished;
2601 
2602 	memset(&cbb, 0, sizeof(cbb));
2603 
2604 	if (s->s3->hs.state == SSL3_ST_SW_FINISHED_A) {
2605 		if (!tls12_derive_finished(s))
2606 			goto err;
2607 
2608 		/* Copy finished so we can use it for renegotiation checks. */
2609 		memcpy(s->s3->previous_server_finished,
2610 		    s->s3->hs.finished, s->s3->hs.finished_len);
2611 		s->s3->previous_server_finished_len = s->s3->hs.finished_len;
2612 
2613 		if (!ssl3_handshake_msg_start(s, &cbb, &finished,
2614 		    SSL3_MT_FINISHED))
2615                         goto err;
2616 		if (!CBB_add_bytes(&finished, s->s3->hs.finished,
2617 		    s->s3->hs.finished_len))
2618 			goto err;
2619 		if (!ssl3_handshake_msg_finish(s, &cbb))
2620 			goto err;
2621 
2622 		s->s3->hs.state = SSL3_ST_SW_FINISHED_B;
2623 	}
2624 
2625 	return (ssl3_handshake_write(s));
2626 
2627  err:
2628 	CBB_cleanup(&cbb);
2629 
2630 	return (-1);
2631 }
2632