xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision 3374c67d44f9b75b98444cbf63020f777792342e)
1 /* $OpenBSD: ssl_clnt.c,v 1.158 2022/12/26 07:31:44 jmc 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 	CBS cbs, signature;
1303 	EVP_MD_CTX *md_ctx;
1304 	const unsigned char *param;
1305 	size_t param_len;
1306 	long alg_k, alg_a;
1307 	int al, ret;
1308 
1309 	alg_k = s->s3->hs.cipher->algorithm_mkey;
1310 	alg_a = s->s3->hs.cipher->algorithm_auth;
1311 
1312 	/*
1313 	 * Use same message size as in ssl3_get_certificate_request()
1314 	 * as ServerKeyExchange message may be skipped.
1315 	 */
1316 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1317 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list)) <= 0)
1318 		return ret;
1319 
1320 	if ((md_ctx = EVP_MD_CTX_new()) == NULL)
1321 		goto err;
1322 
1323 	if (s->init_num < 0)
1324 		goto err;
1325 
1326 	CBS_init(&cbs, s->init_msg, s->init_num);
1327 
1328 	if (s->s3->hs.tls12.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1329 		/*
1330 		 * Do not skip server key exchange if this cipher suite uses
1331 		 * ephemeral keys.
1332 		 */
1333 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1334 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1335 			al = SSL_AD_UNEXPECTED_MESSAGE;
1336 			goto fatal_err;
1337 		}
1338 
1339 		s->s3->hs.tls12.reuse_message = 1;
1340 		EVP_MD_CTX_free(md_ctx);
1341 		return (1);
1342 	}
1343 
1344 	param = CBS_data(&cbs);
1345 	param_len = CBS_len(&cbs);
1346 
1347 	if (alg_k & SSL_kDHE) {
1348 		if (!ssl3_get_server_kex_dhe(s, &cbs))
1349 			goto err;
1350 	} else if (alg_k & SSL_kECDHE) {
1351 		if (!ssl3_get_server_kex_ecdhe(s, &cbs))
1352 			goto err;
1353 	} else if (alg_k != 0) {
1354 		al = SSL_AD_UNEXPECTED_MESSAGE;
1355 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1356 		goto fatal_err;
1357 	}
1358 
1359 	param_len -= CBS_len(&cbs);
1360 
1361 	/* if it was signed, check the signature */
1362 	if ((alg_a & SSL_aNULL) == 0) {
1363 		uint16_t sigalg_value = SIGALG_NONE;
1364 		const struct ssl_sigalg *sigalg;
1365 		EVP_PKEY_CTX *pctx;
1366 		EVP_PKEY *pkey = NULL;
1367 
1368 		if ((alg_a & SSL_aRSA) != 0 &&
1369 		    s->session->peer_cert_type == SSL_PKEY_RSA) {
1370 			pkey = X509_get0_pubkey(s->session->peer_cert);
1371 		} else if ((alg_a & SSL_aECDSA) != 0 &&
1372 		    s->session->peer_cert_type == SSL_PKEY_ECC) {
1373 			pkey = X509_get0_pubkey(s->session->peer_cert);
1374 		}
1375 		if (pkey == NULL) {
1376 			al = SSL_AD_ILLEGAL_PARAMETER;
1377 			SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1378 			goto fatal_err;
1379 		}
1380 
1381 		if (SSL_USE_SIGALGS(s)) {
1382 			if (!CBS_get_u16(&cbs, &sigalg_value))
1383 				goto decode_err;
1384 		}
1385 		if (!CBS_get_u16_length_prefixed(&cbs, &signature))
1386 			goto decode_err;
1387 		if (CBS_len(&signature) > EVP_PKEY_size(pkey)) {
1388 			al = SSL_AD_DECODE_ERROR;
1389 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1390 			goto fatal_err;
1391 		}
1392 
1393 		if ((sigalg = ssl_sigalg_for_peer(s, pkey,
1394 		    sigalg_value)) == NULL) {
1395 			al = SSL_AD_DECODE_ERROR;
1396 			goto fatal_err;
1397 		}
1398 		s->s3->hs.peer_sigalg = sigalg;
1399 
1400 		if (!EVP_DigestVerifyInit(md_ctx, &pctx, sigalg->md(),
1401 		    NULL, pkey))
1402 			goto err;
1403 		if (!EVP_DigestVerifyUpdate(md_ctx, s->s3->client_random,
1404 		    SSL3_RANDOM_SIZE))
1405 			goto err;
1406 		if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
1407 		    (!EVP_PKEY_CTX_set_rsa_padding(pctx,
1408 		    RSA_PKCS1_PSS_PADDING) ||
1409 		    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)))
1410 			goto err;
1411 		if (!EVP_DigestVerifyUpdate(md_ctx, s->s3->server_random,
1412 		    SSL3_RANDOM_SIZE))
1413 			goto err;
1414 		if (!EVP_DigestVerifyUpdate(md_ctx, param, param_len))
1415 			goto err;
1416 		if (EVP_DigestVerifyFinal(md_ctx, CBS_data(&signature),
1417 		    CBS_len(&signature)) <= 0) {
1418 			al = SSL_AD_DECRYPT_ERROR;
1419 			SSLerror(s, SSL_R_BAD_SIGNATURE);
1420 			goto fatal_err;
1421 		}
1422 	}
1423 
1424 	if (CBS_len(&cbs) != 0) {
1425 		al = SSL_AD_DECODE_ERROR;
1426 		SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1427 		goto fatal_err;
1428 	}
1429 
1430 	EVP_MD_CTX_free(md_ctx);
1431 
1432 	return (1);
1433 
1434  decode_err:
1435 	al = SSL_AD_DECODE_ERROR;
1436 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1437 
1438  fatal_err:
1439 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1440 
1441  err:
1442 	EVP_MD_CTX_free(md_ctx);
1443 
1444 	return (-1);
1445 }
1446 
1447 static int
1448 ssl3_get_certificate_request(SSL *s)
1449 {
1450 	CBS cert_request, cert_types, rdn_list;
1451 	X509_NAME *xn = NULL;
1452 	const unsigned char *q;
1453 	STACK_OF(X509_NAME) *ca_sk = NULL;
1454 	int ret;
1455 
1456 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1457 	    SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list)) <= 0)
1458 		return ret;
1459 
1460 	ret = 0;
1461 
1462 	s->s3->hs.tls12.cert_request = 0;
1463 
1464 	if (s->s3->hs.tls12.message_type == SSL3_MT_SERVER_DONE) {
1465 		s->s3->hs.tls12.reuse_message = 1;
1466 		/*
1467 		 * If we get here we don't need any cached handshake records
1468 		 * as we wont be doing client auth.
1469 		 */
1470 		tls1_transcript_free(s);
1471 		return (1);
1472 	}
1473 
1474 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1475 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1476 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1477 		goto err;
1478 	}
1479 
1480 	/* TLS does not like anon-DH with client cert */
1481 	if (s->s3->hs.cipher->algorithm_auth & SSL_aNULL) {
1482 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1483 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1484 		goto err;
1485 	}
1486 
1487 	if (s->init_num < 0)
1488 		goto decode_err;
1489 	CBS_init(&cert_request, s->init_msg, s->init_num);
1490 
1491 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1492 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1493 		goto err;
1494 	}
1495 
1496 	if (!CBS_get_u8_length_prefixed(&cert_request, &cert_types))
1497 		goto decode_err;
1498 
1499 	if (SSL_USE_SIGALGS(s)) {
1500 		CBS sigalgs;
1501 
1502 		if (CBS_len(&cert_request) < 2) {
1503 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1504 			goto err;
1505 		}
1506 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1507 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1508 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1509 			goto err;
1510 		}
1511 		if (CBS_len(&sigalgs) % 2 != 0 || CBS_len(&sigalgs) > 64) {
1512 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1513 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1514 			goto err;
1515 		}
1516 		if (!CBS_stow(&sigalgs, &s->s3->hs.sigalgs,
1517 		    &s->s3->hs.sigalgs_len))
1518 			goto err;
1519 	}
1520 
1521 	/* get the CA RDNs */
1522 	if (CBS_len(&cert_request) < 2) {
1523 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1524 		goto err;
1525 	}
1526 
1527 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1528 	    CBS_len(&cert_request) != 0) {
1529 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1530 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1531 		goto err;
1532 	}
1533 
1534 	while (CBS_len(&rdn_list) > 0) {
1535 		CBS rdn;
1536 
1537 		if (CBS_len(&rdn_list) < 2) {
1538 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1539 			goto err;
1540 		}
1541 
1542 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1543 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1544 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1545 			goto err;
1546 		}
1547 
1548 		q = CBS_data(&rdn);
1549 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1550 			ssl3_send_alert(s, SSL3_AL_FATAL,
1551 			    SSL_AD_DECODE_ERROR);
1552 			SSLerror(s, ERR_R_ASN1_LIB);
1553 			goto err;
1554 		}
1555 
1556 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1557 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1558 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1559 			goto err;
1560 		}
1561 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1562 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1563 			goto err;
1564 		}
1565 		xn = NULL;	/* avoid free in err block */
1566 	}
1567 
1568 	/* we should setup a certificate to return.... */
1569 	s->s3->hs.tls12.cert_request = 1;
1570 	sk_X509_NAME_pop_free(s->s3->hs.tls12.ca_names, X509_NAME_free);
1571 	s->s3->hs.tls12.ca_names = ca_sk;
1572 	ca_sk = NULL;
1573 
1574 	ret = 1;
1575 	if (0) {
1576  decode_err:
1577 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1578 	}
1579  err:
1580 	X509_NAME_free(xn);
1581 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1582 	return (ret);
1583 }
1584 
1585 static int
1586 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1587 {
1588 	return (X509_NAME_cmp(*a, *b));
1589 }
1590 
1591 static int
1592 ssl3_get_new_session_ticket(SSL *s)
1593 {
1594 	uint32_t lifetime_hint;
1595 	CBS cbs, session_ticket;
1596 	unsigned int session_id_length = 0;
1597 	int al, ret;
1598 
1599 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1600 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384)) <= 0)
1601 		return ret;
1602 
1603 	if (s->s3->hs.tls12.message_type == SSL3_MT_FINISHED) {
1604 		s->s3->hs.tls12.reuse_message = 1;
1605 		return (1);
1606 	}
1607 	if (s->s3->hs.tls12.message_type != SSL3_MT_NEWSESSION_TICKET) {
1608 		al = SSL_AD_UNEXPECTED_MESSAGE;
1609 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1610 		goto fatal_err;
1611 	}
1612 
1613 	if (s->init_num < 0) {
1614 		al = SSL_AD_DECODE_ERROR;
1615 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1616 		goto fatal_err;
1617 	}
1618 
1619 	CBS_init(&cbs, s->init_msg, s->init_num);
1620 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1621 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1622 	    CBS_len(&cbs) != 0) {
1623 		al = SSL_AD_DECODE_ERROR;
1624 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1625 		goto fatal_err;
1626 	}
1627 	s->session->tlsext_tick_lifetime_hint = lifetime_hint;
1628 
1629 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1630 	    &s->session->tlsext_ticklen)) {
1631 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1632 		goto err;
1633 	}
1634 
1635 	/*
1636 	 * There are two ways to detect a resumed ticket session.
1637 	 * One is to set an appropriate session ID and then the server
1638 	 * must return a match in ServerHello. This allows the normal
1639 	 * client session ID matching to work and we know much
1640 	 * earlier that the ticket has been accepted.
1641 	 *
1642 	 * The other way is to set zero length session ID when the
1643 	 * ticket is presented and rely on the handshake to determine
1644 	 * session resumption.
1645 	 *
1646 	 * We choose the former approach because this fits in with
1647 	 * assumptions elsewhere in OpenSSL. The session ID is set
1648 	 * to the SHA256 hash of the ticket.
1649 	 */
1650 	/* XXX - ensure this doesn't overflow session_id if hash is changed. */
1651 	if (!EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1652 	    s->session->session_id, &session_id_length, EVP_sha256(), NULL)) {
1653 		al = SSL_AD_INTERNAL_ERROR;
1654 		SSLerror(s, ERR_R_EVP_LIB);
1655 		goto fatal_err;
1656 	}
1657 	s->session->session_id_length = session_id_length;
1658 
1659 	return (1);
1660 
1661  fatal_err:
1662 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1663  err:
1664 	return (-1);
1665 }
1666 
1667 static int
1668 ssl3_get_cert_status(SSL *s)
1669 {
1670 	CBS cert_status, response;
1671 	uint8_t	status_type;
1672 	int al, ret;
1673 
1674 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1675 	    SSL3_ST_CR_CERT_STATUS_B, -1, 16384)) <= 0)
1676 		return ret;
1677 
1678 	if (s->s3->hs.tls12.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
1679 		/*
1680 		 * Tell the callback the server did not send us an OSCP
1681 		 * response, and has decided to head directly to key exchange.
1682 		 */
1683 		if (s->ctx->tlsext_status_cb) {
1684 			free(s->tlsext_ocsp_resp);
1685 			s->tlsext_ocsp_resp = NULL;
1686 			s->tlsext_ocsp_resp_len = 0;
1687 
1688 			ret = s->ctx->tlsext_status_cb(s,
1689 			    s->ctx->tlsext_status_arg);
1690 			if (ret == 0) {
1691 				al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1692 				SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1693 				goto fatal_err;
1694 			}
1695 			if (ret < 0) {
1696 				al = SSL_AD_INTERNAL_ERROR;
1697 				SSLerror(s, ERR_R_MALLOC_FAILURE);
1698 				goto fatal_err;
1699 			}
1700 		}
1701 		s->s3->hs.tls12.reuse_message = 1;
1702 		return (1);
1703 	}
1704 
1705 	if (s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE &&
1706 	    s->s3->hs.tls12.message_type != SSL3_MT_CERTIFICATE_STATUS) {
1707 		al = SSL_AD_UNEXPECTED_MESSAGE;
1708 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1709 		goto fatal_err;
1710 	}
1711 
1712 	if (s->init_num < 0) {
1713 		/* need at least status type + length */
1714 		al = SSL_AD_DECODE_ERROR;
1715 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1716 		goto fatal_err;
1717 	}
1718 
1719 	CBS_init(&cert_status, s->init_msg, s->init_num);
1720 	if (!CBS_get_u8(&cert_status, &status_type) ||
1721 	    CBS_len(&cert_status) < 3) {
1722 		/* need at least status type + length */
1723 		al = SSL_AD_DECODE_ERROR;
1724 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1725 		goto fatal_err;
1726 	}
1727 
1728 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1729 		al = SSL_AD_DECODE_ERROR;
1730 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1731 		goto fatal_err;
1732 	}
1733 
1734 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1735 	    CBS_len(&cert_status) != 0) {
1736 		al = SSL_AD_DECODE_ERROR;
1737 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1738 		goto fatal_err;
1739 	}
1740 
1741 	if (!CBS_stow(&response, &s->tlsext_ocsp_resp,
1742 	    &s->tlsext_ocsp_resp_len)) {
1743 		al = SSL_AD_INTERNAL_ERROR;
1744 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1745 		goto fatal_err;
1746 	}
1747 
1748 	if (s->ctx->tlsext_status_cb) {
1749 		ret = s->ctx->tlsext_status_cb(s,
1750 		    s->ctx->tlsext_status_arg);
1751 		if (ret == 0) {
1752 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1753 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1754 			goto fatal_err;
1755 		}
1756 		if (ret < 0) {
1757 			al = SSL_AD_INTERNAL_ERROR;
1758 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1759 			goto fatal_err;
1760 		}
1761 	}
1762 	return (1);
1763  fatal_err:
1764 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1765 	return (-1);
1766 }
1767 
1768 static int
1769 ssl3_get_server_done(SSL *s)
1770 {
1771 	int ret;
1772 
1773 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1774 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1775 	    30 /* should be very small, like 0 :-) */)) <= 0)
1776 		return ret;
1777 
1778 	if (s->init_num != 0) {
1779 		/* should contain no data */
1780 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1781 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1782 		return -1;
1783 	}
1784 
1785 	return 1;
1786 }
1787 
1788 static int
1789 ssl3_send_client_kex_rsa(SSL *s, CBB *cbb)
1790 {
1791 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1792 	unsigned char *enc_pms = NULL;
1793 	uint16_t max_legacy_version;
1794 	EVP_PKEY *pkey;
1795 	RSA *rsa;
1796 	int ret = 0;
1797 	int enc_len;
1798 	CBB epms;
1799 
1800 	/*
1801 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1802 	 */
1803 
1804 	pkey = X509_get0_pubkey(s->session->peer_cert);
1805 	if (pkey == NULL || (rsa = EVP_PKEY_get0_RSA(pkey)) == NULL) {
1806 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1807 		goto err;
1808 	}
1809 
1810 	/*
1811 	 * Our maximum legacy protocol version - while RFC 5246 section 7.4.7.1
1812 	 * says "The latest (newest) version supported by the client", if we're
1813 	 * doing RSA key exchange then we have to presume that we're talking to
1814 	 * a server that does not understand the supported versions extension
1815 	 * and therefore our maximum version is that sent in the ClientHello.
1816 	 */
1817 	if (!ssl_max_legacy_version(s, &max_legacy_version))
1818 		goto err;
1819 	pms[0] = max_legacy_version >> 8;
1820 	pms[1] = max_legacy_version & 0xff;
1821 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1822 
1823 	if ((enc_pms = malloc(RSA_size(rsa))) == NULL) {
1824 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1825 		goto err;
1826 	}
1827 
1828 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, rsa,
1829 	    RSA_PKCS1_PADDING);
1830 	if (enc_len <= 0) {
1831 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1832 		goto err;
1833 	}
1834 
1835 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
1836 		goto err;
1837 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
1838 		goto err;
1839 	if (!CBB_flush(cbb))
1840 		goto err;
1841 
1842 	if (!tls12_derive_master_secret(s, pms, sizeof(pms)))
1843 		goto err;
1844 
1845 	ret = 1;
1846 
1847  err:
1848 	explicit_bzero(pms, sizeof(pms));
1849 	free(enc_pms);
1850 
1851 	return ret;
1852 }
1853 
1854 static int
1855 ssl3_send_client_kex_dhe(SSL *s, CBB *cbb)
1856 {
1857 	uint8_t *key = NULL;
1858 	size_t key_len = 0;
1859 	int ret = 0;
1860 
1861 	/* Ensure that we have an ephemeral key from the server for DHE. */
1862 	if (s->s3->hs.key_share == NULL) {
1863 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1864 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1865 		goto err;
1866 	}
1867 
1868 	if (!tls_key_share_generate(s->s3->hs.key_share))
1869 		goto err;
1870 	if (!tls_key_share_public(s->s3->hs.key_share, cbb))
1871 		goto err;
1872 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1873 		goto err;
1874 
1875 	if (!tls_key_share_peer_security(s, s->s3->hs.key_share)) {
1876 		SSLerror(s, SSL_R_DH_KEY_TOO_SMALL);
1877 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1878 		return 0;
1879 	}
1880 
1881 	if (!tls12_derive_master_secret(s, key, key_len))
1882 		goto err;
1883 
1884 	ret = 1;
1885 
1886  err:
1887 	freezero(key, key_len);
1888 
1889 	return ret;
1890 }
1891 
1892 static int
1893 ssl3_send_client_kex_ecdhe(SSL *s, CBB *cbb)
1894 {
1895 	uint8_t *key = NULL;
1896 	size_t key_len = 0;
1897 	CBB public;
1898 	int ret = 0;
1899 
1900 	/* Ensure that we have an ephemeral key for ECDHE. */
1901 	if (s->s3->hs.key_share == NULL) {
1902 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1903 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1904 		goto err;
1905 	}
1906 
1907 	if (!tls_key_share_generate(s->s3->hs.key_share))
1908 		goto err;
1909 
1910 	if (!CBB_add_u8_length_prefixed(cbb, &public))
1911 		return 0;
1912 	if (!tls_key_share_public(s->s3->hs.key_share, &public))
1913 		goto err;
1914 	if (!CBB_flush(cbb))
1915 		goto err;
1916 
1917 	if (!tls_key_share_derive(s->s3->hs.key_share, &key, &key_len))
1918 		goto err;
1919 
1920 	if (!tls12_derive_master_secret(s, key, key_len))
1921 		goto err;
1922 
1923 	ret = 1;
1924 
1925  err:
1926 	freezero(key, key_len);
1927 
1928 	return ret;
1929 }
1930 
1931 static int
1932 ssl3_send_client_kex_gost(SSL *s, CBB *cbb)
1933 {
1934 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
1935 	EVP_PKEY_CTX *pkey_ctx = NULL;
1936 	EVP_MD_CTX *ukm_hash = NULL;
1937 	EVP_PKEY *pkey;
1938 	size_t msglen;
1939 	unsigned int md_len;
1940 	CBB gostblob;
1941 	int nid;
1942 	int ret = 0;
1943 
1944 	/* Get server certificate PKEY and create ctx from it */
1945 	pkey = X509_get0_pubkey(s->session->peer_cert);
1946 	if (pkey == NULL || s->session->peer_cert_type != SSL_PKEY_GOST01) {
1947 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
1948 		goto err;
1949 	}
1950 	if ((pkey_ctx = EVP_PKEY_CTX_new(pkey, NULL)) == NULL) {
1951 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1952 		goto err;
1953 	}
1954 
1955 	/*
1956 	 * If we have send a certificate, and certificate key parameters match
1957 	 * those of server certificate, use certificate key for key exchange.
1958 	 * Otherwise, generate ephemeral key pair.
1959 	 */
1960 	if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0)
1961 		goto err;
1962 
1963 	/* Generate session key. */
1964 	arc4random_buf(premaster_secret, sizeof(premaster_secret));
1965 
1966 	/*
1967 	 * If we have client certificate, use its secret as peer key.
1968 	 * XXX - this presumably lacks PFS.
1969 	 */
1970 	if (s->s3->hs.tls12.cert_request != 0 &&
1971 	    s->cert->key->privatekey != NULL) {
1972 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
1973 		    s->cert->key->privatekey) <=0) {
1974 			/*
1975 			 * If there was an error - just ignore it.
1976 			 * Ephemeral key would be used.
1977 			 */
1978 			ERR_clear_error();
1979 		}
1980 	}
1981 
1982 	/*
1983 	 * Compute shared IV and store it in algorithm-specific context data.
1984 	 */
1985 	if ((ukm_hash = EVP_MD_CTX_new()) == NULL) {
1986 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1987 		goto err;
1988 	}
1989 
1990 	/* XXX check handshake hash instead. */
1991 	if (s->s3->hs.cipher->algorithm2 & SSL_HANDSHAKE_MAC_GOST94)
1992 		nid = NID_id_GostR3411_94;
1993 	else
1994 		nid = NID_id_tc26_gost3411_2012_256;
1995 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
1996 		goto err;
1997 	if (!EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE))
1998 		goto err;
1999 	if (!EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE))
2000 		goto err;
2001 	if (!EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len))
2002 		goto err;
2003 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2004 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2005 		SSLerror(s, SSL_R_LIBRARY_BUG);
2006 		goto err;
2007 	}
2008 
2009 	/*
2010 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2011 	 */
2012 	msglen = 255;
2013 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2014 	    sizeof(premaster_secret)) < 0) {
2015 		SSLerror(s, SSL_R_LIBRARY_BUG);
2016 		goto err;
2017 	}
2018 
2019 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2020 		goto err;
2021 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2022 		goto err;
2023 	if (!CBB_flush(cbb))
2024 		goto err;
2025 
2026 	/* Check if pubkey from client certificate was used. */
2027 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2028 	    NULL) > 0)
2029 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2030 
2031 	if (!tls12_derive_master_secret(s, premaster_secret, 32))
2032 		goto err;
2033 
2034 	ret = 1;
2035 
2036  err:
2037 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2038 	EVP_PKEY_CTX_free(pkey_ctx);
2039 	EVP_MD_CTX_free(ukm_hash);
2040 
2041 	return ret;
2042 }
2043 
2044 static int
2045 ssl3_send_client_key_exchange(SSL *s)
2046 {
2047 	unsigned long alg_k;
2048 	CBB cbb, kex;
2049 
2050 	memset(&cbb, 0, sizeof(cbb));
2051 
2052 	if (s->s3->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2053 		alg_k = s->s3->hs.cipher->algorithm_mkey;
2054 
2055 		if (!ssl3_handshake_msg_start(s, &cbb, &kex,
2056 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2057 			goto err;
2058 
2059 		if (alg_k & SSL_kRSA) {
2060 			if (!ssl3_send_client_kex_rsa(s, &kex))
2061 				goto err;
2062 		} else if (alg_k & SSL_kDHE) {
2063 			if (!ssl3_send_client_kex_dhe(s, &kex))
2064 				goto err;
2065 		} else if (alg_k & SSL_kECDHE) {
2066 			if (!ssl3_send_client_kex_ecdhe(s, &kex))
2067 				goto err;
2068 		} else if (alg_k & SSL_kGOST) {
2069 			if (!ssl3_send_client_kex_gost(s, &kex))
2070 				goto err;
2071 		} else {
2072 			ssl3_send_alert(s, SSL3_AL_FATAL,
2073 			    SSL_AD_HANDSHAKE_FAILURE);
2074 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2075 			goto err;
2076 		}
2077 
2078 		if (!ssl3_handshake_msg_finish(s, &cbb))
2079 			goto err;
2080 
2081 		s->s3->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2082 	}
2083 
2084 	/* SSL3_ST_CW_KEY_EXCH_B */
2085 	return (ssl3_handshake_write(s));
2086 
2087  err:
2088 	CBB_cleanup(&cbb);
2089 
2090 	return (-1);
2091 }
2092 
2093 static int
2094 ssl3_send_client_verify_sigalgs(SSL *s, EVP_PKEY *pkey,
2095     const struct ssl_sigalg *sigalg, CBB *cert_verify)
2096 {
2097 	CBB cbb_signature;
2098 	EVP_PKEY_CTX *pctx = NULL;
2099 	EVP_MD_CTX *mctx = NULL;
2100 	const unsigned char *hdata;
2101 	unsigned char *signature = NULL;
2102 	size_t signature_len, hdata_len;
2103 	int ret = 0;
2104 
2105 	if ((mctx = EVP_MD_CTX_new()) == NULL)
2106 		goto err;
2107 
2108 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2109 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2110 		goto err;
2111 	}
2112 	if (!EVP_DigestSignInit(mctx, &pctx, sigalg->md(), NULL, pkey)) {
2113 		SSLerror(s, ERR_R_EVP_LIB);
2114 		goto err;
2115 	}
2116 	if (sigalg->key_type == EVP_PKEY_GOSTR01 &&
2117 	    EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2118 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2119 		SSLerror(s, ERR_R_EVP_LIB);
2120 		goto err;
2121 	}
2122 	if ((sigalg->flags & SIGALG_FLAG_RSA_PSS) &&
2123 	    (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) ||
2124 	    !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))) {
2125 		SSLerror(s, ERR_R_EVP_LIB);
2126 		goto err;
2127 	}
2128 	if (!EVP_DigestSignUpdate(mctx, hdata, hdata_len)) {
2129 		SSLerror(s, ERR_R_EVP_LIB);
2130 		goto err;
2131 	}
2132 	if (!EVP_DigestSignFinal(mctx, NULL, &signature_len) ||
2133 	    signature_len == 0) {
2134 		SSLerror(s, ERR_R_EVP_LIB);
2135 		goto err;
2136 	}
2137 	if ((signature = calloc(1, signature_len)) == NULL) {
2138 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2139 		goto err;
2140 	}
2141 	if (!EVP_DigestSignFinal(mctx, signature, &signature_len)) {
2142 		SSLerror(s, ERR_R_EVP_LIB);
2143 		goto err;
2144 	}
2145 
2146 	if (!CBB_add_u16(cert_verify, sigalg->value))
2147 		goto err;
2148 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2149 		goto err;
2150 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2151 		goto err;
2152 	if (!CBB_flush(cert_verify))
2153 		goto err;
2154 
2155 	ret = 1;
2156 
2157  err:
2158 	EVP_MD_CTX_free(mctx);
2159 	free(signature);
2160 	return ret;
2161 }
2162 
2163 static int
2164 ssl3_send_client_verify_rsa(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2165 {
2166 	CBB cbb_signature;
2167 	RSA *rsa;
2168 	unsigned char data[EVP_MAX_MD_SIZE];
2169 	unsigned char *signature = NULL;
2170 	unsigned int signature_len;
2171 	size_t data_len;
2172 	int ret = 0;
2173 
2174 	if (!tls1_transcript_hash_value(s, data, sizeof(data), &data_len))
2175 		goto err;
2176 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2177 		goto err;
2178 	if ((rsa = EVP_PKEY_get0_RSA(pkey)) == NULL)
2179 		goto err;
2180 	if (RSA_sign(NID_md5_sha1, data, data_len, signature, &signature_len,
2181 	    rsa) <= 0 ) {
2182 		SSLerror(s, ERR_R_RSA_LIB);
2183 		goto err;
2184 	}
2185 
2186 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2187 		goto err;
2188 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2189 		goto err;
2190 	if (!CBB_flush(cert_verify))
2191 		goto err;
2192 
2193 	ret = 1;
2194  err:
2195 	free(signature);
2196 	return ret;
2197 }
2198 
2199 static int
2200 ssl3_send_client_verify_ec(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2201 {
2202 	CBB cbb_signature;
2203 	EC_KEY *eckey;
2204 	unsigned char data[EVP_MAX_MD_SIZE];
2205 	unsigned char *signature = NULL;
2206 	unsigned int signature_len;
2207 	int ret = 0;
2208 
2209 	if (!tls1_transcript_hash_value(s, data, sizeof(data), NULL))
2210 		goto err;
2211 	if ((signature = calloc(1, EVP_PKEY_size(pkey))) == NULL)
2212 		goto err;
2213 	if ((eckey = EVP_PKEY_get0_EC_KEY(pkey)) == NULL)
2214 		goto err;
2215 	if (!ECDSA_sign(0, &data[MD5_DIGEST_LENGTH], SHA_DIGEST_LENGTH,
2216 	    signature, &signature_len, eckey)) {
2217 		SSLerror(s, ERR_R_ECDSA_LIB);
2218 		goto err;
2219 	}
2220 
2221 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2222 		goto err;
2223 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2224 		goto err;
2225 	if (!CBB_flush(cert_verify))
2226 		goto err;
2227 
2228 	ret = 1;
2229  err:
2230 	free(signature);
2231 	return ret;
2232 }
2233 
2234 #ifndef OPENSSL_NO_GOST
2235 static int
2236 ssl3_send_client_verify_gost(SSL *s, EVP_PKEY *pkey, CBB *cert_verify)
2237 {
2238 	CBB cbb_signature;
2239 	EVP_MD_CTX *mctx;
2240 	EVP_PKEY_CTX *pctx;
2241 	const EVP_MD *md;
2242 	const unsigned char *hdata;
2243 	unsigned char *signature = NULL;
2244 	size_t signature_len;
2245 	size_t hdata_len;
2246 	int nid;
2247 	int ret = 0;
2248 
2249 	if ((mctx = EVP_MD_CTX_new()) == NULL)
2250 		goto err;
2251 
2252 	if (!tls1_transcript_data(s, &hdata, &hdata_len)) {
2253 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2254 		goto err;
2255 	}
2256 	if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2257 	    (md = EVP_get_digestbynid(nid)) == NULL) {
2258 		SSLerror(s, ERR_R_EVP_LIB);
2259 		goto err;
2260 	}
2261 	if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, pkey)) {
2262 		SSLerror(s, ERR_R_EVP_LIB);
2263 		goto err;
2264 	}
2265 	if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2266 	    EVP_PKEY_CTRL_GOST_SIG_FORMAT, GOST_SIG_FORMAT_RS_LE, NULL) <= 0) {
2267 		SSLerror(s, ERR_R_EVP_LIB);
2268 		goto err;
2269 	}
2270 	if (!EVP_DigestSignUpdate(mctx, hdata, hdata_len)) {
2271 		SSLerror(s, ERR_R_EVP_LIB);
2272 		goto err;
2273 	}
2274 	if (!EVP_DigestSignFinal(mctx, NULL, &signature_len) ||
2275 	    signature_len == 0) {
2276 		SSLerror(s, ERR_R_EVP_LIB);
2277 		goto err;
2278 	}
2279 	if ((signature = calloc(1, signature_len)) == NULL) {
2280 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2281 		goto err;
2282 	}
2283 	if (!EVP_DigestSignFinal(mctx, signature, &signature_len)) {
2284 		SSLerror(s, ERR_R_EVP_LIB);
2285 		goto err;
2286 	}
2287 
2288 	if (!CBB_add_u16_length_prefixed(cert_verify, &cbb_signature))
2289 		goto err;
2290 	if (!CBB_add_bytes(&cbb_signature, signature, signature_len))
2291 		goto err;
2292 	if (!CBB_flush(cert_verify))
2293 		goto err;
2294 
2295 	ret = 1;
2296  err:
2297 	EVP_MD_CTX_free(mctx);
2298 	free(signature);
2299 	return ret;
2300 }
2301 #endif
2302 
2303 static int
2304 ssl3_send_client_verify(SSL *s)
2305 {
2306 	const struct ssl_sigalg *sigalg;
2307 	CBB cbb, cert_verify;
2308 	EVP_PKEY *pkey;
2309 
2310 	memset(&cbb, 0, sizeof(cbb));
2311 
2312 	if (s->s3->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2313 		if (!ssl3_handshake_msg_start(s, &cbb, &cert_verify,
2314 		    SSL3_MT_CERTIFICATE_VERIFY))
2315 			goto err;
2316 
2317 		pkey = s->cert->key->privatekey;
2318 		if ((sigalg = ssl_sigalg_select(s, pkey)) == NULL) {
2319 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2320 			goto err;
2321 		}
2322 		s->s3->hs.our_sigalg = sigalg;
2323 
2324 		/*
2325 		 * For TLS v1.2 send signature algorithm and signature using
2326 		 * agreed digest and cached handshake records.
2327 		 */
2328 		if (SSL_USE_SIGALGS(s)) {
2329 			if (!ssl3_send_client_verify_sigalgs(s, pkey, sigalg,
2330 			    &cert_verify))
2331 				goto err;
2332 		} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
2333 			if (!ssl3_send_client_verify_rsa(s, pkey, &cert_verify))
2334 				goto err;
2335 		} else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC) {
2336 			if (!ssl3_send_client_verify_ec(s, pkey, &cert_verify))
2337 				goto err;
2338 #ifndef OPENSSL_NO_GOST
2339 		} else if (EVP_PKEY_id(pkey) == NID_id_GostR3410_94 ||
2340 		    EVP_PKEY_id(pkey) == NID_id_GostR3410_2001) {
2341 			if (!ssl3_send_client_verify_gost(s, pkey, &cert_verify))
2342 				goto err;
2343 #endif
2344 		} else {
2345 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2346 			goto err;
2347 		}
2348 
2349 		tls1_transcript_free(s);
2350 
2351 		if (!ssl3_handshake_msg_finish(s, &cbb))
2352 			goto err;
2353 
2354 		s->s3->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2355 	}
2356 
2357 	return (ssl3_handshake_write(s));
2358 
2359  err:
2360 	CBB_cleanup(&cbb);
2361 
2362 	return (-1);
2363 }
2364 
2365 static int
2366 ssl3_send_client_certificate(SSL *s)
2367 {
2368 	EVP_PKEY *pkey = NULL;
2369 	X509 *x509 = NULL;
2370 	CBB cbb, client_cert;
2371 	int i;
2372 
2373 	memset(&cbb, 0, sizeof(cbb));
2374 
2375 	if (s->s3->hs.state == SSL3_ST_CW_CERT_A) {
2376 		if (s->cert->key->x509 == NULL ||
2377 		    s->cert->key->privatekey == NULL)
2378 			s->s3->hs.state = SSL3_ST_CW_CERT_B;
2379 		else
2380 			s->s3->hs.state = SSL3_ST_CW_CERT_C;
2381 	}
2382 
2383 	/* We need to get a client cert */
2384 	if (s->s3->hs.state == SSL3_ST_CW_CERT_B) {
2385 		/*
2386 		 * If we get an error, we need to
2387 		 * ssl->rwstate = SSL_X509_LOOKUP; return(-1);
2388 		 * We then get retried later.
2389 		 */
2390 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2391 		if (i < 0) {
2392 			s->rwstate = SSL_X509_LOOKUP;
2393 			return (-1);
2394 		}
2395 		s->rwstate = SSL_NOTHING;
2396 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2397 			s->s3->hs.state = SSL3_ST_CW_CERT_B;
2398 			if (!SSL_use_certificate(s, x509) ||
2399 			    !SSL_use_PrivateKey(s, pkey))
2400 				i = 0;
2401 		} else if (i == 1) {
2402 			i = 0;
2403 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2404 		}
2405 
2406 		X509_free(x509);
2407 		EVP_PKEY_free(pkey);
2408 		if (i == 0) {
2409 			s->s3->hs.tls12.cert_request = 2;
2410 
2411 			/* There is no client certificate to verify. */
2412 			tls1_transcript_free(s);
2413 		}
2414 
2415 		/* Ok, we have a cert */
2416 		s->s3->hs.state = SSL3_ST_CW_CERT_C;
2417 	}
2418 
2419 	if (s->s3->hs.state == SSL3_ST_CW_CERT_C) {
2420 		if (!ssl3_handshake_msg_start(s, &cbb, &client_cert,
2421 		    SSL3_MT_CERTIFICATE))
2422 			goto err;
2423 		if (!ssl3_output_cert_chain(s, &client_cert,
2424 		    (s->s3->hs.tls12.cert_request == 2) ? NULL : s->cert->key))
2425 			goto err;
2426 		if (!ssl3_handshake_msg_finish(s, &cbb))
2427 			goto err;
2428 
2429 		s->s3->hs.state = SSL3_ST_CW_CERT_D;
2430 	}
2431 
2432 	/* SSL3_ST_CW_CERT_D */
2433 	return (ssl3_handshake_write(s));
2434 
2435  err:
2436 	CBB_cleanup(&cbb);
2437 
2438 	return (0);
2439 }
2440 
2441 #define has_bits(i,m)	(((i)&(m)) == (m))
2442 
2443 static int
2444 ssl3_check_cert_and_algorithm(SSL *s)
2445 {
2446 	long alg_k, alg_a;
2447 	int nid = NID_undef;
2448 	int i;
2449 
2450 	alg_k = s->s3->hs.cipher->algorithm_mkey;
2451 	alg_a = s->s3->hs.cipher->algorithm_auth;
2452 
2453 	/* We don't have a certificate. */
2454 	if (alg_a & SSL_aNULL)
2455 		return (1);
2456 
2457 	if (s->s3->hs.key_share != NULL)
2458 		nid = tls_key_share_nid(s->s3->hs.key_share);
2459 
2460 	/* This is the passed certificate. */
2461 
2462 	if (s->session->peer_cert_type == SSL_PKEY_ECC) {
2463 		if (!ssl_check_srvr_ecc_cert_and_alg(s, s->session->peer_cert)) {
2464 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2465 			goto fatal_err;
2466 		}
2467 		return (1);
2468 	}
2469 
2470 	i = X509_certificate_type(s->session->peer_cert, NULL);
2471 
2472 	/* Check that we have a certificate if we require one. */
2473 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2474 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2475 		goto fatal_err;
2476 	}
2477 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2478 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2479 		goto fatal_err;
2480 	}
2481 	if ((alg_k & SSL_kDHE) &&
2482 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (nid == NID_dhKeyAgreement))) {
2483 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2484 		goto fatal_err;
2485 	}
2486 
2487 	return (1);
2488 
2489  fatal_err:
2490 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2491 
2492 	return (0);
2493 }
2494 
2495 /*
2496  * Check to see if handshake is full or resumed. Usually this is just a
2497  * case of checking to see if a cache hit has occurred. In the case of
2498  * session tickets we have to check the next message to be sure.
2499  */
2500 
2501 static int
2502 ssl3_check_finished(SSL *s)
2503 {
2504 	int ret;
2505 
2506 	/* If we have no ticket it cannot be a resumed session. */
2507 	if (!s->session->tlsext_tick)
2508 		return (1);
2509 	/* this function is called when we really expect a Certificate
2510 	 * message, so permit appropriate message length */
2511 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_CERT_A,
2512 	    SSL3_ST_CR_CERT_B, -1, s->max_cert_list)) <= 0)
2513 		return ret;
2514 
2515 	s->s3->hs.tls12.reuse_message = 1;
2516 	if ((s->s3->hs.tls12.message_type == SSL3_MT_FINISHED) ||
2517 	    (s->s3->hs.tls12.message_type == SSL3_MT_NEWSESSION_TICKET))
2518 		return (2);
2519 
2520 	return (1);
2521 }
2522 
2523 static int
2524 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2525 {
2526 	int	i = 0;
2527 
2528 #ifndef OPENSSL_NO_ENGINE
2529 	if (s->ctx->client_cert_engine) {
2530 		i = ENGINE_load_ssl_client_cert(
2531 		    s->ctx->client_cert_engine, s,
2532 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2533 		if (i != 0)
2534 			return (i);
2535 	}
2536 #endif
2537 	if (s->ctx->client_cert_cb)
2538 		i = s->ctx->client_cert_cb(s, px509, ppkey);
2539 	return (i);
2540 }
2541 
2542 static int
2543 ssl3_send_client_change_cipher_spec(SSL *s)
2544 {
2545 	size_t outlen;
2546 	CBB cbb;
2547 
2548 	memset(&cbb, 0, sizeof(cbb));
2549 
2550 	if (s->s3->hs.state == SSL3_ST_CW_CHANGE_A) {
2551 		if (!CBB_init_fixed(&cbb, s->init_buf->data,
2552 		    s->init_buf->length))
2553 			goto err;
2554 		if (!CBB_add_u8(&cbb, SSL3_MT_CCS))
2555 			goto err;
2556 		if (!CBB_finish(&cbb, NULL, &outlen))
2557 			goto err;
2558 
2559 		if (outlen > INT_MAX)
2560 			goto err;
2561 
2562 		s->init_num = (int)outlen;
2563 		s->init_off = 0;
2564 
2565 		if (SSL_is_dtls(s)) {
2566 			s->d1->handshake_write_seq =
2567 			    s->d1->next_handshake_write_seq;
2568 			dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
2569 			    s->d1->handshake_write_seq, 0, 0);
2570 			dtls1_buffer_message(s, 1);
2571 		}
2572 
2573 		s->s3->hs.state = SSL3_ST_CW_CHANGE_B;
2574 	}
2575 
2576 	/* SSL3_ST_CW_CHANGE_B */
2577 	return ssl3_record_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
2578 
2579  err:
2580 	CBB_cleanup(&cbb);
2581 
2582 	return -1;
2583 }
2584 
2585 static int
2586 ssl3_send_client_finished(SSL *s)
2587 {
2588 	CBB cbb, finished;
2589 
2590 	memset(&cbb, 0, sizeof(cbb));
2591 
2592 	if (s->s3->hs.state == SSL3_ST_CW_FINISHED_A) {
2593 		if (!tls12_derive_finished(s))
2594 			goto err;
2595 
2596 		/* Copy finished so we can use it for renegotiation checks. */
2597 		memcpy(s->s3->previous_client_finished,
2598 		    s->s3->hs.finished, s->s3->hs.finished_len);
2599 		s->s3->previous_client_finished_len =
2600 		    s->s3->hs.finished_len;
2601 
2602 		if (!ssl3_handshake_msg_start(s, &cbb, &finished,
2603 		    SSL3_MT_FINISHED))
2604                         goto err;
2605 		if (!CBB_add_bytes(&finished, s->s3->hs.finished,
2606 		    s->s3->hs.finished_len))
2607 			goto err;
2608 		if (!ssl3_handshake_msg_finish(s, &cbb))
2609 			goto err;
2610 
2611 		s->s3->hs.state = SSL3_ST_CW_FINISHED_B;
2612 	}
2613 
2614 	return (ssl3_handshake_write(s));
2615 
2616  err:
2617 	CBB_cleanup(&cbb);
2618 
2619 	return (-1);
2620 }
2621 
2622 static int
2623 ssl3_get_server_finished(SSL *s)
2624 {
2625 	int al, md_len, ret;
2626 	CBS cbs;
2627 
2628 	/* should actually be 36+4 :-) */
2629 	if ((ret = ssl3_get_message(s, SSL3_ST_CR_FINISHED_A,
2630 	    SSL3_ST_CR_FINISHED_B, SSL3_MT_FINISHED, 64)) <= 0)
2631 		return ret;
2632 
2633 	/* If this occurs, we have missed a message */
2634 	if (!s->s3->change_cipher_spec) {
2635 		al = SSL_AD_UNEXPECTED_MESSAGE;
2636 		SSLerror(s, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
2637 		goto fatal_err;
2638 	}
2639 	s->s3->change_cipher_spec = 0;
2640 
2641 	md_len = TLS1_FINISH_MAC_LENGTH;
2642 
2643 	if (s->init_num < 0) {
2644 		al = SSL_AD_DECODE_ERROR;
2645 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2646 		goto fatal_err;
2647 	}
2648 
2649 	CBS_init(&cbs, s->init_msg, s->init_num);
2650 
2651 	if (s->s3->hs.peer_finished_len != md_len ||
2652 	    CBS_len(&cbs) != md_len) {
2653 		al = SSL_AD_DECODE_ERROR;
2654 		SSLerror(s, SSL_R_BAD_DIGEST_LENGTH);
2655 		goto fatal_err;
2656 	}
2657 
2658 	if (!CBS_mem_equal(&cbs, s->s3->hs.peer_finished, CBS_len(&cbs))) {
2659 		al = SSL_AD_DECRYPT_ERROR;
2660 		SSLerror(s, SSL_R_DIGEST_CHECK_FAILED);
2661 		goto fatal_err;
2662 	}
2663 
2664 	/* Copy finished so we can use it for renegotiation checks. */
2665 	OPENSSL_assert(md_len <= EVP_MAX_MD_SIZE);
2666 	memcpy(s->s3->previous_server_finished,
2667 	    s->s3->hs.peer_finished, md_len);
2668 	s->s3->previous_server_finished_len = md_len;
2669 
2670 	return (1);
2671  fatal_err:
2672 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2673 	return (0);
2674 }
2675