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