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