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