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