xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision ffcef06798eb7b98532e76a80212f0772bebc4f6)
1 /* $OpenBSD: ssl_clnt.c,v 1.110 2021/09/02 14:41:03 beck 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 <limits.h>
152 #include <stdint.h>
153 #include <stdio.h>
154 
155 #include <openssl/bn.h>
156 #include <openssl/buffer.h>
157 #include <openssl/curve25519.h>
158 #include <openssl/dh.h>
159 #include <openssl/evp.h>
160 #include <openssl/md5.h>
161 #include <openssl/objects.h>
162 #include <openssl/opensslconf.h>
163 
164 #ifndef OPENSSL_NO_ENGINE
165 #include <openssl/engine.h>
166 #endif
167 #ifndef OPENSSL_NO_GOST
168 #include <openssl/gost.h>
169 #endif
170 
171 #include "bytestring.h"
172 #include "dtls_locl.h"
173 #include "ssl_locl.h"
174 #include "ssl_sigalgs.h"
175 #include "ssl_tlsext.h"
176 
177 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b);
178 
179 int
180 ssl3_connect(SSL *s)
181 {
182 	int new_state, state, skip = 0;
183 	int ret = -1;
184 
185 	ERR_clear_error();
186 	errno = 0;
187 
188 	s->internal->in_handshake++;
189 	if (!SSL_in_init(s) || SSL_in_before(s))
190 		SSL_clear(s);
191 
192 	for (;;) {
193 		state = S3I(s)->hs.state;
194 
195 		switch (S3I(s)->hs.state) {
196 		case SSL_ST_RENEGOTIATE:
197 			s->internal->renegotiate = 1;
198 			S3I(s)->hs.state = SSL_ST_CONNECT;
199 			s->ctx->internal->stats.sess_connect_renegotiate++;
200 			/* break */
201 		case SSL_ST_BEFORE:
202 		case SSL_ST_CONNECT:
203 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
204 		case SSL_ST_OK|SSL_ST_CONNECT:
205 
206 			s->server = 0;
207 
208 			ssl_info_callback(s, SSL_CB_HANDSHAKE_START, 1);
209 
210 			if (!ssl_legacy_stack_version(s, s->version)) {
211 				SSLerror(s, ERR_R_INTERNAL_ERROR);
212 				ret = -1;
213 				goto end;
214 			}
215 
216 			if (!ssl_supported_tls_version_range(s,
217 			    &S3I(s)->hs.our_min_tls_version,
218 			    &S3I(s)->hs.our_max_tls_version)) {
219 				SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
220 				ret = -1;
221 				goto end;
222 			}
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 			if (!ssl_init_wbio_buffer(s, 0)) {
233 				ret = -1;
234 				goto end;
235 			}
236 
237 			/* don't push the buffering BIO quite yet */
238 
239 			if (!tls1_transcript_init(s)) {
240 				ret = -1;
241 				goto end;
242 			}
243 
244 			S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
245 			s->ctx->internal->stats.sess_connect++;
246 			s->internal->init_num = 0;
247 
248 			if (SSL_is_dtls(s)) {
249 				/* mark client_random uninitialized */
250 				memset(s->s3->client_random, 0,
251 				    sizeof(s->s3->client_random));
252 				D1I(s)->send_cookie = 0;
253 				s->internal->hit = 0;
254 			}
255 			break;
256 
257 		case SSL3_ST_CW_CLNT_HELLO_A:
258 		case SSL3_ST_CW_CLNT_HELLO_B:
259 			s->internal->shutdown = 0;
260 
261 			if (SSL_is_dtls(s)) {
262 				/* every DTLS ClientHello resets Finished MAC */
263 				tls1_transcript_reset(s);
264 
265 				dtls1_start_timer(s);
266 			}
267 
268 			ret = ssl3_send_client_hello(s);
269 			if (ret <= 0)
270 				goto end;
271 
272 			if (SSL_is_dtls(s) && D1I(s)->send_cookie) {
273 				S3I(s)->hs.state = SSL3_ST_CW_FLUSH;
274 				S3I(s)->hs.tls12.next_state = SSL3_ST_CR_SRVR_HELLO_A;
275 			} else
276 				S3I(s)->hs.state = SSL3_ST_CR_SRVR_HELLO_A;
277 
278 			s->internal->init_num = 0;
279 
280 			/* turn on buffering for the next lot of output */
281 			if (s->bbio != s->wbio)
282 				s->wbio = BIO_push(s->bbio, s->wbio);
283 
284 			break;
285 
286 		case SSL3_ST_CR_SRVR_HELLO_A:
287 		case SSL3_ST_CR_SRVR_HELLO_B:
288 			ret = ssl3_get_server_hello(s);
289 			if (ret <= 0)
290 				goto end;
291 
292 			if (s->internal->hit) {
293 				S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
294 				if (!SSL_is_dtls(s)) {
295 					if (s->internal->tlsext_ticket_expected) {
296 						/* receive renewed session ticket */
297 						S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
298 					}
299 
300 					/* No client certificate verification. */
301 					tls1_transcript_free(s);
302 				}
303 			} else if (SSL_is_dtls(s)) {
304 				S3I(s)->hs.state = DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
305 			} else {
306 				S3I(s)->hs.state = SSL3_ST_CR_CERT_A;
307 			}
308 			s->internal->init_num = 0;
309 			break;
310 
311 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
312 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
313 			ret = ssl3_get_dtls_hello_verify(s);
314 			if (ret <= 0)
315 				goto end;
316 			dtls1_stop_timer(s);
317 			if (D1I(s)->send_cookie) /* start again, with a cookie */
318 				S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
319 			else
320 				S3I(s)->hs.state = SSL3_ST_CR_CERT_A;
321 			s->internal->init_num = 0;
322 			break;
323 
324 		case SSL3_ST_CR_CERT_A:
325 		case SSL3_ST_CR_CERT_B:
326 			ret = ssl3_check_finished(s);
327 			if (ret <= 0)
328 				goto end;
329 			if (ret == 2) {
330 				s->internal->hit = 1;
331 				if (s->internal->tlsext_ticket_expected)
332 					S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
333 				else
334 					S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
335 				s->internal->init_num = 0;
336 				break;
337 			}
338 			/* Check if it is anon DH/ECDH. */
339 			if (!(S3I(s)->hs.cipher->algorithm_auth &
340 			    SSL_aNULL)) {
341 				ret = ssl3_get_server_certificate(s);
342 				if (ret <= 0)
343 					goto end;
344 				if (s->internal->tlsext_status_expected)
345 					S3I(s)->hs.state = SSL3_ST_CR_CERT_STATUS_A;
346 				else
347 					S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
348 			} else {
349 				skip = 1;
350 				S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
351 			}
352 			s->internal->init_num = 0;
353 			break;
354 
355 		case SSL3_ST_CR_KEY_EXCH_A:
356 		case SSL3_ST_CR_KEY_EXCH_B:
357 			ret = ssl3_get_server_key_exchange(s);
358 			if (ret <= 0)
359 				goto end;
360 			S3I(s)->hs.state = SSL3_ST_CR_CERT_REQ_A;
361 			s->internal->init_num = 0;
362 
363 			/*
364 			 * At this point we check that we have the
365 			 * required stuff from the server.
366 			 */
367 			if (!ssl3_check_cert_and_algorithm(s)) {
368 				ret = -1;
369 				goto end;
370 			}
371 			break;
372 
373 		case SSL3_ST_CR_CERT_REQ_A:
374 		case SSL3_ST_CR_CERT_REQ_B:
375 			ret = ssl3_get_certificate_request(s);
376 			if (ret <= 0)
377 				goto end;
378 			S3I(s)->hs.state = SSL3_ST_CR_SRVR_DONE_A;
379 			s->internal->init_num = 0;
380 			break;
381 
382 		case SSL3_ST_CR_SRVR_DONE_A:
383 		case SSL3_ST_CR_SRVR_DONE_B:
384 			ret = ssl3_get_server_done(s);
385 			if (ret <= 0)
386 				goto end;
387 			if (SSL_is_dtls(s))
388 				dtls1_stop_timer(s);
389 			if (S3I(s)->hs.tls12.cert_request)
390 				S3I(s)->hs.state = SSL3_ST_CW_CERT_A;
391 			else
392 				S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_A;
393 			s->internal->init_num = 0;
394 
395 			break;
396 
397 		case SSL3_ST_CW_CERT_A:
398 		case SSL3_ST_CW_CERT_B:
399 		case SSL3_ST_CW_CERT_C:
400 		case SSL3_ST_CW_CERT_D:
401 			if (SSL_is_dtls(s))
402 				dtls1_start_timer(s);
403 			ret = ssl3_send_client_certificate(s);
404 			if (ret <= 0)
405 				goto end;
406 			S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_A;
407 			s->internal->init_num = 0;
408 			break;
409 
410 		case SSL3_ST_CW_KEY_EXCH_A:
411 		case SSL3_ST_CW_KEY_EXCH_B:
412 			if (SSL_is_dtls(s))
413 				dtls1_start_timer(s);
414 			ret = ssl3_send_client_key_exchange(s);
415 			if (ret <= 0)
416 				goto end;
417 			/*
418 			 * EAY EAY EAY need to check for DH fix cert
419 			 * sent back
420 			 */
421 			/*
422 			 * For TLS, cert_req is set to 2, so a cert chain
423 			 * of nothing is sent, but no verify packet is sent
424 			 */
425 			/*
426 			 * XXX: For now, we do not support client
427 			 * authentication in ECDH cipher suites with
428 			 * ECDH (rather than ECDSA) certificates.
429 			 * We need to skip the certificate verify
430 			 * message when client's ECDH public key is sent
431 			 * inside the client certificate.
432 			 */
433 			if (S3I(s)->hs.tls12.cert_request == 1) {
434 				S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_A;
435 			} else {
436 				S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
437 				S3I(s)->change_cipher_spec = 0;
438 			}
439 			if (!SSL_is_dtls(s)) {
440 				if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
441 					S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
442 					S3I(s)->change_cipher_spec = 0;
443 				}
444 			}
445 
446 			s->internal->init_num = 0;
447 			break;
448 
449 		case SSL3_ST_CW_CERT_VRFY_A:
450 		case SSL3_ST_CW_CERT_VRFY_B:
451 			if (SSL_is_dtls(s))
452 				dtls1_start_timer(s);
453 			ret = ssl3_send_client_verify(s);
454 			if (ret <= 0)
455 				goto end;
456 			S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
457 			s->internal->init_num = 0;
458 			S3I(s)->change_cipher_spec = 0;
459 			break;
460 
461 		case SSL3_ST_CW_CHANGE_A:
462 		case SSL3_ST_CW_CHANGE_B:
463 			if (SSL_is_dtls(s) && !s->internal->hit)
464 				dtls1_start_timer(s);
465 			ret = ssl3_send_change_cipher_spec(s,
466 			    SSL3_ST_CW_CHANGE_A, SSL3_ST_CW_CHANGE_B);
467 			if (ret <= 0)
468 				goto end;
469 
470 			S3I(s)->hs.state = SSL3_ST_CW_FINISHED_A;
471 			s->internal->init_num = 0;
472 			s->session->cipher = S3I(s)->hs.cipher;
473 
474 			if (!tls1_setup_key_block(s)) {
475 				ret = -1;
476 				goto end;
477 			}
478 			if (!tls1_change_write_cipher_state(s)) {
479 				ret = -1;
480 				goto end;
481 			}
482 			break;
483 
484 		case SSL3_ST_CW_FINISHED_A:
485 		case SSL3_ST_CW_FINISHED_B:
486 			if (SSL_is_dtls(s) && !s->internal->hit)
487 				dtls1_start_timer(s);
488 			ret = ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,
489 			    SSL3_ST_CW_FINISHED_B);
490 			if (ret <= 0)
491 				goto end;
492 			if (!SSL_is_dtls(s))
493 				s->s3->flags |= SSL3_FLAGS_CCS_OK;
494 			S3I(s)->hs.state = SSL3_ST_CW_FLUSH;
495 
496 			/* clear flags */
497 			if (s->internal->hit) {
498 				S3I(s)->hs.tls12.next_state = SSL_ST_OK;
499 			} else {
500 				/* Allow NewSessionTicket if ticket expected */
501 				if (s->internal->tlsext_ticket_expected)
502 					S3I(s)->hs.tls12.next_state =
503 					    SSL3_ST_CR_SESSION_TICKET_A;
504 				else
505 					S3I(s)->hs.tls12.next_state =
506 					    SSL3_ST_CR_FINISHED_A;
507 			}
508 			s->internal->init_num = 0;
509 			break;
510 
511 		case SSL3_ST_CR_SESSION_TICKET_A:
512 		case SSL3_ST_CR_SESSION_TICKET_B:
513 			ret = ssl3_get_new_session_ticket(s);
514 			if (ret <= 0)
515 				goto end;
516 			S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
517 			s->internal->init_num = 0;
518 			break;
519 
520 		case SSL3_ST_CR_CERT_STATUS_A:
521 		case SSL3_ST_CR_CERT_STATUS_B:
522 			ret = ssl3_get_cert_status(s);
523 			if (ret <= 0)
524 				goto end;
525 			S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
526 			s->internal->init_num = 0;
527 			break;
528 
529 		case SSL3_ST_CR_FINISHED_A:
530 		case SSL3_ST_CR_FINISHED_B:
531 			if (SSL_is_dtls(s))
532 				D1I(s)->change_cipher_spec_ok = 1;
533 			else
534 				s->s3->flags |= SSL3_FLAGS_CCS_OK;
535 			ret = ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A,
536 			    SSL3_ST_CR_FINISHED_B);
537 			if (ret <= 0)
538 				goto end;
539 			if (SSL_is_dtls(s))
540 				dtls1_stop_timer(s);
541 
542 			if (s->internal->hit)
543 				S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
544 			else
545 				S3I(s)->hs.state = SSL_ST_OK;
546 			s->internal->init_num = 0;
547 			break;
548 
549 		case SSL3_ST_CW_FLUSH:
550 			s->internal->rwstate = SSL_WRITING;
551 			if (BIO_flush(s->wbio) <= 0) {
552 				if (SSL_is_dtls(s)) {
553 					/* If the write error was fatal, stop trying */
554 					if (!BIO_should_retry(s->wbio)) {
555 						s->internal->rwstate = SSL_NOTHING;
556 						S3I(s)->hs.state = S3I(s)->hs.tls12.next_state;
557 					}
558 				}
559 				ret = -1;
560 				goto end;
561 			}
562 			s->internal->rwstate = SSL_NOTHING;
563 			S3I(s)->hs.state = S3I(s)->hs.tls12.next_state;
564 			break;
565 
566 		case SSL_ST_OK:
567 			/* clean a few things up */
568 			tls1_cleanup_key_block(s);
569 
570 			if (S3I(s)->handshake_transcript != NULL) {
571 				SSLerror(s, ERR_R_INTERNAL_ERROR);
572 				ret = -1;
573 				goto end;
574 			}
575 
576 			if (!SSL_is_dtls(s))
577 				ssl3_release_init_buffer(s);
578 
579 			ssl_free_wbio_buffer(s);
580 
581 			s->internal->init_num = 0;
582 			s->internal->renegotiate = 0;
583 			s->internal->new_session = 0;
584 
585 			ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
586 			if (s->internal->hit)
587 				s->ctx->internal->stats.sess_hit++;
588 
589 			ret = 1;
590 			/* s->server=0; */
591 			s->internal->handshake_func = ssl3_connect;
592 			s->ctx->internal->stats.sess_connect_good++;
593 
594 			ssl_info_callback(s, SSL_CB_HANDSHAKE_DONE, 1);
595 
596 			if (SSL_is_dtls(s)) {
597 				/* done with handshaking */
598 				D1I(s)->handshake_read_seq = 0;
599 				D1I(s)->next_handshake_write_seq = 0;
600 			}
601 
602 			goto end;
603 			/* break; */
604 
605 		default:
606 			SSLerror(s, SSL_R_UNKNOWN_STATE);
607 			ret = -1;
608 			goto end;
609 			/* break; */
610 		}
611 
612 		/* did we do anything */
613 		if (!S3I(s)->hs.tls12.reuse_message && !skip) {
614 			if (s->internal->debug) {
615 				if ((ret = BIO_flush(s->wbio)) <= 0)
616 					goto end;
617 			}
618 
619 			if (S3I(s)->hs.state != state) {
620 				new_state = S3I(s)->hs.state;
621 				S3I(s)->hs.state = state;
622 				ssl_info_callback(s, SSL_CB_CONNECT_LOOP, 1);
623 				S3I(s)->hs.state = new_state;
624 			}
625 		}
626 		skip = 0;
627 	}
628 
629  end:
630 	s->internal->in_handshake--;
631 	ssl_info_callback(s, SSL_CB_CONNECT_EXIT, ret);
632 
633 	return (ret);
634 }
635 
636 int
637 ssl3_send_client_hello(SSL *s)
638 {
639 	CBB cbb, client_hello, session_id, cookie, cipher_suites;
640 	CBB compression_methods;
641 	uint16_t max_version;
642 	size_t sl;
643 
644 	memset(&cbb, 0, sizeof(cbb));
645 
646 	if (S3I(s)->hs.state == SSL3_ST_CW_CLNT_HELLO_A) {
647 		SSL_SESSION *sess = s->session;
648 
649 		if (!ssl_max_supported_version(s, &max_version)) {
650 			SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
651 			return (-1);
652 		}
653 		s->client_version = s->version = max_version;
654 
655 		if (sess == NULL ||
656 		    sess->ssl_version != s->version ||
657 		    (!sess->session_id_length && !sess->tlsext_tick) ||
658 		    sess->internal->not_resumable) {
659 			if (!ssl_get_new_session(s, 0))
660 				goto err;
661 		}
662 		/* else use the pre-loaded session */
663 
664 		/*
665 		 * If a DTLS ClientHello message is being resent after a
666 		 * HelloVerifyRequest, we must retain the original client
667 		 * random value.
668 		 */
669 		if (!SSL_is_dtls(s) || D1I(s)->send_cookie == 0)
670 			arc4random_buf(s->s3->client_random, SSL3_RANDOM_SIZE);
671 
672 		if (!ssl3_handshake_msg_start(s, &cbb, &client_hello,
673 		    SSL3_MT_CLIENT_HELLO))
674 			goto err;
675 
676 		/*
677 		 * Version indicates the negotiated version: for example from
678 		 * an SSLv2/v3 compatible client hello). The client_version
679 		 * field is the maximum version we permit and it is also
680 		 * used in RSA encrypted premaster secrets. Some servers can
681 		 * choke if we initially report a higher version then
682 		 * renegotiate to a lower one in the premaster secret. This
683 		 * didn't happen with TLS 1.0 as most servers supported it
684 		 * but it can with TLS 1.1 or later if the server only supports
685 		 * 1.0.
686 		 *
687 		 * Possible scenario with previous logic:
688 		 *	1. Client hello indicates TLS 1.2
689 		 *	2. Server hello says TLS 1.0
690 		 *	3. RSA encrypted premaster secret uses 1.2.
691 		 *	4. Handhaked proceeds using TLS 1.0.
692 		 *	5. Server sends hello request to renegotiate.
693 		 *	6. Client hello indicates TLS v1.0 as we now
694 		 *	   know that is maximum server supports.
695 		 *	7. Server chokes on RSA encrypted premaster secret
696 		 *	   containing version 1.0.
697 		 *
698 		 * For interoperability it should be OK to always use the
699 		 * maximum version we support in client hello and then rely
700 		 * on the checking of version to ensure the servers isn't
701 		 * being inconsistent: for example initially negotiating with
702 		 * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
703 		 * client_version in client hello and not resetting it to
704 		 * the negotiated version.
705 		 */
706 		if (!CBB_add_u16(&client_hello, s->client_version))
707 			goto err;
708 
709 		/* Random stuff */
710 		if (!CBB_add_bytes(&client_hello, s->s3->client_random,
711 		    sizeof(s->s3->client_random)))
712 			goto err;
713 
714 		/* Session ID */
715 		if (!CBB_add_u8_length_prefixed(&client_hello, &session_id))
716 			goto err;
717 		if (!s->internal->new_session &&
718 		    s->session->session_id_length > 0) {
719 			sl = s->session->session_id_length;
720 			if (sl > sizeof(s->session->session_id)) {
721 				SSLerror(s, ERR_R_INTERNAL_ERROR);
722 				goto err;
723 			}
724 			if (!CBB_add_bytes(&session_id,
725 			    s->session->session_id, sl))
726 				goto err;
727 		}
728 
729 		/* DTLS Cookie. */
730 		if (SSL_is_dtls(s)) {
731 			if (D1I(s)->cookie_len > sizeof(D1I(s)->cookie)) {
732 				SSLerror(s, ERR_R_INTERNAL_ERROR);
733 				goto err;
734 			}
735 			if (!CBB_add_u8_length_prefixed(&client_hello, &cookie))
736 				goto err;
737 			if (!CBB_add_bytes(&cookie, D1I(s)->cookie,
738 			    D1I(s)->cookie_len))
739 				goto err;
740 		}
741 
742 		/* Ciphers supported */
743 		if (!CBB_add_u16_length_prefixed(&client_hello, &cipher_suites))
744 			return 0;
745 		if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s),
746 		    &cipher_suites)) {
747 			SSLerror(s, SSL_R_NO_CIPHERS_AVAILABLE);
748 			goto err;
749 		}
750 
751 		/* Add in compression methods (null) */
752 		if (!CBB_add_u8_length_prefixed(&client_hello,
753 		    &compression_methods))
754 			goto err;
755 		if (!CBB_add_u8(&compression_methods, 0))
756 			goto err;
757 
758 		/* TLS extensions */
759 		if (!tlsext_client_build(s, SSL_TLSEXT_MSG_CH, &client_hello)) {
760 			SSLerror(s, ERR_R_INTERNAL_ERROR);
761 			goto err;
762 		}
763 
764 		if (!ssl3_handshake_msg_finish(s, &cbb))
765 			goto err;
766 
767 		S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_B;
768 	}
769 
770 	/* SSL3_ST_CW_CLNT_HELLO_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_dtls_hello_verify(SSL *s)
781 {
782 	long n;
783 	int al, ok = 0;
784 	size_t cookie_len;
785 	uint16_t ssl_version;
786 	CBS hello_verify_request, cookie;
787 
788 	n = ssl3_get_message(s, DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
789 	    DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B, -1, s->internal->max_cert_list, &ok);
790 	if (!ok)
791 		return ((int)n);
792 
793 	if (S3I(s)->hs.tls12.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
794 		D1I(s)->send_cookie = 0;
795 		S3I(s)->hs.tls12.reuse_message = 1;
796 		return (1);
797 	}
798 
799 	if (n < 0)
800 		goto decode_err;
801 
802 	CBS_init(&hello_verify_request, s->internal->init_msg, n);
803 
804 	if (!CBS_get_u16(&hello_verify_request, &ssl_version))
805 		goto decode_err;
806 	if (!CBS_get_u8_length_prefixed(&hello_verify_request, &cookie))
807 		goto decode_err;
808 	if (CBS_len(&hello_verify_request) != 0)
809 		goto decode_err;
810 
811 	/*
812 	 * Per RFC 6347 section 4.2.1, the HelloVerifyRequest should always
813 	 * contain DTLSv1.0 the version that is going to be negotiated.
814 	 * Tolerate DTLSv1.2 just in case.
815 	 */
816 	if (ssl_version != DTLS1_VERSION && ssl_version != DTLS1_2_VERSION) {
817 		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
818 		s->version = (s->version & 0xff00) | (ssl_version & 0xff);
819 		al = SSL_AD_PROTOCOL_VERSION;
820 		goto fatal_err;
821 	}
822 
823 	if (!CBS_write_bytes(&cookie, D1I(s)->cookie,
824 	    sizeof(D1I(s)->cookie), &cookie_len)) {
825 		D1I(s)->cookie_len = 0;
826 		al = SSL_AD_ILLEGAL_PARAMETER;
827 		goto fatal_err;
828 	}
829 	D1I(s)->cookie_len = cookie_len;
830 	D1I(s)->send_cookie = 1;
831 
832 	return 1;
833 
834  decode_err:
835 	al = SSL_AD_DECODE_ERROR;
836  fatal_err:
837 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
838 	return -1;
839 }
840 
841 int
842 ssl3_get_server_hello(SSL *s)
843 {
844 	CBS cbs, server_random, session_id;
845 	uint16_t server_version, cipher_suite;
846 	uint8_t compression_method;
847 	const SSL_CIPHER *cipher;
848 	const SSL_METHOD *method;
849 	unsigned long alg_k;
850 	size_t outlen;
851 	int al, ok;
852 	long n;
853 
854 	s->internal->first_packet = 1;
855 	n = ssl3_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
856 	    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok);
857 	if (!ok)
858 		return ((int)n);
859 	s->internal->first_packet = 0;
860 
861 	if (n < 0)
862 		goto decode_err;
863 
864 	CBS_init(&cbs, s->internal->init_msg, n);
865 
866 	if (SSL_is_dtls(s)) {
867 		if (S3I(s)->hs.tls12.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
868 			if (D1I(s)->send_cookie == 0) {
869 				S3I(s)->hs.tls12.reuse_message = 1;
870 				return (1);
871 			} else {
872 				/* Already sent a cookie. */
873 				al = SSL_AD_UNEXPECTED_MESSAGE;
874 				SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
875 				goto fatal_err;
876 			}
877 		}
878 	}
879 
880 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_SERVER_HELLO) {
881 		al = SSL_AD_UNEXPECTED_MESSAGE;
882 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
883 		goto fatal_err;
884 	}
885 
886 	if (!CBS_get_u16(&cbs, &server_version))
887 		goto decode_err;
888 
889 	if (!ssl_check_version_from_server(s, server_version)) {
890 		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
891 		s->version = (s->version & 0xff00) | (server_version & 0xff);
892 		al = SSL_AD_PROTOCOL_VERSION;
893 		goto fatal_err;
894 	}
895 	s->version = server_version;
896 
897 	S3I(s)->hs.negotiated_tls_version = ssl_tls_version(server_version);
898 	if (S3I(s)->hs.negotiated_tls_version == 0) {
899 		SSLerror(s, ERR_R_INTERNAL_ERROR);
900 		goto err;
901 	}
902 
903 	if ((method = ssl_get_method(server_version)) == NULL) {
904 		SSLerror(s, ERR_R_INTERNAL_ERROR);
905 		goto err;
906 	}
907 	s->method = method;
908 
909 	/* Server random. */
910 	if (!CBS_get_bytes(&cbs, &server_random, SSL3_RANDOM_SIZE))
911 		goto decode_err;
912 	if (!CBS_write_bytes(&server_random, s->s3->server_random,
913 	    sizeof(s->s3->server_random), NULL))
914 		goto err;
915 
916 	if (S3I(s)->hs.our_max_tls_version >= TLS1_2_VERSION &&
917 	    S3I(s)->hs.negotiated_tls_version < S3I(s)->hs.our_max_tls_version) {
918 		/*
919 		 * RFC 8446 section 4.1.3. We must not downgrade if the server
920 		 * random value contains the TLS 1.2 or TLS 1.1 magical value.
921 		 */
922 		if (!CBS_skip(&server_random,
923 		    CBS_len(&server_random) - sizeof(tls13_downgrade_12)))
924 			goto err;
925 		if (S3I(s)->hs.negotiated_tls_version == TLS1_2_VERSION &&
926 		    CBS_mem_equal(&server_random, tls13_downgrade_12,
927 		    sizeof(tls13_downgrade_12))) {
928 			al = SSL_AD_ILLEGAL_PARAMETER;
929 			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
930 			goto fatal_err;
931 		}
932 		if (CBS_mem_equal(&server_random, tls13_downgrade_11,
933 		    sizeof(tls13_downgrade_11))) {
934 			al = SSL_AD_ILLEGAL_PARAMETER;
935 			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
936 			goto fatal_err;
937 		}
938 	}
939 
940 	/* Session ID. */
941 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
942 		goto decode_err;
943 
944 	if (CBS_len(&session_id) > SSL3_SESSION_ID_SIZE) {
945 		al = SSL_AD_ILLEGAL_PARAMETER;
946 		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
947 		goto fatal_err;
948 	}
949 
950 	/* Cipher suite. */
951 	if (!CBS_get_u16(&cbs, &cipher_suite))
952 		goto decode_err;
953 
954 	/*
955 	 * Check if we want to resume the session based on external
956 	 * pre-shared secret.
957 	 */
958 	if (s->internal->tls_session_secret_cb) {
959 		SSL_CIPHER *pref_cipher = NULL;
960 		s->session->master_key_length = sizeof(s->session->master_key);
961 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
962 		    &s->session->master_key_length, NULL, &pref_cipher,
963 		    s->internal->tls_session_secret_cb_arg)) {
964 			s->session->cipher = pref_cipher ? pref_cipher :
965 			    ssl3_get_cipher_by_value(cipher_suite);
966 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
967 		}
968 	}
969 
970 	if (s->session->session_id_length != 0 &&
971 	    CBS_mem_equal(&session_id, s->session->session_id,
972 		s->session->session_id_length)) {
973 		if (s->sid_ctx_length != s->session->sid_ctx_length ||
974 		    timingsafe_memcmp(s->session->sid_ctx,
975 		    s->sid_ctx, s->sid_ctx_length) != 0) {
976 			/* actually a client application bug */
977 			al = SSL_AD_ILLEGAL_PARAMETER;
978 			SSLerror(s, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
979 			goto fatal_err;
980 		}
981 		s->s3->flags |= SSL3_FLAGS_CCS_OK;
982 		s->internal->hit = 1;
983 	} else {
984 		/* a miss or crap from the other end */
985 
986 		/* If we were trying for session-id reuse, make a new
987 		 * SSL_SESSION so we don't stuff up other people */
988 		s->internal->hit = 0;
989 		if (s->session->session_id_length > 0) {
990 			if (!ssl_get_new_session(s, 0)) {
991 				al = SSL_AD_INTERNAL_ERROR;
992 				goto fatal_err;
993 			}
994 		}
995 
996 		/*
997 		 * XXX - improve the handling for the case where there is a
998 		 * zero length session identifier.
999 		 */
1000 		if (!CBS_write_bytes(&session_id, s->session->session_id,
1001 		    sizeof(s->session->session_id), &outlen))
1002 			goto err;
1003 		s->session->session_id_length = outlen;
1004 
1005 		s->session->ssl_version = s->version;
1006 	}
1007 
1008 	if ((cipher = ssl3_get_cipher_by_value(cipher_suite)) == NULL) {
1009 		al = SSL_AD_ILLEGAL_PARAMETER;
1010 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_RETURNED);
1011 		goto fatal_err;
1012 	}
1013 
1014 	/* TLS v1.2 only ciphersuites require v1.2 or later. */
1015 	if ((cipher->algorithm_ssl & SSL_TLSV1_2) &&
1016 	    S3I(s)->hs.negotiated_tls_version < TLS1_2_VERSION) {
1017 		al = SSL_AD_ILLEGAL_PARAMETER;
1018 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
1019 		goto fatal_err;
1020 	}
1021 
1022 	if (!ssl_cipher_in_list(SSL_get_ciphers(s), cipher)) {
1023 		/* we did not say we would use this cipher */
1024 		al = SSL_AD_ILLEGAL_PARAMETER;
1025 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
1026 		goto fatal_err;
1027 	}
1028 
1029 	/*
1030 	 * Depending on the session caching (internal/external), the cipher
1031 	 * and/or cipher_id values may not be set. Make sure that
1032 	 * cipher_id is set and use it for comparison.
1033 	 */
1034 	if (s->session->cipher)
1035 		s->session->cipher_id = s->session->cipher->id;
1036 	if (s->internal->hit && (s->session->cipher_id != cipher->id)) {
1037 		al = SSL_AD_ILLEGAL_PARAMETER;
1038 		SSLerror(s, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1039 		goto fatal_err;
1040 	}
1041 	S3I(s)->hs.cipher = cipher;
1042 
1043 	if (!tls1_transcript_hash_init(s))
1044 		goto err;
1045 
1046 	/*
1047 	 * Don't digest cached records if no sigalgs: we may need them for
1048 	 * client authentication.
1049 	 */
1050 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
1051 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)))
1052 		tls1_transcript_free(s);
1053 
1054 	if (!CBS_get_u8(&cbs, &compression_method))
1055 		goto decode_err;
1056 
1057 	if (compression_method != 0) {
1058 		al = SSL_AD_ILLEGAL_PARAMETER;
1059 		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1060 		goto fatal_err;
1061 	}
1062 
1063 	if (!tlsext_client_parse(s, SSL_TLSEXT_MSG_SH, &cbs, &al)) {
1064 		SSLerror(s, SSL_R_PARSE_TLSEXT);
1065 		goto fatal_err;
1066 	}
1067 
1068 	/*
1069 	 * Determine if we need to see RI. Strictly speaking if we want to
1070 	 * avoid an attack we should *always* see RI even on initial server
1071 	 * hello because the client doesn't see any renegotiation during an
1072 	 * attack. However this would mean we could not connect to any server
1073 	 * which doesn't support RI so for the immediate future tolerate RI
1074 	 * absence on initial connect only.
1075 	 */
1076 	if (!S3I(s)->renegotiate_seen &&
1077 	    !(s->internal->options & SSL_OP_LEGACY_SERVER_CONNECT)) {
1078 		al = SSL_AD_HANDSHAKE_FAILURE;
1079 		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1080 		goto fatal_err;
1081 	}
1082 
1083 	if (ssl_check_serverhello_tlsext(s) <= 0) {
1084 		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
1085 		goto err;
1086 	}
1087 
1088 	return (1);
1089 
1090  decode_err:
1091 	/* wrong packet length */
1092 	al = SSL_AD_DECODE_ERROR;
1093 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1094  fatal_err:
1095 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1096  err:
1097 	return (-1);
1098 }
1099 
1100 int
1101 ssl3_get_server_certificate(SSL *s)
1102 {
1103 	int			 al, i, ok, ret = -1;
1104 	long			 n;
1105 	CBS			 cbs, cert_list;
1106 	X509			*x = NULL;
1107 	const unsigned char	*q;
1108 	STACK_OF(X509)		*sk = NULL;
1109 	SESS_CERT		*sc;
1110 	EVP_PKEY		*pkey = NULL;
1111 
1112 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
1113 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
1114 	if (!ok)
1115 		return ((int)n);
1116 
1117 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1118 		S3I(s)->hs.tls12.reuse_message = 1;
1119 		return (1);
1120 	}
1121 
1122 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
1123 		al = SSL_AD_UNEXPECTED_MESSAGE;
1124 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1125 		goto fatal_err;
1126 	}
1127 
1128 
1129 	if ((sk = sk_X509_new_null()) == NULL) {
1130 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1131 		goto err;
1132 	}
1133 
1134 	if (n < 0)
1135 		goto decode_err;
1136 
1137 	CBS_init(&cbs, s->internal->init_msg, n);
1138 	if (CBS_len(&cbs) < 3)
1139 		goto decode_err;
1140 
1141 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
1142 	    CBS_len(&cbs) != 0) {
1143 		al = SSL_AD_DECODE_ERROR;
1144 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1145 		goto fatal_err;
1146 	}
1147 
1148 	while (CBS_len(&cert_list) > 0) {
1149 		CBS cert;
1150 
1151 		if (CBS_len(&cert_list) < 3)
1152 			goto decode_err;
1153 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1154 			al = SSL_AD_DECODE_ERROR;
1155 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1156 			goto fatal_err;
1157 		}
1158 
1159 		q = CBS_data(&cert);
1160 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1161 		if (x == NULL) {
1162 			al = SSL_AD_BAD_CERTIFICATE;
1163 			SSLerror(s, ERR_R_ASN1_LIB);
1164 			goto fatal_err;
1165 		}
1166 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1167 			al = SSL_AD_DECODE_ERROR;
1168 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1169 			goto fatal_err;
1170 		}
1171 		if (!sk_X509_push(sk, x)) {
1172 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1173 			goto err;
1174 		}
1175 		x = NULL;
1176 	}
1177 
1178 	i = ssl_verify_cert_chain(s, sk);
1179 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1180 		al = ssl_verify_alarm_type(s->verify_result);
1181 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1182 		goto fatal_err;
1183 
1184 	}
1185 	ERR_clear_error(); /* but we keep s->verify_result */
1186 
1187 	sc = ssl_sess_cert_new();
1188 	if (sc == NULL)
1189 		goto err;
1190 	ssl_sess_cert_free(SSI(s)->sess_cert);
1191 	SSI(s)->sess_cert = sc;
1192 
1193 	sc->cert_chain = sk;
1194 	/*
1195 	 * Inconsistency alert: cert_chain does include the peer's
1196 	 * certificate, which we don't include in s3_srvr.c
1197 	 */
1198 	x = sk_X509_value(sk, 0);
1199 	sk = NULL;
1200 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1201 
1202 	pkey = X509_get_pubkey(x);
1203 
1204 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1205 		x = NULL;
1206 		al = SSL3_AL_FATAL;
1207 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1208 		goto fatal_err;
1209 	}
1210 
1211 	i = ssl_cert_type(x, pkey);
1212 	if (i < 0) {
1213 		x = NULL;
1214 		al = SSL3_AL_FATAL;
1215 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1216 		goto fatal_err;
1217 	}
1218 
1219 	sc->peer_cert_type = i;
1220 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1221 	/*
1222 	 * Why would the following ever happen?
1223 	 * We just created sc a couple of lines ago.
1224 	 */
1225 	X509_free(sc->peer_pkeys[i].x509);
1226 	sc->peer_pkeys[i].x509 = x;
1227 	sc->peer_key = &(sc->peer_pkeys[i]);
1228 
1229 	X509_free(s->session->peer);
1230 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1231 	s->session->peer = x;
1232 	s->session->verify_result = s->verify_result;
1233 
1234 	x = NULL;
1235 	ret = 1;
1236 
1237 	if (0) {
1238  decode_err:
1239 		/* wrong packet length */
1240 		al = SSL_AD_DECODE_ERROR;
1241 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1242  fatal_err:
1243 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1244 	}
1245  err:
1246 	EVP_PKEY_free(pkey);
1247 	X509_free(x);
1248 	sk_X509_pop_free(sk, X509_free);
1249 
1250 	return (ret);
1251 }
1252 
1253 static int
1254 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1255 {
1256 	CBS dhp, dhg, dhpk;
1257 	BN_CTX *bn_ctx = NULL;
1258 	SESS_CERT *sc = NULL;
1259 	DH *dh = NULL;
1260 	long alg_a;
1261 	int al;
1262 
1263 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1264 	sc = SSI(s)->sess_cert;
1265 
1266 	if ((dh = DH_new()) == NULL) {
1267 		SSLerror(s, ERR_R_DH_LIB);
1268 		goto err;
1269 	}
1270 
1271 	if (!CBS_get_u16_length_prefixed(cbs, &dhp))
1272 		goto decode_err;
1273 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1274 		SSLerror(s, ERR_R_BN_LIB);
1275 		goto err;
1276 	}
1277 
1278 	if (!CBS_get_u16_length_prefixed(cbs, &dhg))
1279 		goto decode_err;
1280 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1281 		SSLerror(s, ERR_R_BN_LIB);
1282 		goto err;
1283 	}
1284 
1285 	if (!CBS_get_u16_length_prefixed(cbs, &dhpk))
1286 		goto decode_err;
1287 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1288 	    NULL)) == NULL) {
1289 		SSLerror(s, ERR_R_BN_LIB);
1290 		goto err;
1291 	}
1292 
1293 	/*
1294 	 * Check the strength of the DH key just constructed.
1295 	 * Discard keys weaker than 1024 bits.
1296 	 */
1297 	if (DH_size(dh) < 1024 / 8) {
1298 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1299 		goto err;
1300 	}
1301 
1302 	if (alg_a & SSL_aRSA)
1303 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1304 	else
1305 		/* XXX - Anonymous DH, so no certificate or pkey. */
1306 		*pkey = NULL;
1307 
1308 	sc->peer_dh_tmp = dh;
1309 
1310 	return (1);
1311 
1312  decode_err:
1313 	al = SSL_AD_DECODE_ERROR;
1314 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1315 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1316 
1317  err:
1318 	DH_free(dh);
1319 	BN_CTX_free(bn_ctx);
1320 
1321 	return (-1);
1322 }
1323 
1324 static int
1325 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1326 {
1327 	EC_KEY *ecdh = NULL;
1328 	int ret = -1;
1329 
1330 	/* Extract the server's ephemeral ECDH public key. */
1331 	if ((ecdh = EC_KEY_new()) == NULL) {
1332 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1333 		goto err;
1334 	}
1335 	if (!ssl_kex_peer_public_ecdhe_ecp(ecdh, nid, public)) {
1336 		SSLerror(s, SSL_R_BAD_ECPOINT);
1337 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1338 		goto err;
1339 	}
1340 
1341 	sc->peer_nid = nid;
1342 	sc->peer_ecdh_tmp = ecdh;
1343 	ecdh = NULL;
1344 
1345 	ret = 1;
1346 
1347  err:
1348 	EC_KEY_free(ecdh);
1349 
1350 	return (ret);
1351 }
1352 
1353 static int
1354 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1355 {
1356 	size_t outlen;
1357 
1358 	if (nid != NID_X25519) {
1359 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1360 		goto err;
1361 	}
1362 
1363 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1364 		SSLerror(s, SSL_R_BAD_ECPOINT);
1365 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1366 		goto err;
1367 	}
1368 
1369 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1370 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1371 		goto err;
1372 	}
1373 
1374 	return (1);
1375 
1376  err:
1377 	return (-1);
1378 }
1379 
1380 static int
1381 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1382 {
1383 	CBS public;
1384 	uint8_t curve_type;
1385 	uint16_t curve_id;
1386 	SESS_CERT *sc;
1387 	long alg_a;
1388 	int nid;
1389 	int al;
1390 
1391 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1392 	sc = SSI(s)->sess_cert;
1393 
1394 	/* Only named curves are supported. */
1395 	if (!CBS_get_u8(cbs, &curve_type) ||
1396 	    curve_type != NAMED_CURVE_TYPE ||
1397 	    !CBS_get_u16(cbs, &curve_id)) {
1398 		al = SSL_AD_DECODE_ERROR;
1399 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1400 		goto fatal_err;
1401 	}
1402 
1403 	/*
1404 	 * Check that the curve is one of our preferences - if it is not,
1405 	 * the server has sent us an invalid curve.
1406 	 */
1407 	if (tls1_check_curve(s, curve_id) != 1) {
1408 		al = SSL_AD_DECODE_ERROR;
1409 		SSLerror(s, SSL_R_WRONG_CURVE);
1410 		goto fatal_err;
1411 	}
1412 
1413 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1414 		al = SSL_AD_INTERNAL_ERROR;
1415 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1416 		goto fatal_err;
1417 	}
1418 
1419 	if (!CBS_get_u8_length_prefixed(cbs, &public))
1420 		goto decode_err;
1421 
1422 	if (nid == NID_X25519) {
1423 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1424 			goto err;
1425 	} else {
1426 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1427 			goto err;
1428 	}
1429 
1430 	/*
1431 	 * The ECC/TLS specification does not mention the use of DSA to sign
1432 	 * ECParameters in the server key exchange message. We do support RSA
1433 	 * and ECDSA.
1434 	 */
1435 	if (alg_a & SSL_aRSA)
1436 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1437 	else if (alg_a & SSL_aECDSA)
1438 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1439 	else
1440 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1441 		*pkey = NULL;
1442 
1443 	return (1);
1444 
1445  decode_err:
1446 	al = SSL_AD_DECODE_ERROR;
1447 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1448 
1449  fatal_err:
1450 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1451 
1452  err:
1453 	return (-1);
1454 }
1455 
1456 int
1457 ssl3_get_server_key_exchange(SSL *s)
1458 {
1459 	CBS cbs, signature;
1460 	EVP_PKEY *pkey = NULL;
1461 	EVP_MD_CTX md_ctx;
1462 	const unsigned char *param;
1463 	long n, alg_k, alg_a;
1464 	int al, ok;
1465 	size_t param_len;
1466 
1467 	EVP_MD_CTX_init(&md_ctx);
1468 
1469 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
1470 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1471 
1472 	/*
1473 	 * Use same message size as in ssl3_get_certificate_request()
1474 	 * as ServerKeyExchange message may be skipped.
1475 	 */
1476 	n = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1477 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1478 	if (!ok)
1479 		return ((int)n);
1480 
1481 	if (n < 0)
1482 		goto err;
1483 
1484 	CBS_init(&cbs, s->internal->init_msg, n);
1485 
1486 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1487 		/*
1488 		 * Do not skip server key exchange if this cipher suite uses
1489 		 * ephemeral keys.
1490 		 */
1491 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1492 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1493 			al = SSL_AD_UNEXPECTED_MESSAGE;
1494 			goto fatal_err;
1495 		}
1496 
1497 		S3I(s)->hs.tls12.reuse_message = 1;
1498 		EVP_MD_CTX_cleanup(&md_ctx);
1499 		return (1);
1500 	}
1501 
1502 	if (SSI(s)->sess_cert != NULL) {
1503 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1504 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1505 
1506 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1507 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1508 
1509 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1510 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1511 	} else {
1512 		SSI(s)->sess_cert = ssl_sess_cert_new();
1513 		if (SSI(s)->sess_cert == NULL)
1514 			goto err;
1515 	}
1516 
1517 	param = CBS_data(&cbs);
1518 	param_len = CBS_len(&cbs);
1519 
1520 	if (alg_k & SSL_kDHE) {
1521 		if (ssl3_get_server_kex_dhe(s, &pkey, &cbs) != 1)
1522 			goto err;
1523 	} else if (alg_k & SSL_kECDHE) {
1524 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &cbs) != 1)
1525 			goto err;
1526 	} else if (alg_k != 0) {
1527 		al = SSL_AD_UNEXPECTED_MESSAGE;
1528 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1529 		goto fatal_err;
1530 	}
1531 
1532 	param_len -= CBS_len(&cbs);
1533 
1534 	/* if it was signed, check the signature */
1535 	if (pkey != NULL) {
1536 		uint16_t sigalg_value = SIGALG_NONE;
1537 		const struct ssl_sigalg *sigalg;
1538 		EVP_PKEY_CTX *pctx;
1539 
1540 		if (SSL_USE_SIGALGS(s)) {
1541 			if (!CBS_get_u16(&cbs, &sigalg_value))
1542 				goto decode_err;
1543 		}
1544 		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1545 			goto decode_err;
1546 		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1547 			al = SSL_AD_DECODE_ERROR;
1548 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1549 			goto fatal_err;
1550 		}
1551 
1552 		if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1553 		    sigalg_value)) == NULL) {
1554 			al = SSL_AD_DECODE_ERROR;
1555 			goto fatal_err;
1556 		}
1557 		S3I(s)->hs.peer_sigalg = sigalg;
1558 
1559 		if (!EVP_DigestVerifyInit(&md_ctx, &pctx, sigalg->md(),
1560 		    NULL, pkey))
1561 			goto err;
1562 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
1563 		    SSL3_RANDOM_SIZE))
1564 			goto err;
1565 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1566 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1567 		    RSA_PKCS1_PSS_PADDING) ||
1568 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1569 			goto err;
1570 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
1571 		    SSL3_RANDOM_SIZE))
1572 			goto err;
1573 		if (!EVP_DigestVerifyUpdate(&md_ctx, param, param_len))
1574 			goto err;
1575 		if (EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
1576 		    CBS_len(&signature)) <= 0) {
1577 			al = SSL_AD_DECRYPT_ERROR;
1578 			SSLerror(s, SSL_R_BAD_SIGNATURE);
1579 			goto fatal_err;
1580 		}
1581 	} else {
1582 		/* aNULL does not need public keys. */
1583 		if (!(alg_a & SSL_aNULL)) {
1584 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1585 			goto err;
1586 		}
1587 	}
1588 
1589 	if (CBS_len(&cbs) != 0) {
1590 		al = SSL_AD_DECODE_ERROR;
1591 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1592 		goto fatal_err;
1593 	}
1594 
1595 	EVP_PKEY_free(pkey);
1596 	EVP_MD_CTX_cleanup(&md_ctx);
1597 
1598 	return (1);
1599 
1600  decode_err:
1601 	al = SSL_AD_DECODE_ERROR;
1602 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1603 
1604  fatal_err:
1605 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1606 
1607  err:
1608 	EVP_PKEY_free(pkey);
1609 	EVP_MD_CTX_cleanup(&md_ctx);
1610 
1611 	return (-1);
1612 }
1613 
1614 int
1615 ssl3_get_certificate_request(SSL *s)
1616 {
1617 	int			 ok, ret = 0;
1618 	long			 n;
1619 	CBS			 cert_request, cert_types, rdn_list;
1620 	X509_NAME		*xn = NULL;
1621 	const unsigned char	*q;
1622 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1623 
1624 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1625 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1626 	if (!ok)
1627 		return ((int)n);
1628 
1629 	S3I(s)->hs.tls12.cert_request = 0;
1630 
1631 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_DONE) {
1632 		S3I(s)->hs.tls12.reuse_message = 1;
1633 		/*
1634 		 * If we get here we don't need any cached handshake records
1635 		 * as we wont be doing client auth.
1636 		 */
1637 		tls1_transcript_free(s);
1638 		return (1);
1639 	}
1640 
1641 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1642 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1643 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1644 		goto err;
1645 	}
1646 
1647 	/* TLS does not like anon-DH with client cert */
1648 	if (S3I(s)->hs.cipher->algorithm_auth & SSL_aNULL) {
1649 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1650 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1651 		goto err;
1652 	}
1653 
1654 	if (n < 0)
1655 		goto decode_err;
1656 	CBS_init(&cert_request, s->internal->init_msg, n);
1657 
1658 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1659 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1660 		goto err;
1661 	}
1662 
1663 	if (!CBS_get_u8_length_prefixed(&cert_request, &cert_types))
1664 		goto decode_err;
1665 
1666 	if (SSL_USE_SIGALGS(s)) {
1667 		CBS sigalgs;
1668 
1669 		if (CBS_len(&cert_request) < 2) {
1670 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1671 			goto err;
1672 		}
1673 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1674 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1675 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1676 			goto err;
1677 		}
1678 		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1679 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1680 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1681 			goto err;
1682 		}
1683 		if (!CBS_stow(&sigalgs, &S3I(s)->hs.sigalgs,
1684 		    &S3I(s)->hs.sigalgs_len))
1685 			goto err;
1686 	}
1687 
1688 	/* get the CA RDNs */
1689 	if (CBS_len(&cert_request) < 2) {
1690 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1691 		goto err;
1692 	}
1693 
1694 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1695 	    CBS_len(&cert_request) != 0) {
1696 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1697 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1698 		goto err;
1699 	}
1700 
1701 	while (CBS_len(&rdn_list) > 0) {
1702 		CBS rdn;
1703 
1704 		if (CBS_len(&rdn_list) < 2) {
1705 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1706 			goto err;
1707 		}
1708 
1709 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1710 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1711 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1712 			goto err;
1713 		}
1714 
1715 		q = CBS_data(&rdn);
1716 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1717 			ssl3_send_alert(s, SSL3_AL_FATAL,
1718 			    SSL_AD_DECODE_ERROR);
1719 			SSLerror(s, ERR_R_ASN1_LIB);
1720 			goto err;
1721 		}
1722 
1723 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1724 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1725 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1726 			goto err;
1727 		}
1728 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1729 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1730 			goto err;
1731 		}
1732 		xn = NULL;	/* avoid free in err block */
1733 	}
1734 
1735 	/* we should setup a certificate to return.... */
1736 	S3I(s)->hs.tls12.cert_request = 1;
1737 	sk_X509_NAME_pop_free(S3I(s)->hs.tls12.ca_names, X509_NAME_free);
1738 	S3I(s)->hs.tls12.ca_names = ca_sk;
1739 	ca_sk = NULL;
1740 
1741 	ret = 1;
1742 	if (0) {
1743  decode_err:
1744 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1745 	}
1746  err:
1747 	X509_NAME_free(xn);
1748 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1749 	return (ret);
1750 }
1751 
1752 static int
1753 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1754 {
1755 	return (X509_NAME_cmp(*a, *b));
1756 }
1757 
1758 int
1759 ssl3_get_new_session_ticket(SSL *s)
1760 {
1761 	int			 ok, al, ret = 0;
1762 	uint32_t		 lifetime_hint;
1763 	long			 n;
1764 	CBS			 cbs, session_ticket;
1765 
1766 	n = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1767 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1768 	if (!ok)
1769 		return ((int)n);
1770 
1771 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) {
1772 		S3I(s)->hs.tls12.reuse_message = 1;
1773 		return (1);
1774 	}
1775 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_NEWSESSION_TICKET) {
1776 		al = SSL_AD_UNEXPECTED_MESSAGE;
1777 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1778 		goto fatal_err;
1779 	}
1780 
1781 	if (n < 0) {
1782 		al = SSL_AD_DECODE_ERROR;
1783 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1784 		goto fatal_err;
1785 	}
1786 
1787 	CBS_init(&cbs, s->internal->init_msg, n);
1788 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1789 #if UINT32_MAX > LONG_MAX
1790 	    lifetime_hint > LONG_MAX ||
1791 #endif
1792 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1793 	    CBS_len(&cbs) != 0) {
1794 		al = SSL_AD_DECODE_ERROR;
1795 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1796 		goto fatal_err;
1797 	}
1798 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1799 
1800 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1801 	    &s->session->tlsext_ticklen)) {
1802 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1803 		goto err;
1804 	}
1805 
1806 	/*
1807 	 * There are two ways to detect a resumed ticket sesion.
1808 	 * One is to set an appropriate session ID and then the server
1809 	 * must return a match in ServerHello. This allows the normal
1810 	 * client session ID matching to work and we know much
1811 	 * earlier that the ticket has been accepted.
1812 	 *
1813 	 * The other way is to set zero length session ID when the
1814 	 * ticket is presented and rely on the handshake to determine
1815 	 * session resumption.
1816 	 *
1817 	 * We choose the former approach because this fits in with
1818 	 * assumptions elsewhere in OpenSSL. The session ID is set
1819 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1820 	 * ticket.
1821 	 */
1822 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1823 	    s->session->session_id, &s->session->session_id_length,
1824 	    EVP_sha256(), NULL);
1825 	ret = 1;
1826 	return (ret);
1827  fatal_err:
1828 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1829  err:
1830 	return (-1);
1831 }
1832 
1833 int
1834 ssl3_get_cert_status(SSL *s)
1835 {
1836 	CBS			 cert_status, response;
1837 	int			 ok, al;
1838 	long			 n;
1839 	uint8_t			 status_type;
1840 
1841 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1842 	    SSL3_ST_CR_CERT_STATUS_B, -1, 16384, &ok);
1843 	if (!ok)
1844 		return ((int)n);
1845 
1846 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1847 		/*
1848 		 * Tell the callback the server did not send us an OSCP
1849 		 * response, and has decided to head directly to key exchange.
1850 		 */
1851 		if (s->ctx->internal->tlsext_status_cb) {
1852 			int ret;
1853 
1854 			free(s->internal->tlsext_ocsp_resp);
1855 			s->internal->tlsext_ocsp_resp = NULL;
1856 			s->internal->tlsext_ocsp_resp_len = 0;
1857 
1858 			ret = s->ctx->internal->tlsext_status_cb(s,
1859 			    s->ctx->internal->tlsext_status_arg);
1860 			if (ret == 0) {
1861 				al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1862 				SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1863 				goto fatal_err;
1864 			}
1865 			if (ret < 0) {
1866 				al = SSL_AD_INTERNAL_ERROR;
1867 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1868 				goto fatal_err;
1869 			}
1870 		}
1871 		S3I(s)->hs.tls12.reuse_message = 1;
1872 		return (1);
1873 	}
1874 
1875 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE &&
1876 	    S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1877 		al = SSL_AD_UNEXPECTED_MESSAGE;
1878 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1879 		goto fatal_err;
1880 	}
1881 
1882 	if (n < 0) {
1883 		/* need at least status type + length */
1884 		al = SSL_AD_DECODE_ERROR;
1885 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1886 		goto fatal_err;
1887 	}
1888 
1889 	CBS_init(&cert_status, s->internal->init_msg, n);
1890 	if (!CBS_get_u8(&cert_status, &status_type) ||
1891 	    CBS_len(&cert_status) < 3) {
1892 		/* need at least status type + length */
1893 		al = SSL_AD_DECODE_ERROR;
1894 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1895 		goto fatal_err;
1896 	}
1897 
1898 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1899 		al = SSL_AD_DECODE_ERROR;
1900 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1901 		goto fatal_err;
1902 	}
1903 
1904 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1905 	    CBS_len(&cert_status) != 0) {
1906 		al = SSL_AD_DECODE_ERROR;
1907 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1908 		goto fatal_err;
1909 	}
1910 
1911 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1912 	    &s->internal->tlsext_ocsp_resp_len)) {
1913 		al = SSL_AD_INTERNAL_ERROR;
1914 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1915 		goto fatal_err;
1916 	}
1917 
1918 	if (s->ctx->internal->tlsext_status_cb) {
1919 		int ret;
1920 		ret = s->ctx->internal->tlsext_status_cb(s,
1921 		    s->ctx->internal->tlsext_status_arg);
1922 		if (ret == 0) {
1923 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1924 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1925 			goto fatal_err;
1926 		}
1927 		if (ret < 0) {
1928 			al = SSL_AD_INTERNAL_ERROR;
1929 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1930 			goto fatal_err;
1931 		}
1932 	}
1933 	return (1);
1934  fatal_err:
1935 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1936 	return (-1);
1937 }
1938 
1939 int
1940 ssl3_get_server_done(SSL *s)
1941 {
1942 	int	ok, ret = 0;
1943 	long	n;
1944 
1945 	n = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1946 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1947 	    30, /* should be very small, like 0 :-) */ &ok);
1948 	if (!ok)
1949 		return ((int)n);
1950 
1951 	if (n > 0) {
1952 		/* should contain no data */
1953 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1954 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1955 		return (-1);
1956 	}
1957 	ret = 1;
1958 	return (ret);
1959 }
1960 
1961 static int
1962 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1963 {
1964 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1965 	unsigned char *enc_pms = NULL;
1966 	EVP_PKEY *pkey = NULL;
1967 	int ret = -1;
1968 	int enc_len;
1969 	CBB epms;
1970 
1971 	/*
1972 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1973 	 */
1974 
1975 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA].x509);
1976 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1977 	    pkey->pkey.rsa == NULL) {
1978 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1979 		goto err;
1980 	}
1981 
1982 	/* XXX - our max protocol version. */
1983 	pms[0] = s->client_version >> 8;
1984 	pms[1] = s->client_version & 0xff;
1985 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1986 
1987 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1988 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1989 		goto err;
1990 	}
1991 
1992 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1993 	    RSA_PKCS1_PADDING);
1994 	if (enc_len <= 0) {
1995 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1996 		goto err;
1997 	}
1998 
1999 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
2000 		goto err;
2001 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
2002 		goto err;
2003 	if (!CBB_flush(cbb))
2004 		goto err;
2005 
2006 	if (!tls12_derive_master_secret(s, pms, sizeof(pms)))
2007 		goto err;
2008 
2009 	ret = 1;
2010 
2011  err:
2012 	explicit_bzero(pms, sizeof(pms));
2013 	EVP_PKEY_free(pkey);
2014 	free(enc_pms);
2015 
2016 	return (ret);
2017 }
2018 
2019 static int
2020 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2021 {
2022 	DH *dh_srvr = NULL, *dh_clnt = NULL;
2023 	unsigned char *key = NULL;
2024 	int key_size = 0, key_len;
2025 	unsigned char *data;
2026 	int ret = -1;
2027 	CBB dh_Yc;
2028 
2029 	/* Ensure that we have an ephemeral key for DHE. */
2030 	if (sess_cert->peer_dh_tmp == NULL) {
2031 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2032 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2033 		goto err;
2034 	}
2035 	dh_srvr = sess_cert->peer_dh_tmp;
2036 
2037 	/* Generate a new random key. */
2038 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2039 		SSLerror(s, ERR_R_DH_LIB);
2040 		goto err;
2041 	}
2042 	if (!DH_generate_key(dh_clnt)) {
2043 		SSLerror(s, ERR_R_DH_LIB);
2044 		goto err;
2045 	}
2046 	if ((key_size = DH_size(dh_clnt)) <= 0) {
2047 		SSLerror(s, ERR_R_DH_LIB);
2048 		goto err;
2049 	}
2050 	if ((key = malloc(key_size)) == NULL) {
2051 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2052 		goto err;
2053 	}
2054 	if ((key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt)) <= 0) {
2055 		SSLerror(s, ERR_R_DH_LIB);
2056 		goto err;
2057 	}
2058 
2059 	if (!tls12_derive_master_secret(s, key, key_len))
2060 		goto err;
2061 
2062 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2063 		goto err;
2064 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2065 		goto err;
2066 	BN_bn2bin(dh_clnt->pub_key, data);
2067 	if (!CBB_flush(cbb))
2068 		goto err;
2069 
2070 	ret = 1;
2071 
2072  err:
2073 	DH_free(dh_clnt);
2074 	freezero(key, key_size);
2075 
2076 	return (ret);
2077 }
2078 
2079 static int
2080 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2081 {
2082 	EC_KEY *ecdh = NULL;
2083 	uint8_t *key = NULL;
2084 	size_t key_len = 0;
2085 	int ret = -1;
2086 	CBB ecpoint;
2087 
2088 	if ((ecdh = EC_KEY_new()) == NULL) {
2089 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2090 		goto err;
2091 	}
2092 
2093 	if (!ssl_kex_generate_ecdhe_ecp(ecdh, sc->peer_nid))
2094 		goto err;
2095 
2096 	/* Encode our public key. */
2097 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2098 		goto err;
2099 	if (!ssl_kex_public_ecdhe_ecp(ecdh, &ecpoint))
2100 		goto err;
2101 	if (!CBB_flush(cbb))
2102 		goto err;
2103 
2104 	if (!ssl_kex_derive_ecdhe_ecp(ecdh, sc->peer_ecdh_tmp, &key, &key_len))
2105 		goto err;
2106 	if (!tls12_derive_master_secret(s, key, key_len))
2107 		goto err;
2108 
2109 	ret = 1;
2110 
2111  err:
2112 	freezero(key, key_len);
2113 	EC_KEY_free(ecdh);
2114 
2115 	return (ret);
2116 }
2117 
2118 static int
2119 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2120 {
2121 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2122 	int ret = -1;
2123 	CBB ecpoint;
2124 
2125 	/* Generate X25519 key pair and derive shared key. */
2126 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2127 		goto err;
2128 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2129 		goto err;
2130 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2131 		goto err;
2132 	X25519_keypair(public_key, private_key);
2133 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2134 		goto err;
2135 
2136 	/* Serialize the public key. */
2137 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2138 		goto err;
2139 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2140 		goto err;
2141 	if (!CBB_flush(cbb))
2142 		goto err;
2143 
2144 	if (!tls12_derive_master_secret(s, shared_key, X25519_KEY_LENGTH))
2145 		goto err;
2146 
2147 	ret = 1;
2148 
2149  err:
2150 	free(public_key);
2151 	freezero(private_key, X25519_KEY_LENGTH);
2152 	freezero(shared_key, X25519_KEY_LENGTH);
2153 
2154 	return (ret);
2155 }
2156 
2157 static int
2158 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2159 {
2160 	if (sc->peer_x25519_tmp != NULL) {
2161 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2162 			goto err;
2163 	} else if (sc->peer_ecdh_tmp != NULL) {
2164 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2165 			goto err;
2166 	} else {
2167 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2168 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2169 		goto err;
2170 	}
2171 
2172 	return (1);
2173 
2174  err:
2175 	return (-1);
2176 }
2177 
2178 static int
2179 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2180 {
2181 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2182 	EVP_PKEY *pub_key = NULL;
2183 	EVP_PKEY_CTX *pkey_ctx;
2184 	X509 *peer_cert;
2185 	size_t msglen;
2186 	unsigned int md_len;
2187 	EVP_MD_CTX *ukm_hash;
2188 	int ret = -1;
2189 	int nid;
2190 	CBB gostblob;
2191 
2192 	/* Get server sertificate PKEY and create ctx from it */
2193 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2194 	if (peer_cert == NULL) {
2195 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2196 		goto err;
2197 	}
2198 
2199 	pub_key = X509_get_pubkey(peer_cert);
2200 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2201 
2202 	/*
2203 	 * If we have send a certificate, and certificate key parameters match
2204 	 * those of server certificate, use certificate key for key exchange.
2205 	 * Otherwise, generate ephemeral key pair.
2206 	 */
2207 	EVP_PKEY_encrypt_init(pkey_ctx);
2208 
2209 	/* Generate session key. */
2210 	arc4random_buf(premaster_secret, 32);
2211 
2212 	/*
2213 	 * If we have client certificate, use its secret as peer key.
2214 	 */
2215 	if (S3I(s)->hs.tls12.cert_request && s->cert->key->privatekey) {
2216 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2217 		    s->cert->key->privatekey) <=0) {
2218 			/*
2219 			 * If there was an error - just ignore it.
2220 			 * Ephemeral key would be used.
2221 			 */
2222 			ERR_clear_error();
2223 		}
2224 	}
2225 
2226 	/*
2227 	 * Compute shared IV and store it in algorithm-specific context data.
2228 	 */
2229 	ukm_hash = EVP_MD_CTX_new();
2230 	if (ukm_hash == NULL) {
2231 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2232 		goto err;
2233 	}
2234 
2235 	/* XXX check handshake hash instead. */
2236 	if (S3I(s)->hs.cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
2237 		nid = NID_id_GostR3411_94;
2238 	else
2239 		nid = NID_id_tc26_gost3411_2012_256;
2240 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2241 		goto err;
2242 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2243 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2244 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2245 	EVP_MD_CTX_free(ukm_hash);
2246 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2247 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2248 		SSLerror(s, SSL_R_LIBRARY_BUG);
2249 		goto err;
2250 	}
2251 
2252 	/*
2253 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2254 	 */
2255 	msglen = 255;
2256 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2257 	    32) < 0) {
2258 		SSLerror(s, SSL_R_LIBRARY_BUG);
2259 		goto err;
2260 	}
2261 
2262 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2263 		goto err;
2264 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2265 		goto err;
2266 	if (!CBB_flush(cbb))
2267 		goto err;
2268 
2269 	/* Check if pubkey from client certificate was used. */
2270 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2271 	    NULL) > 0) {
2272 		/* Set flag "skip certificate verify". */
2273 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2274 	}
2275 	EVP_PKEY_CTX_free(pkey_ctx);
2276 
2277 	if (!tls12_derive_master_secret(s, premaster_secret, 32))
2278 		goto err;
2279 
2280 	ret = 1;
2281 
2282  err:
2283 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2284 	EVP_PKEY_free(pub_key);
2285 
2286 	return (ret);
2287 }
2288 
2289 int
2290 ssl3_send_client_key_exchange(SSL *s)
2291 {
2292 	SESS_CERT *sess_cert;
2293 	unsigned long alg_k;
2294 	CBB cbb, kex;
2295 
2296 	memset(&cbb, 0, sizeof(cbb));
2297 
2298 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2299 		alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2300 
2301 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2302 			ssl3_send_alert(s, SSL3_AL_FATAL,
2303 			    SSL_AD_UNEXPECTED_MESSAGE);
2304 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2305 			goto err;
2306 		}
2307 
2308 		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
2309 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2310 			goto err;
2311 
2312 		if (alg_k & SSL_kRSA) {
2313 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2314 				goto err;
2315 		} else if (alg_k & SSL_kDHE) {
2316 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2317 				goto err;
2318 		} else if (alg_k & SSL_kECDHE) {
2319 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2320 				goto err;
2321 		} else if (alg_k & SSL_kGOST) {
2322 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2323 				goto err;
2324 		} else {
2325 			ssl3_send_alert(s, SSL3_AL_FATAL,
2326 			    SSL_AD_HANDSHAKE_FAILURE);
2327 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2328 			goto err;
2329 		}
2330 
2331 		if (!ssl3_handshake_msg_finish(s, &cbb))
2332 			goto err;
2333 
2334 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2335 	}
2336 
2337 	/* SSL3_ST_CW_KEY_EXCH_B */
2338 	return (ssl3_handshake_write(s));
2339 
2340  err:
2341 	CBB_cleanup(&cbb);
2342 
2343 	return (-1);
2344 }
2345 
2346 static int
2347 ssl3_send_client_verify_sigalgs(SSL *s, EVP_PKEY *pkey,
2348     const struct ssl_sigalg *sigalg, CBB *cert_verify)
2349 {
2350 	CBB cbb_signature;
2351 	EVP_PKEY_CTX *pctx = NULL;
2352 	EVP_MD_CTX mctx;
2353 	const unsigned char *hdata;
2354 	unsigned char *signature = NULL;
2355 	size_t signature_len, hdata_len;
2356 	int ret = 0;
2357 
2358 	EVP_MD_CTX_init(&mctx);
2359 
2360 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2361 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2362 		goto err;
2363 	}
2364 	if (!EVP_DigestSignInit(&mctx, &pctx, sigalg->md(), NULL, pkey)) {
2365 		SSLerror(s, ERR_R_EVP_LIB);
2366 		goto err;
2367 	}
2368 	if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2369 	    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2370 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2371 		SSLerror(s, ERR_R_EVP_LIB);
2372 		goto err;
2373 	}
2374 	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2375 	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
2376 	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2377 		SSLerror(s, ERR_R_EVP_LIB);
2378 		goto err;
2379 	}
2380 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2381 		SSLerror(s, ERR_R_EVP_LIB);
2382 		goto err;
2383 	}
2384 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2385 	    signature_len == 0) {
2386 		SSLerror(s, ERR_R_EVP_LIB);
2387 		goto err;
2388 	}
2389 	if ((signature = calloc(1, signature_len)) == NULL) {
2390 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2391 		goto err;
2392 	}
2393 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2394 		SSLerror(s, ERR_R_EVP_LIB);
2395 		goto err;
2396 	}
2397 
2398 	if (!CBB_add_u16(cert_verify, sigalg->value))
2399 		goto err;
2400 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2401 		goto err;
2402 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2403 		goto err;
2404 	if (!CBB_flush(cert_verify))
2405 		goto err;
2406 
2407 	ret = 1;
2408 
2409  err:
2410 	EVP_MD_CTX_cleanup(&mctx);
2411 	free(signature);
2412 	return ret;
2413 }
2414 
2415 static int
2416 ssl3_send_client_verify_rsa(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2417 {
2418 	CBB cbb_signature;
2419 	unsigned char data[EVP_MAX_MD_SIZE];
2420 	unsigned char *signature = NULL;
2421 	unsigned int signature_len;
2422 	size_t data_len;
2423 	int ret = 0;
2424 
2425 	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2426 		goto err;
2427 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2428 		goto err;
2429 	if (RSA_sign(NID_md5_sha1, data, data_len, signature,
2430 	    &signature_len, pkey->pkey.rsa) <= 0 ) {
2431 		SSLerror(s, ERR_R_RSA_LIB);
2432 		goto err;
2433 	}
2434 
2435 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2436 		goto err;
2437 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2438 		goto err;
2439 	if (!CBB_flush(cert_verify))
2440 		goto err;
2441 
2442 	ret = 1;
2443  err:
2444 	free(signature);
2445 	return ret;
2446 }
2447 
2448 static int
2449 ssl3_send_client_verify_ec(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2450 {
2451 	CBB cbb_signature;
2452 	unsigned char data[EVP_MAX_MD_SIZE];
2453 	unsigned char *signature = NULL;
2454 	unsigned int signature_len;
2455 	int ret = 0;
2456 
2457 	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2458 		goto err;
2459 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2460 		goto err;
2461 	if (!ECDSA_sign(pkey->save_type, &data[MD5_DIGEST_LENGTH],
2462 	    SHA_DIGEST_LENGTH, signature, &signature_len, pkey->pkey.ec)) {
2463 		SSLerror(s, ERR_R_ECDSA_LIB);
2464 		goto err;
2465 	}
2466 
2467 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2468 		goto err;
2469 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2470 		goto err;
2471 	if (!CBB_flush(cert_verify))
2472 		goto err;
2473 
2474 	ret = 1;
2475  err:
2476 	free(signature);
2477 	return ret;
2478 }
2479 
2480 #ifndef OPENSSL_NO_GOST
2481 static int
2482 ssl3_send_client_verify_gost(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2483 {
2484 	CBB cbb_signature;
2485 	EVP_MD_CTX mctx;
2486 	EVP_PKEY_CTX *pctx;
2487 	const EVP_MD *md;
2488 	const unsigned char *hdata;
2489 	unsigned char *signature = NULL;
2490 	size_t signature_len;
2491 	size_t hdata_len;
2492 	int nid;
2493 	int ret = 0;
2494 
2495 	EVP_MD_CTX_init(&mctx);
2496 
2497 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2498 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2499 		goto err;
2500 	}
2501 	if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2502 	    (md = EVP_get_digestbynid(nid)) == NULL) {
2503 		SSLerror(s, ERR_R_EVP_LIB);
2504 		goto err;
2505 	}
2506 	if (!EVP_DigestSignInit(&mctx, &pctx, md, NULL, pkey)) {
2507 		SSLerror(s, ERR_R_EVP_LIB);
2508 		goto err;
2509 	}
2510 	if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2511 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2512 		SSLerror(s, ERR_R_EVP_LIB);
2513 		goto err;
2514 	}
2515 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2516 		SSLerror(s, ERR_R_EVP_LIB);
2517 		goto err;
2518 	}
2519 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2520 	    signature_len == 0) {
2521 		SSLerror(s, ERR_R_EVP_LIB);
2522 		goto err;
2523 	}
2524 	if ((signature = calloc(1, signature_len)) == NULL) {
2525 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2526 		goto err;
2527 	}
2528 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2529 		SSLerror(s, ERR_R_EVP_LIB);
2530 		goto err;
2531 	}
2532 
2533 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2534 		goto err;
2535 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2536 		goto err;
2537 	if (!CBB_flush(cert_verify))
2538 		goto err;
2539 
2540 	ret = 1;
2541  err:
2542 	EVP_MD_CTX_cleanup(&mctx);
2543 	free(signature);
2544 	return ret;
2545 }
2546 #endif
2547 
2548 int
2549 ssl3_send_client_verify(SSL *s)
2550 {
2551 	const struct ssl_sigalg *sigalg;
2552 	CBB cbb, cert_verify;
2553 	EVP_PKEY *pkey;
2554 
2555 	memset(&cbb, 0, sizeof(cbb));
2556 
2557 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2558 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2559 		    SSL3_MT_CERTIFICATE_VERIFY))
2560 			goto err;
2561 
2562 		pkey = s->cert->key->privatekey;
2563 		if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2564 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2565 			goto err;
2566 		}
2567 		S3I(s)->hs.our_sigalg = sigalg;
2568 
2569 		/*
2570 		 * For TLS v1.2 send signature algorithm and signature using
2571 		 * agreed digest and cached handshake records.
2572 		 */
2573 		if (SSL_USE_SIGALGS(s)) {
2574 			if (!ssl3_send_client_verify_sigalgs(s, pkey, sigalg,
2575 			    &cert_verify))
2576 				goto err;
2577 		} else if (pkey->type == EVP_PKEY_RSA) {
2578 			if (!ssl3_send_client_verify_rsa(s, pkey, &cert_verify))
2579 				goto err;
2580 		} else if (pkey->type == EVP_PKEY_EC) {
2581 			if (!ssl3_send_client_verify_ec(s, pkey, &cert_verify))
2582 				goto err;
2583 #ifndef OPENSSL_NO_GOST
2584 		} else if (pkey->type == NID_id_GostR3410_94 ||
2585 		    pkey->type == NID_id_GostR3410_2001) {
2586 			if (!ssl3_send_client_verify_gost(s, pkey, &cert_verify))
2587 				goto err;
2588 #endif
2589 		} else {
2590 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2591 			goto err;
2592 		}
2593 
2594 		tls1_transcript_free(s);
2595 
2596 		if (!ssl3_handshake_msg_finish(s, &cbb))
2597 			goto err;
2598 
2599 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2600 	}
2601 
2602 	return (ssl3_handshake_write(s));
2603 
2604  err:
2605 	CBB_cleanup(&cbb);
2606 
2607 	return (-1);
2608 }
2609 
2610 int
2611 ssl3_send_client_certificate(SSL *s)
2612 {
2613 	EVP_PKEY *pkey = NULL;
2614 	X509 *x509 = NULL;
2615 	CBB cbb, client_cert;
2616 	int i;
2617 
2618 	memset(&cbb, 0, sizeof(cbb));
2619 
2620 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2621 		if (s->cert->key->x509 == NULL ||
2622 		    s->cert->key->privatekey == NULL)
2623 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2624 		else
2625 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2626 	}
2627 
2628 	/* We need to get a client cert */
2629 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2630 		/*
2631 		 * If we get an error, we need to
2632 		 * ssl->internal->rwstate = SSL_X509_LOOKUP; return(-1);
2633 		 * We then get retried later.
2634 		 */
2635 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2636 		if (i < 0) {
2637 			s->internal->rwstate = SSL_X509_LOOKUP;
2638 			return (-1);
2639 		}
2640 		s->internal->rwstate = SSL_NOTHING;
2641 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2642 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2643 			if (!SSL_use_certificate(s, x509) ||
2644 			    !SSL_use_PrivateKey(s, pkey))
2645 				i = 0;
2646 		} else if (i == 1) {
2647 			i = 0;
2648 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2649 		}
2650 
2651 		X509_free(x509);
2652 		EVP_PKEY_free(pkey);
2653 		if (i == 0) {
2654 			S3I(s)->hs.tls12.cert_request = 2;
2655 
2656 			/* There is no client certificate to verify. */
2657 			tls1_transcript_free(s);
2658 		}
2659 
2660 		/* Ok, we have a cert */
2661 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2662 	}
2663 
2664 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2665 		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2666 		    SSL3_MT_CERTIFICATE))
2667 			goto err;
2668 		if (!ssl3_output_cert_chain(s, &client_cert,
2669 		    (S3I(s)->hs.tls12.cert_request == 2) ? NULL : s->cert->key))
2670 			goto err;
2671 		if (!ssl3_handshake_msg_finish(s, &cbb))
2672 			goto err;
2673 
2674 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2675 	}
2676 
2677 	/* SSL3_ST_CW_CERT_D */
2678 	return (ssl3_handshake_write(s));
2679 
2680  err:
2681 	CBB_cleanup(&cbb);
2682 
2683 	return (0);
2684 }
2685 
2686 #define has_bits(i,m)	(((i)&(m)) == (m))
2687 
2688 int
2689 ssl3_check_cert_and_algorithm(SSL *s)
2690 {
2691 	int		 i, idx;
2692 	long		 alg_k, alg_a;
2693 	EVP_PKEY	*pkey = NULL;
2694 	SESS_CERT	*sc;
2695 	DH		*dh;
2696 
2697 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2698 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
2699 
2700 	/* We don't have a certificate. */
2701 	if (alg_a & SSL_aNULL)
2702 		return (1);
2703 
2704 	sc = SSI(s)->sess_cert;
2705 	if (sc == NULL) {
2706 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2707 		goto err;
2708 	}
2709 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2710 
2711 	/* This is the passed certificate. */
2712 
2713 	idx = sc->peer_cert_type;
2714 	if (idx == SSL_PKEY_ECC) {
2715 		if (ssl_check_srvr_ecc_cert_and_alg(
2716 		    sc->peer_pkeys[idx].x509, s) == 0) {
2717 			/* check failed */
2718 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2719 			goto fatal_err;
2720 		} else {
2721 			return (1);
2722 		}
2723 	}
2724 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2725 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2726 	EVP_PKEY_free(pkey);
2727 
2728 	/* Check that we have a certificate if we require one. */
2729 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2730 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2731 		goto fatal_err;
2732 	}
2733 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2734 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2735 		goto fatal_err;
2736 	}
2737 	if ((alg_k & SSL_kDHE) &&
2738 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2739 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2740 		goto fatal_err;
2741 	}
2742 
2743 	return (1);
2744  fatal_err:
2745 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2746  err:
2747 	return (0);
2748 }
2749 
2750 /*
2751  * Check to see if handshake is full or resumed. Usually this is just a
2752  * case of checking to see if a cache hit has occurred. In the case of
2753  * session tickets we have to check the next message to be sure.
2754  */
2755 
2756 int
2757 ssl3_check_finished(SSL *s)
2758 {
2759 	int	ok;
2760 	long	n;
2761 
2762 	/* If we have no ticket it cannot be a resumed session. */
2763 	if (!s->session->tlsext_tick)
2764 		return (1);
2765 	/* this function is called when we really expect a Certificate
2766 	 * message, so permit appropriate message length */
2767 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2768 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2769 	if (!ok)
2770 		return ((int)n);
2771 
2772 	S3I(s)->hs.tls12.reuse_message = 1;
2773 	if ((S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) ||
2774 	    (S3I(s)->hs.tls12.message_type == SSL3_MT_NEWSESSION_TICKET))
2775 		return (2);
2776 
2777 	return (1);
2778 }
2779 
2780 int
2781 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2782 {
2783 	int	i = 0;
2784 
2785 #ifndef OPENSSL_NO_ENGINE
2786 	if (s->ctx->internal->client_cert_engine) {
2787 		i = ENGINE_load_ssl_client_cert(
2788 		    s->ctx->internal->client_cert_engine, s,
2789 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2790 		if (i != 0)
2791 			return (i);
2792 	}
2793 #endif
2794 	if (s->ctx->internal->client_cert_cb)
2795 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2796 	return (i);
2797 }
2798