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