xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision c020cf82e0cc147236f01a8dca7052034cf9d30d)
1 /* $OpenBSD: ssl_clnt.c,v 1.69 2020/06/05 17:53:26 jsing Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150 
151 #include <limits.h>
152 #include <stdint.h>
153 #include <stdio.h>
154 
155 #include "ssl_locl.h"
156 
157 #include <openssl/bn.h>
158 #include <openssl/buffer.h>
159 #include <openssl/curve25519.h>
160 #include <openssl/dh.h>
161 #include <openssl/evp.h>
162 #include <openssl/md5.h>
163 #include <openssl/objects.h>
164 
165 #ifndef OPENSSL_NO_ENGINE
166 #include <openssl/engine.h>
167 #endif
168 #ifndef OPENSSL_NO_GOST
169 #include <openssl/gost.h>
170 #endif
171 
172 #include "bytestring.h"
173 #include "ssl_sigalgs.h"
174 #include "ssl_tlsext.h"
175 
176 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b);
177 
178 int
179 ssl3_connect(SSL *s)
180 {
181 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
182 	int ret = -1;
183 	int new_state, state, skip = 0;
184 
185 	ERR_clear_error();
186 	errno = 0;
187 
188 	if (s->internal->info_callback != NULL)
189 		cb = s->internal->info_callback;
190 	else if (s->ctx->internal->info_callback != NULL)
191 		cb = s->ctx->internal->info_callback;
192 
193 	s->internal->in_handshake++;
194 	if (!SSL_in_init(s) || SSL_in_before(s))
195 		SSL_clear(s);
196 
197 	for (;;) {
198 		state = S3I(s)->hs.state;
199 
200 		switch (S3I(s)->hs.state) {
201 		case SSL_ST_RENEGOTIATE:
202 			s->internal->renegotiate = 1;
203 			S3I(s)->hs.state = SSL_ST_CONNECT;
204 			s->ctx->internal->stats.sess_connect_renegotiate++;
205 			/* break */
206 		case SSL_ST_BEFORE:
207 		case SSL_ST_CONNECT:
208 		case SSL_ST_BEFORE|SSL_ST_CONNECT:
209 		case SSL_ST_OK|SSL_ST_CONNECT:
210 
211 			s->server = 0;
212 			if (cb != NULL)
213 				cb(s, SSL_CB_HANDSHAKE_START, 1);
214 
215 			if (SSL_IS_DTLS(s)) {
216 				if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
217 					SSLerror(s, ERR_R_INTERNAL_ERROR);
218 					ret = -1;
219 					goto end;
220 				}
221 			} else {
222 				if ((s->version & 0xff00) != 0x0300) {
223 					SSLerror(s, ERR_R_INTERNAL_ERROR);
224 					ret = -1;
225 					goto end;
226 				}
227 			}
228 
229 			/* s->version=SSL3_VERSION; */
230 			s->internal->type = SSL_ST_CONNECT;
231 
232 			if (!ssl3_setup_init_buffer(s)) {
233 				ret = -1;
234 				goto end;
235 			}
236 			if (!ssl3_setup_buffers(s)) {
237 				ret = -1;
238 				goto end;
239 			}
240 			if (!ssl_init_wbio_buffer(s, 0)) {
241 				ret = -1;
242 				goto end;
243 			}
244 
245 			/* don't push the buffering BIO quite yet */
246 
247 			if (!tls1_transcript_init(s)) {
248 				ret = -1;
249 				goto end;
250 			}
251 
252 			S3I(s)->hs.state = SSL3_ST_CW_CLNT_HELLO_A;
253 			s->ctx->internal->stats.sess_connect++;
254 			s->internal->init_num = 0;
255 
256 			if (SSL_IS_DTLS(s)) {
257 				/* mark client_random uninitialized */
258 				memset(s->s3->client_random, 0,
259 				    sizeof(s->s3->client_random));
260 				D1I(s)->send_cookie = 0;
261 				s->internal->hit = 0;
262 			}
263 			break;
264 
265 		case SSL3_ST_CW_CLNT_HELLO_A:
266 		case SSL3_ST_CW_CLNT_HELLO_B:
267 			s->internal->shutdown = 0;
268 
269 			if (SSL_IS_DTLS(s)) {
270 				/* every DTLS ClientHello resets Finished MAC */
271 				tls1_transcript_reset(s);
272 
273 				dtls1_start_timer(s);
274 			}
275 
276 			ret = ssl3_send_client_hello(s);
277 			if (ret <= 0)
278 				goto end;
279 
280 			if (SSL_IS_DTLS(s) && D1I(s)->send_cookie) {
281 				S3I(s)->hs.state = SSL3_ST_CW_FLUSH;
282 				S3I(s)->hs.next_state = SSL3_ST_CR_SRVR_HELLO_A;
283 			} else
284 				S3I(s)->hs.state = SSL3_ST_CR_SRVR_HELLO_A;
285 
286 			s->internal->init_num = 0;
287 
288 			/* turn on buffering for the next lot of output */
289 			if (s->bbio != s->wbio)
290 				s->wbio = BIO_push(s->bbio, s->wbio);
291 
292 			break;
293 
294 		case SSL3_ST_CR_SRVR_HELLO_A:
295 		case SSL3_ST_CR_SRVR_HELLO_B:
296 			ret = ssl3_get_server_hello(s);
297 			if (ret <= 0)
298 				goto end;
299 
300 			if (s->internal->hit) {
301 				S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
302 				if (!SSL_IS_DTLS(s)) {
303 					if (s->internal->tlsext_ticket_expected) {
304 						/* receive renewed session ticket */
305 						S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
306 					}
307 
308 					/* No client certificate verification. */
309 					tls1_transcript_free(s);
310 				}
311 			} else if (SSL_IS_DTLS(s)) {
312 				S3I(s)->hs.state = DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A;
313 			} else {
314 				S3I(s)->hs.state = SSL3_ST_CR_CERT_A;
315 			}
316 			s->internal->init_num = 0;
317 			break;
318 
319 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_A:
320 		case DTLS1_ST_CR_HELLO_VERIFY_REQUEST_B:
321 			ret = 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_downgrade_max_version(s, &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) > SSL3_SESSION_ID_SIZE) {
907 		al = SSL_AD_ILLEGAL_PARAMETER;
908 		SSLerror(s, SSL_R_SSL3_SESSION_ID_TOO_LONG);
909 		goto f_err;
910 	}
911 
912 	/* Cipher suite. */
913 	if (!CBS_get_u16(&cbs, &cipher_suite))
914 		goto truncated;
915 
916 	/*
917 	 * Check if we want to resume the session based on external
918 	 * pre-shared secret.
919 	 */
920 	if (s->internal->tls_session_secret_cb) {
921 		SSL_CIPHER *pref_cipher = NULL;
922 		s->session->master_key_length = sizeof(s->session->master_key);
923 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
924 		    &s->session->master_key_length, NULL, &pref_cipher,
925 		    s->internal->tls_session_secret_cb_arg)) {
926 			s->session->cipher = pref_cipher ? pref_cipher :
927 			    ssl3_get_cipher_by_value(cipher_suite);
928 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
929 		}
930 	}
931 
932 	if (s->session->session_id_length != 0 &&
933 	    CBS_mem_equal(&session_id, s->session->session_id,
934 		s->session->session_id_length)) {
935 		if (s->sid_ctx_length != s->session->sid_ctx_length ||
936 		    timingsafe_memcmp(s->session->sid_ctx,
937 		    s->sid_ctx, s->sid_ctx_length) != 0) {
938 			/* actually a client application bug */
939 			al = SSL_AD_ILLEGAL_PARAMETER;
940 			SSLerror(s, SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
941 			goto f_err;
942 		}
943 		s->s3->flags |= SSL3_FLAGS_CCS_OK;
944 		s->internal->hit = 1;
945 	} else {
946 		/* a miss or crap from the other end */
947 
948 		/* If we were trying for session-id reuse, make a new
949 		 * SSL_SESSION so we don't stuff up other people */
950 		s->internal->hit = 0;
951 		if (s->session->session_id_length > 0) {
952 			if (!ssl_get_new_session(s, 0)) {
953 				al = SSL_AD_INTERNAL_ERROR;
954 				goto f_err;
955 			}
956 		}
957 
958 		/*
959 		 * XXX - improve the handling for the case where there is a
960 		 * zero length session identifier.
961 		 */
962 		if (!CBS_write_bytes(&session_id, s->session->session_id,
963 		    sizeof(s->session->session_id), &outlen))
964 			goto err;
965 		s->session->session_id_length = outlen;
966 
967 		s->session->ssl_version = s->version;
968 	}
969 
970 	if ((cipher = ssl3_get_cipher_by_value(cipher_suite)) == NULL) {
971 		al = SSL_AD_ILLEGAL_PARAMETER;
972 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_RETURNED);
973 		goto f_err;
974 	}
975 
976 	/* TLS v1.2 only ciphersuites require v1.2 or later. */
977 	if ((cipher->algorithm_ssl & SSL_TLSV1_2) &&
978 	    (TLS1_get_version(s) < TLS1_2_VERSION)) {
979 		al = SSL_AD_ILLEGAL_PARAMETER;
980 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
981 		goto f_err;
982 	}
983 
984 	sk = ssl_get_ciphers_by_id(s);
985 	i = sk_SSL_CIPHER_find(sk, cipher);
986 	if (i < 0) {
987 		/* we did not say we would use this cipher */
988 		al = SSL_AD_ILLEGAL_PARAMETER;
989 		SSLerror(s, SSL_R_WRONG_CIPHER_RETURNED);
990 		goto f_err;
991 	}
992 
993 	/*
994 	 * Depending on the session caching (internal/external), the cipher
995 	 * and/or cipher_id values may not be set. Make sure that
996 	 * cipher_id is set and use it for comparison.
997 	 */
998 	if (s->session->cipher)
999 		s->session->cipher_id = s->session->cipher->id;
1000 	if (s->internal->hit && (s->session->cipher_id != cipher->id)) {
1001 		al = SSL_AD_ILLEGAL_PARAMETER;
1002 		SSLerror(s, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1003 		goto f_err;
1004 	}
1005 	S3I(s)->hs.new_cipher = cipher;
1006 
1007 	if (!tls1_transcript_hash_init(s))
1008 		goto err;
1009 
1010 	/*
1011 	 * Don't digest cached records if no sigalgs: we may need them for
1012 	 * client authentication.
1013 	 */
1014 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1015 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)))
1016 		tls1_transcript_free(s);
1017 
1018 	if (!CBS_get_u8(&cbs, &compression_method))
1019 		goto truncated;
1020 
1021 	if (compression_method != 0) {
1022 		al = SSL_AD_ILLEGAL_PARAMETER;
1023 		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1024 		goto f_err;
1025 	}
1026 
1027 	if (!tlsext_client_parse(s, &cbs, &al, SSL_TLSEXT_MSG_SH)) {
1028 		SSLerror(s, SSL_R_PARSE_TLSEXT);
1029 		goto f_err;
1030 	}
1031 
1032 	/*
1033 	 * Determine if we need to see RI. Strictly speaking if we want to
1034 	 * avoid an attack we should *always* see RI even on initial server
1035 	 * hello because the client doesn't see any renegotiation during an
1036 	 * attack. However this would mean we could not connect to any server
1037 	 * which doesn't support RI so for the immediate future tolerate RI
1038 	 * absence on initial connect only.
1039 	 */
1040 	if (!S3I(s)->renegotiate_seen &&
1041 	    !(s->internal->options & SSL_OP_LEGACY_SERVER_CONNECT)) {
1042 		al = SSL_AD_HANDSHAKE_FAILURE;
1043 		SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
1044 		goto f_err;
1045 	}
1046 
1047 	if (ssl_check_serverhello_tlsext(s) <= 0) {
1048 		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
1049 		goto err;
1050 	}
1051 
1052 	return (1);
1053 
1054 truncated:
1055 	/* wrong packet length */
1056 	al = SSL_AD_DECODE_ERROR;
1057 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1058 f_err:
1059 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1060 err:
1061 	return (-1);
1062 }
1063 
1064 int
1065 ssl3_get_server_certificate(SSL *s)
1066 {
1067 	int			 al, i, ok, ret = -1;
1068 	long			 n;
1069 	CBS			 cbs, cert_list;
1070 	X509			*x = NULL;
1071 	const unsigned char	*q;
1072 	STACK_OF(X509)		*sk = NULL;
1073 	SESS_CERT		*sc;
1074 	EVP_PKEY		*pkey = NULL;
1075 
1076 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
1077 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
1078 	if (!ok)
1079 		return ((int)n);
1080 
1081 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1082 		S3I(s)->tmp.reuse_message = 1;
1083 		return (1);
1084 	}
1085 
1086 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
1087 		al = SSL_AD_UNEXPECTED_MESSAGE;
1088 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1089 		goto f_err;
1090 	}
1091 
1092 
1093 	if ((sk = sk_X509_new_null()) == NULL) {
1094 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1095 		goto err;
1096 	}
1097 
1098 	if (n < 0)
1099 		goto truncated;
1100 
1101 	CBS_init(&cbs, s->internal->init_msg, n);
1102 	if (CBS_len(&cbs) < 3)
1103 		goto truncated;
1104 
1105 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
1106 	    CBS_len(&cbs) != 0) {
1107 		al = SSL_AD_DECODE_ERROR;
1108 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1109 		goto f_err;
1110 	}
1111 
1112 	while (CBS_len(&cert_list) > 0) {
1113 		CBS cert;
1114 
1115 		if (CBS_len(&cert_list) < 3)
1116 			goto truncated;
1117 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1118 			al = SSL_AD_DECODE_ERROR;
1119 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1120 			goto f_err;
1121 		}
1122 
1123 		q = CBS_data(&cert);
1124 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1125 		if (x == NULL) {
1126 			al = SSL_AD_BAD_CERTIFICATE;
1127 			SSLerror(s, ERR_R_ASN1_LIB);
1128 			goto f_err;
1129 		}
1130 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1131 			al = SSL_AD_DECODE_ERROR;
1132 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1133 			goto f_err;
1134 		}
1135 		if (!sk_X509_push(sk, x)) {
1136 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1137 			goto err;
1138 		}
1139 		x = NULL;
1140 	}
1141 
1142 	i = ssl_verify_cert_chain(s, sk);
1143 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1144 		al = ssl_verify_alarm_type(s->verify_result);
1145 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1146 		goto f_err;
1147 
1148 	}
1149 	ERR_clear_error(); /* but we keep s->verify_result */
1150 
1151 	sc = ssl_sess_cert_new();
1152 	if (sc == NULL)
1153 		goto err;
1154 	ssl_sess_cert_free(SSI(s)->sess_cert);
1155 	SSI(s)->sess_cert = sc;
1156 
1157 	sc->cert_chain = sk;
1158 	/*
1159 	 * Inconsistency alert: cert_chain does include the peer's
1160 	 * certificate, which we don't include in s3_srvr.c
1161 	 */
1162 	x = sk_X509_value(sk, 0);
1163 	sk = NULL;
1164 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1165 
1166 	pkey = X509_get_pubkey(x);
1167 
1168 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1169 		x = NULL;
1170 		al = SSL3_AL_FATAL;
1171 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1172 		goto f_err;
1173 	}
1174 
1175 	i = ssl_cert_type(x, pkey);
1176 	if (i < 0) {
1177 		x = NULL;
1178 		al = SSL3_AL_FATAL;
1179 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1180 		goto f_err;
1181 	}
1182 
1183 	sc->peer_cert_type = i;
1184 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1185 	/*
1186 	 * Why would the following ever happen?
1187 	 * We just created sc a couple of lines ago.
1188 	 */
1189 	X509_free(sc->peer_pkeys[i].x509);
1190 	sc->peer_pkeys[i].x509 = x;
1191 	sc->peer_key = &(sc->peer_pkeys[i]);
1192 
1193 	X509_free(s->session->peer);
1194 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1195 	s->session->peer = x;
1196 	s->session->verify_result = s->verify_result;
1197 
1198 	x = NULL;
1199 	ret = 1;
1200 
1201 	if (0) {
1202 truncated:
1203 		/* wrong packet length */
1204 		al = SSL_AD_DECODE_ERROR;
1205 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1206 f_err:
1207 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1208 	}
1209 err:
1210 	EVP_PKEY_free(pkey);
1211 	X509_free(x);
1212 	sk_X509_pop_free(sk, X509_free);
1213 
1214 	return (ret);
1215 }
1216 
1217 static int
1218 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1219 {
1220 	CBS dhp, dhg, dhpk;
1221 	BN_CTX *bn_ctx = NULL;
1222 	SESS_CERT *sc = NULL;
1223 	DH *dh = NULL;
1224 	long alg_a;
1225 	int al;
1226 
1227 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1228 	sc = SSI(s)->sess_cert;
1229 
1230 	if ((dh = DH_new()) == NULL) {
1231 		SSLerror(s, ERR_R_DH_LIB);
1232 		goto err;
1233 	}
1234 
1235 	if (!CBS_get_u16_length_prefixed(cbs, &dhp))
1236 		goto truncated;
1237 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1238 		SSLerror(s, ERR_R_BN_LIB);
1239 		goto err;
1240 	}
1241 
1242 	if (!CBS_get_u16_length_prefixed(cbs, &dhg))
1243 		goto truncated;
1244 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1245 		SSLerror(s, ERR_R_BN_LIB);
1246 		goto err;
1247 	}
1248 
1249 	if (!CBS_get_u16_length_prefixed(cbs, &dhpk))
1250 		goto truncated;
1251 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1252 	    NULL)) == NULL) {
1253 		SSLerror(s, ERR_R_BN_LIB);
1254 		goto err;
1255 	}
1256 
1257 	/*
1258 	 * Check the strength of the DH key just constructed.
1259 	 * Discard keys weaker than 1024 bits.
1260 	 */
1261 	if (DH_size(dh) < 1024 / 8) {
1262 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1263 		goto err;
1264 	}
1265 
1266 	if (alg_a & SSL_aRSA)
1267 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1268 	else
1269 		/* XXX - Anonymous DH, so no certificate or pkey. */
1270 		*pkey = NULL;
1271 
1272 	sc->peer_dh_tmp = dh;
1273 
1274 	return (1);
1275 
1276  truncated:
1277 	al = SSL_AD_DECODE_ERROR;
1278 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1279 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1280 
1281  err:
1282 	DH_free(dh);
1283 	BN_CTX_free(bn_ctx);
1284 
1285 	return (-1);
1286 }
1287 
1288 static int
1289 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1290 {
1291 	EC_KEY *ecdh = NULL;
1292 	int ret = -1;
1293 
1294 	/* Extract the server's ephemeral ECDH public key. */
1295 	if ((ecdh = EC_KEY_new()) == NULL) {
1296 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1297 		goto err;
1298 	}
1299 	if (!ssl_kex_peer_public_ecdhe_ecp(ecdh, nid, public)) {
1300 		SSLerror(s, SSL_R_BAD_ECPOINT);
1301 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1302 		goto err;
1303 	}
1304 
1305 	sc->peer_nid = nid;
1306 	sc->peer_ecdh_tmp = ecdh;
1307 	ecdh = NULL;
1308 
1309 	ret = 1;
1310 
1311  err:
1312 	EC_KEY_free(ecdh);
1313 
1314 	return (ret);
1315 }
1316 
1317 static int
1318 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1319 {
1320 	size_t outlen;
1321 
1322 	if (nid != NID_X25519) {
1323 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1324 		goto err;
1325 	}
1326 
1327 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1328 		SSLerror(s, SSL_R_BAD_ECPOINT);
1329 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1330 		goto err;
1331 	}
1332 
1333 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1334 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1335 		goto err;
1336 	}
1337 
1338 	return (1);
1339 
1340  err:
1341 	return (-1);
1342 }
1343 
1344 static int
1345 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, CBS *cbs)
1346 {
1347 	CBS public;
1348 	uint8_t curve_type;
1349 	uint16_t curve_id;
1350 	SESS_CERT *sc;
1351 	long alg_a;
1352 	int nid;
1353 	int al;
1354 
1355 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1356 	sc = SSI(s)->sess_cert;
1357 
1358 	/* Only named curves are supported. */
1359 	if (!CBS_get_u8(cbs, &curve_type) ||
1360 	    curve_type != NAMED_CURVE_TYPE ||
1361 	    !CBS_get_u16(cbs, &curve_id)) {
1362 		al = SSL_AD_DECODE_ERROR;
1363 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1364 		goto f_err;
1365 	}
1366 
1367 	/*
1368 	 * Check that the curve is one of our preferences - if it is not,
1369 	 * the server has sent us an invalid curve.
1370 	 */
1371 	if (tls1_check_curve(s, curve_id) != 1) {
1372 		al = SSL_AD_DECODE_ERROR;
1373 		SSLerror(s, SSL_R_WRONG_CURVE);
1374 		goto f_err;
1375 	}
1376 
1377 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1378 		al = SSL_AD_INTERNAL_ERROR;
1379 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1380 		goto f_err;
1381 	}
1382 
1383 	if (!CBS_get_u8_length_prefixed(cbs, &public))
1384 		goto truncated;
1385 
1386 	if (nid == NID_X25519) {
1387 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1388 			goto err;
1389 	} else {
1390 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1391 			goto err;
1392 	}
1393 
1394 	/*
1395 	 * The ECC/TLS specification does not mention the use of DSA to sign
1396 	 * ECParameters in the server key exchange message. We do support RSA
1397 	 * and ECDSA.
1398 	 */
1399 	if (alg_a & SSL_aRSA)
1400 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA].x509);
1401 	else if (alg_a & SSL_aECDSA)
1402 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1403 	else
1404 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1405 		*pkey = NULL;
1406 
1407 	return (1);
1408 
1409  truncated:
1410 	al = SSL_AD_DECODE_ERROR;
1411 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1412 
1413  f_err:
1414 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1415 
1416  err:
1417 	return (-1);
1418 }
1419 
1420 int
1421 ssl3_get_server_key_exchange(SSL *s)
1422 {
1423 	CBS cbs, signature;
1424 	const EVP_MD *md = NULL;
1425 	EVP_PKEY *pkey = NULL;
1426 	EVP_MD_CTX md_ctx;
1427 	const unsigned char *param;
1428 	long n, alg_k, alg_a;
1429 	int al, ok;
1430 	size_t param_len;
1431 
1432 	EVP_MD_CTX_init(&md_ctx);
1433 
1434 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1435 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1436 
1437 	/*
1438 	 * Use same message size as in ssl3_get_certificate_request()
1439 	 * as ServerKeyExchange message may be skipped.
1440 	 */
1441 	n = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1442 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1443 	if (!ok)
1444 		return ((int)n);
1445 
1446 	if (n < 0)
1447 		goto err;
1448 
1449 	CBS_init(&cbs, s->internal->init_msg, n);
1450 
1451 	if (S3I(s)->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1452 		/*
1453 		 * Do not skip server key exchange if this cipher suite uses
1454 		 * ephemeral keys.
1455 		 */
1456 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1457 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1458 			al = SSL_AD_UNEXPECTED_MESSAGE;
1459 			goto f_err;
1460 		}
1461 
1462 		S3I(s)->tmp.reuse_message = 1;
1463 		EVP_MD_CTX_cleanup(&md_ctx);
1464 		return (1);
1465 	}
1466 
1467 	if (SSI(s)->sess_cert != NULL) {
1468 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1469 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1470 
1471 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1472 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1473 
1474 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1475 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1476 	} else {
1477 		SSI(s)->sess_cert = ssl_sess_cert_new();
1478 		if (SSI(s)->sess_cert == NULL)
1479 			goto err;
1480 	}
1481 
1482 	param = CBS_data(&cbs);
1483 	param_len = CBS_len(&cbs);
1484 
1485 	if (alg_k & SSL_kDHE) {
1486 		if (ssl3_get_server_kex_dhe(s, &pkey, &cbs) != 1)
1487 			goto err;
1488 	} else if (alg_k & SSL_kECDHE) {
1489 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &cbs) != 1)
1490 			goto err;
1491 	} else if (alg_k != 0) {
1492 		al = SSL_AD_UNEXPECTED_MESSAGE;
1493 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1494 			goto f_err;
1495 	}
1496 
1497 	param_len -= CBS_len(&cbs);
1498 
1499 	/* if it was signed, check the signature */
1500 	if (pkey != NULL) {
1501 		EVP_PKEY_CTX *pctx;
1502 		const struct ssl_sigalg *sigalg;
1503 
1504 		if (SSL_USE_SIGALGS(s)) {
1505 			uint16_t sigalg_value;
1506 
1507 			if (!CBS_get_u16(&cbs, &sigalg_value))
1508 				goto truncated;
1509 			if ((sigalg = ssl_sigalg(sigalg_value, tls12_sigalgs,
1510 			    tls12_sigalgs_len)) == NULL) {
1511 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
1512 				al = SSL_AD_DECODE_ERROR;
1513 				goto f_err;
1514 			}
1515 			if ((md = sigalg->md()) == NULL) {
1516 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
1517 				al = SSL_AD_DECODE_ERROR;
1518 				goto f_err;
1519 			}
1520 			if (!ssl_sigalg_pkey_ok(sigalg, pkey, 0)) {
1521 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
1522 				al = SSL_AD_DECODE_ERROR;
1523 				goto f_err;
1524 			}
1525 		} else if (pkey->type == EVP_PKEY_RSA) {
1526 			sigalg = ssl_sigalg_lookup(SIGALG_RSA_PKCS1_MD5_SHA1);
1527 		} else if (pkey->type == EVP_PKEY_EC) {
1528 			sigalg = ssl_sigalg_lookup(SIGALG_ECDSA_SHA1);
1529 		} else {
1530 			SSLerror(s, SSL_R_UNKNOWN_PKEY_TYPE);
1531 			al = SSL_AD_DECODE_ERROR;
1532 			goto f_err;
1533 		}
1534 		md = sigalg->md();
1535 
1536 		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1537 			goto truncated;
1538 		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1539 			al = SSL_AD_DECODE_ERROR;
1540 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1541 			goto f_err;
1542 		}
1543 
1544 		if (!EVP_DigestVerifyInit(&md_ctx, &pctx, md, NULL, pkey))
1545 			goto err;
1546 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
1547 		    SSL3_RANDOM_SIZE))
1548 			goto err;
1549 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1550 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1551 		    RSA_PKCS1_PSS_PADDING) ||
1552 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1553 			goto err;
1554 		if (!EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
1555 		    SSL3_RANDOM_SIZE))
1556 			goto err;
1557 		if (!EVP_DigestVerifyUpdate(&md_ctx, param, param_len))
1558 			goto err;
1559 		if (EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
1560 		    CBS_len(&signature)) <= 0) {
1561 			al = SSL_AD_DECRYPT_ERROR;
1562 			SSLerror(s, SSL_R_BAD_SIGNATURE);
1563 			goto f_err;
1564 		}
1565 	} else {
1566 		/* aNULL does not need public keys. */
1567 		if (!(alg_a & SSL_aNULL)) {
1568 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1569 			goto err;
1570 		}
1571 	}
1572 
1573 	if (CBS_len(&cbs) != 0) {
1574 		al = SSL_AD_DECODE_ERROR;
1575 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1576 		goto f_err;
1577 	}
1578 
1579 	EVP_PKEY_free(pkey);
1580 	EVP_MD_CTX_cleanup(&md_ctx);
1581 
1582 	return (1);
1583 
1584  truncated:
1585 	al = SSL_AD_DECODE_ERROR;
1586 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1587 
1588  f_err:
1589 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1590 
1591  err:
1592 	EVP_PKEY_free(pkey);
1593 	EVP_MD_CTX_cleanup(&md_ctx);
1594 
1595 	return (-1);
1596 }
1597 
1598 int
1599 ssl3_get_certificate_request(SSL *s)
1600 {
1601 	int			 ok, ret = 0;
1602 	long		 	 n;
1603 	uint8_t			 ctype_num;
1604 	CBS			 cert_request, ctypes, rdn_list;
1605 	X509_NAME		*xn = NULL;
1606 	const unsigned char	*q;
1607 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1608 
1609 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1610 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1611 	if (!ok)
1612 		return ((int)n);
1613 
1614 	S3I(s)->tmp.cert_req = 0;
1615 
1616 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_DONE) {
1617 		S3I(s)->tmp.reuse_message = 1;
1618 		/*
1619 		 * If we get here we don't need any cached handshake records
1620 		 * as we wont be doing client auth.
1621 		 */
1622 		tls1_transcript_free(s);
1623 		return (1);
1624 	}
1625 
1626 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1627 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1628 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1629 		goto err;
1630 	}
1631 
1632 	/* TLS does not like anon-DH with client cert */
1633 	if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
1634 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1635 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1636 		goto err;
1637 	}
1638 
1639 	if (n < 0)
1640 		goto truncated;
1641 	CBS_init(&cert_request, s->internal->init_msg, n);
1642 
1643 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1644 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1645 		goto err;
1646 	}
1647 
1648 	/* get the certificate types */
1649 	if (!CBS_get_u8(&cert_request, &ctype_num))
1650 		goto truncated;
1651 
1652 	if (ctype_num > SSL3_CT_NUMBER)
1653 		ctype_num = SSL3_CT_NUMBER;
1654 	if (!CBS_get_bytes(&cert_request, &ctypes, ctype_num) ||
1655 	    !CBS_write_bytes(&ctypes, (uint8_t *)S3I(s)->tmp.ctype,
1656 	    sizeof(S3I(s)->tmp.ctype), NULL)) {
1657 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1658 		goto err;
1659 	}
1660 
1661 	if (SSL_USE_SIGALGS(s)) {
1662 		CBS sigalgs;
1663 
1664 		if (CBS_len(&cert_request) < 2) {
1665 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1666 			goto err;
1667 		}
1668 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1669 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1670 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1671 			goto err;
1672 		}
1673 		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1674 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1675 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1676 			goto err;
1677 		}
1678 		if (!CBS_stow(&sigalgs, &S3I(s)->hs.sigalgs,
1679 		    &S3I(s)->hs.sigalgs_len))
1680 			goto err;
1681 	}
1682 
1683 	/* get the CA RDNs */
1684 	if (CBS_len(&cert_request) < 2) {
1685 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1686 		goto err;
1687 	}
1688 
1689 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1690 	    CBS_len(&cert_request) != 0) {
1691 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1692 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1693 		goto err;
1694 	}
1695 
1696 	while (CBS_len(&rdn_list) > 0) {
1697 		CBS rdn;
1698 
1699 		if (CBS_len(&rdn_list) < 2) {
1700 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1701 			goto err;
1702 		}
1703 
1704 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1705 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1706 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1707 			goto err;
1708 		}
1709 
1710 		q = CBS_data(&rdn);
1711 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1712 			ssl3_send_alert(s, SSL3_AL_FATAL,
1713 			    SSL_AD_DECODE_ERROR);
1714 			SSLerror(s, ERR_R_ASN1_LIB);
1715 			goto err;
1716 		}
1717 
1718 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1719 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1720 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1721 			goto err;
1722 		}
1723 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1724 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1725 			goto err;
1726 		}
1727 		xn = NULL;	/* avoid free in err block */
1728 	}
1729 
1730 	/* we should setup a certificate to return.... */
1731 	S3I(s)->tmp.cert_req = 1;
1732 	S3I(s)->tmp.ctype_num = ctype_num;
1733 	sk_X509_NAME_pop_free(S3I(s)->tmp.ca_names, X509_NAME_free);
1734 	S3I(s)->tmp.ca_names = ca_sk;
1735 	ca_sk = NULL;
1736 
1737 	ret = 1;
1738 	if (0) {
1739 truncated:
1740 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1741 	}
1742 err:
1743 	X509_NAME_free(xn);
1744 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1745 	return (ret);
1746 }
1747 
1748 static int
1749 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1750 {
1751 	return (X509_NAME_cmp(*a, *b));
1752 }
1753 
1754 int
1755 ssl3_get_new_session_ticket(SSL *s)
1756 {
1757 	int			 ok, al, ret = 0;
1758 	uint32_t		 lifetime_hint;
1759 	long			 n;
1760 	CBS			 cbs, session_ticket;
1761 
1762 	n = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1763 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1764 	if (!ok)
1765 		return ((int)n);
1766 
1767 	if (S3I(s)->tmp.message_type == SSL3_MT_FINISHED) {
1768 		S3I(s)->tmp.reuse_message = 1;
1769 		return (1);
1770 	}
1771 	if (S3I(s)->tmp.message_type != SSL3_MT_NEWSESSION_TICKET) {
1772 		al = SSL_AD_UNEXPECTED_MESSAGE;
1773 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1774 		goto f_err;
1775 	}
1776 
1777 	if (n < 0) {
1778 		al = SSL_AD_DECODE_ERROR;
1779 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1780 		goto f_err;
1781 	}
1782 
1783 	CBS_init(&cbs, s->internal->init_msg, n);
1784 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1785 #if UINT32_MAX > LONG_MAX
1786 	    lifetime_hint > LONG_MAX ||
1787 #endif
1788 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1789 	    CBS_len(&cbs) != 0) {
1790 		al = SSL_AD_DECODE_ERROR;
1791 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1792 		goto f_err;
1793 	}
1794 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1795 
1796 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1797 	    &s->session->tlsext_ticklen)) {
1798 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1799 		goto err;
1800 	}
1801 
1802 	/*
1803 	 * There are two ways to detect a resumed ticket sesion.
1804 	 * One is to set an appropriate session ID and then the server
1805 	 * must return a match in ServerHello. This allows the normal
1806 	 * client session ID matching to work and we know much
1807 	 * earlier that the ticket has been accepted.
1808 	 *
1809 	 * The other way is to set zero length session ID when the
1810 	 * ticket is presented and rely on the handshake to determine
1811 	 * session resumption.
1812 	 *
1813 	 * We choose the former approach because this fits in with
1814 	 * assumptions elsewhere in OpenSSL. The session ID is set
1815 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1816 	 * ticket.
1817 	 */
1818 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1819 	    s->session->session_id, &s->session->session_id_length,
1820 	    EVP_sha256(), NULL);
1821 	ret = 1;
1822 	return (ret);
1823 f_err:
1824 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1825 err:
1826 	return (-1);
1827 }
1828 
1829 int
1830 ssl3_get_cert_status(SSL *s)
1831 {
1832 	CBS			 cert_status, response;
1833 	int			 ok, al;
1834 	long			 n;
1835 	uint8_t			 status_type;
1836 
1837 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1838 	    SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS,
1839 	    16384, &ok);
1840 	if (!ok)
1841 		return ((int)n);
1842 
1843 	if (n < 0) {
1844 		/* need at least status type + length */
1845 		al = SSL_AD_DECODE_ERROR;
1846 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1847 		goto f_err;
1848 	}
1849 
1850 	CBS_init(&cert_status, s->internal->init_msg, n);
1851 	if (!CBS_get_u8(&cert_status, &status_type) ||
1852 	    CBS_len(&cert_status) < 3) {
1853 		/* need at least status type + length */
1854 		al = SSL_AD_DECODE_ERROR;
1855 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1856 		goto f_err;
1857 	}
1858 
1859 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1860 		al = SSL_AD_DECODE_ERROR;
1861 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1862 		goto f_err;
1863 	}
1864 
1865 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1866 	    CBS_len(&cert_status) != 0) {
1867 		al = SSL_AD_DECODE_ERROR;
1868 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1869 		goto f_err;
1870 	}
1871 
1872 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1873 	    &s->internal->tlsext_ocsp_resp_len)) {
1874  		al = SSL_AD_INTERNAL_ERROR;
1875  		SSLerror(s, ERR_R_MALLOC_FAILURE);
1876  		goto f_err;
1877  	}
1878 
1879 	if (s->ctx->internal->tlsext_status_cb) {
1880 		int ret;
1881 		ret = s->ctx->internal->tlsext_status_cb(s,
1882 		    s->ctx->internal->tlsext_status_arg);
1883 		if (ret == 0) {
1884 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1885 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1886 			goto f_err;
1887 		}
1888 		if (ret < 0) {
1889 			al = SSL_AD_INTERNAL_ERROR;
1890 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1891 			goto f_err;
1892 		}
1893 	}
1894 	return (1);
1895 f_err:
1896 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1897 	return (-1);
1898 }
1899 
1900 int
1901 ssl3_get_server_done(SSL *s)
1902 {
1903 	int	ok, ret = 0;
1904 	long	n;
1905 
1906 	n = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1907 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1908 	    30, /* should be very small, like 0 :-) */ &ok);
1909 	if (!ok)
1910 		return ((int)n);
1911 
1912 	if (n > 0) {
1913 		/* should contain no data */
1914 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1915 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1916 		return (-1);
1917 	}
1918 	ret = 1;
1919 	return (ret);
1920 }
1921 
1922 static int
1923 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1924 {
1925 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1926 	unsigned char *enc_pms = NULL;
1927 	EVP_PKEY *pkey = NULL;
1928 	int ret = -1;
1929 	int enc_len;
1930 	CBB epms;
1931 
1932 	/*
1933 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1934 	 */
1935 
1936 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA].x509);
1937 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1938 	    pkey->pkey.rsa == NULL) {
1939 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1940 		goto err;
1941 	}
1942 
1943 	pms[0] = s->client_version >> 8;
1944 	pms[1] = s->client_version & 0xff;
1945 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1946 
1947 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1948 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1949 		goto err;
1950 	}
1951 
1952 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1953 	    RSA_PKCS1_PADDING);
1954 	if (enc_len <= 0) {
1955 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1956 		goto err;
1957 	}
1958 
1959 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
1960 		goto err;
1961 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
1962 		goto err;
1963 	if (!CBB_flush(cbb))
1964 		goto err;
1965 
1966 	s->session->master_key_length =
1967 	    tls1_generate_master_secret(s,
1968 		s->session->master_key, pms, sizeof(pms));
1969 
1970 	ret = 1;
1971 
1972 err:
1973 	explicit_bzero(pms, sizeof(pms));
1974 	EVP_PKEY_free(pkey);
1975 	free(enc_pms);
1976 
1977 	return (ret);
1978 }
1979 
1980 static int
1981 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1982 {
1983 	DH *dh_srvr = NULL, *dh_clnt = NULL;
1984 	unsigned char *key = NULL;
1985 	int key_size = 0, key_len;
1986 	unsigned char *data;
1987 	int ret = -1;
1988 	CBB dh_Yc;
1989 
1990 	/* Ensure that we have an ephemeral key for DHE. */
1991 	if (sess_cert->peer_dh_tmp == NULL) {
1992 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1993 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1994 		goto err;
1995 	}
1996 	dh_srvr = sess_cert->peer_dh_tmp;
1997 
1998 	/* Generate a new random key. */
1999 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2000 		SSLerror(s, ERR_R_DH_LIB);
2001 		goto err;
2002 	}
2003 	if (!DH_generate_key(dh_clnt)) {
2004 		SSLerror(s, ERR_R_DH_LIB);
2005 		goto err;
2006 	}
2007 	if ((key_size = DH_size(dh_clnt)) <= 0) {
2008 		SSLerror(s, ERR_R_DH_LIB);
2009 		goto err;
2010 	}
2011 	if ((key = malloc(key_size)) == NULL) {
2012 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2013 		goto err;
2014 	}
2015 	if ((key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt)) <= 0) {
2016 		SSLerror(s, ERR_R_DH_LIB);
2017 		goto err;
2018 	}
2019 
2020 	/* Generate master key from the result. */
2021 	s->session->master_key_length =
2022 	    tls1_generate_master_secret(s,
2023 		s->session->master_key, key, key_len);
2024 
2025 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2026 		goto err;
2027 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2028 		goto err;
2029 	BN_bn2bin(dh_clnt->pub_key, data);
2030 	if (!CBB_flush(cbb))
2031 		goto err;
2032 
2033 	ret = 1;
2034 
2035 err:
2036 	DH_free(dh_clnt);
2037 	freezero(key, key_size);
2038 
2039 	return (ret);
2040 }
2041 
2042 static int
2043 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2044 {
2045 	EC_KEY *ecdh = NULL;
2046 	uint8_t *key = NULL;
2047 	size_t key_len = 0;
2048 	int ret = -1;
2049 	CBB ecpoint;
2050 
2051 	if ((ecdh = EC_KEY_new()) == NULL) {
2052 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2053 		goto err;
2054 	}
2055 
2056 	if (!ssl_kex_generate_ecdhe_ecp(ecdh, sc->peer_nid))
2057 		goto err;
2058 
2059 	/* Encode our public key. */
2060 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2061 		goto err;
2062 	if (!ssl_kex_public_ecdhe_ecp(ecdh, &ecpoint))
2063 		goto err;
2064 	if (!CBB_flush(cbb))
2065 		goto err;
2066 
2067 	if (!ssl_kex_derive_ecdhe_ecp(ecdh, sc->peer_ecdh_tmp, &key, &key_len))
2068 		goto err;
2069 	s->session->master_key_length = tls1_generate_master_secret(s,
2070 		s->session->master_key, key, key_len);
2071 
2072 	ret = 1;
2073 
2074  err:
2075 	freezero(key, key_len);
2076 	EC_KEY_free(ecdh);
2077 
2078 	return (ret);
2079 }
2080 
2081 static int
2082 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2083 {
2084 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2085 	int ret = -1;
2086 	CBB ecpoint;
2087 
2088 	/* Generate X25519 key pair and derive shared key. */
2089 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2090 		goto err;
2091 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2092 		goto err;
2093 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2094 		goto err;
2095 	X25519_keypair(public_key, private_key);
2096 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2097 		goto err;
2098 
2099 	/* Serialize the public key. */
2100 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2101 		goto err;
2102 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2103 		goto err;
2104 	if (!CBB_flush(cbb))
2105 		goto err;
2106 
2107 	/* Generate master key from the result. */
2108 	s->session->master_key_length =
2109 	    tls1_generate_master_secret(s,
2110 		s->session->master_key, shared_key, X25519_KEY_LENGTH);
2111 
2112 	ret = 1;
2113 
2114  err:
2115 	free(public_key);
2116 	freezero(private_key, X25519_KEY_LENGTH);
2117 	freezero(shared_key, X25519_KEY_LENGTH);
2118 
2119 	return (ret);
2120 }
2121 
2122 static int
2123 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2124 {
2125 	if (sc->peer_x25519_tmp != NULL) {
2126 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2127 			goto err;
2128 	} else if (sc->peer_ecdh_tmp != NULL) {
2129 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2130 			goto err;
2131 	} else {
2132 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2133 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2134 		goto err;
2135 	}
2136 
2137 	return (1);
2138 
2139  err:
2140 	return (-1);
2141 }
2142 
2143 static int
2144 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2145 {
2146 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2147 	EVP_PKEY *pub_key = NULL;
2148 	EVP_PKEY_CTX *pkey_ctx;
2149 	X509 *peer_cert;
2150 	size_t msglen;
2151 	unsigned int md_len;
2152 	EVP_MD_CTX *ukm_hash;
2153 	int ret = -1;
2154 	int nid;
2155 	CBB gostblob;
2156 
2157 	/* Get server sertificate PKEY and create ctx from it */
2158 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2159 	if (peer_cert == NULL) {
2160 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2161 		goto err;
2162 	}
2163 
2164 	pub_key = X509_get_pubkey(peer_cert);
2165 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2166 
2167 	/*
2168 	 * If we have send a certificate, and certificate key parameters match
2169 	 * those of server certificate, use certificate key for key exchange.
2170 	 * Otherwise, generate ephemeral key pair.
2171 	 */
2172 	EVP_PKEY_encrypt_init(pkey_ctx);
2173 
2174 	/* Generate session key. */
2175 	arc4random_buf(premaster_secret, 32);
2176 
2177 	/*
2178 	 * If we have client certificate, use its secret as peer key.
2179 	 */
2180 	if (S3I(s)->tmp.cert_req && s->cert->key->privatekey) {
2181 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2182 		    s->cert->key->privatekey) <=0) {
2183 			/*
2184 			 * If there was an error - just ignore it.
2185 			 * Ephemeral key would be used.
2186 			 */
2187 			ERR_clear_error();
2188 		}
2189 	}
2190 
2191 	/*
2192 	 * Compute shared IV and store it in algorithm-specific context data.
2193 	 */
2194 	ukm_hash = EVP_MD_CTX_new();
2195 	if (ukm_hash == NULL) {
2196 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2197 		goto err;
2198 	}
2199 
2200 	if (ssl_get_algorithm2(s) & SSL_HANDSHAKE_MAC_GOST94)
2201 		nid = NID_id_GostR3411_94;
2202 	else
2203 		nid = NID_id_tc26_gost3411_2012_256;
2204 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2205 		goto err;
2206 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2207 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2208 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2209 	EVP_MD_CTX_free(ukm_hash);
2210 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2211 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2212 		SSLerror(s, SSL_R_LIBRARY_BUG);
2213 		goto err;
2214 	}
2215 
2216 	/*
2217 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2218 	 */
2219 	msglen = 255;
2220 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2221 	    32) < 0) {
2222 		SSLerror(s, SSL_R_LIBRARY_BUG);
2223 		goto err;
2224 	}
2225 
2226 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2227 		goto err;
2228 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2229 		goto err;
2230 	if (!CBB_flush(cbb))
2231 		goto err;
2232 
2233 	/* Check if pubkey from client certificate was used. */
2234 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2235 	    NULL) > 0) {
2236 		/* Set flag "skip certificate verify". */
2237 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2238 	}
2239 	EVP_PKEY_CTX_free(pkey_ctx);
2240 	s->session->master_key_length =
2241 	    tls1_generate_master_secret(s,
2242 		s->session->master_key, premaster_secret, 32);
2243 
2244 	ret = 1;
2245 
2246  err:
2247 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2248 	EVP_PKEY_free(pub_key);
2249 
2250 	return (ret);
2251 }
2252 
2253 int
2254 ssl3_send_client_key_exchange(SSL *s)
2255 {
2256 	SESS_CERT *sess_cert;
2257 	unsigned long alg_k;
2258 	CBB cbb, kex;
2259 
2260 	memset(&cbb, 0, sizeof(cbb));
2261 
2262 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2263 		alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2264 
2265 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2266 			ssl3_send_alert(s, SSL3_AL_FATAL,
2267 			    SSL_AD_UNEXPECTED_MESSAGE);
2268 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2269 			goto err;
2270 		}
2271 
2272 		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
2273 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2274 			goto err;
2275 
2276 		if (alg_k & SSL_kRSA) {
2277 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2278 				goto err;
2279 		} else if (alg_k & SSL_kDHE) {
2280 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2281 				goto err;
2282 		} else if (alg_k & SSL_kECDHE) {
2283 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2284 				goto err;
2285 		} else if (alg_k & SSL_kGOST) {
2286 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2287 				goto err;
2288 		} else {
2289 			ssl3_send_alert(s, SSL3_AL_FATAL,
2290 			    SSL_AD_HANDSHAKE_FAILURE);
2291 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2292 			goto err;
2293 		}
2294 
2295 		if (!ssl3_handshake_msg_finish(s, &cbb))
2296 			goto err;
2297 
2298 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2299 	}
2300 
2301 	/* SSL3_ST_CW_KEY_EXCH_B */
2302 	return (ssl3_handshake_write(s));
2303 
2304 err:
2305 	CBB_cleanup(&cbb);
2306 
2307 	return (-1);
2308 }
2309 
2310 static int
2311 ssl3_send_client_verify_sigalgs(SSL *s, CBB *cert_verify)
2312 {
2313 	const struct ssl_sigalg *sigalg;
2314 	CBB cbb_signature;
2315 	EVP_PKEY_CTX *pctx = NULL;
2316 	EVP_PKEY *pkey;
2317 	EVP_MD_CTX mctx;
2318 	const EVP_MD *md;
2319 	const unsigned char *hdata;
2320 	unsigned char *signature = NULL;
2321 	size_t signature_len, hdata_len;
2322 	int ret = 0;
2323 
2324 	EVP_MD_CTX_init(&mctx);
2325 
2326 	pkey = s->cert->key->privatekey;
2327 	if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2328 		SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2329 		goto err;
2330 	}
2331 	if ((md = sigalg->md()) == NULL) {
2332 		SSLerror(s, SSL_R_UNKNOWN_DIGEST);
2333 		goto err;
2334 	}
2335 
2336 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2337 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2338 		goto err;
2339 	}
2340 	if (!EVP_DigestSignInit(&mctx, &pctx, md, NULL, pkey)) {
2341 		SSLerror(s, ERR_R_EVP_LIB);
2342 		goto err;
2343 	}
2344 	if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2345 	    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2346 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2347 		SSLerror(s, ERR_R_EVP_LIB);
2348 		goto err;
2349 	}
2350 	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2351 	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
2352 	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2353 		SSLerror(s, ERR_R_EVP_LIB);
2354 		goto err;
2355 	}
2356 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2357 		SSLerror(s, ERR_R_EVP_LIB);
2358 		goto err;
2359 	}
2360 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2361 	    signature_len == 0) {
2362 		SSLerror(s, ERR_R_EVP_LIB);
2363 		goto err;
2364 	}
2365 	if ((signature = calloc(1, signature_len)) == NULL) {
2366 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2367 		goto err;
2368 	}
2369 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2370 		SSLerror(s, ERR_R_EVP_LIB);
2371 		goto err;
2372 	}
2373 
2374 	if (!CBB_add_u16(cert_verify, sigalg->value))
2375 		goto err;
2376 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2377 		goto err;
2378 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2379 		goto err;
2380 	if (!CBB_flush(cert_verify))
2381 		goto err;
2382 
2383 	ret = 1;
2384 
2385  err:
2386 	EVP_MD_CTX_cleanup(&mctx);
2387 	free(signature);
2388 	return ret;
2389 }
2390 
2391 static int
2392 ssl3_send_client_verify_rsa(SSL *s, CBB *cert_verify)
2393 {
2394 	CBB cbb_signature;
2395 	EVP_PKEY *pkey;
2396 	unsigned char data[EVP_MAX_MD_SIZE];
2397 	unsigned char *signature = NULL;
2398 	unsigned int signature_len;
2399 	size_t data_len;
2400 	int ret = 0;
2401 
2402 	pkey = s->cert->key->privatekey;
2403 
2404 	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2405 		goto err;
2406 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2407 		goto err;
2408 	if (RSA_sign(NID_md5_sha1, data, data_len, signature,
2409 	    &signature_len, pkey->pkey.rsa) <= 0 ) {
2410 		SSLerror(s, ERR_R_RSA_LIB);
2411 		goto err;
2412 	}
2413 
2414 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2415 		goto err;
2416 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2417 		goto err;
2418 	if (!CBB_flush(cert_verify))
2419 		goto err;
2420 
2421 	ret = 1;
2422  err:
2423 	free(signature);
2424 	return ret;
2425 }
2426 
2427 static int
2428 ssl3_send_client_verify_ec(SSL *s, CBB *cert_verify)
2429 {
2430 	CBB cbb_signature;
2431 	EVP_PKEY *pkey;
2432 	unsigned char data[EVP_MAX_MD_SIZE];
2433 	unsigned char *signature = NULL;
2434 	unsigned int signature_len;
2435 	int ret = 0;
2436 
2437 	pkey = s->cert->key->privatekey;
2438 
2439 	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2440 		goto err;
2441 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2442 		goto err;
2443 	if (!ECDSA_sign(pkey->save_type, &data[MD5_DIGEST_LENGTH],
2444 	    SHA_DIGEST_LENGTH, signature, &signature_len, pkey->pkey.ec)) {
2445 		SSLerror(s, ERR_R_ECDSA_LIB);
2446 		goto err;
2447 	}
2448 
2449 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2450 		goto err;
2451 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2452 		goto err;
2453 	if (!CBB_flush(cert_verify))
2454 		goto err;
2455 
2456 	ret = 1;
2457  err:
2458 	free(signature);
2459 	return ret;
2460 }
2461 
2462 #ifndef OPENSSL_NO_GOST
2463 static int
2464 ssl3_send_client_verify_gost(SSL *s, CBB *cert_verify)
2465 {
2466 	CBB cbb_signature;
2467 	EVP_MD_CTX mctx;
2468 	EVP_PKEY_CTX *pctx;
2469 	EVP_PKEY *pkey;
2470 	const EVP_MD *md;
2471 	const unsigned char *hdata;
2472 	unsigned char *signature = NULL;
2473 	size_t signature_len;
2474 	size_t hdata_len;
2475 	int nid;
2476 	int ret = 0;
2477 
2478 	EVP_MD_CTX_init(&mctx);
2479 
2480 	pkey = s->cert->key->privatekey;
2481 
2482 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2483 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2484 		goto err;
2485 	}
2486 	if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2487 	    (md = EVP_get_digestbynid(nid)) == NULL) {
2488 		SSLerror(s, ERR_R_EVP_LIB);
2489 		goto err;
2490 	}
2491 	if (!EVP_DigestSignInit(&mctx, &pctx, md, NULL, pkey)) {
2492 		SSLerror(s, ERR_R_EVP_LIB);
2493 		goto err;
2494 	}
2495 	if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2496 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2497 		SSLerror(s, ERR_R_EVP_LIB);
2498 		goto err;
2499 	}
2500 	if (!EVP_DigestSignUpdate(&mctx, hdata, hdata_len)) {
2501 		SSLerror(s, ERR_R_EVP_LIB);
2502 		goto err;
2503 	}
2504 	if (!EVP_DigestSignFinal(&mctx, NULL, &signature_len) ||
2505 	    signature_len == 0) {
2506 		SSLerror(s, ERR_R_EVP_LIB);
2507 		goto err;
2508 	}
2509 	if ((signature = calloc(1, signature_len)) == NULL) {
2510 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2511 		goto err;
2512 	}
2513 	if (!EVP_DigestSignFinal(&mctx, signature, &signature_len)) {
2514 		SSLerror(s, ERR_R_EVP_LIB);
2515 		goto err;
2516 	}
2517 
2518 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2519 		goto err;
2520 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2521 		goto err;
2522 	if (!CBB_flush(cert_verify))
2523 		goto err;
2524 
2525 	ret = 1;
2526  err:
2527 	EVP_MD_CTX_cleanup(&mctx);
2528 	free(signature);
2529 	return ret;
2530 }
2531 #endif
2532 
2533 int
2534 ssl3_send_client_verify(SSL *s)
2535 {
2536 	CBB cbb, cert_verify;
2537 	EVP_PKEY *pkey;
2538 
2539 	memset(&cbb, 0, sizeof(cbb));
2540 
2541 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2542 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2543 		    SSL3_MT_CERTIFICATE_VERIFY))
2544 			goto err;
2545 
2546 		pkey = s->cert->key->privatekey;
2547 
2548 		/*
2549 		 * For TLS v1.2 send signature algorithm and signature
2550 		 * using agreed digest and cached handshake records.
2551 		 */
2552 		if (SSL_USE_SIGALGS(s)) {
2553 			if (!ssl3_send_client_verify_sigalgs(s, &cert_verify))
2554 				goto err;
2555 		} else if (pkey->type == EVP_PKEY_RSA) {
2556 			if (!ssl3_send_client_verify_rsa(s, &cert_verify))
2557 				goto err;
2558 		} else if (pkey->type == EVP_PKEY_EC) {
2559 			if (!ssl3_send_client_verify_ec(s, &cert_verify))
2560 				goto err;
2561 #ifndef OPENSSL_NO_GOST
2562 		} else if (pkey->type == NID_id_GostR3410_94 ||
2563 		    pkey->type == NID_id_GostR3410_2001) {
2564 			if (!ssl3_send_client_verify_gost(s, &cert_verify))
2565 				goto err;
2566 #endif
2567 		} else {
2568 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2569 			goto err;
2570 		}
2571 
2572 		tls1_transcript_free(s);
2573 
2574 		if (!ssl3_handshake_msg_finish(s, &cbb))
2575 			goto err;
2576 
2577 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2578 	}
2579 
2580 	return (ssl3_handshake_write(s));
2581 
2582  err:
2583 	CBB_cleanup(&cbb);
2584 
2585 	return (-1);
2586 }
2587 
2588 int
2589 ssl3_send_client_certificate(SSL *s)
2590 {
2591 	EVP_PKEY *pkey = NULL;
2592 	X509 *x509 = NULL;
2593 	CBB cbb, client_cert;
2594 	int i;
2595 
2596 	memset(&cbb, 0, sizeof(cbb));
2597 
2598 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2599 		if (s->cert->key->x509 == NULL ||
2600 		    s->cert->key->privatekey == NULL)
2601 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2602 		else
2603 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2604 	}
2605 
2606 	/* We need to get a client cert */
2607 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2608 		/*
2609 		 * If we get an error, we need to
2610 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2611 		 * We then get retied later
2612 		 */
2613 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2614 		if (i < 0) {
2615 			s->internal->rwstate = SSL_X509_LOOKUP;
2616 			return (-1);
2617 		}
2618 		s->internal->rwstate = SSL_NOTHING;
2619 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2620 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2621 			if (!SSL_use_certificate(s, x509) ||
2622 			    !SSL_use_PrivateKey(s, pkey))
2623 				i = 0;
2624 		} else if (i == 1) {
2625 			i = 0;
2626 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2627 		}
2628 
2629 		X509_free(x509);
2630 		EVP_PKEY_free(pkey);
2631 		if (i == 0) {
2632 			S3I(s)->tmp.cert_req = 2;
2633 
2634 			/* There is no client certificate to verify. */
2635 			tls1_transcript_free(s);
2636 		}
2637 
2638 		/* Ok, we have a cert */
2639 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2640 	}
2641 
2642 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2643 		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2644 		    SSL3_MT_CERTIFICATE))
2645 			goto err;
2646 		if (!ssl3_output_cert_chain(s, &client_cert,
2647 		    (S3I(s)->tmp.cert_req == 2) ? NULL : s->cert->key))
2648 			goto err;
2649 		if (!ssl3_handshake_msg_finish(s, &cbb))
2650 			goto err;
2651 
2652 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2653 	}
2654 
2655 	/* SSL3_ST_CW_CERT_D */
2656 	return (ssl3_handshake_write(s));
2657 
2658  err:
2659 	CBB_cleanup(&cbb);
2660 
2661 	return (0);
2662 }
2663 
2664 #define has_bits(i,m)	(((i)&(m)) == (m))
2665 
2666 int
2667 ssl3_check_cert_and_algorithm(SSL *s)
2668 {
2669 	int		 i, idx;
2670 	long		 alg_k, alg_a;
2671 	EVP_PKEY	*pkey = NULL;
2672 	SESS_CERT	*sc;
2673 	DH		*dh;
2674 
2675 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2676 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2677 
2678 	/* We don't have a certificate. */
2679 	if (alg_a & SSL_aNULL)
2680 		return (1);
2681 
2682 	sc = SSI(s)->sess_cert;
2683 	if (sc == NULL) {
2684 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2685 		goto err;
2686 	}
2687 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2688 
2689 	/* This is the passed certificate. */
2690 
2691 	idx = sc->peer_cert_type;
2692 	if (idx == SSL_PKEY_ECC) {
2693 		if (ssl_check_srvr_ecc_cert_and_alg(
2694 		    sc->peer_pkeys[idx].x509, s) == 0) {
2695 			/* check failed */
2696 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2697 			goto f_err;
2698 		} else {
2699 			return (1);
2700 		}
2701 	}
2702 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2703 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2704 	EVP_PKEY_free(pkey);
2705 
2706 	/* Check that we have a certificate if we require one. */
2707 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2708 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2709 		goto f_err;
2710 	}
2711 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2712 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2713 		goto f_err;
2714 	}
2715 	if ((alg_k & SSL_kDHE) &&
2716 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2717 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2718 		goto f_err;
2719 	}
2720 
2721 	return (1);
2722 f_err:
2723 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2724 err:
2725 	return (0);
2726 }
2727 
2728 /*
2729  * Check to see if handshake is full or resumed. Usually this is just a
2730  * case of checking to see if a cache hit has occurred. In the case of
2731  * session tickets we have to check the next message to be sure.
2732  */
2733 
2734 int
2735 ssl3_check_finished(SSL *s)
2736 {
2737 	int	ok;
2738 	long	n;
2739 
2740 	/* If we have no ticket it cannot be a resumed session. */
2741 	if (!s->session->tlsext_tick)
2742 		return (1);
2743 	/* this function is called when we really expect a Certificate
2744 	 * message, so permit appropriate message length */
2745 	n = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2746 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2747 	if (!ok)
2748 		return ((int)n);
2749 
2750 	S3I(s)->tmp.reuse_message = 1;
2751 	if ((S3I(s)->tmp.message_type == SSL3_MT_FINISHED) ||
2752 	    (S3I(s)->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2753 		return (2);
2754 
2755 	return (1);
2756 }
2757 
2758 int
2759 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2760 {
2761 	int	i = 0;
2762 
2763 #ifndef OPENSSL_NO_ENGINE
2764 	if (s->ctx->internal->client_cert_engine) {
2765 		i = ENGINE_load_ssl_client_cert(
2766 		    s->ctx->internal->client_cert_engine, s,
2767 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2768 		if (i != 0)
2769 			return (i);
2770 	}
2771 #endif
2772 	if (s->ctx->internal->client_cert_cb)
2773 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2774 	return (i);
2775 }
2776