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