xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision 824adb5411e4389b29bae28eba5c2c2bbd147f34)
1 /* $OpenBSD: ssl_clnt.c,v 1.111 2021/09/03 13:18:17 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 	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 	if (CBS_len(&cbs) != 0)
1069 		goto decode_err;
1070 
1071 	/*
1072 	 * Determine if we need to see RI. Strictly speaking if we want to
1073 	 * avoid an attack we should *always* see RI even on initial server
1074 	 * hello because the client doesn't see any renegotiation during an
1075 	 * attack. However this would mean we could not connect to any server
1076 	 * which doesn't support RI so for the immediate future tolerate RI
1077 	 * absence on initial connect only.
1078 	 */
1079 	if (!S3I(s)->renegotiate_seen &&
1080 	    !(s->internal->options & SSL_OP_LEGACY_SERVER_CONNECT)) {
1081 		al = SSL_AD_HANDSHAKE_FAILURE;
1082 		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1083 		goto fatal_err;
1084 	}
1085 
1086 	if (ssl_check_serverhello_tlsext(s) <= 0) {
1087 		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
1088 		goto err;
1089 	}
1090 
1091 	return (1);
1092 
1093  decode_err:
1094 	/* wrong packet length */
1095 	al = SSL_AD_DECODE_ERROR;
1096 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1097  fatal_err:
1098 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1099  err:
1100 	return (-1);
1101 }
1102 
1103 int
1104 ssl3_get_server_certificate(SSL *s)
1105 {
1106 	int			 al, i, ok, ret = -1;
1107 	long			 n;
1108 	CBS			 cbs, cert_list;
1109 	X509			*x = NULL;
1110 	const unsigned char	*q;
1111 	STACK_OF(X509)		*sk = NULL;
1112 	SESS_CERT		*sc;
1113 	EVP_PKEY		*pkey = NULL;
1114 
1115 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
1116 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
1117 	if (!ok)
1118 		return ((int)n);
1119 
1120 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1121 		S3I(s)->hs.tls12.reuse_message = 1;
1122 		return (1);
1123 	}
1124 
1125 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE) {
1126 		al = SSL_AD_UNEXPECTED_MESSAGE;
1127 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1128 		goto fatal_err;
1129 	}
1130 
1131 
1132 	if ((sk = sk_X509_new_null()) == NULL) {
1133 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1134 		goto err;
1135 	}
1136 
1137 	if (n < 0)
1138 		goto decode_err;
1139 
1140 	CBS_init(&cbs, s->internal->init_msg, n);
1141 	if (CBS_len(&cbs) < 3)
1142 		goto decode_err;
1143 
1144 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
1145 	    CBS_len(&cbs) != 0) {
1146 		al = SSL_AD_DECODE_ERROR;
1147 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1148 		goto fatal_err;
1149 	}
1150 
1151 	while (CBS_len(&cert_list) > 0) {
1152 		CBS cert;
1153 
1154 		if (CBS_len(&cert_list) < 3)
1155 			goto decode_err;
1156 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1157 			al = SSL_AD_DECODE_ERROR;
1158 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1159 			goto fatal_err;
1160 		}
1161 
1162 		q = CBS_data(&cert);
1163 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1164 		if (x == NULL) {
1165 			al = SSL_AD_BAD_CERTIFICATE;
1166 			SSLerror(s, ERR_R_ASN1_LIB);
1167 			goto fatal_err;
1168 		}
1169 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1170 			al = SSL_AD_DECODE_ERROR;
1171 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1172 			goto fatal_err;
1173 		}
1174 		if (!sk_X509_push(sk, x)) {
1175 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1176 			goto err;
1177 		}
1178 		x = NULL;
1179 	}
1180 
1181 	i = ssl_verify_cert_chain(s, sk);
1182 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1183 		al = ssl_verify_alarm_type(s->verify_result);
1184 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1185 		goto fatal_err;
1186 
1187 	}
1188 	ERR_clear_error(); /* but we keep s->verify_result */
1189 
1190 	sc = ssl_sess_cert_new();
1191 	if (sc == NULL)
1192 		goto err;
1193 	ssl_sess_cert_free(SSI(s)->sess_cert);
1194 	SSI(s)->sess_cert = sc;
1195 
1196 	sc->cert_chain = sk;
1197 	/*
1198 	 * Inconsistency alert: cert_chain does include the peer's
1199 	 * certificate, which we don't include in s3_srvr.c
1200 	 */
1201 	x = sk_X509_value(sk, 0);
1202 	sk = NULL;
1203 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1204 
1205 	pkey = X509_get_pubkey(x);
1206 
1207 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1208 		x = NULL;
1209 		al = SSL3_AL_FATAL;
1210 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1211 		goto fatal_err;
1212 	}
1213 
1214 	i = ssl_cert_type(x, pkey);
1215 	if (i < 0) {
1216 		x = NULL;
1217 		al = SSL3_AL_FATAL;
1218 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1219 		goto fatal_err;
1220 	}
1221 
1222 	sc->peer_cert_type = i;
1223 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1224 	/*
1225 	 * Why would the following ever happen?
1226 	 * We just created sc a couple of lines ago.
1227 	 */
1228 	X509_free(sc->peer_pkeys[i].x509);
1229 	sc->peer_pkeys[i].x509 = x;
1230 	sc->peer_key = &(sc->peer_pkeys[i]);
1231 
1232 	X509_free(s->session->peer);
1233 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1234 	s->session->peer = x;
1235 	s->session->verify_result = s->verify_result;
1236 
1237 	x = NULL;
1238 	ret = 1;
1239 
1240 	if (0) {
1241  decode_err:
1242 		/* wrong packet length */
1243 		al = SSL_AD_DECODE_ERROR;
1244 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1245  fatal_err:
1246 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1247 	}
1248  err:
1249 	EVP_PKEY_free(pkey);
1250 	X509_free(x);
1251 	sk_X509_pop_free(sk, X509_free);
1252 
1253 	return (ret);
1254 }
1255 
1256 static int
1257 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1258 {
1259 	CBS dhp, dhg, dhpk;
1260 	BN_CTX *bn_ctx = NULL;
1261 	SESS_CERT *sc = NULL;
1262 	DH *dh = NULL;
1263 	long alg_a;
1264 	int al;
1265 
1266 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1267 	sc = SSI(s)->sess_cert;
1268 
1269 	if ((dh = DH_new()) == NULL) {
1270 		SSLerror(s, ERR_R_DH_LIB);
1271 		goto err;
1272 	}
1273 
1274 	if (!CBS_get_u16_length_prefixed(cbs, &dhp))
1275 		goto decode_err;
1276 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1277 		SSLerror(s, ERR_R_BN_LIB);
1278 		goto err;
1279 	}
1280 
1281 	if (!CBS_get_u16_length_prefixed(cbs, &dhg))
1282 		goto decode_err;
1283 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1284 		SSLerror(s, ERR_R_BN_LIB);
1285 		goto err;
1286 	}
1287 
1288 	if (!CBS_get_u16_length_prefixed(cbs, &dhpk))
1289 		goto decode_err;
1290 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1291 	    NULL)) == NULL) {
1292 		SSLerror(s, ERR_R_BN_LIB);
1293 		goto err;
1294 	}
1295 
1296 	/*
1297 	 * Check the strength of the DH key just constructed.
1298 	 * Discard keys weaker than 1024 bits.
1299 	 */
1300 	if (DH_size(dh) < 1024 / 8) {
1301 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1302 		goto err;
1303 	}
1304 
1305 	if (alg_a & SSL_aRSA)
1306 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1307 	else
1308 		/* XXX - Anonymous DH, so no certificate or pkey. */
1309 		*pkey = NULL;
1310 
1311 	sc->peer_dh_tmp = dh;
1312 
1313 	return (1);
1314 
1315  decode_err:
1316 	al = SSL_AD_DECODE_ERROR;
1317 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1318 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1319 
1320  err:
1321 	DH_free(dh);
1322 	BN_CTX_free(bn_ctx);
1323 
1324 	return (-1);
1325 }
1326 
1327 static int
1328 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1329 {
1330 	EC_KEY *ecdh = NULL;
1331 	int ret = -1;
1332 
1333 	/* Extract the server's ephemeral ECDH public key. */
1334 	if ((ecdh = EC_KEY_new()) == NULL) {
1335 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1336 		goto err;
1337 	}
1338 	if (!ssl_kex_peer_public_ecdhe_ecp(ecdh, nid, public)) {
1339 		SSLerror(s, SSL_R_BAD_ECPOINT);
1340 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1341 		goto err;
1342 	}
1343 
1344 	sc->peer_nid = nid;
1345 	sc->peer_ecdh_tmp = ecdh;
1346 	ecdh = NULL;
1347 
1348 	ret = 1;
1349 
1350  err:
1351 	EC_KEY_free(ecdh);
1352 
1353 	return (ret);
1354 }
1355 
1356 static int
1357 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1358 {
1359 	size_t outlen;
1360 
1361 	if (nid != NID_X25519) {
1362 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1363 		goto err;
1364 	}
1365 
1366 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1367 		SSLerror(s, SSL_R_BAD_ECPOINT);
1368 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1369 		goto err;
1370 	}
1371 
1372 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1373 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1374 		goto err;
1375 	}
1376 
1377 	return (1);
1378 
1379  err:
1380 	return (-1);
1381 }
1382 
1383 static int
1384 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1385 {
1386 	CBS public;
1387 	uint8_t curve_type;
1388 	uint16_t curve_id;
1389 	SESS_CERT *sc;
1390 	long alg_a;
1391 	int nid;
1392 	int al;
1393 
1394 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1395 	sc = SSI(s)->sess_cert;
1396 
1397 	/* Only named curves are supported. */
1398 	if (!CBS_get_u8(cbs, &curve_type) ||
1399 	    curve_type != NAMED_CURVE_TYPE ||
1400 	    !CBS_get_u16(cbs, &curve_id)) {
1401 		al = SSL_AD_DECODE_ERROR;
1402 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1403 		goto fatal_err;
1404 	}
1405 
1406 	/*
1407 	 * Check that the curve is one of our preferences - if it is not,
1408 	 * the server has sent us an invalid curve.
1409 	 */
1410 	if (tls1_check_curve(s, curve_id) != 1) {
1411 		al = SSL_AD_DECODE_ERROR;
1412 		SSLerror(s, SSL_R_WRONG_CURVE);
1413 		goto fatal_err;
1414 	}
1415 
1416 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1417 		al = SSL_AD_INTERNAL_ERROR;
1418 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1419 		goto fatal_err;
1420 	}
1421 
1422 	if (!CBS_get_u8_length_prefixed(cbs, &public))
1423 		goto decode_err;
1424 
1425 	if (nid == NID_X25519) {
1426 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1427 			goto err;
1428 	} else {
1429 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1430 			goto err;
1431 	}
1432 
1433 	/*
1434 	 * The ECC/TLS specification does not mention the use of DSA to sign
1435 	 * ECParameters in the server key exchange message. We do support RSA
1436 	 * and ECDSA.
1437 	 */
1438 	if (alg_a & SSL_aRSA)
1439 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1440 	else if (alg_a & SSL_aECDSA)
1441 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1442 	else
1443 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1444 		*pkey = NULL;
1445 
1446 	return (1);
1447 
1448  decode_err:
1449 	al = SSL_AD_DECODE_ERROR;
1450 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1451 
1452  fatal_err:
1453 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1454 
1455  err:
1456 	return (-1);
1457 }
1458 
1459 int
1460 ssl3_get_server_key_exchange(SSL *s)
1461 {
1462 	CBS cbs, signature;
1463 	EVP_PKEY *pkey = NULL;
1464 	EVP_MD_CTX md_ctx;
1465 	const unsigned char *param;
1466 	long n, alg_k, alg_a;
1467 	int al, ok;
1468 	size_t param_len;
1469 
1470 	EVP_MD_CTX_init(&md_ctx);
1471 
1472 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
1473 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
1474 
1475 	/*
1476 	 * Use same message size as in ssl3_get_certificate_request()
1477 	 * as ServerKeyExchange message may be skipped.
1478 	 */
1479 	n = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1480 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1481 	if (!ok)
1482 		return ((int)n);
1483 
1484 	if (n < 0)
1485 		goto err;
1486 
1487 	CBS_init(&cbs, s->internal->init_msg, n);
1488 
1489 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1490 		/*
1491 		 * Do not skip server key exchange if this cipher suite uses
1492 		 * ephemeral keys.
1493 		 */
1494 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1495 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1496 			al = SSL_AD_UNEXPECTED_MESSAGE;
1497 			goto fatal_err;
1498 		}
1499 
1500 		S3I(s)->hs.tls12.reuse_message = 1;
1501 		EVP_MD_CTX_cleanup(&md_ctx);
1502 		return (1);
1503 	}
1504 
1505 	if (SSI(s)->sess_cert != NULL) {
1506 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1507 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1508 
1509 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1510 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1511 
1512 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1513 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1514 	} else {
1515 		SSI(s)->sess_cert = ssl_sess_cert_new();
1516 		if (SSI(s)->sess_cert == NULL)
1517 			goto err;
1518 	}
1519 
1520 	param = CBS_data(&cbs);
1521 	param_len = CBS_len(&cbs);
1522 
1523 	if (alg_k & SSL_kDHE) {
1524 		if (ssl3_get_server_kex_dhe(s, &pkey, &cbs) != 1)
1525 			goto err;
1526 	} else if (alg_k & SSL_kECDHE) {
1527 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &cbs) != 1)
1528 			goto err;
1529 	} else if (alg_k != 0) {
1530 		al = SSL_AD_UNEXPECTED_MESSAGE;
1531 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1532 		goto fatal_err;
1533 	}
1534 
1535 	param_len -= CBS_len(&cbs);
1536 
1537 	/* if it was signed, check the signature */
1538 	if (pkey != NULL) {
1539 		uint16_t sigalg_value = SIGALG_NONE;
1540 		const struct ssl_sigalg *sigalg;
1541 		EVP_PKEY_CTX *pctx;
1542 
1543 		if (SSL_USE_SIGALGS(s)) {
1544 			if (!CBS_get_u16(&cbs, &sigalg_value))
1545 				goto decode_err;
1546 		}
1547 		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1548 			goto decode_err;
1549 		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1550 			al = SSL_AD_DECODE_ERROR;
1551 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1552 			goto fatal_err;
1553 		}
1554 
1555 		if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1556 		    sigalg_value)) == NULL) {
1557 			al = SSL_AD_DECODE_ERROR;
1558 			goto fatal_err;
1559 		}
1560 		S3I(s)->hs.peer_sigalg = sigalg;
1561 
1562 		if (!EVP_DigestVerifyInit(&md_ctx, &pctx, sigalg->md(),
1563 		    NULL, pkey))
1564 			goto err;
1565 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
1566 		    SSL3_RANDOM_SIZE))
1567 			goto err;
1568 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1569 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1570 		    RSA_PKCS1_PSS_PADDING) ||
1571 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1572 			goto err;
1573 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
1574 		    SSL3_RANDOM_SIZE))
1575 			goto err;
1576 		if (!EVP_DigestVerifyUpdate(&md_ctx, param, param_len))
1577 			goto err;
1578 		if (EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
1579 		    CBS_len(&signature)) <= 0) {
1580 			al = SSL_AD_DECRYPT_ERROR;
1581 			SSLerror(s, SSL_R_BAD_SIGNATURE);
1582 			goto fatal_err;
1583 		}
1584 	} else {
1585 		/* aNULL does not need public keys. */
1586 		if (!(alg_a & SSL_aNULL)) {
1587 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1588 			goto err;
1589 		}
1590 	}
1591 
1592 	if (CBS_len(&cbs) != 0) {
1593 		al = SSL_AD_DECODE_ERROR;
1594 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1595 		goto fatal_err;
1596 	}
1597 
1598 	EVP_PKEY_free(pkey);
1599 	EVP_MD_CTX_cleanup(&md_ctx);
1600 
1601 	return (1);
1602 
1603  decode_err:
1604 	al = SSL_AD_DECODE_ERROR;
1605 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1606 
1607  fatal_err:
1608 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1609 
1610  err:
1611 	EVP_PKEY_free(pkey);
1612 	EVP_MD_CTX_cleanup(&md_ctx);
1613 
1614 	return (-1);
1615 }
1616 
1617 int
1618 ssl3_get_certificate_request(SSL *s)
1619 {
1620 	int			 ok, ret = 0;
1621 	long			 n;
1622 	CBS			 cert_request, cert_types, rdn_list;
1623 	X509_NAME		*xn = NULL;
1624 	const unsigned char	*q;
1625 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1626 
1627 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1628 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1629 	if (!ok)
1630 		return ((int)n);
1631 
1632 	S3I(s)->hs.tls12.cert_request = 0;
1633 
1634 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_DONE) {
1635 		S3I(s)->hs.tls12.reuse_message = 1;
1636 		/*
1637 		 * If we get here we don't need any cached handshake records
1638 		 * as we wont be doing client auth.
1639 		 */
1640 		tls1_transcript_free(s);
1641 		return (1);
1642 	}
1643 
1644 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1645 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1646 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1647 		goto err;
1648 	}
1649 
1650 	/* TLS does not like anon-DH with client cert */
1651 	if (S3I(s)->hs.cipher->algorithm_auth & SSL_aNULL) {
1652 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1653 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1654 		goto err;
1655 	}
1656 
1657 	if (n < 0)
1658 		goto decode_err;
1659 	CBS_init(&cert_request, s->internal->init_msg, n);
1660 
1661 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1662 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1663 		goto err;
1664 	}
1665 
1666 	if (!CBS_get_u8_length_prefixed(&cert_request, &cert_types))
1667 		goto decode_err;
1668 
1669 	if (SSL_USE_SIGALGS(s)) {
1670 		CBS sigalgs;
1671 
1672 		if (CBS_len(&cert_request) < 2) {
1673 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1674 			goto err;
1675 		}
1676 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1677 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1678 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1679 			goto err;
1680 		}
1681 		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1682 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1683 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1684 			goto err;
1685 		}
1686 		if (!CBS_stow(&sigalgs, &S3I(s)->hs.sigalgs,
1687 		    &S3I(s)->hs.sigalgs_len))
1688 			goto err;
1689 	}
1690 
1691 	/* get the CA RDNs */
1692 	if (CBS_len(&cert_request) < 2) {
1693 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1694 		goto err;
1695 	}
1696 
1697 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1698 	    CBS_len(&cert_request) != 0) {
1699 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1700 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1701 		goto err;
1702 	}
1703 
1704 	while (CBS_len(&rdn_list) > 0) {
1705 		CBS rdn;
1706 
1707 		if (CBS_len(&rdn_list) < 2) {
1708 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1709 			goto err;
1710 		}
1711 
1712 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1713 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1714 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1715 			goto err;
1716 		}
1717 
1718 		q = CBS_data(&rdn);
1719 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1720 			ssl3_send_alert(s, SSL3_AL_FATAL,
1721 			    SSL_AD_DECODE_ERROR);
1722 			SSLerror(s, ERR_R_ASN1_LIB);
1723 			goto err;
1724 		}
1725 
1726 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1727 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1728 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1729 			goto err;
1730 		}
1731 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1732 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1733 			goto err;
1734 		}
1735 		xn = NULL;	/* avoid free in err block */
1736 	}
1737 
1738 	/* we should setup a certificate to return.... */
1739 	S3I(s)->hs.tls12.cert_request = 1;
1740 	sk_X509_NAME_pop_free(S3I(s)->hs.tls12.ca_names, X509_NAME_free);
1741 	S3I(s)->hs.tls12.ca_names = ca_sk;
1742 	ca_sk = NULL;
1743 
1744 	ret = 1;
1745 	if (0) {
1746  decode_err:
1747 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1748 	}
1749  err:
1750 	X509_NAME_free(xn);
1751 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1752 	return (ret);
1753 }
1754 
1755 static int
1756 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1757 {
1758 	return (X509_NAME_cmp(*a, *b));
1759 }
1760 
1761 int
1762 ssl3_get_new_session_ticket(SSL *s)
1763 {
1764 	int			 ok, al, ret = 0;
1765 	uint32_t		 lifetime_hint;
1766 	long			 n;
1767 	CBS			 cbs, session_ticket;
1768 
1769 	n = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1770 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1771 	if (!ok)
1772 		return ((int)n);
1773 
1774 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) {
1775 		S3I(s)->hs.tls12.reuse_message = 1;
1776 		return (1);
1777 	}
1778 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_NEWSESSION_TICKET) {
1779 		al = SSL_AD_UNEXPECTED_MESSAGE;
1780 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1781 		goto fatal_err;
1782 	}
1783 
1784 	if (n < 0) {
1785 		al = SSL_AD_DECODE_ERROR;
1786 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1787 		goto fatal_err;
1788 	}
1789 
1790 	CBS_init(&cbs, s->internal->init_msg, n);
1791 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1792 #if UINT32_MAX > LONG_MAX
1793 	    lifetime_hint > LONG_MAX ||
1794 #endif
1795 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1796 	    CBS_len(&cbs) != 0) {
1797 		al = SSL_AD_DECODE_ERROR;
1798 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1799 		goto fatal_err;
1800 	}
1801 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1802 
1803 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1804 	    &s->session->tlsext_ticklen)) {
1805 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1806 		goto err;
1807 	}
1808 
1809 	/*
1810 	 * There are two ways to detect a resumed ticket sesion.
1811 	 * One is to set an appropriate session ID and then the server
1812 	 * must return a match in ServerHello. This allows the normal
1813 	 * client session ID matching to work and we know much
1814 	 * earlier that the ticket has been accepted.
1815 	 *
1816 	 * The other way is to set zero length session ID when the
1817 	 * ticket is presented and rely on the handshake to determine
1818 	 * session resumption.
1819 	 *
1820 	 * We choose the former approach because this fits in with
1821 	 * assumptions elsewhere in OpenSSL. The session ID is set
1822 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1823 	 * ticket.
1824 	 */
1825 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1826 	    s->session->session_id, &s->session->session_id_length,
1827 	    EVP_sha256(), NULL);
1828 	ret = 1;
1829 	return (ret);
1830  fatal_err:
1831 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1832  err:
1833 	return (-1);
1834 }
1835 
1836 int
1837 ssl3_get_cert_status(SSL *s)
1838 {
1839 	CBS			 cert_status, response;
1840 	int			 ok, al;
1841 	long			 n;
1842 	uint8_t			 status_type;
1843 
1844 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1845 	    SSL3_ST_CR_CERT_STATUS_B, -1, 16384, &ok);
1846 	if (!ok)
1847 		return ((int)n);
1848 
1849 	if (S3I(s)->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1850 		/*
1851 		 * Tell the callback the server did not send us an OSCP
1852 		 * response, and has decided to head directly to key exchange.
1853 		 */
1854 		if (s->ctx->internal->tlsext_status_cb) {
1855 			int ret;
1856 
1857 			free(s->internal->tlsext_ocsp_resp);
1858 			s->internal->tlsext_ocsp_resp = NULL;
1859 			s->internal->tlsext_ocsp_resp_len = 0;
1860 
1861 			ret = s->ctx->internal->tlsext_status_cb(s,
1862 			    s->ctx->internal->tlsext_status_arg);
1863 			if (ret == 0) {
1864 				al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1865 				SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1866 				goto fatal_err;
1867 			}
1868 			if (ret < 0) {
1869 				al = SSL_AD_INTERNAL_ERROR;
1870 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1871 				goto fatal_err;
1872 			}
1873 		}
1874 		S3I(s)->hs.tls12.reuse_message = 1;
1875 		return (1);
1876 	}
1877 
1878 	if (S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE &&
1879 	    S3I(s)->hs.tls12.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1880 		al = SSL_AD_UNEXPECTED_MESSAGE;
1881 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1882 		goto fatal_err;
1883 	}
1884 
1885 	if (n < 0) {
1886 		/* need at least status type + length */
1887 		al = SSL_AD_DECODE_ERROR;
1888 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1889 		goto fatal_err;
1890 	}
1891 
1892 	CBS_init(&cert_status, s->internal->init_msg, n);
1893 	if (!CBS_get_u8(&cert_status, &status_type) ||
1894 	    CBS_len(&cert_status) < 3) {
1895 		/* need at least status type + length */
1896 		al = SSL_AD_DECODE_ERROR;
1897 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1898 		goto fatal_err;
1899 	}
1900 
1901 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1902 		al = SSL_AD_DECODE_ERROR;
1903 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1904 		goto fatal_err;
1905 	}
1906 
1907 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1908 	    CBS_len(&cert_status) != 0) {
1909 		al = SSL_AD_DECODE_ERROR;
1910 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1911 		goto fatal_err;
1912 	}
1913 
1914 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1915 	    &s->internal->tlsext_ocsp_resp_len)) {
1916 		al = SSL_AD_INTERNAL_ERROR;
1917 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1918 		goto fatal_err;
1919 	}
1920 
1921 	if (s->ctx->internal->tlsext_status_cb) {
1922 		int ret;
1923 		ret = s->ctx->internal->tlsext_status_cb(s,
1924 		    s->ctx->internal->tlsext_status_arg);
1925 		if (ret == 0) {
1926 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1927 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1928 			goto fatal_err;
1929 		}
1930 		if (ret < 0) {
1931 			al = SSL_AD_INTERNAL_ERROR;
1932 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1933 			goto fatal_err;
1934 		}
1935 	}
1936 	return (1);
1937  fatal_err:
1938 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1939 	return (-1);
1940 }
1941 
1942 int
1943 ssl3_get_server_done(SSL *s)
1944 {
1945 	int	ok, ret = 0;
1946 	long	n;
1947 
1948 	n = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1949 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1950 	    30, /* should be very small, like 0 :-) */ &ok);
1951 	if (!ok)
1952 		return ((int)n);
1953 
1954 	if (n > 0) {
1955 		/* should contain no data */
1956 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1957 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1958 		return (-1);
1959 	}
1960 	ret = 1;
1961 	return (ret);
1962 }
1963 
1964 static int
1965 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1966 {
1967 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1968 	unsigned char *enc_pms = NULL;
1969 	EVP_PKEY *pkey = NULL;
1970 	int ret = -1;
1971 	int enc_len;
1972 	CBB epms;
1973 
1974 	/*
1975 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1976 	 */
1977 
1978 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA].x509);
1979 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1980 	    pkey->pkey.rsa == NULL) {
1981 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1982 		goto err;
1983 	}
1984 
1985 	/* XXX - our max protocol version. */
1986 	pms[0] = s->client_version >> 8;
1987 	pms[1] = s->client_version & 0xff;
1988 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1989 
1990 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1991 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1992 		goto err;
1993 	}
1994 
1995 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1996 	    RSA_PKCS1_PADDING);
1997 	if (enc_len <= 0) {
1998 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1999 		goto err;
2000 	}
2001 
2002 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
2003 		goto err;
2004 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
2005 		goto err;
2006 	if (!CBB_flush(cbb))
2007 		goto err;
2008 
2009 	if (!tls12_derive_master_secret(s, pms, sizeof(pms)))
2010 		goto err;
2011 
2012 	ret = 1;
2013 
2014  err:
2015 	explicit_bzero(pms, sizeof(pms));
2016 	EVP_PKEY_free(pkey);
2017 	free(enc_pms);
2018 
2019 	return (ret);
2020 }
2021 
2022 static int
2023 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2024 {
2025 	DH *dh_srvr = NULL, *dh_clnt = NULL;
2026 	unsigned char *key = NULL;
2027 	int key_size = 0, key_len;
2028 	unsigned char *data;
2029 	int ret = -1;
2030 	CBB dh_Yc;
2031 
2032 	/* Ensure that we have an ephemeral key for DHE. */
2033 	if (sess_cert->peer_dh_tmp == NULL) {
2034 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2035 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2036 		goto err;
2037 	}
2038 	dh_srvr = sess_cert->peer_dh_tmp;
2039 
2040 	/* Generate a new random key. */
2041 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2042 		SSLerror(s, ERR_R_DH_LIB);
2043 		goto err;
2044 	}
2045 	if (!DH_generate_key(dh_clnt)) {
2046 		SSLerror(s, ERR_R_DH_LIB);
2047 		goto err;
2048 	}
2049 	if ((key_size = DH_size(dh_clnt)) <= 0) {
2050 		SSLerror(s, ERR_R_DH_LIB);
2051 		goto err;
2052 	}
2053 	if ((key = malloc(key_size)) == NULL) {
2054 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2055 		goto err;
2056 	}
2057 	if ((key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt)) <= 0) {
2058 		SSLerror(s, ERR_R_DH_LIB);
2059 		goto err;
2060 	}
2061 
2062 	if (!tls12_derive_master_secret(s, key, key_len))
2063 		goto err;
2064 
2065 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2066 		goto err;
2067 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2068 		goto err;
2069 	BN_bn2bin(dh_clnt->pub_key, data);
2070 	if (!CBB_flush(cbb))
2071 		goto err;
2072 
2073 	ret = 1;
2074 
2075  err:
2076 	DH_free(dh_clnt);
2077 	freezero(key, key_size);
2078 
2079 	return (ret);
2080 }
2081 
2082 static int
2083 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2084 {
2085 	EC_KEY *ecdh = NULL;
2086 	uint8_t *key = NULL;
2087 	size_t key_len = 0;
2088 	int ret = -1;
2089 	CBB ecpoint;
2090 
2091 	if ((ecdh = EC_KEY_new()) == NULL) {
2092 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2093 		goto err;
2094 	}
2095 
2096 	if (!ssl_kex_generate_ecdhe_ecp(ecdh, sc->peer_nid))
2097 		goto err;
2098 
2099 	/* Encode our public key. */
2100 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2101 		goto err;
2102 	if (!ssl_kex_public_ecdhe_ecp(ecdh, &ecpoint))
2103 		goto err;
2104 	if (!CBB_flush(cbb))
2105 		goto err;
2106 
2107 	if (!ssl_kex_derive_ecdhe_ecp(ecdh, sc->peer_ecdh_tmp, &key, &key_len))
2108 		goto err;
2109 	if (!tls12_derive_master_secret(s, key, key_len))
2110 		goto err;
2111 
2112 	ret = 1;
2113 
2114  err:
2115 	freezero(key, key_len);
2116 	EC_KEY_free(ecdh);
2117 
2118 	return (ret);
2119 }
2120 
2121 static int
2122 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2123 {
2124 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2125 	int ret = -1;
2126 	CBB ecpoint;
2127 
2128 	/* Generate X25519 key pair and derive shared key. */
2129 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2130 		goto err;
2131 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2132 		goto err;
2133 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2134 		goto err;
2135 	X25519_keypair(public_key, private_key);
2136 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2137 		goto err;
2138 
2139 	/* Serialize the public key. */
2140 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2141 		goto err;
2142 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2143 		goto err;
2144 	if (!CBB_flush(cbb))
2145 		goto err;
2146 
2147 	if (!tls12_derive_master_secret(s, shared_key, X25519_KEY_LENGTH))
2148 		goto err;
2149 
2150 	ret = 1;
2151 
2152  err:
2153 	free(public_key);
2154 	freezero(private_key, X25519_KEY_LENGTH);
2155 	freezero(shared_key, X25519_KEY_LENGTH);
2156 
2157 	return (ret);
2158 }
2159 
2160 static int
2161 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2162 {
2163 	if (sc->peer_x25519_tmp != NULL) {
2164 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2165 			goto err;
2166 	} else if (sc->peer_ecdh_tmp != NULL) {
2167 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2168 			goto err;
2169 	} else {
2170 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2171 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2172 		goto err;
2173 	}
2174 
2175 	return (1);
2176 
2177  err:
2178 	return (-1);
2179 }
2180 
2181 static int
2182 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2183 {
2184 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2185 	EVP_PKEY *pub_key = NULL;
2186 	EVP_PKEY_CTX *pkey_ctx;
2187 	X509 *peer_cert;
2188 	size_t msglen;
2189 	unsigned int md_len;
2190 	EVP_MD_CTX *ukm_hash;
2191 	int ret = -1;
2192 	int nid;
2193 	CBB gostblob;
2194 
2195 	/* Get server sertificate PKEY and create ctx from it */
2196 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2197 	if (peer_cert == NULL) {
2198 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2199 		goto err;
2200 	}
2201 
2202 	pub_key = X509_get_pubkey(peer_cert);
2203 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2204 
2205 	/*
2206 	 * If we have send a certificate, and certificate key parameters match
2207 	 * those of server certificate, use certificate key for key exchange.
2208 	 * Otherwise, generate ephemeral key pair.
2209 	 */
2210 	EVP_PKEY_encrypt_init(pkey_ctx);
2211 
2212 	/* Generate session key. */
2213 	arc4random_buf(premaster_secret, 32);
2214 
2215 	/*
2216 	 * If we have client certificate, use its secret as peer key.
2217 	 */
2218 	if (S3I(s)->hs.tls12.cert_request && s->cert->key->privatekey) {
2219 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2220 		    s->cert->key->privatekey) <=0) {
2221 			/*
2222 			 * If there was an error - just ignore it.
2223 			 * Ephemeral key would be used.
2224 			 */
2225 			ERR_clear_error();
2226 		}
2227 	}
2228 
2229 	/*
2230 	 * Compute shared IV and store it in algorithm-specific context data.
2231 	 */
2232 	ukm_hash = EVP_MD_CTX_new();
2233 	if (ukm_hash == NULL) {
2234 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2235 		goto err;
2236 	}
2237 
2238 	/* XXX check handshake hash instead. */
2239 	if (S3I(s)->hs.cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
2240 		nid = NID_id_GostR3411_94;
2241 	else
2242 		nid = NID_id_tc26_gost3411_2012_256;
2243 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2244 		goto err;
2245 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2246 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2247 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2248 	EVP_MD_CTX_free(ukm_hash);
2249 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2250 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2251 		SSLerror(s, SSL_R_LIBRARY_BUG);
2252 		goto err;
2253 	}
2254 
2255 	/*
2256 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2257 	 */
2258 	msglen = 255;
2259 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2260 	    32) < 0) {
2261 		SSLerror(s, SSL_R_LIBRARY_BUG);
2262 		goto err;
2263 	}
2264 
2265 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2266 		goto err;
2267 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2268 		goto err;
2269 	if (!CBB_flush(cbb))
2270 		goto err;
2271 
2272 	/* Check if pubkey from client certificate was used. */
2273 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2274 	    NULL) > 0) {
2275 		/* Set flag "skip certificate verify". */
2276 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2277 	}
2278 	EVP_PKEY_CTX_free(pkey_ctx);
2279 
2280 	if (!tls12_derive_master_secret(s, premaster_secret, 32))
2281 		goto err;
2282 
2283 	ret = 1;
2284 
2285  err:
2286 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2287 	EVP_PKEY_free(pub_key);
2288 
2289 	return (ret);
2290 }
2291 
2292 int
2293 ssl3_send_client_key_exchange(SSL *s)
2294 {
2295 	SESS_CERT *sess_cert;
2296 	unsigned long alg_k;
2297 	CBB cbb, kex;
2298 
2299 	memset(&cbb, 0, sizeof(cbb));
2300 
2301 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2302 		alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2303 
2304 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2305 			ssl3_send_alert(s, SSL3_AL_FATAL,
2306 			    SSL_AD_UNEXPECTED_MESSAGE);
2307 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2308 			goto err;
2309 		}
2310 
2311 		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
2312 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2313 			goto err;
2314 
2315 		if (alg_k & SSL_kRSA) {
2316 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2317 				goto err;
2318 		} else if (alg_k & SSL_kDHE) {
2319 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2320 				goto err;
2321 		} else if (alg_k & SSL_kECDHE) {
2322 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2323 				goto err;
2324 		} else if (alg_k & SSL_kGOST) {
2325 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2326 				goto err;
2327 		} else {
2328 			ssl3_send_alert(s, SSL3_AL_FATAL,
2329 			    SSL_AD_HANDSHAKE_FAILURE);
2330 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2331 			goto err;
2332 		}
2333 
2334 		if (!ssl3_handshake_msg_finish(s, &cbb))
2335 			goto err;
2336 
2337 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2338 	}
2339 
2340 	/* SSL3_ST_CW_KEY_EXCH_B */
2341 	return (ssl3_handshake_write(s));
2342 
2343  err:
2344 	CBB_cleanup(&cbb);
2345 
2346 	return (-1);
2347 }
2348 
2349 static int
2350 ssl3_send_client_verify_sigalgs(SSL *s, EVP_PKEY *pkey,
2351     const struct ssl_sigalg *sigalg, CBB *cert_verify)
2352 {
2353 	CBB cbb_signature;
2354 	EVP_PKEY_CTX *pctx = NULL;
2355 	EVP_MD_CTX mctx;
2356 	const unsigned char *hdata;
2357 	unsigned char *signature = NULL;
2358 	size_t signature_len, hdata_len;
2359 	int ret = 0;
2360 
2361 	EVP_MD_CTX_init(&mctx);
2362 
2363 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2364 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2365 		goto err;
2366 	}
2367 	if (!EVP_DigestSignInit(&mctx, &pctx, sigalg->md(), NULL, pkey)) {
2368 		SSLerror(s, ERR_R_EVP_LIB);
2369 		goto err;
2370 	}
2371 	if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2372 	    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2373 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2374 		SSLerror(s, ERR_R_EVP_LIB);
2375 		goto err;
2376 	}
2377 	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2378 	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
2379 	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2380 		SSLerror(s, ERR_R_EVP_LIB);
2381 		goto err;
2382 	}
2383 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2384 		SSLerror(s, ERR_R_EVP_LIB);
2385 		goto err;
2386 	}
2387 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2388 	    signature_len == 0) {
2389 		SSLerror(s, ERR_R_EVP_LIB);
2390 		goto err;
2391 	}
2392 	if ((signature = calloc(1, signature_len)) == NULL) {
2393 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2394 		goto err;
2395 	}
2396 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2397 		SSLerror(s, ERR_R_EVP_LIB);
2398 		goto err;
2399 	}
2400 
2401 	if (!CBB_add_u16(cert_verify, sigalg->value))
2402 		goto err;
2403 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2404 		goto err;
2405 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2406 		goto err;
2407 	if (!CBB_flush(cert_verify))
2408 		goto err;
2409 
2410 	ret = 1;
2411 
2412  err:
2413 	EVP_MD_CTX_cleanup(&mctx);
2414 	free(signature);
2415 	return ret;
2416 }
2417 
2418 static int
2419 ssl3_send_client_verify_rsa(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2420 {
2421 	CBB cbb_signature;
2422 	unsigned char data[EVP_MAX_MD_SIZE];
2423 	unsigned char *signature = NULL;
2424 	unsigned int signature_len;
2425 	size_t data_len;
2426 	int ret = 0;
2427 
2428 	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2429 		goto err;
2430 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2431 		goto err;
2432 	if (RSA_sign(NID_md5_sha1, data, data_len, signature,
2433 	    &signature_len, pkey->pkey.rsa) <= 0 ) {
2434 		SSLerror(s, ERR_R_RSA_LIB);
2435 		goto err;
2436 	}
2437 
2438 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2439 		goto err;
2440 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2441 		goto err;
2442 	if (!CBB_flush(cert_verify))
2443 		goto err;
2444 
2445 	ret = 1;
2446  err:
2447 	free(signature);
2448 	return ret;
2449 }
2450 
2451 static int
2452 ssl3_send_client_verify_ec(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2453 {
2454 	CBB cbb_signature;
2455 	unsigned char data[EVP_MAX_MD_SIZE];
2456 	unsigned char *signature = NULL;
2457 	unsigned int signature_len;
2458 	int ret = 0;
2459 
2460 	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2461 		goto err;
2462 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2463 		goto err;
2464 	if (!ECDSA_sign(pkey->save_type, &data[MD5_DIGEST_LENGTH],
2465 	    SHA_DIGEST_LENGTH, signature, &signature_len, pkey->pkey.ec)) {
2466 		SSLerror(s, ERR_R_ECDSA_LIB);
2467 		goto err;
2468 	}
2469 
2470 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2471 		goto err;
2472 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2473 		goto err;
2474 	if (!CBB_flush(cert_verify))
2475 		goto err;
2476 
2477 	ret = 1;
2478  err:
2479 	free(signature);
2480 	return ret;
2481 }
2482 
2483 #ifndef OPENSSL_NO_GOST
2484 static int
2485 ssl3_send_client_verify_gost(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2486 {
2487 	CBB cbb_signature;
2488 	EVP_MD_CTX mctx;
2489 	EVP_PKEY_CTX *pctx;
2490 	const EVP_MD *md;
2491 	const unsigned char *hdata;
2492 	unsigned char *signature = NULL;
2493 	size_t signature_len;
2494 	size_t hdata_len;
2495 	int nid;
2496 	int ret = 0;
2497 
2498 	EVP_MD_CTX_init(&mctx);
2499 
2500 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2501 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2502 		goto err;
2503 	}
2504 	if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2505 	    (md = EVP_get_digestbynid(nid)) == NULL) {
2506 		SSLerror(s, ERR_R_EVP_LIB);
2507 		goto err;
2508 	}
2509 	if (!EVP_DigestSignInit(&mctx, &pctx, md, NULL, pkey)) {
2510 		SSLerror(s, ERR_R_EVP_LIB);
2511 		goto err;
2512 	}
2513 	if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2514 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2515 		SSLerror(s, ERR_R_EVP_LIB);
2516 		goto err;
2517 	}
2518 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2519 		SSLerror(s, ERR_R_EVP_LIB);
2520 		goto err;
2521 	}
2522 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2523 	    signature_len == 0) {
2524 		SSLerror(s, ERR_R_EVP_LIB);
2525 		goto err;
2526 	}
2527 	if ((signature = calloc(1, signature_len)) == NULL) {
2528 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2529 		goto err;
2530 	}
2531 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2532 		SSLerror(s, ERR_R_EVP_LIB);
2533 		goto err;
2534 	}
2535 
2536 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2537 		goto err;
2538 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2539 		goto err;
2540 	if (!CBB_flush(cert_verify))
2541 		goto err;
2542 
2543 	ret = 1;
2544  err:
2545 	EVP_MD_CTX_cleanup(&mctx);
2546 	free(signature);
2547 	return ret;
2548 }
2549 #endif
2550 
2551 int
2552 ssl3_send_client_verify(SSL *s)
2553 {
2554 	const struct ssl_sigalg *sigalg;
2555 	CBB cbb, cert_verify;
2556 	EVP_PKEY *pkey;
2557 
2558 	memset(&cbb, 0, sizeof(cbb));
2559 
2560 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2561 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2562 		    SSL3_MT_CERTIFICATE_VERIFY))
2563 			goto err;
2564 
2565 		pkey = s->cert->key->privatekey;
2566 		if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2567 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2568 			goto err;
2569 		}
2570 		S3I(s)->hs.our_sigalg = sigalg;
2571 
2572 		/*
2573 		 * For TLS v1.2 send signature algorithm and signature using
2574 		 * agreed digest and cached handshake records.
2575 		 */
2576 		if (SSL_USE_SIGALGS(s)) {
2577 			if (!ssl3_send_client_verify_sigalgs(s, pkey, sigalg,
2578 			    &cert_verify))
2579 				goto err;
2580 		} else if (pkey->type == EVP_PKEY_RSA) {
2581 			if (!ssl3_send_client_verify_rsa(s, pkey, &cert_verify))
2582 				goto err;
2583 		} else if (pkey->type == EVP_PKEY_EC) {
2584 			if (!ssl3_send_client_verify_ec(s, pkey, &cert_verify))
2585 				goto err;
2586 #ifndef OPENSSL_NO_GOST
2587 		} else if (pkey->type == NID_id_GostR3410_94 ||
2588 		    pkey->type == NID_id_GostR3410_2001) {
2589 			if (!ssl3_send_client_verify_gost(s, pkey, &cert_verify))
2590 				goto err;
2591 #endif
2592 		} else {
2593 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2594 			goto err;
2595 		}
2596 
2597 		tls1_transcript_free(s);
2598 
2599 		if (!ssl3_handshake_msg_finish(s, &cbb))
2600 			goto err;
2601 
2602 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2603 	}
2604 
2605 	return (ssl3_handshake_write(s));
2606 
2607  err:
2608 	CBB_cleanup(&cbb);
2609 
2610 	return (-1);
2611 }
2612 
2613 int
2614 ssl3_send_client_certificate(SSL *s)
2615 {
2616 	EVP_PKEY *pkey = NULL;
2617 	X509 *x509 = NULL;
2618 	CBB cbb, client_cert;
2619 	int i;
2620 
2621 	memset(&cbb, 0, sizeof(cbb));
2622 
2623 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2624 		if (s->cert->key->x509 == NULL ||
2625 		    s->cert->key->privatekey == NULL)
2626 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2627 		else
2628 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2629 	}
2630 
2631 	/* We need to get a client cert */
2632 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2633 		/*
2634 		 * If we get an error, we need to
2635 		 * ssl->internal->rwstate = SSL_X509_LOOKUP; return(-1);
2636 		 * We then get retried later.
2637 		 */
2638 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2639 		if (i < 0) {
2640 			s->internal->rwstate = SSL_X509_LOOKUP;
2641 			return (-1);
2642 		}
2643 		s->internal->rwstate = SSL_NOTHING;
2644 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2645 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2646 			if (!SSL_use_certificate(s, x509) ||
2647 			    !SSL_use_PrivateKey(s, pkey))
2648 				i = 0;
2649 		} else if (i == 1) {
2650 			i = 0;
2651 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2652 		}
2653 
2654 		X509_free(x509);
2655 		EVP_PKEY_free(pkey);
2656 		if (i == 0) {
2657 			S3I(s)->hs.tls12.cert_request = 2;
2658 
2659 			/* There is no client certificate to verify. */
2660 			tls1_transcript_free(s);
2661 		}
2662 
2663 		/* Ok, we have a cert */
2664 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2665 	}
2666 
2667 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2668 		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2669 		    SSL3_MT_CERTIFICATE))
2670 			goto err;
2671 		if (!ssl3_output_cert_chain(s, &client_cert,
2672 		    (S3I(s)->hs.tls12.cert_request == 2) ? NULL : s->cert->key))
2673 			goto err;
2674 		if (!ssl3_handshake_msg_finish(s, &cbb))
2675 			goto err;
2676 
2677 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2678 	}
2679 
2680 	/* SSL3_ST_CW_CERT_D */
2681 	return (ssl3_handshake_write(s));
2682 
2683  err:
2684 	CBB_cleanup(&cbb);
2685 
2686 	return (0);
2687 }
2688 
2689 #define has_bits(i,m)	(((i)&(m)) == (m))
2690 
2691 int
2692 ssl3_check_cert_and_algorithm(SSL *s)
2693 {
2694 	int		 i, idx;
2695 	long		 alg_k, alg_a;
2696 	EVP_PKEY	*pkey = NULL;
2697 	SESS_CERT	*sc;
2698 	DH		*dh;
2699 
2700 	alg_k = S3I(s)->hs.cipher->algorithm_mkey;
2701 	alg_a = S3I(s)->hs.cipher->algorithm_auth;
2702 
2703 	/* We don't have a certificate. */
2704 	if (alg_a & SSL_aNULL)
2705 		return (1);
2706 
2707 	sc = SSI(s)->sess_cert;
2708 	if (sc == NULL) {
2709 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2710 		goto err;
2711 	}
2712 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2713 
2714 	/* This is the passed certificate. */
2715 
2716 	idx = sc->peer_cert_type;
2717 	if (idx == SSL_PKEY_ECC) {
2718 		if (ssl_check_srvr_ecc_cert_and_alg(
2719 		    sc->peer_pkeys[idx].x509, s) == 0) {
2720 			/* check failed */
2721 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2722 			goto fatal_err;
2723 		} else {
2724 			return (1);
2725 		}
2726 	}
2727 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2728 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2729 	EVP_PKEY_free(pkey);
2730 
2731 	/* Check that we have a certificate if we require one. */
2732 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2733 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2734 		goto fatal_err;
2735 	}
2736 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2737 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2738 		goto fatal_err;
2739 	}
2740 	if ((alg_k & SSL_kDHE) &&
2741 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2742 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2743 		goto fatal_err;
2744 	}
2745 
2746 	return (1);
2747  fatal_err:
2748 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2749  err:
2750 	return (0);
2751 }
2752 
2753 /*
2754  * Check to see if handshake is full or resumed. Usually this is just a
2755  * case of checking to see if a cache hit has occurred. In the case of
2756  * session tickets we have to check the next message to be sure.
2757  */
2758 
2759 int
2760 ssl3_check_finished(SSL *s)
2761 {
2762 	int	ok;
2763 	long	n;
2764 
2765 	/* If we have no ticket it cannot be a resumed session. */
2766 	if (!s->session->tlsext_tick)
2767 		return (1);
2768 	/* this function is called when we really expect a Certificate
2769 	 * message, so permit appropriate message length */
2770 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2771 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2772 	if (!ok)
2773 		return ((int)n);
2774 
2775 	S3I(s)->hs.tls12.reuse_message = 1;
2776 	if ((S3I(s)->hs.tls12.message_type == SSL3_MT_FINISHED) ||
2777 	    (S3I(s)->hs.tls12.message_type == SSL3_MT_NEWSESSION_TICKET))
2778 		return (2);
2779 
2780 	return (1);
2781 }
2782 
2783 int
2784 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2785 {
2786 	int	i = 0;
2787 
2788 #ifndef OPENSSL_NO_ENGINE
2789 	if (s->ctx->internal->client_cert_engine) {
2790 		i = ENGINE_load_ssl_client_cert(
2791 		    s->ctx->internal->client_cert_engine, s,
2792 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2793 		if (i != 0)
2794 			return (i);
2795 	}
2796 #endif
2797 	if (s->ctx->internal->client_cert_cb)
2798 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2799 	return (i);
2800 }
2801