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