xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /* $OpenBSD: ssl_srvr.c,v 1.117 2021/06/29 19:43:15 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 			S3I(s)->hs.our_sigalg = sigalg;
1569 
1570 			/* Send signature algorithm. */
1571 			if (SSL_USE_SIGALGS(s)) {
1572 				if (!CBB_add_u16(&server_kex, sigalg->value)) {
1573 					al = SSL_AD_INTERNAL_ERROR;
1574 					SSLerror(s, ERR_R_INTERNAL_ERROR);
1575 					goto fatal_err;
1576 				}
1577 			}
1578 
1579 			if (!EVP_DigestSignInit(&md_ctx, &pctx, md, NULL, pkey)) {
1580 				SSLerror(s, ERR_R_EVP_LIB);
1581 				goto err;
1582 			}
1583 			if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1584 			    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1585 			    RSA_PKCS1_PSS_PADDING) ||
1586 			    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
1587 				SSLerror(s, ERR_R_EVP_LIB);
1588 				goto err;
1589 			}
1590 			if (!EVP_DigestSignUpdate(&md_ctx, s->s3->client_random,
1591 			    SSL3_RANDOM_SIZE)) {
1592 				SSLerror(s, ERR_R_EVP_LIB);
1593 				goto err;
1594 			}
1595 			if (!EVP_DigestSignUpdate(&md_ctx, s->s3->server_random,
1596 			    SSL3_RANDOM_SIZE)) {
1597 				SSLerror(s, ERR_R_EVP_LIB);
1598 				goto err;
1599 			}
1600 			if (!EVP_DigestSignUpdate(&md_ctx, params, params_len)) {
1601 				SSLerror(s, ERR_R_EVP_LIB);
1602 				goto err;
1603 			}
1604 			if (!EVP_DigestSignFinal(&md_ctx, NULL, &signature_len) ||
1605 			    !signature_len) {
1606 				SSLerror(s, ERR_R_EVP_LIB);
1607 				goto err;
1608 			}
1609 			if ((signature = calloc(1, signature_len)) == NULL) {
1610 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1611 				goto err;
1612 			}
1613 			if (!EVP_DigestSignFinal(&md_ctx, signature, &signature_len)) {
1614 				SSLerror(s, ERR_R_EVP_LIB);
1615 				goto err;
1616 			}
1617 
1618 			if (!CBB_add_u16_length_prefixed(&server_kex,
1619 			    &cbb_signature))
1620 				goto err;
1621 			if (!CBB_add_bytes(&cbb_signature, signature,
1622 			    signature_len))
1623 				goto err;
1624 		}
1625 
1626 		if (!ssl3_handshake_msg_finish(s, &cbb))
1627 			goto err;
1628 
1629 		S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1630 	}
1631 
1632 	EVP_MD_CTX_cleanup(&md_ctx);
1633 	free(params);
1634 	free(signature);
1635 
1636 	return (ssl3_handshake_write(s));
1637 
1638  fatal_err:
1639 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1640  err:
1641 	CBB_cleanup(&cbb_params);
1642 	CBB_cleanup(&cbb);
1643 	EVP_MD_CTX_cleanup(&md_ctx);
1644 	free(params);
1645 	free(signature);
1646 
1647 	return (-1);
1648 }
1649 
1650 int
1651 ssl3_send_certificate_request(SSL *s)
1652 {
1653 	CBB cbb, cert_request, cert_types, sigalgs, cert_auth, dn;
1654 	STACK_OF(X509_NAME) *sk = NULL;
1655 	X509_NAME *name;
1656 	int i;
1657 
1658 	/*
1659 	 * Certificate Request - RFC 5246 section 7.4.4.
1660 	 */
1661 
1662 	memset(&cbb, 0, sizeof(cbb));
1663 
1664 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1665 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_request,
1666 		    SSL3_MT_CERTIFICATE_REQUEST))
1667 			goto err;
1668 
1669 		if (!CBB_add_u8_length_prefixed(&cert_request, &cert_types))
1670 			goto err;
1671 		if (!ssl3_get_req_cert_types(s, &cert_types))
1672 			goto err;
1673 
1674 		if (SSL_USE_SIGALGS(s)) {
1675 			if (!CBB_add_u16_length_prefixed(&cert_request,
1676 			    &sigalgs))
1677 				goto err;
1678 			if (!ssl_sigalgs_build(
1679 			    S3I(s)->hs.negotiated_tls_version, &sigalgs))
1680 				goto err;
1681 		}
1682 
1683 		if (!CBB_add_u16_length_prefixed(&cert_request, &cert_auth))
1684 			goto err;
1685 
1686 		sk = SSL_get_client_CA_list(s);
1687 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1688 			unsigned char *name_data;
1689 			size_t name_len;
1690 
1691 			name = sk_X509_NAME_value(sk, i);
1692 			name_len = i2d_X509_NAME(name, NULL);
1693 
1694 			if (!CBB_add_u16_length_prefixed(&cert_auth, &dn))
1695 				goto err;
1696 			if (!CBB_add_space(&dn, &name_data, name_len))
1697 				goto err;
1698 			if (i2d_X509_NAME(name, &name_data) != name_len)
1699 				goto err;
1700 		}
1701 
1702 		if (!ssl3_handshake_msg_finish(s, &cbb))
1703 			goto err;
1704 
1705 		S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_B;
1706 	}
1707 
1708 	/* SSL3_ST_SW_CERT_REQ_B */
1709 	return (ssl3_handshake_write(s));
1710 
1711  err:
1712 	CBB_cleanup(&cbb);
1713 
1714 	return (-1);
1715 }
1716 
1717 static int
1718 ssl3_get_client_kex_rsa(SSL *s, CBS *cbs)
1719 {
1720 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1721 	unsigned char *pms = NULL;
1722 	unsigned char *p;
1723 	size_t pms_len = 0;
1724 	EVP_PKEY *pkey = NULL;
1725 	RSA *rsa = NULL;
1726 	CBS enc_pms;
1727 	int decrypt_len;
1728 	int al = -1;
1729 
1730 	arc4random_buf(fakekey, sizeof(fakekey));
1731 
1732 	/* XXX - peer max protocol version. */
1733 	fakekey[0] = s->client_version >> 8;
1734 	fakekey[1] = s->client_version & 0xff;
1735 
1736 	pkey = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
1737 	if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1738 	    (pkey->pkey.rsa == NULL)) {
1739 		al = SSL_AD_HANDSHAKE_FAILURE;
1740 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1741 		goto fatal_err;
1742 	}
1743 	rsa = pkey->pkey.rsa;
1744 
1745 	pms_len = RSA_size(rsa);
1746 	if (pms_len < SSL_MAX_MASTER_KEY_LENGTH)
1747 		goto err;
1748 	if ((pms = malloc(pms_len)) == NULL)
1749 		goto err;
1750 	p = pms;
1751 
1752 	if (!CBS_get_u16_length_prefixed(cbs, &enc_pms))
1753 		goto decode_err;
1754 	if (CBS_len(cbs) != 0 || CBS_len(&enc_pms) != RSA_size(rsa)) {
1755 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1756 		goto err;
1757 	}
1758 
1759 	decrypt_len = RSA_private_decrypt(CBS_len(&enc_pms), CBS_data(&enc_pms),
1760 	    pms, rsa, RSA_PKCS1_PADDING);
1761 
1762 	ERR_clear_error();
1763 
1764 	if (decrypt_len != SSL_MAX_MASTER_KEY_LENGTH) {
1765 		al = SSL_AD_DECODE_ERROR;
1766 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1767 	}
1768 
1769 	/* XXX - peer max version. */
1770 	if ((al == -1) && !((pms[0] == (s->client_version >> 8)) &&
1771 	    (pms[1] == (s->client_version & 0xff)))) {
1772 		/*
1773 		 * The premaster secret must contain the same version number
1774 		 * as the ClientHello to detect version rollback attacks
1775 		 * (strangely, the protocol does not offer such protection for
1776 		 * DH ciphersuites).
1777 		 *
1778 		 * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1779 		 * (http://eprint.iacr.org/2003/052/) exploits the version
1780 		 * number check as a "bad version oracle" -- an alert would
1781 		 * reveal that the plaintext corresponding to some ciphertext
1782 		 * made up by the adversary is properly formatted except that
1783 		 * the version number is wrong. To avoid such attacks, we should
1784 		 * treat this just like any other decryption error.
1785 		 */
1786 		al = SSL_AD_DECODE_ERROR;
1787 		/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1788 	}
1789 
1790 	if (al != -1) {
1791 		/*
1792 		 * Some decryption failure -- use random value instead
1793 		 * as countermeasure against Bleichenbacher's attack
1794 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1795 		 * section 7.4.7.1).
1796 		 */
1797 		p = fakekey;
1798 	}
1799 
1800 	if (!tls12_derive_master_secret(s, p, SSL_MAX_MASTER_KEY_LENGTH))
1801 		goto err;
1802 
1803 	freezero(pms, pms_len);
1804 
1805 	return (1);
1806 
1807  decode_err:
1808 	al = SSL_AD_DECODE_ERROR;
1809 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1810  fatal_err:
1811 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1812  err:
1813 	freezero(pms, pms_len);
1814 
1815 	return (-1);
1816 }
1817 
1818 static int
1819 ssl3_get_client_kex_dhe(SSL *s, CBS *cbs)
1820 {
1821 	int key_size = 0;
1822 	int key_is_invalid, key_len, al;
1823 	unsigned char *key = NULL;
1824 	BIGNUM *bn = NULL;
1825 	CBS dh_Yc;
1826 	DH *dh;
1827 
1828 	if (!CBS_get_u16_length_prefixed(cbs, &dh_Yc))
1829 		goto decode_err;
1830 	if (CBS_len(cbs) != 0)
1831 		goto decode_err;
1832 
1833 	if (S3I(s)->tmp.dh == NULL) {
1834 		al = SSL_AD_HANDSHAKE_FAILURE;
1835 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1836 		goto fatal_err;
1837 	}
1838 	dh = S3I(s)->tmp.dh;
1839 
1840 	if ((bn = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL)) == NULL) {
1841 		SSLerror(s, SSL_R_BN_LIB);
1842 		goto err;
1843 	}
1844 
1845 	if ((key_size = DH_size(dh)) <= 0) {
1846 		SSLerror(s, ERR_R_DH_LIB);
1847 		goto err;
1848 	}
1849 	if ((key = malloc(key_size)) == NULL) {
1850 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1851 		goto err;
1852 	}
1853 	if (!DH_check_pub_key(dh, bn, &key_is_invalid)) {
1854 		al = SSL_AD_INTERNAL_ERROR;
1855 		SSLerror(s, ERR_R_DH_LIB);
1856 		goto fatal_err;
1857 	}
1858 	if (key_is_invalid) {
1859 		al = SSL_AD_ILLEGAL_PARAMETER;
1860 		SSLerror(s, ERR_R_DH_LIB);
1861 		goto fatal_err;
1862 	}
1863 	if ((key_len = DH_compute_key(key, bn, dh)) <= 0) {
1864 		al = SSL_AD_INTERNAL_ERROR;
1865 		SSLerror(s, ERR_R_DH_LIB);
1866 		goto fatal_err;
1867 	}
1868 
1869 	if (!tls12_derive_master_secret(s, key, key_len))
1870 		goto err;
1871 
1872 	DH_free(S3I(s)->tmp.dh);
1873 	S3I(s)->tmp.dh = NULL;
1874 
1875 	freezero(key, key_size);
1876 	BN_clear_free(bn);
1877 
1878 	return (1);
1879 
1880  decode_err:
1881 	al = SSL_AD_DECODE_ERROR;
1882 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1883  fatal_err:
1884 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1885  err:
1886 	freezero(key, key_size);
1887 	BN_clear_free(bn);
1888 
1889 	return (-1);
1890 }
1891 
1892 static int
1893 ssl3_get_client_kex_ecdhe_ecp(SSL *s, CBS *cbs)
1894 {
1895 	uint8_t *key = NULL;
1896 	size_t key_len = 0;
1897 	EC_KEY *ecdh_peer = NULL;
1898 	EC_KEY *ecdh;
1899 	CBS public;
1900 	int ret = -1;
1901 
1902 	/*
1903 	 * Use the ephemeral values we saved when generating the
1904 	 * ServerKeyExchange message.
1905 	 */
1906 	if ((ecdh = S3I(s)->tmp.ecdh) == NULL) {
1907 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1908 		goto err;
1909 	}
1910 
1911 	/*
1912 	 * Get client's public key from encoded point in the ClientKeyExchange
1913 	 * message.
1914 	 */
1915 	if (!CBS_get_u8_length_prefixed(cbs, &public))
1916 		goto err;
1917 	if (CBS_len(cbs) != 0)
1918 		goto err;
1919 
1920 	if ((ecdh_peer = EC_KEY_new()) == NULL)
1921 		goto err;
1922 
1923 	if (!ssl_kex_peer_public_ecdhe_ecp(ecdh_peer, S3I(s)->tmp.ecdh_nid,
1924 	    &public))
1925 		goto err;
1926 
1927 	/* Derive the shared secret and compute master secret. */
1928 	if (!ssl_kex_derive_ecdhe_ecp(ecdh, ecdh_peer, &key, &key_len))
1929 		goto err;
1930 	if (!tls12_derive_master_secret(s, key, key_len))
1931 		goto err;
1932 
1933 	EC_KEY_free(S3I(s)->tmp.ecdh);
1934 	S3I(s)->tmp.ecdh = NULL;
1935 	S3I(s)->tmp.ecdh_nid = NID_undef;
1936 
1937 	ret = 1;
1938 
1939  err:
1940 	freezero(key, key_len);
1941 	EC_KEY_free(ecdh_peer);
1942 
1943 	return (ret);
1944 }
1945 
1946 static int
1947 ssl3_get_client_kex_ecdhe_ecx(SSL *s, CBS *cbs)
1948 {
1949 	uint8_t *shared_key = NULL;
1950 	CBS ecpoint;
1951 	int ret = -1;
1952 
1953 	if (!CBS_get_u8_length_prefixed(cbs, &ecpoint))
1954 		goto err;
1955 	if (CBS_len(cbs) != 0)
1956 		goto err;
1957 	if (CBS_len(&ecpoint) != X25519_KEY_LENGTH)
1958 		goto err;
1959 
1960 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
1961 		goto err;
1962 	if (!X25519(shared_key, S3I(s)->tmp.x25519, CBS_data(&ecpoint)))
1963 		goto err;
1964 
1965 	freezero(S3I(s)->tmp.x25519, X25519_KEY_LENGTH);
1966 	S3I(s)->tmp.x25519 = NULL;
1967 
1968 	if (!tls12_derive_master_secret(s, shared_key, X25519_KEY_LENGTH))
1969 		goto err;
1970 
1971 	ret = 1;
1972 
1973  err:
1974 	freezero(shared_key, X25519_KEY_LENGTH);
1975 
1976 	return (ret);
1977 }
1978 
1979 static int
1980 ssl3_get_client_kex_ecdhe(SSL *s, CBS *cbs)
1981 {
1982 	if (S3I(s)->tmp.x25519 != NULL)
1983 		return ssl3_get_client_kex_ecdhe_ecx(s, cbs);
1984 
1985 	return ssl3_get_client_kex_ecdhe_ecp(s, cbs);
1986 }
1987 
1988 static int
1989 ssl3_get_client_kex_gost(SSL *s, CBS *cbs)
1990 {
1991 	EVP_PKEY_CTX *pkey_ctx;
1992 	EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
1993 	unsigned char premaster_secret[32];
1994 	unsigned long alg_a;
1995 	size_t outlen = 32;
1996 	CBS gostblob;
1997 	int al;
1998 	int ret = 0;
1999 
2000 	/* Get our certificate private key*/
2001 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
2002 	if (alg_a & SSL_aGOST01)
2003 		pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2004 
2005 	if ((pkey_ctx = EVP_PKEY_CTX_new(pk, NULL)) == NULL)
2006 		goto err;
2007 	if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0)
2008 		goto gerr;
2009 
2010 	/*
2011 	 * If client certificate is present and is of the same type,
2012 	 * maybe use it for key exchange.
2013 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
2014 	 * it is completely valid to use a client certificate for
2015 	 * authorization only.
2016 	 */
2017 	if ((client_pub_pkey = X509_get_pubkey(s->session->peer)) != NULL) {
2018 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2019 		    client_pub_pkey) <= 0)
2020 			ERR_clear_error();
2021 	}
2022 
2023 	/* Decrypt session key */
2024 	if (!CBS_get_asn1(cbs, &gostblob, CBS_ASN1_SEQUENCE))
2025 		goto decode_err;
2026 	if (CBS_len(cbs) != 0)
2027 		goto decode_err;
2028 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
2029 	    CBS_data(&gostblob), CBS_len(&gostblob)) <= 0) {
2030 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2031 		goto gerr;
2032 	}
2033 
2034 	if (!tls12_derive_master_secret(s, premaster_secret, 32))
2035 		goto err;
2036 
2037 	/* Check if pubkey from client certificate was used */
2038 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
2039 	    EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2040 		ret = 2;
2041 	else
2042 		ret = 1;
2043  gerr:
2044 	EVP_PKEY_free(client_pub_pkey);
2045 	EVP_PKEY_CTX_free(pkey_ctx);
2046 	if (ret)
2047 		return (ret);
2048 	else
2049 		goto err;
2050 
2051  decode_err:
2052 	al = SSL_AD_DECODE_ERROR;
2053 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2054 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2055  err:
2056 	return (-1);
2057 }
2058 
2059 int
2060 ssl3_get_client_key_exchange(SSL *s)
2061 {
2062 	unsigned long alg_k;
2063 	int al, ok;
2064 	CBS cbs;
2065 	long n;
2066 
2067 	/* 2048 maxlen is a guess.  How long a key does that permit? */
2068 	n = ssl3_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
2069 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2070 	if (!ok)
2071 		return ((int)n);
2072 
2073 	if (n < 0)
2074 		goto err;
2075 
2076 	CBS_init(&cbs, s->internal->init_msg, n);
2077 
2078 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2079 
2080 	if (alg_k & SSL_kRSA) {
2081 		if (ssl3_get_client_kex_rsa(s, &cbs) != 1)
2082 			goto err;
2083 	} else if (alg_k & SSL_kDHE) {
2084 		if (ssl3_get_client_kex_dhe(s, &cbs) != 1)
2085 			goto err;
2086 	} else if (alg_k & SSL_kECDHE) {
2087 		if (ssl3_get_client_kex_ecdhe(s, &cbs) != 1)
2088 			goto err;
2089 	} else if (alg_k & SSL_kGOST) {
2090 		if (ssl3_get_client_kex_gost(s, &cbs) != 1)
2091 			goto err;
2092 	} else {
2093 		al = SSL_AD_HANDSHAKE_FAILURE;
2094 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
2095 		goto fatal_err;
2096 	}
2097 
2098 	if (CBS_len(&cbs) != 0) {
2099 		al = SSL_AD_DECODE_ERROR;
2100 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2101 		goto fatal_err;
2102 	}
2103 
2104 	return (1);
2105 
2106  fatal_err:
2107 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2108  err:
2109 	return (-1);
2110 }
2111 
2112 int
2113 ssl3_get_cert_verify(SSL *s)
2114 {
2115 	CBS cbs, signature;
2116 	const struct ssl_sigalg *sigalg = NULL;
2117 	uint16_t sigalg_value = SIGALG_NONE;
2118 	EVP_PKEY *pkey = NULL;
2119 	X509 *peer = NULL;
2120 	EVP_MD_CTX mctx;
2121 	int al, ok, verify;
2122 	const unsigned char *hdata;
2123 	size_t hdatalen;
2124 	int type = 0;
2125 	int ret = 0;
2126 	long n;
2127 
2128 	EVP_MD_CTX_init(&mctx);
2129 
2130 	n = ssl3_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2131 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2132 	if (!ok)
2133 		return ((int)n);
2134 
2135 	if (n < 0)
2136 		goto err;
2137 
2138 	CBS_init(&cbs, s->internal->init_msg, n);
2139 
2140 	if (s->session->peer != NULL) {
2141 		peer = s->session->peer;
2142 		pkey = X509_get_pubkey(peer);
2143 		type = X509_certificate_type(peer, pkey);
2144 	}
2145 
2146 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2147 		S3I(s)->hs.tls12.reuse_message = 1;
2148 		if (peer != NULL) {
2149 			al = SSL_AD_UNEXPECTED_MESSAGE;
2150 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
2151 			goto fatal_err;
2152 		}
2153 		ret = 1;
2154 		goto end;
2155 	}
2156 
2157 	if (peer == NULL) {
2158 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
2159 		al = SSL_AD_UNEXPECTED_MESSAGE;
2160 		goto fatal_err;
2161 	}
2162 
2163 	if (!(type & EVP_PKT_SIGN)) {
2164 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2165 		al = SSL_AD_ILLEGAL_PARAMETER;
2166 		goto fatal_err;
2167 	}
2168 
2169 	if (S3I(s)->change_cipher_spec) {
2170 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2171 		al = SSL_AD_UNEXPECTED_MESSAGE;
2172 		goto fatal_err;
2173 	}
2174 
2175 	if (SSL_USE_SIGALGS(s)) {
2176 		if (!CBS_get_u16(&cbs, &sigalg_value))
2177 			goto decode_err;
2178 	}
2179 	if (!CBS_get_u16_length_prefixed(&cbs, &signature))
2180 		goto err;
2181 	if (CBS_len(&cbs) != 0) {
2182 		al = SSL_AD_DECODE_ERROR;
2183 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
2184 		goto fatal_err;
2185 	}
2186 
2187 	if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
2188 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2189 		al = SSL_AD_DECODE_ERROR;
2190 		goto fatal_err;
2191 	}
2192 
2193 	if ((sigalg = ssl_sigalg_for_peer(s, pkey,
2194 	    sigalg_value)) == NULL) {
2195 		al = SSL_AD_DECODE_ERROR;
2196 		goto fatal_err;
2197 	}
2198 	S3I(s)->hs.peer_sigalg = sigalg;
2199 
2200 	if (SSL_USE_SIGALGS(s)) {
2201 		EVP_PKEY_CTX *pctx;
2202 
2203 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2204 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2205 			al = SSL_AD_INTERNAL_ERROR;
2206 			goto fatal_err;
2207 		}
2208 		if (!EVP_DigestVerifyInit(&mctx, &pctx, sigalg->md(),
2209 		    NULL, pkey)) {
2210 			SSLerror(s, ERR_R_EVP_LIB);
2211 			al = SSL_AD_INTERNAL_ERROR;
2212 			goto fatal_err;
2213 		}
2214 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2215 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
2216 			RSA_PKCS1_PSS_PADDING) ||
2217 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2218 			al = SSL_AD_INTERNAL_ERROR;
2219 			goto fatal_err;
2220 		}
2221 		if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2222 		    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2223 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE,
2224 		    NULL) <= 0) {
2225 			al = SSL_AD_INTERNAL_ERROR;
2226 			goto fatal_err;
2227 		}
2228 		if (!EVP_DigestVerifyUpdate(&mctx, hdata, hdatalen)) {
2229 			SSLerror(s, ERR_R_EVP_LIB);
2230 			al = SSL_AD_INTERNAL_ERROR;
2231 			goto fatal_err;
2232 		}
2233 		if (EVP_DigestVerifyFinal(&mctx, CBS_data(&signature),
2234 		    CBS_len(&signature)) <= 0) {
2235 			al = SSL_AD_DECRYPT_ERROR;
2236 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2237 			goto fatal_err;
2238 		}
2239 	} else if (pkey->type == EVP_PKEY_RSA) {
2240 		verify = RSA_verify(NID_md5_sha1, S3I(s)->hs.tls12.cert_verify,
2241 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, CBS_data(&signature),
2242 		    CBS_len(&signature), pkey->pkey.rsa);
2243 		if (verify < 0) {
2244 			al = SSL_AD_DECRYPT_ERROR;
2245 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2246 			goto fatal_err;
2247 		}
2248 		if (verify == 0) {
2249 			al = SSL_AD_DECRYPT_ERROR;
2250 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2251 			goto fatal_err;
2252 		}
2253 	} else if (pkey->type == EVP_PKEY_EC) {
2254 		verify = ECDSA_verify(pkey->save_type,
2255 		    &(S3I(s)->hs.tls12.cert_verify[MD5_DIGEST_LENGTH]),
2256 		    SHA_DIGEST_LENGTH, CBS_data(&signature),
2257 		    CBS_len(&signature), pkey->pkey.ec);
2258 		if (verify <= 0) {
2259 			al = SSL_AD_DECRYPT_ERROR;
2260 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2261 			goto fatal_err;
2262 		}
2263 #ifndef OPENSSL_NO_GOST
2264 	} else if (pkey->type == NID_id_GostR3410_94 ||
2265 	    pkey->type == NID_id_GostR3410_2001) {
2266 		unsigned char sigbuf[128];
2267 		unsigned int siglen = sizeof(sigbuf);
2268 		EVP_PKEY_CTX *pctx;
2269 		const EVP_MD *md;
2270 		int nid;
2271 
2272 		if (!tls1_transcript_data(s, &hdata, &hdatalen)) {
2273 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2274 			al = SSL_AD_INTERNAL_ERROR;
2275 			goto fatal_err;
2276 		}
2277 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2278 		    !(md = EVP_get_digestbynid(nid))) {
2279 			SSLerror(s, ERR_R_EVP_LIB);
2280 			al = SSL_AD_INTERNAL_ERROR;
2281 			goto fatal_err;
2282 		}
2283 		if ((pctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
2284 			SSLerror(s, ERR_R_EVP_LIB);
2285 			al = SSL_AD_INTERNAL_ERROR;
2286 			goto fatal_err;
2287 		}
2288 		if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2289 		    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2290 		    !EVP_DigestFinal(&mctx, sigbuf, &siglen) ||
2291 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2292 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2293 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2294 		    EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2295 		    GOST_SIG_FORMAT_RS_LE, NULL) <= 0)) {
2296 			SSLerror(s, ERR_R_EVP_LIB);
2297 			al = SSL_AD_INTERNAL_ERROR;
2298 			EVP_PKEY_CTX_free(pctx);
2299 			goto fatal_err;
2300 		}
2301 		if (EVP_PKEY_verify(pctx, CBS_data(&signature),
2302 		    CBS_len(&signature), sigbuf, siglen) <= 0) {
2303 			al = SSL_AD_DECRYPT_ERROR;
2304 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2305 			EVP_PKEY_CTX_free(pctx);
2306 			goto fatal_err;
2307 		}
2308 
2309 		EVP_PKEY_CTX_free(pctx);
2310 #endif
2311 	} else {
2312 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2313 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2314 		goto fatal_err;
2315 	}
2316 
2317 	ret = 1;
2318 	if (0) {
2319  decode_err:
2320 		al = SSL_AD_DECODE_ERROR;
2321 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2322  fatal_err:
2323 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2324 	}
2325  end:
2326 	tls1_transcript_free(s);
2327  err:
2328 	EVP_MD_CTX_cleanup(&mctx);
2329 	EVP_PKEY_free(pkey);
2330 	return (ret);
2331 }
2332 
2333 int
2334 ssl3_get_client_certificate(SSL *s)
2335 {
2336 	CBS cbs, client_certs;
2337 	int i, ok, al, ret = -1;
2338 	X509 *x = NULL;
2339 	long n;
2340 	const unsigned char *q;
2341 	STACK_OF(X509) *sk = NULL;
2342 
2343 	n = ssl3_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2344 	    -1, s->internal->max_cert_list, &ok);
2345 	if (!ok)
2346 		return ((int)n);
2347 
2348 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2349 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2350 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2351 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2352 			al = SSL_AD_HANDSHAKE_FAILURE;
2353 			goto fatal_err;
2354 		}
2355 		/*
2356 		 * If tls asked for a client cert,
2357 		 * the client must return a 0 list.
2358 		 */
2359 		if (S3I(s)->hs.tls12.cert_request) {
2360 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2361 			    );
2362 			al = SSL_AD_UNEXPECTED_MESSAGE;
2363 			goto fatal_err;
2364 		}
2365 		S3I(s)->hs.tls12.reuse_message = 1;
2366 		return (1);
2367 	}
2368 
2369 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
2370 		al = SSL_AD_UNEXPECTED_MESSAGE;
2371 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2372 		goto fatal_err;
2373 	}
2374 
2375 	if (n < 0)
2376 		goto decode_err;
2377 
2378 	CBS_init(&cbs, s->internal->init_msg, n);
2379 
2380 	if ((sk = sk_X509_new_null()) == NULL) {
2381 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2382 		goto err;
2383 	}
2384 
2385 	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2386 	    CBS_len(&cbs) != 0)
2387 		goto decode_err;
2388 
2389 	while (CBS_len(&client_certs) > 0) {
2390 		CBS cert;
2391 
2392 		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2393 			al = SSL_AD_DECODE_ERROR;
2394 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2395 			goto fatal_err;
2396 		}
2397 
2398 		q = CBS_data(&cert);
2399 		x = d2i_X509(NULL, &q, CBS_len(&cert));
2400 		if (x == NULL) {
2401 			SSLerror(s, ERR_R_ASN1_LIB);
2402 			goto err;
2403 		}
2404 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2405 			al = SSL_AD_DECODE_ERROR;
2406 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2407 			goto fatal_err;
2408 		}
2409 		if (!sk_X509_push(sk, x)) {
2410 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2411 			goto err;
2412 		}
2413 		x = NULL;
2414 	}
2415 
2416 	if (sk_X509_num(sk) <= 0) {
2417 		/*
2418 		 * TLS does not mind 0 certs returned.
2419 		 * Fail for TLS only if we required a certificate.
2420 		 */
2421 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2422 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2423 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2424 			al = SSL_AD_HANDSHAKE_FAILURE;
2425 			goto fatal_err;
2426 		}
2427 		/* No client certificate so free transcript. */
2428 		tls1_transcript_free(s);
2429 	} else {
2430 		i = ssl_verify_cert_chain(s, sk);
2431 		if (i <= 0) {
2432 			al = ssl_verify_alarm_type(s->verify_result);
2433 			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2434 			goto fatal_err;
2435 		}
2436 	}
2437 
2438 	X509_free(s->session->peer);
2439 	s->session->peer = sk_X509_shift(sk);
2440 	s->session->verify_result = s->verify_result;
2441 
2442 	/*
2443 	 * With the current implementation, sess_cert will always be NULL
2444 	 * when we arrive here
2445 	 */
2446 	if (SSI(s)->sess_cert == NULL) {
2447 		SSI(s)->sess_cert = ssl_sess_cert_new();
2448 		if (SSI(s)->sess_cert == NULL) {
2449 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2450 			goto err;
2451 		}
2452 	}
2453 	sk_X509_pop_free(SSI(s)->sess_cert->cert_chain, X509_free);
2454 	SSI(s)->sess_cert->cert_chain = sk;
2455 
2456 	/*
2457 	 * Inconsistency alert: cert_chain does *not* include the
2458 	 * peer's own certificate, while we do include it in s3_clnt.c
2459 	 */
2460 
2461 	sk = NULL;
2462 
2463 	ret = 1;
2464 	if (0) {
2465  decode_err:
2466 		al = SSL_AD_DECODE_ERROR;
2467 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2468  fatal_err:
2469 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2470 	}
2471  err:
2472 	X509_free(x);
2473 	sk_X509_pop_free(sk, X509_free);
2474 
2475 	return (ret);
2476 }
2477 
2478 int
2479 ssl3_send_server_certificate(SSL *s)
2480 {
2481 	CBB cbb, server_cert;
2482 	CERT_PKEY *cpk;
2483 
2484 	/*
2485 	 * Server Certificate - RFC 5246, section 7.4.2.
2486 	 */
2487 
2488 	memset(&cbb, 0, sizeof(cbb));
2489 
2490 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_A) {
2491 		if ((cpk = ssl_get_server_send_pkey(s)) == NULL) {
2492 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2493 			return (0);
2494 		}
2495 
2496 		if (!ssl3_handshake_msg_start(s, &cbb, &server_cert,
2497 		    SSL3_MT_CERTIFICATE))
2498 			goto err;
2499 		if (!ssl3_output_cert_chain(s, &server_cert, cpk))
2500 			goto err;
2501 		if (!ssl3_handshake_msg_finish(s, &cbb))
2502 			goto err;
2503 
2504 		S3I(s)->hs.state = SSL3_ST_SW_CERT_B;
2505 	}
2506 
2507 	/* SSL3_ST_SW_CERT_B */
2508 	return (ssl3_handshake_write(s));
2509 
2510  err:
2511 	CBB_cleanup(&cbb);
2512 
2513 	return (0);
2514 }
2515 
2516 /* send a new session ticket (not necessarily for a new session) */
2517 int
2518 ssl3_send_newsession_ticket(SSL *s)
2519 {
2520 	CBB cbb, session_ticket, ticket;
2521 	SSL_CTX *tctx = s->initial_ctx;
2522 	size_t enc_session_len, enc_session_max_len, hmac_len;
2523 	size_t session_len = 0;
2524 	unsigned char *enc_session = NULL, *session = NULL;
2525 	unsigned char iv[EVP_MAX_IV_LENGTH];
2526 	unsigned char key_name[16];
2527 	unsigned char *hmac;
2528 	unsigned int hlen;
2529 	EVP_CIPHER_CTX ctx;
2530 	HMAC_CTX hctx;
2531 	int len;
2532 
2533 	/*
2534 	 * New Session Ticket - RFC 5077, section 3.3.
2535 	 */
2536 
2537 	EVP_CIPHER_CTX_init(&ctx);
2538 	HMAC_CTX_init(&hctx);
2539 
2540 	memset(&cbb, 0, sizeof(cbb));
2541 
2542 	if (S3I(s)->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2543 		if (!ssl3_handshake_msg_start(s, &cbb, &session_ticket,
2544 		    SSL3_MT_NEWSESSION_TICKET))
2545 			goto err;
2546 
2547 		if (!SSL_SESSION_ticket(s->session, &session, &session_len))
2548 			goto err;
2549 		if (session_len > 0xffff)
2550 			goto err;
2551 
2552 		/*
2553 		 * Initialize HMAC and cipher contexts. If callback is present
2554 		 * it does all the work, otherwise use generated values from
2555 		 * parent context.
2556 		 */
2557 		if (tctx->internal->tlsext_ticket_key_cb != NULL) {
2558 			if (tctx->internal->tlsext_ticket_key_cb(s,
2559 			    key_name, iv, &ctx, &hctx, 1) < 0) {
2560 				EVP_CIPHER_CTX_cleanup(&ctx);
2561 				goto err;
2562 			}
2563 		} else {
2564 			arc4random_buf(iv, 16);
2565 			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2566 			    tctx->internal->tlsext_tick_aes_key, iv);
2567 			HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
2568 			    16, EVP_sha256(), NULL);
2569 			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2570 		}
2571 
2572 		/* Encrypt the session state. */
2573 		enc_session_max_len = session_len + EVP_MAX_BLOCK_LENGTH;
2574 		if ((enc_session = calloc(1, enc_session_max_len)) == NULL)
2575 			goto err;
2576 		enc_session_len = 0;
2577 		if (!EVP_EncryptUpdate(&ctx, enc_session, &len, session,
2578 		    session_len))
2579 			goto err;
2580 		enc_session_len += len;
2581 		if (!EVP_EncryptFinal_ex(&ctx, enc_session + enc_session_len,
2582 		    &len))
2583 			goto err;
2584 		enc_session_len += len;
2585 
2586 		if (enc_session_len > enc_session_max_len)
2587 			goto err;
2588 
2589 		/* Generate the HMAC. */
2590 		if (!HMAC_Update(&hctx, key_name, sizeof(key_name)))
2591 			goto err;
2592 		if (!HMAC_Update(&hctx, iv, EVP_CIPHER_CTX_iv_length(&ctx)))
2593 			goto err;
2594 		if (!HMAC_Update(&hctx, enc_session, enc_session_len))
2595 			goto err;
2596 
2597 		if ((hmac_len = HMAC_size(&hctx)) <= 0)
2598 			goto err;
2599 
2600 		/*
2601 		 * Ticket lifetime hint (advisory only):
2602 		 * We leave this unspecified for resumed session
2603 		 * (for simplicity), and guess that tickets for new
2604 		 * sessions will live as long as their sessions.
2605 		 */
2606 		if (!CBB_add_u32(&session_ticket,
2607 		    s->internal->hit ? 0 : s->session->timeout))
2608 			goto err;
2609 
2610 		if (!CBB_add_u16_length_prefixed(&session_ticket, &ticket))
2611 			goto err;
2612 		if (!CBB_add_bytes(&ticket, key_name, sizeof(key_name)))
2613 			goto err;
2614 		if (!CBB_add_bytes(&ticket, iv, EVP_CIPHER_CTX_iv_length(&ctx)))
2615 			goto err;
2616 		if (!CBB_add_bytes(&ticket, enc_session, enc_session_len))
2617 			goto err;
2618 		if (!CBB_add_space(&ticket, &hmac, hmac_len))
2619 			goto err;
2620 
2621 		if (!HMAC_Final(&hctx, hmac, &hlen))
2622 			goto err;
2623 		if (hlen != hmac_len)
2624 			goto err;
2625 
2626 		if (!ssl3_handshake_msg_finish(s, &cbb))
2627 			goto err;
2628 
2629 		S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2630 	}
2631 
2632 	EVP_CIPHER_CTX_cleanup(&ctx);
2633 	HMAC_CTX_cleanup(&hctx);
2634 	freezero(session, session_len);
2635 	free(enc_session);
2636 
2637 	/* SSL3_ST_SW_SESSION_TICKET_B */
2638 	return (ssl3_handshake_write(s));
2639 
2640  err:
2641 	CBB_cleanup(&cbb);
2642 	EVP_CIPHER_CTX_cleanup(&ctx);
2643 	HMAC_CTX_cleanup(&hctx);
2644 	freezero(session, session_len);
2645 	free(enc_session);
2646 
2647 	return (-1);
2648 }
2649 
2650 int
2651 ssl3_send_cert_status(SSL *s)
2652 {
2653 	CBB cbb, certstatus, ocspresp;
2654 
2655 	memset(&cbb, 0, sizeof(cbb));
2656 
2657 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2658 		if (!ssl3_handshake_msg_start(s, &cbb, &certstatus,
2659 		    SSL3_MT_CERTIFICATE_STATUS))
2660 			goto err;
2661 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2662 			goto err;
2663 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2664 			goto err;
2665 		if (!CBB_add_bytes(&ocspresp, s->internal->tlsext_ocsp_resp,
2666 		    s->internal->tlsext_ocsp_resp_len))
2667 			goto err;
2668 		if (!ssl3_handshake_msg_finish(s, &cbb))
2669 			goto err;
2670 
2671 		S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2672 	}
2673 
2674 	/* SSL3_ST_SW_CERT_STATUS_B */
2675 	return (ssl3_handshake_write(s));
2676 
2677  err:
2678 	CBB_cleanup(&cbb);
2679 
2680 	return (-1);
2681 }
2682