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