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