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