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