xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 /* $OpenBSD: ssl_clnt.c,v 1.113 2021/10/23 08:34:36 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150 
151 #include <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 	CBS hello_verify_request, cookie;
783 	size_t cookie_len;
784 	uint16_t ssl_version;
785 	int al, ret;
786 
787 	if ((ret = ssl3_get_message(s, DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A,
788 	    DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B, -1, s->internal->max_cert_list)) <= 0)
789 		return ret;
790 
791 	if (S3I(s)->hs.tls12.message_type != DTLS1_MT_HELLO_VERIFY_REQUEST) {
792 		D1I(s)->send_cookie = 0;
793 		S3I(s)->hs.tls12.reuse_message = 1;
794 		return (1);
795 	}
796 
797 	if (s->internal->init_num < 0)
798 		goto decode_err;
799 
800 	CBS_init(&hello_verify_request, s->internal->init_msg,
801 	    s->internal->init_num);
802 
803 	if (!CBS_get_u16(&hello_verify_request, &ssl_version))
804 		goto decode_err;
805 	if (!CBS_get_u8_length_prefixed(&hello_verify_request, &cookie))
806 		goto decode_err;
807 	if (CBS_len(&hello_verify_request) != 0)
808 		goto decode_err;
809 
810 	/*
811 	 * Per RFC 6347 section 4.2.1, the HelloVerifyRequest should always
812 	 * contain DTLSv1.0 the version that is going to be negotiated.
813 	 * Tolerate DTLSv1.2 just in case.
814 	 */
815 	if (ssl_version != DTLS1_VERSION && ssl_version != DTLS1_2_VERSION) {
816 		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
817 		s->version = (s->version & 0xff00) | (ssl_version & 0xff);
818 		al = SSL_AD_PROTOCOL_VERSION;
819 		goto fatal_err;
820 	}
821 
822 	if (!CBS_write_bytes(&cookie, D1I(s)->cookie,
823 	    sizeof(D1I(s)->cookie), &cookie_len)) {
824 		D1I(s)->cookie_len = 0;
825 		al = SSL_AD_ILLEGAL_PARAMETER;
826 		goto fatal_err;
827 	}
828 	D1I(s)->cookie_len = cookie_len;
829 	D1I(s)->send_cookie = 1;
830 
831 	return 1;
832 
833  decode_err:
834 	al = SSL_AD_DECODE_ERROR;
835  fatal_err:
836 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
837 	return -1;
838 }
839 
840 int
841 ssl3_get_server_hello(SSL *s)
842 {
843 	CBS cbs, server_random, session_id;
844 	uint16_t server_version, cipher_suite;
845 	uint8_t compression_method;
846 	const SSL_CIPHER *cipher;
847 	const SSL_METHOD *method;
848 	unsigned long alg_k;
849 	size_t outlen;
850 	int al, ret;
851 
852 	s->internal->first_packet = 1;
853 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
854 	    SSL3_ST_CR_SRVR_HELLO_B, -1, 20000 /* ?? */)) <= 0)
855 		return ret;
856 	s->internal->first_packet = 0;
857 
858 	if (s->internal->init_num < 0)
859 		goto decode_err;
860 
861 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
862 
863 	if (SSL_is_dtls(s)) {
864 		if (S3I(s)->hs.tls12.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) {
865 			if (D1I(s)->send_cookie == 0) {
866 				S3I(s)->hs.tls12.reuse_message = 1;
867 				return (1);
868 			} else {
869 				/* Already sent a cookie. */
870 				al = SSL_AD_UNEXPECTED_MESSAGE;
871 				SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
872 				goto fatal_err;
873 			}
874 		}
875 	}
876 
877 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_SERVER_HELLO) {
878 		al = SSL_AD_UNEXPECTED_MESSAGE;
879 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
880 		goto fatal_err;
881 	}
882 
883 	if (!CBS_get_u16(&cbs, &server_version))
884 		goto decode_err;
885 
886 	if (!ssl_check_version_from_server(s, server_version)) {
887 		SSLerror(s, SSL_R_WRONG_SSL_VERSION);
888 		s->version = (s->version & 0xff00) | (server_version & 0xff);
889 		al = SSL_AD_PROTOCOL_VERSION;
890 		goto fatal_err;
891 	}
892 	s->version = server_version;
893 
894 	S3I(s)->hs.negotiated_tls_version = ssl_tls_version(server_version);
895 	if (S3I(s)->hs.negotiated_tls_version == 0) {
896 		SSLerror(s, ERR_R_INTERNAL_ERROR);
897 		goto err;
898 	}
899 
900 	if ((method = ssl_get_method(server_version)) == NULL) {
901 		SSLerror(s, ERR_R_INTERNAL_ERROR);
902 		goto err;
903 	}
904 	s->method = method;
905 
906 	/* Server random. */
907 	if (!CBS_get_bytes(&cbs, &server_random, SSL3_RANDOM_SIZE))
908 		goto decode_err;
909 	if (!CBS_write_bytes(&server_random, s->s3->server_random,
910 	    sizeof(s->s3->server_random), NULL))
911 		goto err;
912 
913 	if (S3I(s)->hs.our_max_tls_version >= TLS1_2_VERSION &&
914 	    S3I(s)->hs.negotiated_tls_version < S3I(s)->hs.our_max_tls_version) {
915 		/*
916 		 * RFC 8446 section 4.1.3. We must not downgrade if the server
917 		 * random value contains the TLS 1.2 or TLS 1.1 magical value.
918 		 */
919 		if (!CBS_skip(&server_random,
920 		    CBS_len(&server_random) - sizeof(tls13_downgrade_12)))
921 			goto err;
922 		if (S3I(s)->hs.negotiated_tls_version == TLS1_2_VERSION &&
923 		    CBS_mem_equal(&server_random, tls13_downgrade_12,
924 		    sizeof(tls13_downgrade_12))) {
925 			al = SSL_AD_ILLEGAL_PARAMETER;
926 			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
927 			goto fatal_err;
928 		}
929 		if (CBS_mem_equal(&server_random, tls13_downgrade_11,
930 		    sizeof(tls13_downgrade_11))) {
931 			al = SSL_AD_ILLEGAL_PARAMETER;
932 			SSLerror(s, SSL_R_INAPPROPRIATE_FALLBACK);
933 			goto fatal_err;
934 		}
935 	}
936 
937 	/* Session ID. */
938 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
939 		goto decode_err;
940 
941 	if (CBS_len(&session_id) > SSL3_SESSION_ID_SIZE) {
942 		al = SSL_AD_ILLEGAL_PARAMETER;
943 		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
944 		goto fatal_err;
945 	}
946 
947 	/* Cipher suite. */
948 	if (!CBS_get_u16(&cbs, &cipher_suite))
949 		goto decode_err;
950 
951 	/*
952 	 * Check if we want to resume the session based on external
953 	 * pre-shared secret.
954 	 */
955 	if (s->internal->tls_session_secret_cb) {
956 		SSL_CIPHER *pref_cipher = NULL;
957 		s->session->master_key_length = sizeof(s->session->master_key);
958 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
959 		    &s->session->master_key_length, NULL, &pref_cipher,
960 		    s->internal->tls_session_secret_cb_arg)) {
961 			s->session->cipher = pref_cipher ? pref_cipher :
962 			    ssl3_get_cipher_by_value(cipher_suite);
963 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
964 		}
965 	}
966 
967 	if (s->session->session_id_length != 0 &&
968 	    CBS_mem_equal(&session_id, s->session->session_id,
969 		s->session->session_id_length)) {
970 		if (s->sid_ctx_length != s->session->sid_ctx_length ||
971 		    timingsafe_memcmp(s->session->sid_ctx,
972 		    s->sid_ctx, s->sid_ctx_length) != 0) {
973 			/* actually a client application bug */
974 			al = SSL_AD_ILLEGAL_PARAMETER;
975 			SSLerror(s, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
976 			goto fatal_err;
977 		}
978 		s->s3->flags |= SSL3_FLAGS_CCS_OK;
979 		s->internal->hit = 1;
980 	} else {
981 		/* a miss or crap from the other end */
982 
983 		/* If we were trying for session-id reuse, make a new
984 		 * SSL_SESSION so we don't stuff up other people */
985 		s->internal->hit = 0;
986 		if (s->session->session_id_length > 0) {
987 			if (!ssl_get_new_session(s, 0)) {
988 				al = SSL_AD_INTERNAL_ERROR;
989 				goto fatal_err;
990 			}
991 		}
992 
993 		/*
994 		 * XXX - improve the handling for the case where there is a
995 		 * zero length session identifier.
996 		 */
997 		if (!CBS_write_bytes(&session_id, s->session->session_id,
998 		    sizeof(s->session->session_id), &outlen))
999 			goto err;
1000 		s->session->session_id_length = outlen;
1001 
1002 		s->session->ssl_version = s->version;
1003 	}
1004 
1005 	if ((cipher = ssl3_get_cipher_by_value(cipher_suite)) == NULL) {
1006 		al = SSL_AD_ILLEGAL_PARAMETER;
1007 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_RETURNED);
1008 		goto fatal_err;
1009 	}
1010 
1011 	/* TLS v1.2 only ciphersuites require v1.2 or later. */
1012 	if ((cipher->algorithm_ssl & SSL_TLSV1_2) &&
1013 	    S3I(s)->hs.negotiated_tls_version < TLS1_2_VERSION) {
1014 		al = SSL_AD_ILLEGAL_PARAMETER;
1015 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
1016 		goto fatal_err;
1017 	}
1018 
1019 	if (!ssl_cipher_in_list(SSL_get_ciphers(s), cipher)) {
1020 		/* we did not say we would use this cipher */
1021 		al = SSL_AD_ILLEGAL_PARAMETER;
1022 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
1023 		goto fatal_err;
1024 	}
1025 
1026 	/*
1027 	 * Depending on the session caching (internal/external), the cipher
1028 	 * and/or cipher_id values may not be set. Make sure that
1029 	 * cipher_id is set and use it for comparison.
1030 	 */
1031 	if (s->session->cipher)
1032 		s->session->cipher_id = s->session->cipher->id;
1033 	if (s->internal->hit && (s->session->cipher_id != cipher->id)) {
1034 		al = SSL_AD_ILLEGAL_PARAMETER;
1035 		SSLerror(s, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1036 		goto fatal_err;
1037 	}
1038 	S3I(s)->hs.cipher = cipher;
1039 
1040 	if (!tls1_transcript_hash_init(s))
1041 		goto err;
1042 
1043 	/*
1044 	 * Don't digest cached records if no sigalgs: we may need them for
1045 	 * client authentication.
1046 	 */
1047 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
1048 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)))
1049 		tls1_transcript_free(s);
1050 
1051 	if (!CBS_get_u8(&cbs, &compression_method))
1052 		goto decode_err;
1053 
1054 	if (compression_method != 0) {
1055 		al = SSL_AD_ILLEGAL_PARAMETER;
1056 		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1057 		goto fatal_err;
1058 	}
1059 
1060 	if (!tlsext_client_parse(s, SSL_TLSEXT_MSG_SH, &cbs, &al)) {
1061 		SSLerror(s, SSL_R_PARSE_TLSEXT);
1062 		goto fatal_err;
1063 	}
1064 
1065 	if (CBS_len(&cbs) != 0)
1066 		goto decode_err;
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, ret;
1104 	CBS cbs, cert_list;
1105 	X509 *x = NULL;
1106 	const unsigned char *q;
1107 	STACK_OF(X509) *sk = NULL;
1108 	SESS_CERT *sc;
1109 	EVP_PKEY *pkey = NULL;
1110 
1111 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
1112 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list)) <= 0)
1113 		return ret;
1114 
1115 	ret = -1;
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 	if ((sk = sk_X509_new_null()) == NULL) {
1129 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1130 		goto err;
1131 	}
1132 
1133 	if (s->internal->init_num < 0)
1134 		goto decode_err;
1135 
1136 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
1137 	if (CBS_len(&cbs) < 3)
1138 		goto decode_err;
1139 
1140 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
1141 	    CBS_len(&cbs) != 0) {
1142 		al = SSL_AD_DECODE_ERROR;
1143 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1144 		goto fatal_err;
1145 	}
1146 
1147 	while (CBS_len(&cert_list) > 0) {
1148 		CBS cert;
1149 
1150 		if (CBS_len(&cert_list) < 3)
1151 			goto decode_err;
1152 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1153 			al = SSL_AD_DECODE_ERROR;
1154 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1155 			goto fatal_err;
1156 		}
1157 
1158 		q = CBS_data(&cert);
1159 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1160 		if (x == NULL) {
1161 			al = SSL_AD_BAD_CERTIFICATE;
1162 			SSLerror(s, ERR_R_ASN1_LIB);
1163 			goto fatal_err;
1164 		}
1165 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1166 			al = SSL_AD_DECODE_ERROR;
1167 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1168 			goto fatal_err;
1169 		}
1170 		if (!sk_X509_push(sk, x)) {
1171 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1172 			goto err;
1173 		}
1174 		x = NULL;
1175 	}
1176 
1177 	i = ssl_verify_cert_chain(s, sk);
1178 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1179 		al = ssl_verify_alarm_type(s->verify_result);
1180 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1181 		goto fatal_err;
1182 
1183 	}
1184 	ERR_clear_error(); /* but we keep s->verify_result */
1185 
1186 	sc = ssl_sess_cert_new();
1187 	if (sc == NULL)
1188 		goto err;
1189 	ssl_sess_cert_free(SSI(s)->sess_cert);
1190 	SSI(s)->sess_cert = sc;
1191 
1192 	sc->cert_chain = sk;
1193 	/*
1194 	 * Inconsistency alert: cert_chain does include the peer's
1195 	 * certificate, which we don't include in s3_srvr.c
1196 	 */
1197 	x = sk_X509_value(sk, 0);
1198 	sk = NULL;
1199 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1200 
1201 	pkey = X509_get_pubkey(x);
1202 
1203 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1204 		x = NULL;
1205 		al = SSL3_AL_FATAL;
1206 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1207 		goto fatal_err;
1208 	}
1209 
1210 	i = ssl_cert_type(x, pkey);
1211 	if (i < 0) {
1212 		x = NULL;
1213 		al = SSL3_AL_FATAL;
1214 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1215 		goto fatal_err;
1216 	}
1217 
1218 	sc->peer_cert_type = i;
1219 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1220 	/*
1221 	 * Why would the following ever happen?
1222 	 * We just created sc a couple of lines ago.
1223 	 */
1224 	X509_free(sc->peer_pkeys[i].x509);
1225 	sc->peer_pkeys[i].x509 = x;
1226 	sc->peer_key = &(sc->peer_pkeys[i]);
1227 
1228 	X509_free(s->session->peer);
1229 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1230 	s->session->peer = x;
1231 	s->session->verify_result = s->verify_result;
1232 
1233 	x = NULL;
1234 	ret = 1;
1235 
1236 	if (0) {
1237  decode_err:
1238 		/* wrong packet length */
1239 		al = SSL_AD_DECODE_ERROR;
1240 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1241  fatal_err:
1242 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1243 	}
1244  err:
1245 	EVP_PKEY_free(pkey);
1246 	X509_free(x);
1247 	sk_X509_pop_free(sk, X509_free);
1248 
1249 	return (ret);
1250 }
1251 
1252 static int
1253 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1254 {
1255 	CBS dhp, dhg, dhpk;
1256 	BN_CTX *bn_ctx = NULL;
1257 	SESS_CERT *sc = NULL;
1258 	DH *dh = NULL;
1259 	long alg_a;
1260 	int al;
1261 
1262 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1263 	sc = SSI(s)->sess_cert;
1264 
1265 	if ((dh = DH_new()) == NULL) {
1266 		SSLerror(s, ERR_R_DH_LIB);
1267 		goto err;
1268 	}
1269 
1270 	if (!CBS_get_u16_length_prefixed(cbs, &dhp))
1271 		goto decode_err;
1272 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1273 		SSLerror(s, ERR_R_BN_LIB);
1274 		goto err;
1275 	}
1276 
1277 	if (!CBS_get_u16_length_prefixed(cbs, &dhg))
1278 		goto decode_err;
1279 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1280 		SSLerror(s, ERR_R_BN_LIB);
1281 		goto err;
1282 	}
1283 
1284 	if (!CBS_get_u16_length_prefixed(cbs, &dhpk))
1285 		goto decode_err;
1286 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1287 	    NULL)) == NULL) {
1288 		SSLerror(s, ERR_R_BN_LIB);
1289 		goto err;
1290 	}
1291 
1292 	/*
1293 	 * Check the strength of the DH key just constructed.
1294 	 * Discard keys weaker than 1024 bits.
1295 	 */
1296 	if (DH_size(dh) < 1024 / 8) {
1297 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1298 		goto err;
1299 	}
1300 
1301 	if (alg_a & SSL_aRSA)
1302 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1303 	else
1304 		/* XXX - Anonymous DH, so no certificate or pkey. */
1305 		*pkey = NULL;
1306 
1307 	sc->peer_dh_tmp = dh;
1308 
1309 	return (1);
1310 
1311  decode_err:
1312 	al = SSL_AD_DECODE_ERROR;
1313 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1314 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1315 
1316  err:
1317 	DH_free(dh);
1318 	BN_CTX_free(bn_ctx);
1319 
1320 	return (-1);
1321 }
1322 
1323 static int
1324 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1325 {
1326 	EC_KEY *ecdh = NULL;
1327 	int ret = -1;
1328 
1329 	/* Extract the server's ephemeral ECDH public key. */
1330 	if ((ecdh = EC_KEY_new()) == NULL) {
1331 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1332 		goto err;
1333 	}
1334 	if (!ssl_kex_peer_public_ecdhe_ecp(ecdh, nid, public)) {
1335 		SSLerror(s, SSL_R_BAD_ECPOINT);
1336 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1337 		goto err;
1338 	}
1339 
1340 	sc->peer_nid = nid;
1341 	sc->peer_ecdh_tmp = ecdh;
1342 	ecdh = NULL;
1343 
1344 	ret = 1;
1345 
1346  err:
1347 	EC_KEY_free(ecdh);
1348 
1349 	return (ret);
1350 }
1351 
1352 static int
1353 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1354 {
1355 	size_t outlen;
1356 
1357 	if (nid != NID_X25519) {
1358 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1359 		goto err;
1360 	}
1361 
1362 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1363 		SSLerror(s, SSL_R_BAD_ECPOINT);
1364 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1365 		goto err;
1366 	}
1367 
1368 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1369 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1370 		goto err;
1371 	}
1372 
1373 	return (1);
1374 
1375  err:
1376 	return (-1);
1377 }
1378 
1379 static int
1380 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1381 {
1382 	CBS public;
1383 	uint8_t curve_type;
1384 	uint16_t curve_id;
1385 	SESS_CERT *sc;
1386 	long alg_a;
1387 	int nid;
1388 	int al;
1389 
1390 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1391 	sc = SSI(s)->sess_cert;
1392 
1393 	/* Only named curves are supported. */
1394 	if (!CBS_get_u8(cbs, &curve_type) ||
1395 	    curve_type != NAMED_CURVE_TYPE ||
1396 	    !CBS_get_u16(cbs, &curve_id)) {
1397 		al = SSL_AD_DECODE_ERROR;
1398 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1399 		goto fatal_err;
1400 	}
1401 
1402 	/*
1403 	 * Check that the curve is one of our preferences - if it is not,
1404 	 * the server has sent us an invalid curve.
1405 	 */
1406 	if (tls1_check_curve(s, curve_id) != 1) {
1407 		al = SSL_AD_DECODE_ERROR;
1408 		SSLerror(s, SSL_R_WRONG_CURVE);
1409 		goto fatal_err;
1410 	}
1411 
1412 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1413 		al = SSL_AD_INTERNAL_ERROR;
1414 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1415 		goto fatal_err;
1416 	}
1417 
1418 	if (!CBS_get_u8_length_prefixed(cbs, &public))
1419 		goto decode_err;
1420 
1421 	if (nid == NID_X25519) {
1422 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1423 			goto err;
1424 	} else {
1425 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1426 			goto err;
1427 	}
1428 
1429 	/*
1430 	 * The ECC/TLS specification does not mention the use of DSA to sign
1431 	 * ECParameters in the server key exchange message. We do support RSA
1432 	 * and ECDSA.
1433 	 */
1434 	if (alg_a & SSL_aRSA)
1435 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1436 	else if (alg_a & SSL_aECDSA)
1437 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1438 	else
1439 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1440 		*pkey = NULL;
1441 
1442 	return (1);
1443 
1444  decode_err:
1445 	al = SSL_AD_DECODE_ERROR;
1446 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1447 
1448  fatal_err:
1449 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1450 
1451  err:
1452 	return (-1);
1453 }
1454 
1455 int
1456 ssl3_get_server_key_exchange(SSL *s)
1457 {
1458 	CBS cbs, signature;
1459 	EVP_PKEY *pkey = NULL;
1460 	EVP_MD_CTX md_ctx;
1461 	const unsigned char *param;
1462 	size_t param_len;
1463 	long alg_k, alg_a;
1464 	int al, ret;
1465 
1466 	EVP_MD_CTX_init(&md_ctx);
1467 
1468 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
1469 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1470 
1471 	/*
1472 	 * Use same message size as in ssl3_get_certificate_request()
1473 	 * as ServerKeyExchange message may be skipped.
1474 	 */
1475 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1476 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list)) <= 0)
1477 		return ret;
1478 
1479 	if (s->internal->init_num < 0)
1480 		goto err;
1481 
1482 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
1483 
1484 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1485 		/*
1486 		 * Do not skip server key exchange if this cipher suite uses
1487 		 * ephemeral keys.
1488 		 */
1489 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1490 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1491 			al = SSL_AD_UNEXPECTED_MESSAGE;
1492 			goto fatal_err;
1493 		}
1494 
1495 		S3I(s)->hs.tls12.reuse_message = 1;
1496 		EVP_MD_CTX_cleanup(&md_ctx);
1497 		return (1);
1498 	}
1499 
1500 	if (SSI(s)->sess_cert != NULL) {
1501 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1502 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1503 
1504 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1505 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1506 
1507 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1508 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1509 	} else {
1510 		SSI(s)->sess_cert = ssl_sess_cert_new();
1511 		if (SSI(s)->sess_cert == NULL)
1512 			goto err;
1513 	}
1514 
1515 	param = CBS_data(&cbs);
1516 	param_len = CBS_len(&cbs);
1517 
1518 	if (alg_k & SSL_kDHE) {
1519 		if (ssl3_get_server_kex_dhe(s, &pkey, &cbs) != 1)
1520 			goto err;
1521 	} else if (alg_k & SSL_kECDHE) {
1522 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &cbs) != 1)
1523 			goto err;
1524 	} else if (alg_k != 0) {
1525 		al = SSL_AD_UNEXPECTED_MESSAGE;
1526 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1527 		goto fatal_err;
1528 	}
1529 
1530 	param_len -= CBS_len(&cbs);
1531 
1532 	/* if it was signed, check the signature */
1533 	if (pkey != NULL) {
1534 		uint16_t sigalg_value = SIGALG_NONE;
1535 		const struct ssl_sigalg *sigalg;
1536 		EVP_PKEY_CTX *pctx;
1537 
1538 		if (SSL_USE_SIGALGS(s)) {
1539 			if (!CBS_get_u16(&cbs, &sigalg_value))
1540 				goto decode_err;
1541 		}
1542 		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1543 			goto decode_err;
1544 		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1545 			al = SSL_AD_DECODE_ERROR;
1546 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1547 			goto fatal_err;
1548 		}
1549 
1550 		if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1551 		    sigalg_value)) == NULL) {
1552 			al = SSL_AD_DECODE_ERROR;
1553 			goto fatal_err;
1554 		}
1555 		S3I(s)->hs.peer_sigalg = sigalg;
1556 
1557 		if (!EVP_DigestVerifyInit(&md_ctx, &pctx, sigalg->md(),
1558 		    NULL, pkey))
1559 			goto err;
1560 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
1561 		    SSL3_RANDOM_SIZE))
1562 			goto err;
1563 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1564 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1565 		    RSA_PKCS1_PSS_PADDING) ||
1566 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1567 			goto err;
1568 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
1569 		    SSL3_RANDOM_SIZE))
1570 			goto err;
1571 		if (!EVP_DigestVerifyUpdate(&md_ctx, param, param_len))
1572 			goto err;
1573 		if (EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
1574 		    CBS_len(&signature)) <= 0) {
1575 			al = SSL_AD_DECRYPT_ERROR;
1576 			SSLerror(s, SSL_R_BAD_SIGNATURE);
1577 			goto fatal_err;
1578 		}
1579 	} else {
1580 		/* aNULL does not need public keys. */
1581 		if (!(alg_a & SSL_aNULL)) {
1582 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1583 			goto err;
1584 		}
1585 	}
1586 
1587 	if (CBS_len(&cbs) != 0) {
1588 		al = SSL_AD_DECODE_ERROR;
1589 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1590 		goto fatal_err;
1591 	}
1592 
1593 	EVP_PKEY_free(pkey);
1594 	EVP_MD_CTX_cleanup(&md_ctx);
1595 
1596 	return (1);
1597 
1598  decode_err:
1599 	al = SSL_AD_DECODE_ERROR;
1600 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1601 
1602  fatal_err:
1603 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1604 
1605  err:
1606 	EVP_PKEY_free(pkey);
1607 	EVP_MD_CTX_cleanup(&md_ctx);
1608 
1609 	return (-1);
1610 }
1611 
1612 int
1613 ssl3_get_certificate_request(SSL *s)
1614 {
1615 	CBS cert_request, cert_types, rdn_list;
1616 	X509_NAME *xn = NULL;
1617 	const unsigned char *q;
1618 	STACK_OF(X509_NAME) *ca_sk = NULL;
1619 	int ret;
1620 
1621 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1622 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list)) <= 0)
1623 		return ret;
1624 
1625 	ret = 0;
1626 
1627 	S3I(s)->hs.tls12.cert_request = 0;
1628 
1629 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_DONE) {
1630 		S3I(s)->hs.tls12.reuse_message = 1;
1631 		/*
1632 		 * If we get here we don't need any cached handshake records
1633 		 * as we wont be doing client auth.
1634 		 */
1635 		tls1_transcript_free(s);
1636 		return (1);
1637 	}
1638 
1639 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1640 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1641 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1642 		goto err;
1643 	}
1644 
1645 	/* TLS does not like anon-DH with client cert */
1646 	if (S3I(s)->hs.cipher->algorithm_auth & SSL_aNULL) {
1647 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1648 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1649 		goto err;
1650 	}
1651 
1652 	if (s->internal->init_num < 0)
1653 		goto decode_err;
1654 	CBS_init(&cert_request, s->internal->init_msg, s->internal->init_num);
1655 
1656 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1657 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1658 		goto err;
1659 	}
1660 
1661 	if (!CBS_get_u8_length_prefixed(&cert_request, &cert_types))
1662 		goto decode_err;
1663 
1664 	if (SSL_USE_SIGALGS(s)) {
1665 		CBS sigalgs;
1666 
1667 		if (CBS_len(&cert_request) < 2) {
1668 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1669 			goto err;
1670 		}
1671 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1672 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1673 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1674 			goto err;
1675 		}
1676 		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1677 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1678 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1679 			goto err;
1680 		}
1681 		if (!CBS_stow(&sigalgs, &S3I(s)->hs.sigalgs,
1682 		    &S3I(s)->hs.sigalgs_len))
1683 			goto err;
1684 	}
1685 
1686 	/* get the CA RDNs */
1687 	if (CBS_len(&cert_request) < 2) {
1688 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1689 		goto err;
1690 	}
1691 
1692 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1693 	    CBS_len(&cert_request) != 0) {
1694 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1695 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1696 		goto err;
1697 	}
1698 
1699 	while (CBS_len(&rdn_list) > 0) {
1700 		CBS rdn;
1701 
1702 		if (CBS_len(&rdn_list) < 2) {
1703 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1704 			goto err;
1705 		}
1706 
1707 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1708 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1709 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1710 			goto err;
1711 		}
1712 
1713 		q = CBS_data(&rdn);
1714 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1715 			ssl3_send_alert(s, SSL3_AL_FATAL,
1716 			    SSL_AD_DECODE_ERROR);
1717 			SSLerror(s, ERR_R_ASN1_LIB);
1718 			goto err;
1719 		}
1720 
1721 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1722 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1723 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1724 			goto err;
1725 		}
1726 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1727 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1728 			goto err;
1729 		}
1730 		xn = NULL;	/* avoid free in err block */
1731 	}
1732 
1733 	/* we should setup a certificate to return.... */
1734 	S3I(s)->hs.tls12.cert_request = 1;
1735 	sk_X509_NAME_pop_free(S3I(s)->hs.tls12.ca_names, X509_NAME_free);
1736 	S3I(s)->hs.tls12.ca_names = ca_sk;
1737 	ca_sk = NULL;
1738 
1739 	ret = 1;
1740 	if (0) {
1741  decode_err:
1742 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1743 	}
1744  err:
1745 	X509_NAME_free(xn);
1746 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1747 	return (ret);
1748 }
1749 
1750 static int
1751 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1752 {
1753 	return (X509_NAME_cmp(*a, *b));
1754 }
1755 
1756 int
1757 ssl3_get_new_session_ticket(SSL *s)
1758 {
1759 	uint32_t lifetime_hint;
1760 	CBS cbs, session_ticket;
1761 	int al, ret;
1762 
1763 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1764 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384)) <= 0)
1765 		return ret;
1766 
1767 	ret = 0;
1768 
1769 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) {
1770 		S3I(s)->hs.tls12.reuse_message = 1;
1771 		return (1);
1772 	}
1773 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_NEWSESSION_TICKET) {
1774 		al = SSL_AD_UNEXPECTED_MESSAGE;
1775 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1776 		goto fatal_err;
1777 	}
1778 
1779 	if (s->internal->init_num < 0) {
1780 		al = SSL_AD_DECODE_ERROR;
1781 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1782 		goto fatal_err;
1783 	}
1784 
1785 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
1786 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1787 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1788 	    CBS_len(&cbs) != 0) {
1789 		al = SSL_AD_DECODE_ERROR;
1790 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1791 		goto fatal_err;
1792 	}
1793 	s->session->tlsext_tick_lifetime_hint = lifetime_hint;
1794 
1795 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1796 	    &s->session->tlsext_ticklen)) {
1797 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1798 		goto err;
1799 	}
1800 
1801 	/*
1802 	 * There are two ways to detect a resumed ticket sesion.
1803 	 * One is to set an appropriate session ID and then the server
1804 	 * must return a match in ServerHello. This allows the normal
1805 	 * client session ID matching to work and we know much
1806 	 * earlier that the ticket has been accepted.
1807 	 *
1808 	 * The other way is to set zero length session ID when the
1809 	 * ticket is presented and rely on the handshake to determine
1810 	 * session resumption.
1811 	 *
1812 	 * We choose the former approach because this fits in with
1813 	 * assumptions elsewhere in OpenSSL. The session ID is set
1814 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1815 	 * ticket.
1816 	 */
1817 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1818 	    s->session->session_id, &s->session->session_id_length,
1819 	    EVP_sha256(), NULL);
1820 	ret = 1;
1821 	return (ret);
1822  fatal_err:
1823 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1824  err:
1825 	return (-1);
1826 }
1827 
1828 int
1829 ssl3_get_cert_status(SSL *s)
1830 {
1831 	CBS cert_status, response;
1832 	uint8_t	status_type;
1833 	int al, ret;
1834 
1835 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1836 	    SSL3_ST_CR_CERT_STATUS_B, -1, 16384)) <= 0)
1837 		return ret;
1838 
1839 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1840 		/*
1841 		 * Tell the callback the server did not send us an OSCP
1842 		 * response, and has decided to head directly to key exchange.
1843 		 */
1844 		if (s->ctx->internal->tlsext_status_cb) {
1845 			free(s->internal->tlsext_ocsp_resp);
1846 			s->internal->tlsext_ocsp_resp = NULL;
1847 			s->internal->tlsext_ocsp_resp_len = 0;
1848 
1849 			ret = s->ctx->internal->tlsext_status_cb(s,
1850 			    s->ctx->internal->tlsext_status_arg);
1851 			if (ret == 0) {
1852 				al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1853 				SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1854 				goto fatal_err;
1855 			}
1856 			if (ret < 0) {
1857 				al = SSL_AD_INTERNAL_ERROR;
1858 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1859 				goto fatal_err;
1860 			}
1861 		}
1862 		S3I(s)->hs.tls12.reuse_message = 1;
1863 		return (1);
1864 	}
1865 
1866 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE &&
1867 	    S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1868 		al = SSL_AD_UNEXPECTED_MESSAGE;
1869 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1870 		goto fatal_err;
1871 	}
1872 
1873 	if (s->internal->init_num < 0) {
1874 		/* need at least status type + length */
1875 		al = SSL_AD_DECODE_ERROR;
1876 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1877 		goto fatal_err;
1878 	}
1879 
1880 	CBS_init(&cert_status, s->internal->init_msg, s->internal->init_num);
1881 	if (!CBS_get_u8(&cert_status, &status_type) ||
1882 	    CBS_len(&cert_status) < 3) {
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 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1890 		al = SSL_AD_DECODE_ERROR;
1891 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1892 		goto fatal_err;
1893 	}
1894 
1895 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1896 	    CBS_len(&cert_status) != 0) {
1897 		al = SSL_AD_DECODE_ERROR;
1898 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1899 		goto fatal_err;
1900 	}
1901 
1902 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1903 	    &s->internal->tlsext_ocsp_resp_len)) {
1904 		al = SSL_AD_INTERNAL_ERROR;
1905 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1906 		goto fatal_err;
1907 	}
1908 
1909 	if (s->ctx->internal->tlsext_status_cb) {
1910 		int ret;
1911 		ret = s->ctx->internal->tlsext_status_cb(s,
1912 		    s->ctx->internal->tlsext_status_arg);
1913 		if (ret == 0) {
1914 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1915 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1916 			goto fatal_err;
1917 		}
1918 		if (ret < 0) {
1919 			al = SSL_AD_INTERNAL_ERROR;
1920 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1921 			goto fatal_err;
1922 		}
1923 	}
1924 	return (1);
1925  fatal_err:
1926 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1927 	return (-1);
1928 }
1929 
1930 int
1931 ssl3_get_server_done(SSL *s)
1932 {
1933 	int ret;
1934 
1935 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1936 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1937 	    30 /* should be very small, like 0 :-) */)) <= 0)
1938 		return ret;
1939 
1940 	if (s->internal->init_num != 0) {
1941 		/* should contain no data */
1942 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1943 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1944 		return -1;
1945 	}
1946 
1947 	return 1;
1948 }
1949 
1950 static int
1951 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1952 {
1953 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1954 	unsigned char *enc_pms = NULL;
1955 	EVP_PKEY *pkey = NULL;
1956 	int ret = -1;
1957 	int enc_len;
1958 	CBB epms;
1959 
1960 	/*
1961 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1962 	 */
1963 
1964 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA].x509);
1965 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1966 	    pkey->pkey.rsa == NULL) {
1967 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1968 		goto err;
1969 	}
1970 
1971 	/* XXX - our max protocol version. */
1972 	pms[0] = s->client_version >> 8;
1973 	pms[1] = s->client_version & 0xff;
1974 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1975 
1976 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1977 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1978 		goto err;
1979 	}
1980 
1981 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1982 	    RSA_PKCS1_PADDING);
1983 	if (enc_len <= 0) {
1984 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1985 		goto err;
1986 	}
1987 
1988 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
1989 		goto err;
1990 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
1991 		goto err;
1992 	if (!CBB_flush(cbb))
1993 		goto err;
1994 
1995 	if (!tls12_derive_master_secret(s, pms, sizeof(pms)))
1996 		goto err;
1997 
1998 	ret = 1;
1999 
2000  err:
2001 	explicit_bzero(pms, sizeof(pms));
2002 	EVP_PKEY_free(pkey);
2003 	free(enc_pms);
2004 
2005 	return (ret);
2006 }
2007 
2008 static int
2009 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2010 {
2011 	DH *dh_srvr = NULL, *dh_clnt = NULL;
2012 	unsigned char *key = NULL;
2013 	int key_size = 0, key_len;
2014 	unsigned char *data;
2015 	int ret = -1;
2016 	CBB dh_Yc;
2017 
2018 	/* Ensure that we have an ephemeral key for DHE. */
2019 	if (sess_cert->peer_dh_tmp == NULL) {
2020 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2021 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2022 		goto err;
2023 	}
2024 	dh_srvr = sess_cert->peer_dh_tmp;
2025 
2026 	/* Generate a new random key. */
2027 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2028 		SSLerror(s, ERR_R_DH_LIB);
2029 		goto err;
2030 	}
2031 	if (!DH_generate_key(dh_clnt)) {
2032 		SSLerror(s, ERR_R_DH_LIB);
2033 		goto err;
2034 	}
2035 	if ((key_size = DH_size(dh_clnt)) <= 0) {
2036 		SSLerror(s, ERR_R_DH_LIB);
2037 		goto err;
2038 	}
2039 	if ((key = malloc(key_size)) == NULL) {
2040 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2041 		goto err;
2042 	}
2043 	if ((key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt)) <= 0) {
2044 		SSLerror(s, ERR_R_DH_LIB);
2045 		goto err;
2046 	}
2047 
2048 	if (!tls12_derive_master_secret(s, key, key_len))
2049 		goto err;
2050 
2051 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2052 		goto err;
2053 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2054 		goto err;
2055 	BN_bn2bin(dh_clnt->pub_key, data);
2056 	if (!CBB_flush(cbb))
2057 		goto err;
2058 
2059 	ret = 1;
2060 
2061  err:
2062 	DH_free(dh_clnt);
2063 	freezero(key, key_size);
2064 
2065 	return (ret);
2066 }
2067 
2068 static int
2069 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2070 {
2071 	EC_KEY *ecdh = NULL;
2072 	uint8_t *key = NULL;
2073 	size_t key_len = 0;
2074 	int ret = -1;
2075 	CBB ecpoint;
2076 
2077 	if ((ecdh = EC_KEY_new()) == NULL) {
2078 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2079 		goto err;
2080 	}
2081 
2082 	if (!ssl_kex_generate_ecdhe_ecp(ecdh, sc->peer_nid))
2083 		goto err;
2084 
2085 	/* Encode our public key. */
2086 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2087 		goto err;
2088 	if (!ssl_kex_public_ecdhe_ecp(ecdh, &ecpoint))
2089 		goto err;
2090 	if (!CBB_flush(cbb))
2091 		goto err;
2092 
2093 	if (!ssl_kex_derive_ecdhe_ecp(ecdh, sc->peer_ecdh_tmp, &key, &key_len))
2094 		goto err;
2095 	if (!tls12_derive_master_secret(s, key, key_len))
2096 		goto err;
2097 
2098 	ret = 1;
2099 
2100  err:
2101 	freezero(key, key_len);
2102 	EC_KEY_free(ecdh);
2103 
2104 	return (ret);
2105 }
2106 
2107 static int
2108 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2109 {
2110 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2111 	int ret = -1;
2112 	CBB ecpoint;
2113 
2114 	/* Generate X25519 key pair and derive shared key. */
2115 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2116 		goto err;
2117 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2118 		goto err;
2119 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2120 		goto err;
2121 	X25519_keypair(public_key, private_key);
2122 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2123 		goto err;
2124 
2125 	/* Serialize the public key. */
2126 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2127 		goto err;
2128 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2129 		goto err;
2130 	if (!CBB_flush(cbb))
2131 		goto err;
2132 
2133 	if (!tls12_derive_master_secret(s, shared_key, X25519_KEY_LENGTH))
2134 		goto err;
2135 
2136 	ret = 1;
2137 
2138  err:
2139 	free(public_key);
2140 	freezero(private_key, X25519_KEY_LENGTH);
2141 	freezero(shared_key, X25519_KEY_LENGTH);
2142 
2143 	return (ret);
2144 }
2145 
2146 static int
2147 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2148 {
2149 	if (sc->peer_x25519_tmp != NULL) {
2150 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2151 			goto err;
2152 	} else if (sc->peer_ecdh_tmp != NULL) {
2153 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2154 			goto err;
2155 	} else {
2156 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2157 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2158 		goto err;
2159 	}
2160 
2161 	return (1);
2162 
2163  err:
2164 	return (-1);
2165 }
2166 
2167 static int
2168 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2169 {
2170 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2171 	EVP_PKEY *pub_key = NULL;
2172 	EVP_PKEY_CTX *pkey_ctx;
2173 	X509 *peer_cert;
2174 	size_t msglen;
2175 	unsigned int md_len;
2176 	EVP_MD_CTX *ukm_hash;
2177 	int ret = -1;
2178 	int nid;
2179 	CBB gostblob;
2180 
2181 	/* Get server sertificate PKEY and create ctx from it */
2182 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2183 	if (peer_cert == NULL) {
2184 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2185 		goto err;
2186 	}
2187 
2188 	pub_key = X509_get_pubkey(peer_cert);
2189 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2190 
2191 	/*
2192 	 * If we have send a certificate, and certificate key parameters match
2193 	 * those of server certificate, use certificate key for key exchange.
2194 	 * Otherwise, generate ephemeral key pair.
2195 	 */
2196 	EVP_PKEY_encrypt_init(pkey_ctx);
2197 
2198 	/* Generate session key. */
2199 	arc4random_buf(premaster_secret, 32);
2200 
2201 	/*
2202 	 * If we have client certificate, use its secret as peer key.
2203 	 */
2204 	if (S3I(s)->hs.tls12.cert_request && s->cert->key->privatekey) {
2205 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2206 		    s->cert->key->privatekey) <=0) {
2207 			/*
2208 			 * If there was an error - just ignore it.
2209 			 * Ephemeral key would be used.
2210 			 */
2211 			ERR_clear_error();
2212 		}
2213 	}
2214 
2215 	/*
2216 	 * Compute shared IV and store it in algorithm-specific context data.
2217 	 */
2218 	ukm_hash = EVP_MD_CTX_new();
2219 	if (ukm_hash == NULL) {
2220 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2221 		goto err;
2222 	}
2223 
2224 	/* XXX check handshake hash instead. */
2225 	if (S3I(s)->hs.cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
2226 		nid = NID_id_GostR3411_94;
2227 	else
2228 		nid = NID_id_tc26_gost3411_2012_256;
2229 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2230 		goto err;
2231 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2232 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2233 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2234 	EVP_MD_CTX_free(ukm_hash);
2235 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2236 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2237 		SSLerror(s, SSL_R_LIBRARY_BUG);
2238 		goto err;
2239 	}
2240 
2241 	/*
2242 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2243 	 */
2244 	msglen = 255;
2245 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2246 	    32) < 0) {
2247 		SSLerror(s, SSL_R_LIBRARY_BUG);
2248 		goto err;
2249 	}
2250 
2251 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2252 		goto err;
2253 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2254 		goto err;
2255 	if (!CBB_flush(cbb))
2256 		goto err;
2257 
2258 	/* Check if pubkey from client certificate was used. */
2259 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2260 	    NULL) > 0) {
2261 		/* Set flag "skip certificate verify". */
2262 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2263 	}
2264 	EVP_PKEY_CTX_free(pkey_ctx);
2265 
2266 	if (!tls12_derive_master_secret(s, premaster_secret, 32))
2267 		goto err;
2268 
2269 	ret = 1;
2270 
2271  err:
2272 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2273 	EVP_PKEY_free(pub_key);
2274 
2275 	return (ret);
2276 }
2277 
2278 int
2279 ssl3_send_client_key_exchange(SSL *s)
2280 {
2281 	SESS_CERT *sess_cert;
2282 	unsigned long alg_k;
2283 	CBB cbb, kex;
2284 
2285 	memset(&cbb, 0, sizeof(cbb));
2286 
2287 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2288 		alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2289 
2290 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2291 			ssl3_send_alert(s, SSL3_AL_FATAL,
2292 			    SSL_AD_UNEXPECTED_MESSAGE);
2293 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2294 			goto err;
2295 		}
2296 
2297 		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
2298 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2299 			goto err;
2300 
2301 		if (alg_k & SSL_kRSA) {
2302 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2303 				goto err;
2304 		} else if (alg_k & SSL_kDHE) {
2305 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2306 				goto err;
2307 		} else if (alg_k & SSL_kECDHE) {
2308 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2309 				goto err;
2310 		} else if (alg_k & SSL_kGOST) {
2311 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2312 				goto err;
2313 		} else {
2314 			ssl3_send_alert(s, SSL3_AL_FATAL,
2315 			    SSL_AD_HANDSHAKE_FAILURE);
2316 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2317 			goto err;
2318 		}
2319 
2320 		if (!ssl3_handshake_msg_finish(s, &cbb))
2321 			goto err;
2322 
2323 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2324 	}
2325 
2326 	/* SSL3_ST_CW_KEY_EXCH_B */
2327 	return (ssl3_handshake_write(s));
2328 
2329  err:
2330 	CBB_cleanup(&cbb);
2331 
2332 	return (-1);
2333 }
2334 
2335 static int
2336 ssl3_send_client_verify_sigalgs(SSL *s, EVP_PKEY *pkey,
2337     const struct ssl_sigalg *sigalg, CBB *cert_verify)
2338 {
2339 	CBB cbb_signature;
2340 	EVP_PKEY_CTX *pctx = NULL;
2341 	EVP_MD_CTX mctx;
2342 	const unsigned char *hdata;
2343 	unsigned char *signature = NULL;
2344 	size_t signature_len, hdata_len;
2345 	int ret = 0;
2346 
2347 	EVP_MD_CTX_init(&mctx);
2348 
2349 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2350 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2351 		goto err;
2352 	}
2353 	if (!EVP_DigestSignInit(&mctx, &pctx, sigalg->md(), NULL, pkey)) {
2354 		SSLerror(s, ERR_R_EVP_LIB);
2355 		goto err;
2356 	}
2357 	if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2358 	    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2359 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2360 		SSLerror(s, ERR_R_EVP_LIB);
2361 		goto err;
2362 	}
2363 	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2364 	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
2365 	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2366 		SSLerror(s, ERR_R_EVP_LIB);
2367 		goto err;
2368 	}
2369 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2370 		SSLerror(s, ERR_R_EVP_LIB);
2371 		goto err;
2372 	}
2373 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2374 	    signature_len == 0) {
2375 		SSLerror(s, ERR_R_EVP_LIB);
2376 		goto err;
2377 	}
2378 	if ((signature = calloc(1, signature_len)) == NULL) {
2379 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2380 		goto err;
2381 	}
2382 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2383 		SSLerror(s, ERR_R_EVP_LIB);
2384 		goto err;
2385 	}
2386 
2387 	if (!CBB_add_u16(cert_verify, sigalg->value))
2388 		goto err;
2389 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2390 		goto err;
2391 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2392 		goto err;
2393 	if (!CBB_flush(cert_verify))
2394 		goto err;
2395 
2396 	ret = 1;
2397 
2398  err:
2399 	EVP_MD_CTX_cleanup(&mctx);
2400 	free(signature);
2401 	return ret;
2402 }
2403 
2404 static int
2405 ssl3_send_client_verify_rsa(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2406 {
2407 	CBB cbb_signature;
2408 	unsigned char data[EVP_MAX_MD_SIZE];
2409 	unsigned char *signature = NULL;
2410 	unsigned int signature_len;
2411 	size_t data_len;
2412 	int ret = 0;
2413 
2414 	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2415 		goto err;
2416 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2417 		goto err;
2418 	if (RSA_sign(NID_md5_sha1, data, data_len, signature,
2419 	    &signature_len, pkey->pkey.rsa) <= 0 ) {
2420 		SSLerror(s, ERR_R_RSA_LIB);
2421 		goto err;
2422 	}
2423 
2424 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2425 		goto err;
2426 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2427 		goto err;
2428 	if (!CBB_flush(cert_verify))
2429 		goto err;
2430 
2431 	ret = 1;
2432  err:
2433 	free(signature);
2434 	return ret;
2435 }
2436 
2437 static int
2438 ssl3_send_client_verify_ec(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2439 {
2440 	CBB cbb_signature;
2441 	unsigned char data[EVP_MAX_MD_SIZE];
2442 	unsigned char *signature = NULL;
2443 	unsigned int signature_len;
2444 	int ret = 0;
2445 
2446 	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2447 		goto err;
2448 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2449 		goto err;
2450 	if (!ECDSA_sign(pkey->save_type, &data[MD5_DIGEST_LENGTH],
2451 	    SHA_DIGEST_LENGTH, signature, &signature_len, pkey->pkey.ec)) {
2452 		SSLerror(s, ERR_R_ECDSA_LIB);
2453 		goto err;
2454 	}
2455 
2456 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2457 		goto err;
2458 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2459 		goto err;
2460 	if (!CBB_flush(cert_verify))
2461 		goto err;
2462 
2463 	ret = 1;
2464  err:
2465 	free(signature);
2466 	return ret;
2467 }
2468 
2469 #ifndef OPENSSL_NO_GOST
2470 static int
2471 ssl3_send_client_verify_gost(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2472 {
2473 	CBB cbb_signature;
2474 	EVP_MD_CTX mctx;
2475 	EVP_PKEY_CTX *pctx;
2476 	const EVP_MD *md;
2477 	const unsigned char *hdata;
2478 	unsigned char *signature = NULL;
2479 	size_t signature_len;
2480 	size_t hdata_len;
2481 	int nid;
2482 	int ret = 0;
2483 
2484 	EVP_MD_CTX_init(&mctx);
2485 
2486 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2487 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2488 		goto err;
2489 	}
2490 	if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2491 	    (md = EVP_get_digestbynid(nid)) == NULL) {
2492 		SSLerror(s, ERR_R_EVP_LIB);
2493 		goto err;
2494 	}
2495 	if (!EVP_DigestSignInit(&mctx, &pctx, md, NULL, pkey)) {
2496 		SSLerror(s, ERR_R_EVP_LIB);
2497 		goto err;
2498 	}
2499 	if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2500 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2501 		SSLerror(s, ERR_R_EVP_LIB);
2502 		goto err;
2503 	}
2504 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2505 		SSLerror(s, ERR_R_EVP_LIB);
2506 		goto err;
2507 	}
2508 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2509 	    signature_len == 0) {
2510 		SSLerror(s, ERR_R_EVP_LIB);
2511 		goto err;
2512 	}
2513 	if ((signature = calloc(1, signature_len)) == NULL) {
2514 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2515 		goto err;
2516 	}
2517 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2518 		SSLerror(s, ERR_R_EVP_LIB);
2519 		goto err;
2520 	}
2521 
2522 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2523 		goto err;
2524 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2525 		goto err;
2526 	if (!CBB_flush(cert_verify))
2527 		goto err;
2528 
2529 	ret = 1;
2530  err:
2531 	EVP_MD_CTX_cleanup(&mctx);
2532 	free(signature);
2533 	return ret;
2534 }
2535 #endif
2536 
2537 int
2538 ssl3_send_client_verify(SSL *s)
2539 {
2540 	const struct ssl_sigalg *sigalg;
2541 	CBB cbb, cert_verify;
2542 	EVP_PKEY *pkey;
2543 
2544 	memset(&cbb, 0, sizeof(cbb));
2545 
2546 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2547 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2548 		    SSL3_MT_CERTIFICATE_VERIFY))
2549 			goto err;
2550 
2551 		pkey = s->cert->key->privatekey;
2552 		if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2553 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2554 			goto err;
2555 		}
2556 		S3I(s)->hs.our_sigalg = sigalg;
2557 
2558 		/*
2559 		 * For TLS v1.2 send signature algorithm and signature using
2560 		 * agreed digest and cached handshake records.
2561 		 */
2562 		if (SSL_USE_SIGALGS(s)) {
2563 			if (!ssl3_send_client_verify_sigalgs(s, pkey, sigalg,
2564 			    &cert_verify))
2565 				goto err;
2566 		} else if (pkey->type == EVP_PKEY_RSA) {
2567 			if (!ssl3_send_client_verify_rsa(s, pkey, &cert_verify))
2568 				goto err;
2569 		} else if (pkey->type == EVP_PKEY_EC) {
2570 			if (!ssl3_send_client_verify_ec(s, pkey, &cert_verify))
2571 				goto err;
2572 #ifndef OPENSSL_NO_GOST
2573 		} else if (pkey->type == NID_id_GostR3410_94 ||
2574 		    pkey->type == NID_id_GostR3410_2001) {
2575 			if (!ssl3_send_client_verify_gost(s, pkey, &cert_verify))
2576 				goto err;
2577 #endif
2578 		} else {
2579 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2580 			goto err;
2581 		}
2582 
2583 		tls1_transcript_free(s);
2584 
2585 		if (!ssl3_handshake_msg_finish(s, &cbb))
2586 			goto err;
2587 
2588 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2589 	}
2590 
2591 	return (ssl3_handshake_write(s));
2592 
2593  err:
2594 	CBB_cleanup(&cbb);
2595 
2596 	return (-1);
2597 }
2598 
2599 int
2600 ssl3_send_client_certificate(SSL *s)
2601 {
2602 	EVP_PKEY *pkey = NULL;
2603 	X509 *x509 = NULL;
2604 	CBB cbb, client_cert;
2605 	int i;
2606 
2607 	memset(&cbb, 0, sizeof(cbb));
2608 
2609 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2610 		if (s->cert->key->x509 == NULL ||
2611 		    s->cert->key->privatekey == NULL)
2612 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2613 		else
2614 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2615 	}
2616 
2617 	/* We need to get a client cert */
2618 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2619 		/*
2620 		 * If we get an error, we need to
2621 		 * ssl->internal->rwstate = SSL_X509_LOOKUP; return(-1);
2622 		 * We then get retried later.
2623 		 */
2624 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2625 		if (i < 0) {
2626 			s->internal->rwstate = SSL_X509_LOOKUP;
2627 			return (-1);
2628 		}
2629 		s->internal->rwstate = SSL_NOTHING;
2630 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2631 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2632 			if (!SSL_use_certificate(s, x509) ||
2633 			    !SSL_use_PrivateKey(s, pkey))
2634 				i = 0;
2635 		} else if (i == 1) {
2636 			i = 0;
2637 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2638 		}
2639 
2640 		X509_free(x509);
2641 		EVP_PKEY_free(pkey);
2642 		if (i == 0) {
2643 			S3I(s)->hs.tls12.cert_request = 2;
2644 
2645 			/* There is no client certificate to verify. */
2646 			tls1_transcript_free(s);
2647 		}
2648 
2649 		/* Ok, we have a cert */
2650 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2651 	}
2652 
2653 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2654 		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2655 		    SSL3_MT_CERTIFICATE))
2656 			goto err;
2657 		if (!ssl3_output_cert_chain(s, &client_cert,
2658 		    (S3I(s)->hs.tls12.cert_request == 2) ? NULL : s->cert->key))
2659 			goto err;
2660 		if (!ssl3_handshake_msg_finish(s, &cbb))
2661 			goto err;
2662 
2663 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2664 	}
2665 
2666 	/* SSL3_ST_CW_CERT_D */
2667 	return (ssl3_handshake_write(s));
2668 
2669  err:
2670 	CBB_cleanup(&cbb);
2671 
2672 	return (0);
2673 }
2674 
2675 #define has_bits(i,m)	(((i)&(m)) == (m))
2676 
2677 int
2678 ssl3_check_cert_and_algorithm(SSL *s)
2679 {
2680 	int		 i, idx;
2681 	long		 alg_k, alg_a;
2682 	EVP_PKEY	*pkey = NULL;
2683 	SESS_CERT	*sc;
2684 	DH		*dh;
2685 
2686 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2687 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
2688 
2689 	/* We don't have a certificate. */
2690 	if (alg_a & SSL_aNULL)
2691 		return (1);
2692 
2693 	sc = SSI(s)->sess_cert;
2694 	if (sc == NULL) {
2695 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2696 		goto err;
2697 	}
2698 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2699 
2700 	/* This is the passed certificate. */
2701 
2702 	idx = sc->peer_cert_type;
2703 	if (idx == SSL_PKEY_ECC) {
2704 		if (ssl_check_srvr_ecc_cert_and_alg(
2705 		    sc->peer_pkeys[idx].x509, s) == 0) {
2706 			/* check failed */
2707 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2708 			goto fatal_err;
2709 		} else {
2710 			return (1);
2711 		}
2712 	}
2713 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2714 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2715 	EVP_PKEY_free(pkey);
2716 
2717 	/* Check that we have a certificate if we require one. */
2718 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2719 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2720 		goto fatal_err;
2721 	}
2722 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2723 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2724 		goto fatal_err;
2725 	}
2726 	if ((alg_k & SSL_kDHE) &&
2727 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2728 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2729 		goto fatal_err;
2730 	}
2731 
2732 	return (1);
2733  fatal_err:
2734 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2735  err:
2736 	return (0);
2737 }
2738 
2739 /*
2740  * Check to see if handshake is full or resumed. Usually this is just a
2741  * case of checking to see if a cache hit has occurred. In the case of
2742  * session tickets we have to check the next message to be sure.
2743  */
2744 
2745 int
2746 ssl3_check_finished(SSL *s)
2747 {
2748 	int ret;
2749 
2750 	/* If we have no ticket it cannot be a resumed session. */
2751 	if (!s->session->tlsext_tick)
2752 		return (1);
2753 	/* this function is called when we really expect a Certificate
2754 	 * message, so permit appropriate message length */
2755 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2756 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list)) <= 0)
2757 		return ret;
2758 
2759 	S3I(s)->hs.tls12.reuse_message = 1;
2760 	if ((S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) ||
2761 	    (S3I(s)->hs.tls12.message_type == SSL3_MT_NEWSESSION_TICKET))
2762 		return (2);
2763 
2764 	return (1);
2765 }
2766 
2767 int
2768 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2769 {
2770 	int	i = 0;
2771 
2772 #ifndef OPENSSL_NO_ENGINE
2773 	if (s->ctx->internal->client_cert_engine) {
2774 		i = ENGINE_load_ssl_client_cert(
2775 		    s->ctx->internal->client_cert_engine, s,
2776 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2777 		if (i != 0)
2778 			return (i);
2779 	}
2780 #endif
2781 	if (s->ctx->internal->client_cert_cb)
2782 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2783 	return (i);
2784 }
2785