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