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