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