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