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