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