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