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