xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision 5c389b79544373bccfce668b646e62e7ba9802a3)
1 /* $OpenBSD: ssl_srvr.c,v 1.155 2023/06/11 19:01:01 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 	if ((s->s3->hs.cipher->algorithm_auth & SSL_aGOST01) != 0)
1836 		pkey = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
1837 
1838 	if ((pkey_ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL)
1839 		goto err;
1840 	if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0)
1841 		goto err;
1842 
1843 	/*
1844 	 * If client certificate is present and is of the same type,
1845 	 * maybe use it for key exchange.
1846 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
1847 	 * it is completely valid to use a client certificate for
1848 	 * authorization only.
1849 	 */
1850 	if ((client_pubkey = X509_get0_pubkey(s->session->peer_cert)) != NULL) {
1851 		if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pubkey) <= 0)
1852 			ERR_clear_error();
1853 	}
1854 
1855 	/* Decrypt session key */
1856 	if (!CBS_get_asn1(cbs, &gostblob, CBS_ASN1_SEQUENCE))
1857 		goto decode_err;
1858 	if (CBS_len(cbs) != 0)
1859 		goto decode_err;
1860 	outlen = sizeof(premaster_secret);
1861 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
1862 	    CBS_data(&gostblob), CBS_len(&gostblob)) <= 0) {
1863 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
1864 		goto err;
1865 	}
1866 
1867 	if (!tls12_derive_master_secret(s, premaster_secret,
1868 	    sizeof(premaster_secret)))
1869 		goto err;
1870 
1871 	/* Check if pubkey from client certificate was used */
1872 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY,
1873 	    2, NULL) > 0)
1874 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
1875 
1876 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1877 	EVP_PKEY_CTX_free(pkey_ctx);
1878 
1879 	return 1;
1880 
1881  decode_err:
1882 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1883 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1884  err:
1885 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1886 	EVP_PKEY_CTX_free(pkey_ctx);
1887 
1888 	return 0;
1889 }
1890 
1891 static int
1892 ssl3_get_client_key_exchange(SSL *s)
1893 {
1894 	unsigned long alg_k;
1895 	int al, ret;
1896 	CBS cbs;
1897 
1898 	/* 2048 maxlen is a guess.  How long a key does that permit? */
1899 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
1900 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048)) <= 0)
1901 		return ret;
1902 
1903 	if (s->init_num < 0)
1904 		goto err;
1905 
1906 	CBS_init(&cbs, s->init_msg, s->init_num);
1907 
1908 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1909 
1910 	if (alg_k & SSL_kRSA) {
1911 		if (!ssl3_get_client_kex_rsa(s, &cbs))
1912 			goto err;
1913 	} else if (alg_k & SSL_kDHE) {
1914 		if (!ssl3_get_client_kex_dhe(s, &cbs))
1915 			goto err;
1916 	} else if (alg_k & SSL_kECDHE) {
1917 		if (!ssl3_get_client_kex_ecdhe(s, &cbs))
1918 			goto err;
1919 	} else if (alg_k & SSL_kGOST) {
1920 		if (!ssl3_get_client_kex_gost(s, &cbs))
1921 			goto err;
1922 	} else {
1923 		al = SSL_AD_HANDSHAKE_FAILURE;
1924 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
1925 		goto fatal_err;
1926 	}
1927 
1928 	if (CBS_len(&cbs) != 0) {
1929 		al = SSL_AD_DECODE_ERROR;
1930 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1931 		goto fatal_err;
1932 	}
1933 
1934 	return (1);
1935 
1936  fatal_err:
1937 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1938  err:
1939 	return (-1);
1940 }
1941 
1942 static int
1943 ssl3_get_cert_verify(SSL *s)
1944 {
1945 	CBS cbs, signature;
1946 	const struct ssl_sigalg *sigalg = NULL;
1947 	uint16_t sigalg_value = SIGALG_NONE;
1948 	EVP_PKEY *pkey;
1949 	X509 *peer_cert = NULL;
1950 	EVP_MD_CTX *mctx = NULL;
1951 	int al, verify;
1952 	const unsigned char *hdata;
1953 	size_t hdatalen;
1954 	int type = 0;
1955 	int ret;
1956 
1957 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
1958 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH)) <= 0)
1959 		return ret;
1960 
1961 	ret = 0;
1962 
1963 	if (s->init_num < 0)
1964 		goto err;
1965 
1966 	if ((mctx = EVP_MD_CTX_new()) == NULL)
1967 		goto err;
1968 
1969 	CBS_init(&cbs, s->init_msg, s->init_num);
1970 
1971 	peer_cert = s->session->peer_cert;
1972 	pkey = X509_get0_pubkey(peer_cert);
1973 	type = X509_certificate_type(peer_cert, pkey);
1974 
1975 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
1976 		s->s3->hs.tls12.reuse_message = 1;
1977 		if (peer_cert != NULL) {
1978 			al = SSL_AD_UNEXPECTED_MESSAGE;
1979 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
1980 			goto fatal_err;
1981 		}
1982 		ret = 1;
1983 		goto end;
1984 	}
1985 
1986 	if (peer_cert == NULL) {
1987 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
1988 		al = SSL_AD_UNEXPECTED_MESSAGE;
1989 		goto fatal_err;
1990 	}
1991 
1992 	if (!(type & EVP_PKT_SIGN)) {
1993 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1994 		al = SSL_AD_ILLEGAL_PARAMETER;
1995 		goto fatal_err;
1996 	}
1997 
1998 	if (s->s3->change_cipher_spec) {
1999 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2000 		al = SSL_AD_UNEXPECTED_MESSAGE;
2001 		goto fatal_err;
2002 	}
2003 
2004 	if (SSL_USE_SIGALGS(s)) {
2005 		if (!CBS_get_u16(&cbs, &sigalg_value))
2006 			goto decode_err;
2007 	}
2008 	if (!CBS_get_u16_length_prefixed(&cbs, &signature))
2009 		goto err;
2010 	if (CBS_len(&cbs) != 0) {
2011 		al = SSL_AD_DECODE_ERROR;
2012 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
2013 		goto fatal_err;
2014 	}
2015 
2016 	if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
2017 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2018 		al = SSL_AD_DECODE_ERROR;
2019 		goto fatal_err;
2020 	}
2021 
2022 	if ((sigalg = ssl_sigalg_for_peer(s, pkey,
2023 	    sigalg_value)) == NULL) {
2024 		al = SSL_AD_DECODE_ERROR;
2025 		goto fatal_err;
2026 	}
2027 	s->s3->hs.peer_sigalg = sigalg;
2028 
2029 	if (SSL_USE_SIGALGS(s)) {
2030 		EVP_PKEY_CTX *pctx;
2031 
2032 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2033 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2034 			al = SSL_AD_INTERNAL_ERROR;
2035 			goto fatal_err;
2036 		}
2037 		if (!EVP_DigestVerifyInit(mctx, &pctx, sigalg->md(),
2038 		    NULL, pkey)) {
2039 			SSLerror(s, ERR_R_EVP_LIB);
2040 			al = SSL_AD_INTERNAL_ERROR;
2041 			goto fatal_err;
2042 		}
2043 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2044 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
2045 			RSA_PKCS1_PSS_PADDING) ||
2046 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2047 			al = SSL_AD_INTERNAL_ERROR;
2048 			goto fatal_err;
2049 		}
2050 		if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2051 		    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2052 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE,
2053 		    NULL) <= 0) {
2054 			al = SSL_AD_INTERNAL_ERROR;
2055 			goto fatal_err;
2056 		}
2057 		if (EVP_DigestVerify(mctx, CBS_data(&signature),
2058 		    CBS_len(&signature), hdata, hdatalen) <= 0) {
2059 			SSLerror(s, ERR_R_EVP_LIB);
2060 			al = SSL_AD_INTERNAL_ERROR;
2061 			goto fatal_err;
2062 		}
2063 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
2064 		RSA *rsa;
2065 
2066 		if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
2067 			al = SSL_AD_INTERNAL_ERROR;
2068 			SSLerror(s, ERR_R_EVP_LIB);
2069 			goto fatal_err;
2070 		}
2071 		verify = RSA_verify(NID_md5_sha1, s->s3->hs.tls12.cert_verify,
2072 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, CBS_data(&signature),
2073 		    CBS_len(&signature), rsa);
2074 		if (verify < 0) {
2075 			al = SSL_AD_DECRYPT_ERROR;
2076 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2077 			goto fatal_err;
2078 		}
2079 		if (verify == 0) {
2080 			al = SSL_AD_DECRYPT_ERROR;
2081 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2082 			goto fatal_err;
2083 		}
2084 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
2085 		EC_KEY *eckey;
2086 
2087 		if ((eckey = EVP_PKEY_get0_EC_KEY(pkey)) == NULL) {
2088 			al = SSL_AD_INTERNAL_ERROR;
2089 			SSLerror(s, ERR_R_EVP_LIB);
2090 			goto fatal_err;
2091 		}
2092 		verify = ECDSA_verify(0,
2093 		    &(s->s3->hs.tls12.cert_verify[MD5_DIGEST_LENGTH]),
2094 		    SHA_DIGEST_LENGTH, CBS_data(&signature),
2095 		    CBS_len(&signature), eckey);
2096 		if (verify <= 0) {
2097 			al = SSL_AD_DECRYPT_ERROR;
2098 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2099 			goto fatal_err;
2100 		}
2101 #ifndef OPENSSL_NO_GOST
2102 	} else if (EVP_PKEY_id(pkey) == NID_id_GostR3410_94 ||
2103 	    EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2104 		unsigned char sigbuf[128];
2105 		unsigned int siglen = sizeof(sigbuf);
2106 		EVP_PKEY_CTX *pctx;
2107 		const EVP_MD *md;
2108 		int nid;
2109 
2110 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2111 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2112 			al = SSL_AD_INTERNAL_ERROR;
2113 			goto fatal_err;
2114 		}
2115 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2116 		    !(md = EVP_get_digestbynid(nid))) {
2117 			SSLerror(s, ERR_R_EVP_LIB);
2118 			al = SSL_AD_INTERNAL_ERROR;
2119 			goto fatal_err;
2120 		}
2121 		if ((pctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
2122 			SSLerror(s, ERR_R_EVP_LIB);
2123 			al = SSL_AD_INTERNAL_ERROR;
2124 			goto fatal_err;
2125 		}
2126 		if (!EVP_DigestInit_ex(mctx, md, NULL) ||
2127 		    !EVP_DigestUpdate(mctx, hdata, hdatalen) ||
2128 		    !EVP_DigestFinal(mctx, sigbuf, &siglen) ||
2129 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2130 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2131 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2132 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2133 		    GOST_SIG_FORMAT_RS_LE, NULL) <= 0)) {
2134 			SSLerror(s, ERR_R_EVP_LIB);
2135 			al = SSL_AD_INTERNAL_ERROR;
2136 			EVP_PKEY_CTX_free(pctx);
2137 			goto fatal_err;
2138 		}
2139 		if (EVP_PKEY_verify(pctx, CBS_data(&signature),
2140 		    CBS_len(&signature), sigbuf, siglen) <= 0) {
2141 			al = SSL_AD_DECRYPT_ERROR;
2142 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2143 			EVP_PKEY_CTX_free(pctx);
2144 			goto fatal_err;
2145 		}
2146 
2147 		EVP_PKEY_CTX_free(pctx);
2148 #endif
2149 	} else {
2150 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2151 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2152 		goto fatal_err;
2153 	}
2154 
2155 	ret = 1;
2156 	if (0) {
2157  decode_err:
2158 		al = SSL_AD_DECODE_ERROR;
2159 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2160  fatal_err:
2161 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2162 	}
2163  end:
2164 	tls1_transcript_free(s);
2165  err:
2166 	EVP_MD_CTX_free(mctx);
2167 
2168 	return (ret);
2169 }
2170 
2171 static int
2172 ssl3_get_client_certificate(SSL *s)
2173 {
2174 	CBS cbs, cert_list, cert_data;
2175 	STACK_OF(X509) *certs = NULL;
2176 	X509 *cert = NULL;
2177 	const uint8_t *p;
2178 	int al, ret;
2179 
2180 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2181 	    -1, s->max_cert_list)) <= 0)
2182 		return ret;
2183 
2184 	ret = -1;
2185 
2186 	if (s->s3->hs.tls12.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2187 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2188 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2189 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2190 			al = SSL_AD_HANDSHAKE_FAILURE;
2191 			goto fatal_err;
2192 		}
2193 
2194 		/*
2195 		 * If we asked for a client certificate and the client has none,
2196 		 * it must respond with a certificate list of length zero.
2197 		 */
2198 		if (s->s3->hs.tls12.cert_request != 0) {
2199 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2200 			al = SSL_AD_UNEXPECTED_MESSAGE;
2201 			goto fatal_err;
2202 		}
2203 		s->s3->hs.tls12.reuse_message = 1;
2204 		return (1);
2205 	}
2206 
2207 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
2208 		al = SSL_AD_UNEXPECTED_MESSAGE;
2209 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2210 		goto fatal_err;
2211 	}
2212 
2213 	if (s->init_num < 0)
2214 		goto decode_err;
2215 
2216 	CBS_init(&cbs, s->init_msg, s->init_num);
2217 
2218 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list))
2219 		goto decode_err;
2220 	if (CBS_len(&cbs) != 0)
2221 		goto decode_err;
2222 
2223 	/*
2224 	 * A TLS client must send an empty certificate list, if no suitable
2225 	 * certificate is available (rather than omitting the Certificate
2226 	 * handshake message) - see RFC 5246 section 7.4.6.
2227 	 */
2228 	if (CBS_len(&cert_list) == 0) {
2229 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2230 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2231 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2232 			al = SSL_AD_HANDSHAKE_FAILURE;
2233 			goto fatal_err;
2234 		}
2235 		/* No client certificate so free transcript. */
2236 		tls1_transcript_free(s);
2237 		goto done;
2238 	}
2239 
2240 	if ((certs = sk_X509_new_null()) == NULL) {
2241 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2242 		goto err;
2243 	}
2244 
2245 	while (CBS_len(&cert_list) > 0) {
2246 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert_data))
2247 			goto decode_err;
2248 		p = CBS_data(&cert_data);
2249 		if ((cert = d2i_X509(NULL, &p, CBS_len(&cert_data))) == NULL) {
2250 			SSLerror(s, ERR_R_ASN1_LIB);
2251 			goto err;
2252 		}
2253 		if (p != CBS_data(&cert_data) + CBS_len(&cert_data))
2254 			goto decode_err;
2255 		if (!sk_X509_push(certs, cert)) {
2256 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2257 			goto err;
2258 		}
2259 		cert = NULL;
2260 	}
2261 
2262 	if (ssl_verify_cert_chain(s, certs) <= 0) {
2263 		al = ssl_verify_alarm_type(s->verify_result);
2264 		SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2265 		goto fatal_err;
2266 	}
2267 	s->session->verify_result = s->verify_result;
2268 	ERR_clear_error();
2269 
2270 	if (!tls_process_peer_certs(s, certs))
2271 		goto err;
2272 
2273  done:
2274 	ret = 1;
2275 	if (0) {
2276  decode_err:
2277 		al = SSL_AD_DECODE_ERROR;
2278 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2279  fatal_err:
2280 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2281 	}
2282  err:
2283 	sk_X509_pop_free(certs, X509_free);
2284 	X509_free(cert);
2285 
2286 	return (ret);
2287 }
2288 
2289 static int
2290 ssl3_send_server_certificate(SSL *s)
2291 {
2292 	CBB cbb, server_cert;
2293 	SSL_CERT_PKEY *cpk;
2294 
2295 	/*
2296 	 * Server Certificate - RFC 5246, section 7.4.2.
2297 	 */
2298 
2299 	memset(&cbb, 0, sizeof(cbb));
2300 
2301 	if (s->s3->hs.state == SSL3_ST_SW_CERT_A) {
2302 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL) {
2303 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2304 			return (0);
2305 		}
2306 
2307 		if (!ssl3_handshake_msg_start(s, &cbb, &server_cert,
2308 		    SSL3_MT_CERTIFICATE))
2309 			goto err;
2310 		if (!ssl3_output_cert_chain(s, &server_cert, cpk))
2311 			goto err;
2312 		if (!ssl3_handshake_msg_finish(s, &cbb))
2313 			goto err;
2314 
2315 		s->s3->hs.state = SSL3_ST_SW_CERT_B;
2316 	}
2317 
2318 	/* SSL3_ST_SW_CERT_B */
2319 	return (ssl3_handshake_write(s));
2320 
2321  err:
2322 	CBB_cleanup(&cbb);
2323 
2324 	return (0);
2325 }
2326 
2327 /* send a new session ticket (not necessarily for a new session) */
2328 static int
2329 ssl3_send_newsession_ticket(SSL *s)
2330 {
2331 	CBB cbb, session_ticket, ticket;
2332 	SSL_CTX *tctx = s->initial_ctx;
2333 	size_t enc_session_len, enc_session_max_len, hmac_len;
2334 	size_t session_len = 0;
2335 	unsigned char *enc_session = NULL, *session = NULL;
2336 	unsigned char iv[EVP_MAX_IV_LENGTH];
2337 	unsigned char key_name[16];
2338 	unsigned char *hmac;
2339 	unsigned int hlen;
2340 	EVP_CIPHER_CTX *ctx = NULL;
2341 	HMAC_CTX *hctx = NULL;
2342 	int len;
2343 
2344 	/*
2345 	 * New Session Ticket - RFC 5077, section 3.3.
2346 	 */
2347 
2348 	memset(&cbb, 0, sizeof(cbb));
2349 
2350 	if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
2351 		goto err;
2352 	if ((hctx = HMAC_CTX_new()) == NULL)
2353 		goto err;
2354 
2355 	if (s->s3->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2356 		if (!ssl3_handshake_msg_start(s, &cbb, &session_ticket,
2357 		    SSL3_MT_NEWSESSION_TICKET))
2358 			goto err;
2359 
2360 		if (!SSL_SESSION_ticket(s->session, &session, &session_len))
2361 			goto err;
2362 		if (session_len > 0xffff)
2363 			goto err;
2364 
2365 		/*
2366 		 * Initialize HMAC and cipher contexts. If callback is present
2367 		 * it does all the work, otherwise use generated values from
2368 		 * parent context.
2369 		 */
2370 		if (tctx->tlsext_ticket_key_cb != NULL) {
2371 			if (tctx->tlsext_ticket_key_cb(s,
2372 			    key_name, iv, ctx, hctx, 1) < 0)
2373 				goto err;
2374 		} else {
2375 			arc4random_buf(iv, 16);
2376 			EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL,
2377 			    tctx->tlsext_tick_aes_key, iv);
2378 			HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key,
2379 			    16, EVP_sha256(), NULL);
2380 			memcpy(key_name, tctx->tlsext_tick_key_name, 16);
2381 		}
2382 
2383 		/* Encrypt the session state. */
2384 		enc_session_max_len = session_len + EVP_MAX_BLOCK_LENGTH;
2385 		if ((enc_session = calloc(1, enc_session_max_len)) == NULL)
2386 			goto err;
2387 		enc_session_len = 0;
2388 		if (!EVP_EncryptUpdate(ctx, enc_session, &len, session,
2389 		    session_len))
2390 			goto err;
2391 		enc_session_len += len;
2392 		if (!EVP_EncryptFinal_ex(ctx, enc_session + enc_session_len,
2393 		    &len))
2394 			goto err;
2395 		enc_session_len += len;
2396 
2397 		if (enc_session_len > enc_session_max_len)
2398 			goto err;
2399 
2400 		/* Generate the HMAC. */
2401 		if (!HMAC_Update(hctx, key_name, sizeof(key_name)))
2402 			goto err;
2403 		if (!HMAC_Update(hctx, iv, EVP_CIPHER_CTX_iv_length(ctx)))
2404 			goto err;
2405 		if (!HMAC_Update(hctx, enc_session, enc_session_len))
2406 			goto err;
2407 
2408 		if ((hmac_len = HMAC_size(hctx)) <= 0)
2409 			goto err;
2410 
2411 		/*
2412 		 * Ticket lifetime hint (advisory only):
2413 		 * We leave this unspecified for resumed session
2414 		 * (for simplicity), and guess that tickets for new
2415 		 * sessions will live as long as their sessions.
2416 		 */
2417 		if (!CBB_add_u32(&session_ticket,
2418 		    s->hit ? 0 : s->session->timeout))
2419 			goto err;
2420 
2421 		if (!CBB_add_u16_length_prefixed(&session_ticket, &ticket))
2422 			goto err;
2423 		if (!CBB_add_bytes(&ticket, key_name, sizeof(key_name)))
2424 			goto err;
2425 		if (!CBB_add_bytes(&ticket, iv, EVP_CIPHER_CTX_iv_length(ctx)))
2426 			goto err;
2427 		if (!CBB_add_bytes(&ticket, enc_session, enc_session_len))
2428 			goto err;
2429 		if (!CBB_add_space(&ticket, &hmac, hmac_len))
2430 			goto err;
2431 
2432 		if (!HMAC_Final(hctx, hmac, &hlen))
2433 			goto err;
2434 		if (hlen != hmac_len)
2435 			goto err;
2436 
2437 		if (!ssl3_handshake_msg_finish(s, &cbb))
2438 			goto err;
2439 
2440 		s->s3->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2441 	}
2442 
2443 	EVP_CIPHER_CTX_free(ctx);
2444 	HMAC_CTX_free(hctx);
2445 	freezero(session, session_len);
2446 	free(enc_session);
2447 
2448 	/* SSL3_ST_SW_SESSION_TICKET_B */
2449 	return (ssl3_handshake_write(s));
2450 
2451  err:
2452 	CBB_cleanup(&cbb);
2453 	EVP_CIPHER_CTX_free(ctx);
2454 	HMAC_CTX_free(hctx);
2455 	freezero(session, session_len);
2456 	free(enc_session);
2457 
2458 	return (-1);
2459 }
2460 
2461 static int
2462 ssl3_send_cert_status(SSL *s)
2463 {
2464 	CBB cbb, certstatus, ocspresp;
2465 
2466 	memset(&cbb, 0, sizeof(cbb));
2467 
2468 	if (s->s3->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2469 		if (!ssl3_handshake_msg_start(s, &cbb, &certstatus,
2470 		    SSL3_MT_CERTIFICATE_STATUS))
2471 			goto err;
2472 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2473 			goto err;
2474 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2475 			goto err;
2476 		if (!CBB_add_bytes(&ocspresp, s->tlsext_ocsp_resp,
2477 		    s->tlsext_ocsp_resp_len))
2478 			goto err;
2479 		if (!ssl3_handshake_msg_finish(s, &cbb))
2480 			goto err;
2481 
2482 		s->s3->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2483 	}
2484 
2485 	/* SSL3_ST_SW_CERT_STATUS_B */
2486 	return (ssl3_handshake_write(s));
2487 
2488  err:
2489 	CBB_cleanup(&cbb);
2490 
2491 	return (-1);
2492 }
2493 
2494 static int
2495 ssl3_send_server_change_cipher_spec(SSL *s)
2496 {
2497 	size_t outlen;
2498 	CBB cbb;
2499 
2500 	memset(&cbb, 0, sizeof(cbb));
2501 
2502 	if (s->s3->hs.state == SSL3_ST_SW_CHANGE_A) {
2503 		if (!CBB_init_fixed(&cbb, s->init_buf->data,
2504 		    s->init_buf->length))
2505 			goto err;
2506 		if (!CBB_add_u8(&cbb, SSL3_MT_CCS))
2507 			goto err;
2508 		if (!CBB_finish(&cbb, NULL, &outlen))
2509 			goto err;
2510 
2511 		if (outlen > INT_MAX)
2512 			goto err;
2513 
2514 		s->init_num = (int)outlen;
2515 		s->init_off = 0;
2516 
2517 		if (SSL_is_dtls(s)) {
2518 			s->d1->handshake_write_seq =
2519 			    s->d1->next_handshake_write_seq;
2520 			dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
2521 			    s->d1->handshake_write_seq, 0, 0);
2522 			dtls1_buffer_message(s, 1);
2523 		}
2524 
2525 		s->s3->hs.state = SSL3_ST_SW_CHANGE_B;
2526 	}
2527 
2528 	/* SSL3_ST_SW_CHANGE_B */
2529 	return ssl3_record_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
2530 
2531  err:
2532 	CBB_cleanup(&cbb);
2533 
2534 	return -1;
2535 }
2536 
2537 static int
2538 ssl3_get_client_finished(SSL *s)
2539 {
2540 	int al, md_len, ret;
2541 	CBS cbs;
2542 
2543 	/* should actually be 36+4 :-) */
2544 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_FINISHED_A,
2545 	    SSL3_ST_SR_FINISHED_B, SSL3_MT_FINISHED, 64)) <= 0)
2546 		return ret;
2547 
2548 	/* If this occurs, we have missed a message */
2549 	if (!s->s3->change_cipher_spec) {
2550 		al = SSL_AD_UNEXPECTED_MESSAGE;
2551 		SSLerror(s, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
2552 		goto fatal_err;
2553 	}
2554 	s->s3->change_cipher_spec = 0;
2555 
2556 	md_len = TLS1_FINISH_MAC_LENGTH;
2557 
2558 	if (s->init_num < 0) {
2559 		al = SSL_AD_DECODE_ERROR;
2560 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2561 		goto fatal_err;
2562 	}
2563 
2564 	CBS_init(&cbs, s->init_msg, s->init_num);
2565 
2566 	if (s->s3->hs.peer_finished_len != md_len ||
2567 	    CBS_len(&cbs) != md_len) {
2568 		al = SSL_AD_DECODE_ERROR;
2569 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2570 		goto fatal_err;
2571 	}
2572 
2573 	if (!CBS_mem_equal(&cbs, s->s3->hs.peer_finished, CBS_len(&cbs))) {
2574 		al = SSL_AD_DECRYPT_ERROR;
2575 		SSLerror(s, SSL_R_DIGEST_CHECK_FAILED);
2576 		goto fatal_err;
2577 	}
2578 
2579 	/* Copy finished so we can use it for renegotiation checks. */
2580 	OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
2581 	memcpy(s->s3->previous_client_finished,
2582 	    s->s3->hs.peer_finished, md_len);
2583 	s->s3->previous_client_finished_len = md_len;
2584 
2585 	return (1);
2586  fatal_err:
2587 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2588 	return (0);
2589 }
2590 
2591 static int
2592 ssl3_send_server_finished(SSL *s)
2593 {
2594 	CBB cbb, finished;
2595 
2596 	memset(&cbb, 0, sizeof(cbb));
2597 
2598 	if (s->s3->hs.state == SSL3_ST_SW_FINISHED_A) {
2599 		if (!tls12_derive_finished(s))
2600 			goto err;
2601 
2602 		/* Copy finished so we can use it for renegotiation checks. */
2603 		memcpy(s->s3->previous_server_finished,
2604 		    s->s3->hs.finished, s->s3->hs.finished_len);
2605 		s->s3->previous_server_finished_len = s->s3->hs.finished_len;
2606 
2607 		if (!ssl3_handshake_msg_start(s, &cbb, &finished,
2608 		    SSL3_MT_FINISHED))
2609                         goto err;
2610 		if (!CBB_add_bytes(&finished, s->s3->hs.finished,
2611 		    s->s3->hs.finished_len))
2612 			goto err;
2613 		if (!ssl3_handshake_msg_finish(s, &cbb))
2614 			goto err;
2615 
2616 		s->s3->hs.state = SSL3_ST_SW_FINISHED_B;
2617 	}
2618 
2619 	return (ssl3_handshake_write(s));
2620 
2621  err:
2622 	CBB_cleanup(&cbb);
2623 
2624 	return (-1);
2625 }
2626