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