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