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