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