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