xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision 0be5e928845b741c9c0f7c1669bc1b98078d4dae)
1 /* $OpenBSD: ssl_srvr.c,v 1.142 2022/06/07 17:14:17 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150 
151 #include <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 != NULL) {
1059 		SSL_CIPHER *pref_cipher = NULL;
1060 		int master_key_length = sizeof(s->session->master_key);
1061 
1062 		if (!s->internal->tls_session_secret_cb(s,
1063 		    s->session->master_key, &master_key_length, ciphers,
1064 		    &pref_cipher, s->internal->tls_session_secret_cb_arg)) {
1065 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1066 			goto err;
1067 		}
1068 		if (master_key_length <= 0) {
1069 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1070 			goto err;
1071 		}
1072 		s->session->master_key_length = master_key_length;
1073 
1074 		s->internal->hit = 1;
1075 		s->session->verify_result = X509_V_OK;
1076 
1077 		s->session->ciphers = ciphers;
1078 		ciphers = NULL;
1079 
1080 		/* Check if some cipher was preferred by the callback. */
1081 		if (pref_cipher == NULL)
1082 			pref_cipher = ssl3_choose_cipher(s, s->session->ciphers,
1083 			    SSL_get_ciphers(s));
1084 		if (pref_cipher == NULL) {
1085 			al = SSL_AD_HANDSHAKE_FAILURE;
1086 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1087 			goto fatal_err;
1088 		}
1089 		s->session->cipher = pref_cipher;
1090 
1091 		sk_SSL_CIPHER_free(s->cipher_list);
1092 		s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1093 	}
1094 
1095 	/*
1096 	 * Given s->session->ciphers and SSL_get_ciphers, we must
1097 	 * pick a cipher
1098 	 */
1099 
1100 	if (!s->internal->hit) {
1101 		sk_SSL_CIPHER_free(s->session->ciphers);
1102 		s->session->ciphers = ciphers;
1103 		if (ciphers == NULL) {
1104 			al = SSL_AD_ILLEGAL_PARAMETER;
1105 			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
1106 			goto fatal_err;
1107 		}
1108 		ciphers = NULL;
1109 		c = ssl3_choose_cipher(s, s->session->ciphers,
1110 		SSL_get_ciphers(s));
1111 
1112 		if (c == NULL) {
1113 			al = SSL_AD_HANDSHAKE_FAILURE;
1114 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1115 			goto fatal_err;
1116 		}
1117 		s->s3->hs.cipher = c;
1118 	} else {
1119 		s->s3->hs.cipher = s->session->cipher;
1120 	}
1121 
1122 	if (!tls1_transcript_hash_init(s))
1123 		goto err;
1124 
1125 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1126 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1127 	    !(s->verify_mode & SSL_VERIFY_PEER))
1128 		tls1_transcript_free(s);
1129 
1130 	/*
1131 	 * We now have the following setup.
1132 	 * client_random
1133 	 * cipher_list		- our prefered list of ciphers
1134 	 * ciphers		- the clients prefered list of ciphers
1135 	 * compression		- basically ignored right now
1136 	 * ssl version is set	- sslv3
1137 	 * s->session		- The ssl session has been setup.
1138 	 * s->internal->hit		- session reuse flag
1139 	 * s->hs.cipher	- the new cipher to use.
1140 	 */
1141 
1142 	/* Handles TLS extensions that we couldn't check earlier */
1143 	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1144 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1145 		goto err;
1146 	}
1147 
1148 	ret = cookie_valid ? 2 : 1;
1149 
1150 	if (0) {
1151  decode_err:
1152 		al = SSL_AD_DECODE_ERROR;
1153 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1154  fatal_err:
1155 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1156 	}
1157  err:
1158 	sk_SSL_CIPHER_free(ciphers);
1159 
1160 	return (ret);
1161 }
1162 
1163 int
1164 ssl3_send_dtls_hello_verify_request(SSL *s)
1165 {
1166 	CBB cbb, verify, cookie;
1167 
1168 	memset(&cbb, 0, sizeof(cbb));
1169 
1170 	if (s->s3->hs.state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) {
1171 		if (s->ctx->internal->app_gen_cookie_cb == NULL ||
1172 		    s->ctx->internal->app_gen_cookie_cb(s, s->d1->cookie,
1173 			&(s->d1->cookie_len)) == 0) {
1174 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1175 			return 0;
1176 		}
1177 
1178 		/*
1179 		 * Per RFC 6347 section 4.2.1, the HelloVerifyRequest should
1180 		 * always contain DTLSv1.0 regardless of the version that is
1181 		 * going to be negotiated.
1182 		 */
1183 		if (!ssl3_handshake_msg_start(s, &cbb, &verify,
1184 		    DTLS1_MT_HELLO_VERIFY_REQUEST))
1185 			goto err;
1186 		if (!CBB_add_u16(&verify, DTLS1_VERSION))
1187 			goto err;
1188 		if (!CBB_add_u8_length_prefixed(&verify, &cookie))
1189 			goto err;
1190 		if (!CBB_add_bytes(&cookie, s->d1->cookie, s->d1->cookie_len))
1191 			goto err;
1192 		if (!ssl3_handshake_msg_finish(s, &cbb))
1193 			goto err;
1194 
1195 		s->s3->hs.state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B;
1196 	}
1197 
1198 	/* s->s3->hs.state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */
1199 	return (ssl3_handshake_write(s));
1200 
1201  err:
1202 	CBB_cleanup(&cbb);
1203 
1204 	return (-1);
1205 }
1206 
1207 int
1208 ssl3_send_server_hello(SSL *s)
1209 {
1210 	CBB cbb, server_hello, session_id;
1211 	size_t sl;
1212 
1213 	memset(&cbb, 0, sizeof(cbb));
1214 
1215 	if (s->s3->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
1216 		if (!ssl3_handshake_msg_start(s, &cbb, &server_hello,
1217 		    SSL3_MT_SERVER_HELLO))
1218 			goto err;
1219 
1220 		if (!CBB_add_u16(&server_hello, s->version))
1221 			goto err;
1222 		if (!CBB_add_bytes(&server_hello, s->s3->server_random,
1223 		    sizeof(s->s3->server_random)))
1224 			goto err;
1225 
1226 		/*
1227 		 * There are several cases for the session ID to send
1228 		 * back in the server hello:
1229 		 *
1230 		 * - For session reuse from the session cache,
1231 		 *   we send back the old session ID.
1232 		 * - If stateless session reuse (using a session ticket)
1233 		 *   is successful, we send back the client's "session ID"
1234 		 *   (which doesn't actually identify the session).
1235 		 * - If it is a new session, we send back the new
1236 		 *   session ID.
1237 		 * - However, if we want the new session to be single-use,
1238 		 *   we send back a 0-length session ID.
1239 		 *
1240 		 * s->internal->hit is non-zero in either case of session reuse,
1241 		 * so the following won't overwrite an ID that we're supposed
1242 		 * to send back.
1243 		 */
1244 		if (!(s->ctx->internal->session_cache_mode & SSL_SESS_CACHE_SERVER)
1245 		    && !s->internal->hit)
1246 			s->session->session_id_length = 0;
1247 
1248 		sl = s->session->session_id_length;
1249 		if (sl > sizeof(s->session->session_id)) {
1250 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1251 			goto err;
1252 		}
1253 		if (!CBB_add_u8_length_prefixed(&server_hello, &session_id))
1254 			goto err;
1255 		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1256 			goto err;
1257 
1258 		/* Cipher suite. */
1259 		if (!CBB_add_u16(&server_hello,
1260 		    ssl3_cipher_get_value(s->s3->hs.cipher)))
1261 			goto err;
1262 
1263 		/* Compression method (null). */
1264 		if (!CBB_add_u8(&server_hello, 0))
1265 			goto err;
1266 
1267 		/* TLS extensions */
1268 		if (!tlsext_server_build(s, SSL_TLSEXT_MSG_SH, &server_hello)) {
1269 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1270 			goto err;
1271 		}
1272 
1273 		if (!ssl3_handshake_msg_finish(s, &cbb))
1274 			goto err;
1275 	}
1276 
1277 	/* SSL3_ST_SW_SRVR_HELLO_B */
1278 	return (ssl3_handshake_write(s));
1279 
1280  err:
1281 	CBB_cleanup(&cbb);
1282 
1283 	return (-1);
1284 }
1285 
1286 int
1287 ssl3_send_server_done(SSL *s)
1288 {
1289 	CBB cbb, done;
1290 
1291 	memset(&cbb, 0, sizeof(cbb));
1292 
1293 	if (s->s3->hs.state == SSL3_ST_SW_SRVR_DONE_A) {
1294 		if (!ssl3_handshake_msg_start(s, &cbb, &done,
1295 		    SSL3_MT_SERVER_DONE))
1296 			goto err;
1297 		if (!ssl3_handshake_msg_finish(s, &cbb))
1298 			goto err;
1299 
1300 		s->s3->hs.state = SSL3_ST_SW_SRVR_DONE_B;
1301 	}
1302 
1303 	/* SSL3_ST_SW_SRVR_DONE_B */
1304 	return (ssl3_handshake_write(s));
1305 
1306  err:
1307 	CBB_cleanup(&cbb);
1308 
1309 	return (-1);
1310 }
1311 
1312 static int
1313 ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1314 {
1315 	int nid = NID_dhKeyAgreement;
1316 
1317 	tls_key_share_free(s->s3->hs.key_share);
1318 	if ((s->s3->hs.key_share = tls_key_share_new_nid(nid)) == NULL)
1319 		goto err;
1320 
1321 	if (s->cert->dhe_params_auto != 0) {
1322 		size_t key_bits;
1323 
1324 		if ((key_bits = ssl_dhe_params_auto_key_bits(s)) == 0) {
1325 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1326 			ssl3_send_alert(s, SSL3_AL_FATAL,
1327 			    SSL_AD_INTERNAL_ERROR);
1328 			goto err;
1329 		}
1330 		tls_key_share_set_key_bits(s->s3->hs.key_share,
1331 		    key_bits);
1332 	} else {
1333 		DH *dh_params = s->cert->dhe_params;
1334 
1335 		if (dh_params == NULL && s->cert->dhe_params_cb != NULL)
1336 			dh_params = s->cert->dhe_params_cb(s, 0,
1337 			    SSL_C_PKEYLENGTH(s->s3->hs.cipher));
1338 
1339 		if (dh_params == NULL) {
1340 			SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1341 			ssl3_send_alert(s, SSL3_AL_FATAL,
1342 			    SSL_AD_HANDSHAKE_FAILURE);
1343 			goto err;
1344 		}
1345 
1346 		if (!tls_key_share_set_dh_params(s->s3->hs.key_share, dh_params))
1347 			goto err;
1348 	}
1349 
1350 	if (!tls_key_share_generate(s->s3->hs.key_share))
1351 		goto err;
1352 
1353 	if (!tls_key_share_params(s->s3->hs.key_share, cbb))
1354 		goto err;
1355 	if (!tls_key_share_public(s->s3->hs.key_share, cbb))
1356 		goto err;
1357 
1358 	return 1;
1359 
1360  err:
1361 	return 0;
1362 }
1363 
1364 static int
1365 ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1366 {
1367 	CBB public;
1368 	int nid;
1369 
1370 	if ((nid = tls1_get_shared_curve(s)) == NID_undef) {
1371 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1372 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1373 		goto err;
1374 	}
1375 
1376 	tls_key_share_free(s->s3->hs.key_share);
1377 	if ((s->s3->hs.key_share = tls_key_share_new_nid(nid)) == NULL)
1378 		goto err;
1379 
1380 	if (!tls_key_share_generate(s->s3->hs.key_share))
1381 		goto err;
1382 
1383 	/*
1384 	 * ECC key exchange - see RFC 8422, section 5.4.
1385 	 */
1386 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1387 		goto err;
1388 	if (!CBB_add_u16(cbb, tls_key_share_group(s->s3->hs.key_share)))
1389 		goto err;
1390 	if (!CBB_add_u8_length_prefixed(cbb, &public))
1391 		goto err;
1392 	if (!tls_key_share_public(s->s3->hs.key_share, &public))
1393 		goto err;
1394 	if (!CBB_flush(cbb))
1395 		goto err;
1396 
1397 	return 1;
1398 
1399  err:
1400 	return 0;
1401 }
1402 
1403 int
1404 ssl3_send_server_key_exchange(SSL *s)
1405 {
1406 	CBB cbb, cbb_params, cbb_signature, server_kex;
1407 	const struct ssl_sigalg *sigalg = NULL;
1408 	unsigned char *signature = NULL;
1409 	size_t signature_len = 0;
1410 	unsigned char *params = NULL;
1411 	size_t params_len;
1412 	const EVP_MD *md = NULL;
1413 	unsigned long type;
1414 	EVP_MD_CTX *md_ctx = NULL;
1415 	EVP_PKEY_CTX *pctx;
1416 	EVP_PKEY *pkey;
1417 	int al;
1418 
1419 	memset(&cbb, 0, sizeof(cbb));
1420 	memset(&cbb_params, 0, sizeof(cbb_params));
1421 
1422 	if ((md_ctx = EVP_MD_CTX_new()) == NULL)
1423 		goto err;
1424 
1425 	if (s->s3->hs.state == SSL3_ST_SW_KEY_EXCH_A) {
1426 
1427 		if (!ssl3_handshake_msg_start(s, &cbb, &server_kex,
1428 		    SSL3_MT_SERVER_KEY_EXCHANGE))
1429 			goto err;
1430 
1431 		if (!CBB_init(&cbb_params, 0))
1432 			goto err;
1433 
1434 		type = s->s3->hs.cipher->algorithm_mkey;
1435 		if (type & SSL_kDHE) {
1436 			if (!ssl3_send_server_kex_dhe(s, &cbb_params))
1437 				goto err;
1438 		} else if (type & SSL_kECDHE) {
1439 			if (!ssl3_send_server_kex_ecdhe(s, &cbb_params))
1440 				goto err;
1441 		} else {
1442 			al = SSL_AD_HANDSHAKE_FAILURE;
1443 			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1444 			goto fatal_err;
1445 		}
1446 
1447 		if (!CBB_finish(&cbb_params, &params, &params_len))
1448 			goto err;
1449 
1450 		if (!CBB_add_bytes(&server_kex, params, params_len))
1451 			goto err;
1452 
1453 		/* Add signature unless anonymous. */
1454 		if (!(s->s3->hs.cipher->algorithm_auth & SSL_aNULL)) {
1455 			if ((pkey = ssl_get_sign_pkey(s, s->s3->hs.cipher,
1456 			    &md, &sigalg)) == NULL) {
1457 				al = SSL_AD_DECODE_ERROR;
1458 				goto fatal_err;
1459 			}
1460 			s->s3->hs.our_sigalg = sigalg;
1461 
1462 			/* Send signature algorithm. */
1463 			if (SSL_USE_SIGALGS(s)) {
1464 				if (!CBB_add_u16(&server_kex, sigalg->value)) {
1465 					al = SSL_AD_INTERNAL_ERROR;
1466 					SSLerror(s, ERR_R_INTERNAL_ERROR);
1467 					goto fatal_err;
1468 				}
1469 			}
1470 
1471 			if (!EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey)) {
1472 				SSLerror(s, ERR_R_EVP_LIB);
1473 				goto err;
1474 			}
1475 			if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1476 			    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1477 			    RSA_PKCS1_PSS_PADDING) ||
1478 			    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
1479 				SSLerror(s, ERR_R_EVP_LIB);
1480 				goto err;
1481 			}
1482 			if (!EVP_DigestSignUpdate(md_ctx, s->s3->client_random,
1483 			    SSL3_RANDOM_SIZE)) {
1484 				SSLerror(s, ERR_R_EVP_LIB);
1485 				goto err;
1486 			}
1487 			if (!EVP_DigestSignUpdate(md_ctx, s->s3->server_random,
1488 			    SSL3_RANDOM_SIZE)) {
1489 				SSLerror(s, ERR_R_EVP_LIB);
1490 				goto err;
1491 			}
1492 			if (!EVP_DigestSignUpdate(md_ctx, params, params_len)) {
1493 				SSLerror(s, ERR_R_EVP_LIB);
1494 				goto err;
1495 			}
1496 			if (!EVP_DigestSignFinal(md_ctx, NULL, &signature_len) ||
1497 			    !signature_len) {
1498 				SSLerror(s, ERR_R_EVP_LIB);
1499 				goto err;
1500 			}
1501 			if ((signature = calloc(1, signature_len)) == NULL) {
1502 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1503 				goto err;
1504 			}
1505 			if (!EVP_DigestSignFinal(md_ctx, signature, &signature_len)) {
1506 				SSLerror(s, ERR_R_EVP_LIB);
1507 				goto err;
1508 			}
1509 
1510 			if (!CBB_add_u16_length_prefixed(&server_kex,
1511 			    &cbb_signature))
1512 				goto err;
1513 			if (!CBB_add_bytes(&cbb_signature, signature,
1514 			    signature_len))
1515 				goto err;
1516 		}
1517 
1518 		if (!ssl3_handshake_msg_finish(s, &cbb))
1519 			goto err;
1520 
1521 		s->s3->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1522 	}
1523 
1524 	EVP_MD_CTX_free(md_ctx);
1525 	free(params);
1526 	free(signature);
1527 
1528 	return (ssl3_handshake_write(s));
1529 
1530  fatal_err:
1531 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1532  err:
1533 	CBB_cleanup(&cbb_params);
1534 	CBB_cleanup(&cbb);
1535 	EVP_MD_CTX_free(md_ctx);
1536 	free(params);
1537 	free(signature);
1538 
1539 	return (-1);
1540 }
1541 
1542 int
1543 ssl3_send_certificate_request(SSL *s)
1544 {
1545 	CBB cbb, cert_request, cert_types, sigalgs, cert_auth, dn;
1546 	STACK_OF(X509_NAME) *sk = NULL;
1547 	X509_NAME *name;
1548 	int i;
1549 
1550 	/*
1551 	 * Certificate Request - RFC 5246 section 7.4.4.
1552 	 */
1553 
1554 	memset(&cbb, 0, sizeof(cbb));
1555 
1556 	if (s->s3->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1557 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_request,
1558 		    SSL3_MT_CERTIFICATE_REQUEST))
1559 			goto err;
1560 
1561 		if (!CBB_add_u8_length_prefixed(&cert_request, &cert_types))
1562 			goto err;
1563 		if (!ssl3_get_req_cert_types(s, &cert_types))
1564 			goto err;
1565 
1566 		if (SSL_USE_SIGALGS(s)) {
1567 			if (!CBB_add_u16_length_prefixed(&cert_request,
1568 			    &sigalgs))
1569 				goto err;
1570 			if (!ssl_sigalgs_build(
1571 			    s->s3->hs.negotiated_tls_version, &sigalgs))
1572 				goto err;
1573 		}
1574 
1575 		if (!CBB_add_u16_length_prefixed(&cert_request, &cert_auth))
1576 			goto err;
1577 
1578 		sk = SSL_get_client_CA_list(s);
1579 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1580 			unsigned char *name_data;
1581 			size_t name_len;
1582 
1583 			name = sk_X509_NAME_value(sk, i);
1584 			name_len = i2d_X509_NAME(name, NULL);
1585 
1586 			if (!CBB_add_u16_length_prefixed(&cert_auth, &dn))
1587 				goto err;
1588 			if (!CBB_add_space(&dn, &name_data, name_len))
1589 				goto err;
1590 			if (i2d_X509_NAME(name, &name_data) != name_len)
1591 				goto err;
1592 		}
1593 
1594 		if (!ssl3_handshake_msg_finish(s, &cbb))
1595 			goto err;
1596 
1597 		s->s3->hs.state = SSL3_ST_SW_CERT_REQ_B;
1598 	}
1599 
1600 	/* SSL3_ST_SW_CERT_REQ_B */
1601 	return (ssl3_handshake_write(s));
1602 
1603  err:
1604 	CBB_cleanup(&cbb);
1605 
1606 	return (-1);
1607 }
1608 
1609 static int
1610 ssl3_get_client_kex_rsa(SSL *s, CBS *cbs)
1611 {
1612 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1613 	unsigned char *pms = NULL;
1614 	unsigned char *p;
1615 	size_t pms_len = 0;
1616 	EVP_PKEY *pkey = NULL;
1617 	RSA *rsa = NULL;
1618 	CBS enc_pms;
1619 	int decrypt_len;
1620 	int al = -1;
1621 
1622 	arc4random_buf(fakekey, sizeof(fakekey));
1623 
1624 	fakekey[0] = s->s3->hs.peer_legacy_version >> 8;
1625 	fakekey[1] = s->s3->hs.peer_legacy_version & 0xff;
1626 
1627 	pkey = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
1628 	if (pkey == NULL || (rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
1629 		al = SSL_AD_HANDSHAKE_FAILURE;
1630 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1631 		goto fatal_err;
1632 	}
1633 
1634 	pms_len = RSA_size(rsa);
1635 	if (pms_len < SSL_MAX_MASTER_KEY_LENGTH)
1636 		goto err;
1637 	if ((pms = malloc(pms_len)) == NULL)
1638 		goto err;
1639 	p = pms;
1640 
1641 	if (!CBS_get_u16_length_prefixed(cbs, &enc_pms))
1642 		goto decode_err;
1643 	if (CBS_len(cbs) != 0 || CBS_len(&enc_pms) != RSA_size(rsa)) {
1644 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1645 		goto err;
1646 	}
1647 
1648 	decrypt_len = RSA_private_decrypt(CBS_len(&enc_pms), CBS_data(&enc_pms),
1649 	    pms, rsa, RSA_PKCS1_PADDING);
1650 
1651 	ERR_clear_error();
1652 
1653 	if (decrypt_len != SSL_MAX_MASTER_KEY_LENGTH) {
1654 		al = SSL_AD_DECODE_ERROR;
1655 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1656 	}
1657 
1658 	if ((al == -1) && !((pms[0] == (s->s3->hs.peer_legacy_version >> 8)) &&
1659 	    (pms[1] == (s->s3->hs.peer_legacy_version & 0xff)))) {
1660 		/*
1661 		 * The premaster secret must contain the same version number
1662 		 * as the ClientHello to detect version rollback attacks
1663 		 * (strangely, the protocol does not offer such protection for
1664 		 * DH ciphersuites).
1665 		 *
1666 		 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1667 		 * (http://eprint.iacr.org/2003/052/) exploits the version
1668 		 * number check as a "bad version oracle" -- an alert would
1669 		 * reveal that the plaintext corresponding to some ciphertext
1670 		 * made up by the adversary is properly formatted except that
1671 		 * the version number is wrong. To avoid such attacks, we should
1672 		 * treat this just like any other decryption error.
1673 		 */
1674 		al = SSL_AD_DECODE_ERROR;
1675 		/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1676 	}
1677 
1678 	if (al != -1) {
1679 		/*
1680 		 * Some decryption failure -- use random value instead
1681 		 * as countermeasure against Bleichenbacher's attack
1682 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1683 		 * section 7.4.7.1).
1684 		 */
1685 		p = fakekey;
1686 	}
1687 
1688 	if (!tls12_derive_master_secret(s, p, SSL_MAX_MASTER_KEY_LENGTH))
1689 		goto err;
1690 
1691 	freezero(pms, pms_len);
1692 
1693 	return 1;
1694 
1695  decode_err:
1696 	al = SSL_AD_DECODE_ERROR;
1697 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1698  fatal_err:
1699 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1700  err:
1701 	freezero(pms, pms_len);
1702 
1703 	return 0;
1704 }
1705 
1706 static int
1707 ssl3_get_client_kex_dhe(SSL *s, CBS *cbs)
1708 {
1709 	uint8_t *key = NULL;
1710 	size_t key_len = 0;
1711 	int decode_error, invalid_key;
1712 	int ret = 0;
1713 
1714 	if (s->s3->hs.key_share == NULL) {
1715 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1716 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1717 		goto err;
1718 	}
1719 
1720 	if (!tls_key_share_peer_public(s->s3->hs.key_share, cbs,
1721 	    &decode_error, &invalid_key)) {
1722 		if (decode_error) {
1723 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1724 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1725 		}
1726 		goto err;
1727 	}
1728 	if (invalid_key) {
1729 		SSLerror(s, SSL_R_BAD_DH_PUB_KEY_LENGTH);
1730 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
1731 		goto err;
1732 	}
1733 
1734 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1735 		goto err;
1736 
1737 	if (!tls12_derive_master_secret(s, key, key_len))
1738 		goto err;
1739 
1740 	ret = 1;
1741 
1742  err:
1743 	freezero(key, key_len);
1744 
1745 	return ret;
1746 }
1747 
1748 static int
1749 ssl3_get_client_kex_ecdhe(SSL *s, CBS *cbs)
1750 {
1751 	uint8_t *key = NULL;
1752 	size_t key_len = 0;
1753 	int decode_error;
1754 	CBS public;
1755 	int ret = 0;
1756 
1757 	if (s->s3->hs.key_share == NULL) {
1758 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1759 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1760 		goto err;
1761 	}
1762 
1763 	if (!CBS_get_u8_length_prefixed(cbs, &public)) {
1764 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1765 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1766 		goto err;
1767 	}
1768 	if (!tls_key_share_peer_public(s->s3->hs.key_share, &public,
1769 	    &decode_error, NULL)) {
1770 		if (decode_error) {
1771 			SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1772 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1773 		}
1774 		goto err;
1775 	}
1776 
1777 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1778 		goto err;
1779 
1780 	if (!tls12_derive_master_secret(s, key, key_len))
1781 		goto err;
1782 
1783 	ret = 1;
1784 
1785  err:
1786 	freezero(key, key_len);
1787 
1788 	return ret;
1789 }
1790 
1791 static int
1792 ssl3_get_client_kex_gost(SSL *s, CBS *cbs)
1793 {
1794 	unsigned char premaster_secret[32];
1795 	EVP_PKEY_CTX *pkey_ctx = NULL;
1796 	EVP_PKEY *client_pubkey;
1797 	EVP_PKEY *pkey = NULL;
1798 	size_t outlen;
1799 	CBS gostblob;
1800 
1801 	/* Get our certificate private key*/
1802 	if ((s->s3->hs.cipher->algorithm_auth & SSL_aGOST01) != 0)
1803 		pkey = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
1804 
1805 	if ((pkey_ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL)
1806 		goto err;
1807 	if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0)
1808 		goto err;
1809 
1810 	/*
1811 	 * If client certificate is present and is of the same type,
1812 	 * maybe use it for key exchange.
1813 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
1814 	 * it is completely valid to use a client certificate for
1815 	 * authorization only.
1816 	 */
1817 	if ((client_pubkey = X509_get0_pubkey(s->session->peer_cert)) != NULL) {
1818 		if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pubkey) <= 0)
1819 			ERR_clear_error();
1820 	}
1821 
1822 	/* Decrypt session key */
1823 	if (!CBS_get_asn1(cbs, &gostblob, CBS_ASN1_SEQUENCE))
1824 		goto decode_err;
1825 	if (CBS_len(cbs) != 0)
1826 		goto decode_err;
1827 	outlen = sizeof(premaster_secret);
1828 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
1829 	    CBS_data(&gostblob), CBS_len(&gostblob)) <= 0) {
1830 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
1831 		goto err;
1832 	}
1833 
1834 	if (!tls12_derive_master_secret(s, premaster_secret,
1835 	    sizeof(premaster_secret)))
1836 		goto err;
1837 
1838 	/* Check if pubkey from client certificate was used */
1839 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY,
1840 	    2, NULL) > 0)
1841 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
1842 
1843 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1844 	EVP_PKEY_CTX_free(pkey_ctx);
1845 
1846 	return 1;
1847 
1848  decode_err:
1849 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1850 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1851  err:
1852 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
1853 	EVP_PKEY_CTX_free(pkey_ctx);
1854 
1855 	return 0;
1856 }
1857 
1858 int
1859 ssl3_get_client_key_exchange(SSL *s)
1860 {
1861 	unsigned long alg_k;
1862 	int al, ret;
1863 	CBS cbs;
1864 
1865 	/* 2048 maxlen is a guess.  How long a key does that permit? */
1866 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
1867 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048)) <= 0)
1868 		return ret;
1869 
1870 	if (s->internal->init_num < 0)
1871 		goto err;
1872 
1873 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
1874 
1875 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1876 
1877 	if (alg_k & SSL_kRSA) {
1878 		if (!ssl3_get_client_kex_rsa(s, &cbs))
1879 			goto err;
1880 	} else if (alg_k & SSL_kDHE) {
1881 		if (!ssl3_get_client_kex_dhe(s, &cbs))
1882 			goto err;
1883 	} else if (alg_k & SSL_kECDHE) {
1884 		if (!ssl3_get_client_kex_ecdhe(s, &cbs))
1885 			goto err;
1886 	} else if (alg_k & SSL_kGOST) {
1887 		if (!ssl3_get_client_kex_gost(s, &cbs))
1888 			goto err;
1889 	} else {
1890 		al = SSL_AD_HANDSHAKE_FAILURE;
1891 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
1892 		goto fatal_err;
1893 	}
1894 
1895 	if (CBS_len(&cbs) != 0) {
1896 		al = SSL_AD_DECODE_ERROR;
1897 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1898 		goto fatal_err;
1899 	}
1900 
1901 	return (1);
1902 
1903  fatal_err:
1904 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1905  err:
1906 	return (-1);
1907 }
1908 
1909 int
1910 ssl3_get_cert_verify(SSL *s)
1911 {
1912 	CBS cbs, signature;
1913 	const struct ssl_sigalg *sigalg = NULL;
1914 	uint16_t sigalg_value = SIGALG_NONE;
1915 	EVP_PKEY *pkey;
1916 	X509 *peer_cert = NULL;
1917 	EVP_MD_CTX *mctx = NULL;
1918 	int al, verify;
1919 	const unsigned char *hdata;
1920 	size_t hdatalen;
1921 	int type = 0;
1922 	int ret;
1923 
1924 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
1925 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH)) <= 0)
1926 		return ret;
1927 
1928 	ret = 0;
1929 
1930 	if (s->internal->init_num < 0)
1931 		goto err;
1932 
1933 	if ((mctx = EVP_MD_CTX_new()) == NULL)
1934 		goto err;
1935 
1936 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
1937 
1938 	peer_cert = s->session->peer_cert;
1939 	pkey = X509_get0_pubkey(peer_cert);
1940 	type = X509_certificate_type(peer_cert, pkey);
1941 
1942 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
1943 		s->s3->hs.tls12.reuse_message = 1;
1944 		if (peer_cert != NULL) {
1945 			al = SSL_AD_UNEXPECTED_MESSAGE;
1946 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
1947 			goto fatal_err;
1948 		}
1949 		ret = 1;
1950 		goto end;
1951 	}
1952 
1953 	if (peer_cert == NULL) {
1954 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
1955 		al = SSL_AD_UNEXPECTED_MESSAGE;
1956 		goto fatal_err;
1957 	}
1958 
1959 	if (!(type & EVP_PKT_SIGN)) {
1960 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
1961 		al = SSL_AD_ILLEGAL_PARAMETER;
1962 		goto fatal_err;
1963 	}
1964 
1965 	if (s->s3->change_cipher_spec) {
1966 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
1967 		al = SSL_AD_UNEXPECTED_MESSAGE;
1968 		goto fatal_err;
1969 	}
1970 
1971 	if (SSL_USE_SIGALGS(s)) {
1972 		if (!CBS_get_u16(&cbs, &sigalg_value))
1973 			goto decode_err;
1974 	}
1975 	if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1976 		goto err;
1977 	if (CBS_len(&cbs) != 0) {
1978 		al = SSL_AD_DECODE_ERROR;
1979 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1980 		goto fatal_err;
1981 	}
1982 
1983 	if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1984 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
1985 		al = SSL_AD_DECODE_ERROR;
1986 		goto fatal_err;
1987 	}
1988 
1989 	if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1990 	    sigalg_value)) == NULL) {
1991 		al = SSL_AD_DECODE_ERROR;
1992 		goto fatal_err;
1993 	}
1994 	s->s3->hs.peer_sigalg = sigalg;
1995 
1996 	if (SSL_USE_SIGALGS(s)) {
1997 		EVP_PKEY_CTX *pctx;
1998 
1999 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2000 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2001 			al = SSL_AD_INTERNAL_ERROR;
2002 			goto fatal_err;
2003 		}
2004 		if (!EVP_DigestVerifyInit(mctx, &pctx, sigalg->md(),
2005 		    NULL, pkey)) {
2006 			SSLerror(s, ERR_R_EVP_LIB);
2007 			al = SSL_AD_INTERNAL_ERROR;
2008 			goto fatal_err;
2009 		}
2010 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2011 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
2012 			RSA_PKCS1_PSS_PADDING) ||
2013 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2014 			al = SSL_AD_INTERNAL_ERROR;
2015 			goto fatal_err;
2016 		}
2017 		if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2018 		    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2019 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE,
2020 		    NULL) <= 0) {
2021 			al = SSL_AD_INTERNAL_ERROR;
2022 			goto fatal_err;
2023 		}
2024 		if (!EVP_DigestVerifyUpdate(mctx, hdata, hdatalen)) {
2025 			SSLerror(s, ERR_R_EVP_LIB);
2026 			al = SSL_AD_INTERNAL_ERROR;
2027 			goto fatal_err;
2028 		}
2029 		if (EVP_DigestVerifyFinal(mctx, CBS_data(&signature),
2030 		    CBS_len(&signature)) <= 0) {
2031 			al = SSL_AD_DECRYPT_ERROR;
2032 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2033 			goto fatal_err;
2034 		}
2035 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
2036 		RSA *rsa;
2037 
2038 		if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
2039 			al = SSL_AD_INTERNAL_ERROR;
2040 			SSLerror(s, ERR_R_EVP_LIB);
2041 			goto fatal_err;
2042 		}
2043 		verify = RSA_verify(NID_md5_sha1, s->s3->hs.tls12.cert_verify,
2044 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, CBS_data(&signature),
2045 		    CBS_len(&signature), rsa);
2046 		if (verify < 0) {
2047 			al = SSL_AD_DECRYPT_ERROR;
2048 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2049 			goto fatal_err;
2050 		}
2051 		if (verify == 0) {
2052 			al = SSL_AD_DECRYPT_ERROR;
2053 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2054 			goto fatal_err;
2055 		}
2056 	} else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
2057 		EC_KEY *eckey;
2058 
2059 		if ((eckey = EVP_PKEY_get0_EC_KEY(pkey)) == NULL) {
2060 			al = SSL_AD_INTERNAL_ERROR;
2061 			SSLerror(s, ERR_R_EVP_LIB);
2062 			goto fatal_err;
2063 		}
2064 		verify = ECDSA_verify(0,
2065 		    &(s->s3->hs.tls12.cert_verify[MD5_DIGEST_LENGTH]),
2066 		    SHA_DIGEST_LENGTH, CBS_data(&signature),
2067 		    CBS_len(&signature), eckey);
2068 		if (verify <= 0) {
2069 			al = SSL_AD_DECRYPT_ERROR;
2070 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2071 			goto fatal_err;
2072 		}
2073 #ifndef OPENSSL_NO_GOST
2074 	} else if (EVP_PKEY_id(pkey) == NID_id_GostR3410_94 ||
2075 	    EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2076 		unsigned char sigbuf[128];
2077 		unsigned int siglen = sizeof(sigbuf);
2078 		EVP_PKEY_CTX *pctx;
2079 		const EVP_MD *md;
2080 		int nid;
2081 
2082 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2083 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2084 			al = SSL_AD_INTERNAL_ERROR;
2085 			goto fatal_err;
2086 		}
2087 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2088 		    !(md = EVP_get_digestbynid(nid))) {
2089 			SSLerror(s, ERR_R_EVP_LIB);
2090 			al = SSL_AD_INTERNAL_ERROR;
2091 			goto fatal_err;
2092 		}
2093 		if ((pctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
2094 			SSLerror(s, ERR_R_EVP_LIB);
2095 			al = SSL_AD_INTERNAL_ERROR;
2096 			goto fatal_err;
2097 		}
2098 		if (!EVP_DigestInit_ex(mctx, md, NULL) ||
2099 		    !EVP_DigestUpdate(mctx, hdata, hdatalen) ||
2100 		    !EVP_DigestFinal(mctx, sigbuf, &siglen) ||
2101 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2102 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2103 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2104 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2105 		    GOST_SIG_FORMAT_RS_LE, NULL) <= 0)) {
2106 			SSLerror(s, ERR_R_EVP_LIB);
2107 			al = SSL_AD_INTERNAL_ERROR;
2108 			EVP_PKEY_CTX_free(pctx);
2109 			goto fatal_err;
2110 		}
2111 		if (EVP_PKEY_verify(pctx, CBS_data(&signature),
2112 		    CBS_len(&signature), sigbuf, siglen) <= 0) {
2113 			al = SSL_AD_DECRYPT_ERROR;
2114 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2115 			EVP_PKEY_CTX_free(pctx);
2116 			goto fatal_err;
2117 		}
2118 
2119 		EVP_PKEY_CTX_free(pctx);
2120 #endif
2121 	} else {
2122 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2123 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2124 		goto fatal_err;
2125 	}
2126 
2127 	ret = 1;
2128 	if (0) {
2129  decode_err:
2130 		al = SSL_AD_DECODE_ERROR;
2131 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2132  fatal_err:
2133 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2134 	}
2135  end:
2136 	tls1_transcript_free(s);
2137  err:
2138 	EVP_MD_CTX_free(mctx);
2139 
2140 	return (ret);
2141 }
2142 
2143 int
2144 ssl3_get_client_certificate(SSL *s)
2145 {
2146 	CBS cbs, client_certs;
2147 	X509 *x = NULL;
2148 	const unsigned char *q;
2149 	STACK_OF(X509) *sk = NULL;
2150 	int i, al, ret;
2151 
2152 	if ((ret = ssl3_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2153 	    -1, s->internal->max_cert_list)) <= 0)
2154 		return ret;
2155 
2156 	ret = -1;
2157 
2158 	if (s->s3->hs.tls12.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2159 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2160 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2161 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2162 			al = SSL_AD_HANDSHAKE_FAILURE;
2163 			goto fatal_err;
2164 		}
2165 		/*
2166 		 * If tls asked for a client cert,
2167 		 * the client must return a 0 list.
2168 		 */
2169 		if (s->s3->hs.tls12.cert_request) {
2170 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2171 			    );
2172 			al = SSL_AD_UNEXPECTED_MESSAGE;
2173 			goto fatal_err;
2174 		}
2175 		s->s3->hs.tls12.reuse_message = 1;
2176 		return (1);
2177 	}
2178 
2179 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
2180 		al = SSL_AD_UNEXPECTED_MESSAGE;
2181 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2182 		goto fatal_err;
2183 	}
2184 
2185 	if (s->internal->init_num < 0)
2186 		goto decode_err;
2187 
2188 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
2189 
2190 	if ((sk = sk_X509_new_null()) == NULL) {
2191 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2192 		goto err;
2193 	}
2194 
2195 	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2196 	    CBS_len(&cbs) != 0)
2197 		goto decode_err;
2198 
2199 	while (CBS_len(&client_certs) > 0) {
2200 		CBS cert;
2201 
2202 		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2203 			al = SSL_AD_DECODE_ERROR;
2204 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2205 			goto fatal_err;
2206 		}
2207 
2208 		q = CBS_data(&cert);
2209 		x = d2i_X509(NULL, &q, CBS_len(&cert));
2210 		if (x == NULL) {
2211 			SSLerror(s, ERR_R_ASN1_LIB);
2212 			goto err;
2213 		}
2214 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2215 			al = SSL_AD_DECODE_ERROR;
2216 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2217 			goto fatal_err;
2218 		}
2219 		if (!sk_X509_push(sk, x)) {
2220 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2221 			goto err;
2222 		}
2223 		x = NULL;
2224 	}
2225 
2226 	if (sk_X509_num(sk) <= 0) {
2227 		/*
2228 		 * TLS does not mind 0 certs returned.
2229 		 * Fail for TLS only if we required a certificate.
2230 		 */
2231 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2232 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2233 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2234 			al = SSL_AD_HANDSHAKE_FAILURE;
2235 			goto fatal_err;
2236 		}
2237 		/* No client certificate so free transcript. */
2238 		tls1_transcript_free(s);
2239 	} else {
2240 		i = ssl_verify_cert_chain(s, sk);
2241 		if (i <= 0) {
2242 			al = ssl_verify_alarm_type(s->verify_result);
2243 			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2244 			goto fatal_err;
2245 		}
2246 	}
2247 
2248 	X509_free(s->session->peer_cert);
2249 	s->session->peer_cert = sk_X509_shift(sk);
2250 
2251 	/*
2252 	 * Inconsistency alert: cert_chain does *not* include the
2253 	 * peer's own certificate, while we do include it in s3_clnt.c
2254 	 */
2255 	sk_X509_pop_free(s->session->cert_chain, X509_free);
2256 	s->session->cert_chain = sk;
2257 	sk = NULL;
2258 
2259 	s->session->verify_result = s->verify_result;
2260 
2261 	ret = 1;
2262 	if (0) {
2263  decode_err:
2264 		al = SSL_AD_DECODE_ERROR;
2265 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2266  fatal_err:
2267 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2268 	}
2269  err:
2270 	X509_free(x);
2271 	sk_X509_pop_free(sk, X509_free);
2272 
2273 	return (ret);
2274 }
2275 
2276 int
2277 ssl3_send_server_certificate(SSL *s)
2278 {
2279 	CBB cbb, server_cert;
2280 	SSL_CERT_PKEY *cpk;
2281 
2282 	/*
2283 	 * Server Certificate - RFC 5246, section 7.4.2.
2284 	 */
2285 
2286 	memset(&cbb, 0, sizeof(cbb));
2287 
2288 	if (s->s3->hs.state == SSL3_ST_SW_CERT_A) {
2289 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL) {
2290 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2291 			return (0);
2292 		}
2293 
2294 		if (!ssl3_handshake_msg_start(s, &cbb, &server_cert,
2295 		    SSL3_MT_CERTIFICATE))
2296 			goto err;
2297 		if (!ssl3_output_cert_chain(s, &server_cert, cpk))
2298 			goto err;
2299 		if (!ssl3_handshake_msg_finish(s, &cbb))
2300 			goto err;
2301 
2302 		s->s3->hs.state = SSL3_ST_SW_CERT_B;
2303 	}
2304 
2305 	/* SSL3_ST_SW_CERT_B */
2306 	return (ssl3_handshake_write(s));
2307 
2308  err:
2309 	CBB_cleanup(&cbb);
2310 
2311 	return (0);
2312 }
2313 
2314 /* send a new session ticket (not necessarily for a new session) */
2315 int
2316 ssl3_send_newsession_ticket(SSL *s)
2317 {
2318 	CBB cbb, session_ticket, ticket;
2319 	SSL_CTX *tctx = s->initial_ctx;
2320 	size_t enc_session_len, enc_session_max_len, hmac_len;
2321 	size_t session_len = 0;
2322 	unsigned char *enc_session = NULL, *session = NULL;
2323 	unsigned char iv[EVP_MAX_IV_LENGTH];
2324 	unsigned char key_name[16];
2325 	unsigned char *hmac;
2326 	unsigned int hlen;
2327 	EVP_CIPHER_CTX *ctx = NULL;
2328 	HMAC_CTX *hctx = NULL;
2329 	int len;
2330 
2331 	/*
2332 	 * New Session Ticket - RFC 5077, section 3.3.
2333 	 */
2334 
2335 	memset(&cbb, 0, sizeof(cbb));
2336 
2337 	if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
2338 		goto err;
2339 	if ((hctx = HMAC_CTX_new()) == NULL)
2340 		goto err;
2341 
2342 	if (s->s3->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2343 		if (!ssl3_handshake_msg_start(s, &cbb, &session_ticket,
2344 		    SSL3_MT_NEWSESSION_TICKET))
2345 			goto err;
2346 
2347 		if (!SSL_SESSION_ticket(s->session, &session, &session_len))
2348 			goto err;
2349 		if (session_len > 0xffff)
2350 			goto err;
2351 
2352 		/*
2353 		 * Initialize HMAC and cipher contexts. If callback is present
2354 		 * it does all the work, otherwise use generated values from
2355 		 * parent context.
2356 		 */
2357 		if (tctx->internal->tlsext_ticket_key_cb != NULL) {
2358 			if (tctx->internal->tlsext_ticket_key_cb(s,
2359 			    key_name, iv, ctx, hctx, 1) < 0)
2360 				goto err;
2361 		} else {
2362 			arc4random_buf(iv, 16);
2363 			EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL,
2364 			    tctx->internal->tlsext_tick_aes_key, iv);
2365 			HMAC_Init_ex(hctx, tctx->internal->tlsext_tick_hmac_key,
2366 			    16, EVP_sha256(), NULL);
2367 			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2368 		}
2369 
2370 		/* Encrypt the session state. */
2371 		enc_session_max_len = session_len + EVP_MAX_BLOCK_LENGTH;
2372 		if ((enc_session = calloc(1, enc_session_max_len)) == NULL)
2373 			goto err;
2374 		enc_session_len = 0;
2375 		if (!EVP_EncryptUpdate(ctx, enc_session, &len, session,
2376 		    session_len))
2377 			goto err;
2378 		enc_session_len += len;
2379 		if (!EVP_EncryptFinal_ex(ctx, enc_session + enc_session_len,
2380 		    &len))
2381 			goto err;
2382 		enc_session_len += len;
2383 
2384 		if (enc_session_len > enc_session_max_len)
2385 			goto err;
2386 
2387 		/* Generate the HMAC. */
2388 		if (!HMAC_Update(hctx, key_name, sizeof(key_name)))
2389 			goto err;
2390 		if (!HMAC_Update(hctx, iv, EVP_CIPHER_CTX_iv_length(ctx)))
2391 			goto err;
2392 		if (!HMAC_Update(hctx, enc_session, enc_session_len))
2393 			goto err;
2394 
2395 		if ((hmac_len = HMAC_size(hctx)) <= 0)
2396 			goto err;
2397 
2398 		/*
2399 		 * Ticket lifetime hint (advisory only):
2400 		 * We leave this unspecified for resumed session
2401 		 * (for simplicity), and guess that tickets for new
2402 		 * sessions will live as long as their sessions.
2403 		 */
2404 		if (!CBB_add_u32(&session_ticket,
2405 		    s->internal->hit ? 0 : s->session->timeout))
2406 			goto err;
2407 
2408 		if (!CBB_add_u16_length_prefixed(&session_ticket, &ticket))
2409 			goto err;
2410 		if (!CBB_add_bytes(&ticket, key_name, sizeof(key_name)))
2411 			goto err;
2412 		if (!CBB_add_bytes(&ticket, iv, EVP_CIPHER_CTX_iv_length(ctx)))
2413 			goto err;
2414 		if (!CBB_add_bytes(&ticket, enc_session, enc_session_len))
2415 			goto err;
2416 		if (!CBB_add_space(&ticket, &hmac, hmac_len))
2417 			goto err;
2418 
2419 		if (!HMAC_Final(hctx, hmac, &hlen))
2420 			goto err;
2421 		if (hlen != hmac_len)
2422 			goto err;
2423 
2424 		if (!ssl3_handshake_msg_finish(s, &cbb))
2425 			goto err;
2426 
2427 		s->s3->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2428 	}
2429 
2430 	EVP_CIPHER_CTX_free(ctx);
2431 	HMAC_CTX_free(hctx);
2432 	freezero(session, session_len);
2433 	free(enc_session);
2434 
2435 	/* SSL3_ST_SW_SESSION_TICKET_B */
2436 	return (ssl3_handshake_write(s));
2437 
2438  err:
2439 	CBB_cleanup(&cbb);
2440 	EVP_CIPHER_CTX_free(ctx);
2441 	HMAC_CTX_free(hctx);
2442 	freezero(session, session_len);
2443 	free(enc_session);
2444 
2445 	return (-1);
2446 }
2447 
2448 int
2449 ssl3_send_cert_status(SSL *s)
2450 {
2451 	CBB cbb, certstatus, ocspresp;
2452 
2453 	memset(&cbb, 0, sizeof(cbb));
2454 
2455 	if (s->s3->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2456 		if (!ssl3_handshake_msg_start(s, &cbb, &certstatus,
2457 		    SSL3_MT_CERTIFICATE_STATUS))
2458 			goto err;
2459 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2460 			goto err;
2461 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2462 			goto err;
2463 		if (!CBB_add_bytes(&ocspresp, s->internal->tlsext_ocsp_resp,
2464 		    s->internal->tlsext_ocsp_resp_len))
2465 			goto err;
2466 		if (!ssl3_handshake_msg_finish(s, &cbb))
2467 			goto err;
2468 
2469 		s->s3->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2470 	}
2471 
2472 	/* SSL3_ST_SW_CERT_STATUS_B */
2473 	return (ssl3_handshake_write(s));
2474 
2475  err:
2476 	CBB_cleanup(&cbb);
2477 
2478 	return (-1);
2479 }
2480