xref: /openbsd-src/lib/libssl/ssl_clnt.c (revision d4c5fc9dc00f5a9cadd8c2de4e52d85d3c1c6003)
1 /* $OpenBSD: ssl_clnt.c,v 1.25 2018/05/13 17:31:06 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_cbb(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_cbb(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, unsigned char **pp, long *nn)
1193 {
1194 	CBS 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 (*nn < 0)
1205 		goto err;
1206 
1207 	CBS_init(&cbs, *pp, *nn);
1208 
1209 	if ((dh = DH_new()) == NULL) {
1210 		SSLerror(s, ERR_R_DH_LIB);
1211 		goto err;
1212 	}
1213 
1214 	if (!CBS_get_u16_length_prefixed(&cbs, &dhp))
1215 		goto truncated;
1216 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1217 		SSLerror(s, ERR_R_BN_LIB);
1218 		goto err;
1219 	}
1220 
1221 	if (!CBS_get_u16_length_prefixed(&cbs, &dhg))
1222 		goto truncated;
1223 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1224 		SSLerror(s, ERR_R_BN_LIB);
1225 		goto err;
1226 	}
1227 
1228 	if (!CBS_get_u16_length_prefixed(&cbs, &dhpk))
1229 		goto truncated;
1230 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1231 	    NULL)) == NULL) {
1232 		SSLerror(s, ERR_R_BN_LIB);
1233 		goto err;
1234 	}
1235 
1236 	/*
1237 	 * Check the strength of the DH key just constructed.
1238 	 * Discard keys weaker than 1024 bits.
1239 	 */
1240 	if (DH_size(dh) < 1024 / 8) {
1241 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1242 		goto err;
1243 	}
1244 
1245 	if (alg_a & SSL_aRSA)
1246 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1247 	else
1248 		/* XXX - Anonymous DH, so no certificate or pkey. */
1249 		*pkey = NULL;
1250 
1251 	sc->peer_dh_tmp = dh;
1252 
1253 	*nn = CBS_len(&cbs);
1254 	*pp = (unsigned char *)CBS_data(&cbs);
1255 
1256 	return (1);
1257 
1258  truncated:
1259 	al = SSL_AD_DECODE_ERROR;
1260 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1261 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1262 
1263  err:
1264 	DH_free(dh);
1265 	BN_CTX_free(bn_ctx);
1266 
1267 	return (-1);
1268 }
1269 
1270 static int
1271 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1272 {
1273 	const EC_GROUP *group;
1274 	EC_GROUP *ngroup = NULL;
1275 	EC_POINT *point = NULL;
1276 	BN_CTX *bn_ctx = NULL;
1277 	EC_KEY *ecdh = NULL;
1278 	int ret = -1;
1279 
1280 	/*
1281 	 * Extract the server's ephemeral ECDH public key.
1282 	 */
1283 
1284 	if ((ecdh = EC_KEY_new()) == NULL) {
1285 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1286 		goto err;
1287 	}
1288 
1289 	if ((ngroup = EC_GROUP_new_by_curve_name(nid)) == NULL) {
1290 		SSLerror(s, ERR_R_EC_LIB);
1291 		goto err;
1292 	}
1293 	if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1294 		SSLerror(s, ERR_R_EC_LIB);
1295 		goto err;
1296 	}
1297 
1298 	group = EC_KEY_get0_group(ecdh);
1299 
1300 	if ((point = EC_POINT_new(group)) == NULL ||
1301 	    (bn_ctx = BN_CTX_new()) == NULL) {
1302 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1303 		goto err;
1304 	}
1305 
1306 	if (EC_POINT_oct2point(group, point, CBS_data(public),
1307 	    CBS_len(public), bn_ctx) == 0) {
1308 		SSLerror(s, SSL_R_BAD_ECPOINT);
1309 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1310 		goto err;
1311 	}
1312 
1313 	EC_KEY_set_public_key(ecdh, point);
1314 	sc->peer_ecdh_tmp = ecdh;
1315 	ecdh = NULL;
1316 
1317 	ret = 1;
1318 
1319  err:
1320 	BN_CTX_free(bn_ctx);
1321 	EC_GROUP_free(ngroup);
1322 	EC_POINT_free(point);
1323 	EC_KEY_free(ecdh);
1324 
1325 	return (ret);
1326 }
1327 
1328 static int
1329 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1330 {
1331 	size_t outlen;
1332 
1333 	if (nid != NID_X25519) {
1334 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1335 		goto err;
1336 	}
1337 
1338 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1339 		SSLerror(s, SSL_R_BAD_ECPOINT);
1340 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1341 		goto err;
1342 	}
1343 
1344 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1345 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1346 		goto err;
1347 	}
1348 
1349 	return (1);
1350 
1351  err:
1352 	return (-1);
1353 }
1354 
1355 static int
1356 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, unsigned char **pp, long *nn)
1357 {
1358 	CBS cbs, public;
1359 	uint8_t curve_type;
1360 	uint16_t curve_id;
1361 	SESS_CERT *sc;
1362 	long alg_a;
1363 	int nid;
1364 	int al;
1365 
1366 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1367 	sc = SSI(s)->sess_cert;
1368 
1369 	if (*nn < 0)
1370 		goto err;
1371 
1372 	CBS_init(&cbs, *pp, *nn);
1373 
1374 	/* Only named curves are supported. */
1375 	if (!CBS_get_u8(&cbs, &curve_type) ||
1376 	    curve_type != NAMED_CURVE_TYPE ||
1377 	    !CBS_get_u16(&cbs, &curve_id)) {
1378 		al = SSL_AD_DECODE_ERROR;
1379 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1380 		goto f_err;
1381 	}
1382 
1383 	/*
1384 	 * Check that the curve is one of our preferences - if it is not,
1385 	 * the server has sent us an invalid curve.
1386 	 */
1387 	if (tls1_check_curve(s, curve_id) != 1) {
1388 		al = SSL_AD_DECODE_ERROR;
1389 		SSLerror(s, SSL_R_WRONG_CURVE);
1390 		goto f_err;
1391 	}
1392 
1393 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1394 		al = SSL_AD_INTERNAL_ERROR;
1395 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1396 		goto f_err;
1397 	}
1398 
1399 	if (!CBS_get_u8_length_prefixed(&cbs, &public))
1400 		goto truncated;
1401 
1402 	if (nid == NID_X25519) {
1403 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1404 			goto err;
1405 	} else {
1406 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1407 			goto err;
1408 	}
1409 
1410 	/*
1411 	 * The ECC/TLS specification does not mention the use of DSA to sign
1412 	 * ECParameters in the server key exchange message. We do support RSA
1413 	 * and ECDSA.
1414 	 */
1415 	if (alg_a & SSL_aRSA)
1416 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1417 	else if (alg_a & SSL_aECDSA)
1418 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1419 	else
1420 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1421 		*pkey = NULL;
1422 
1423 	*nn = CBS_len(&cbs);
1424 	*pp = (unsigned char *)CBS_data(&cbs);
1425 
1426 	return (1);
1427 
1428  truncated:
1429 	al = SSL_AD_DECODE_ERROR;
1430 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1431 
1432  f_err:
1433 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1434 
1435  err:
1436 	return (-1);
1437 }
1438 
1439 int
1440 ssl3_get_server_key_exchange(SSL *s)
1441 {
1442 	unsigned char	*q, md_buf[EVP_MAX_MD_SIZE*2];
1443 	EVP_MD_CTX	 md_ctx;
1444 	unsigned char	*param, *p;
1445 	int		 al, i, j, param_len, ok;
1446 	long		 n, alg_k, alg_a;
1447 	EVP_PKEY	*pkey = NULL;
1448 	const		 EVP_MD *md = NULL;
1449 	RSA		*rsa = NULL;
1450 
1451 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1452 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1453 
1454 	/*
1455 	 * Use same message size as in ssl3_get_certificate_request()
1456 	 * as ServerKeyExchange message may be skipped.
1457 	 */
1458 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1459 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1460 	if (!ok)
1461 		return ((int)n);
1462 
1463 	EVP_MD_CTX_init(&md_ctx);
1464 
1465 	if (S3I(s)->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1466 		/*
1467 		 * Do not skip server key exchange if this cipher suite uses
1468 		 * ephemeral keys.
1469 		 */
1470 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1471 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1472 			al = SSL_AD_UNEXPECTED_MESSAGE;
1473 			goto f_err;
1474 		}
1475 
1476 		S3I(s)->tmp.reuse_message = 1;
1477 		EVP_MD_CTX_cleanup(&md_ctx);
1478 		return (1);
1479 	}
1480 
1481 	if (SSI(s)->sess_cert != NULL) {
1482 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1483 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1484 
1485 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1486 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1487 
1488 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1489 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1490 	} else {
1491 		SSI(s)->sess_cert = ssl_sess_cert_new();
1492 		if (SSI(s)->sess_cert == NULL)
1493 			goto err;
1494 	}
1495 
1496 	param = p = (unsigned char *)s->internal->init_msg;
1497 	param_len = n;
1498 
1499 	if (alg_k & SSL_kDHE) {
1500 		if (ssl3_get_server_kex_dhe(s, &pkey, &p, &n) != 1)
1501 			goto err;
1502 	} else if (alg_k & SSL_kECDHE) {
1503 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &p, &n) != 1)
1504 			goto err;
1505 	} else if (alg_k != 0) {
1506 		al = SSL_AD_UNEXPECTED_MESSAGE;
1507 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1508 			goto f_err;
1509 	}
1510 
1511 	param_len = param_len - n;
1512 
1513 	/* if it was signed, check the signature */
1514 	if (pkey != NULL) {
1515 		if (SSL_USE_SIGALGS(s)) {
1516 			int sigalg = tls12_get_sigid(pkey);
1517 			/* Should never happen */
1518 			if (sigalg == -1) {
1519 				SSLerror(s, ERR_R_INTERNAL_ERROR);
1520 				goto err;
1521 			}
1522 			/*
1523 			 * Check key type is consistent
1524 			 * with signature
1525 			 */
1526 			if (2 > n)
1527 				goto truncated;
1528 			if (sigalg != (int)p[1]) {
1529 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
1530 				al = SSL_AD_DECODE_ERROR;
1531 				goto f_err;
1532 			}
1533 			md = tls12_get_hash(p[0]);
1534 			if (md == NULL) {
1535 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
1536 				al = SSL_AD_DECODE_ERROR;
1537 				goto f_err;
1538 			}
1539 			p += 2;
1540 			n -= 2;
1541 		} else
1542 			md = EVP_sha1();
1543 
1544 		if (2 > n)
1545 			goto truncated;
1546 		n2s(p, i);
1547 		n -= 2;
1548 		j = EVP_PKEY_size(pkey);
1549 
1550 		if (i != n || n > j) {
1551 			/* wrong packet length */
1552 			al = SSL_AD_DECODE_ERROR;
1553 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1554 			goto f_err;
1555 		}
1556 
1557 		if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1558 			j = 0;
1559 			q = md_buf;
1560 			if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(), NULL)) {
1561 				al = SSL_AD_INTERNAL_ERROR;
1562 				goto f_err;
1563 			}
1564 			EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1565 			    SSL3_RANDOM_SIZE);
1566 			EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1567 			    SSL3_RANDOM_SIZE);
1568 			EVP_DigestUpdate(&md_ctx, param, param_len);
1569 			EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1570 			q += i;
1571 			j += i;
1572 			i = RSA_verify(NID_md5_sha1, md_buf, j,
1573 			    p, n, pkey->pkey.rsa);
1574 			if (i < 0) {
1575 				al = SSL_AD_DECRYPT_ERROR;
1576 				SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
1577 				goto f_err;
1578 			}
1579 			if (i == 0) {
1580 				/* bad signature */
1581 				al = SSL_AD_DECRYPT_ERROR;
1582 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1583 				goto f_err;
1584 			}
1585 		} else {
1586 			EVP_VerifyInit_ex(&md_ctx, md, NULL);
1587 			EVP_VerifyUpdate(&md_ctx, s->s3->client_random,
1588 			    SSL3_RANDOM_SIZE);
1589 			EVP_VerifyUpdate(&md_ctx, s->s3->server_random,
1590 			    SSL3_RANDOM_SIZE);
1591 			EVP_VerifyUpdate(&md_ctx, param, param_len);
1592 			if (EVP_VerifyFinal(&md_ctx, p,(int)n, pkey) <= 0) {
1593 				/* bad signature */
1594 				al = SSL_AD_DECRYPT_ERROR;
1595 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1596 				goto f_err;
1597 			}
1598 		}
1599 	} else {
1600 		/* aNULL does not need public keys. */
1601 		if (!(alg_a & SSL_aNULL)) {
1602 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1603 			goto err;
1604 		}
1605 		/* still data left over */
1606 		if (n != 0) {
1607 			al = SSL_AD_DECODE_ERROR;
1608 			SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1609 			goto f_err;
1610 		}
1611 	}
1612 
1613 	EVP_PKEY_free(pkey);
1614 	EVP_MD_CTX_cleanup(&md_ctx);
1615 
1616 	return (1);
1617 
1618  truncated:
1619 	/* wrong packet length */
1620 	al = SSL_AD_DECODE_ERROR;
1621 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1622 
1623  f_err:
1624 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1625 
1626  err:
1627 	EVP_PKEY_free(pkey);
1628 	RSA_free(rsa);
1629 	EVP_MD_CTX_cleanup(&md_ctx);
1630 
1631 	return (-1);
1632 }
1633 
1634 int
1635 ssl3_get_certificate_request(SSL *s)
1636 {
1637 	int			 ok, ret = 0;
1638 	long		 	 n;
1639 	uint8_t			 ctype_num;
1640 	CBS			 cert_request, ctypes, rdn_list;
1641 	X509_NAME		*xn = NULL;
1642 	const unsigned char	*q;
1643 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1644 
1645 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1646 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1647 
1648 	if (!ok)
1649 		return ((int)n);
1650 
1651 	S3I(s)->tmp.cert_req = 0;
1652 
1653 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_DONE) {
1654 		S3I(s)->tmp.reuse_message = 1;
1655 		/*
1656 		 * If we get here we don't need any cached handshake records
1657 		 * as we wont be doing client auth.
1658 		 */
1659 		if (S3I(s)->handshake_buffer) {
1660 			if (!tls1_digest_cached_records(s))
1661 				goto err;
1662 		}
1663 		return (1);
1664 	}
1665 
1666 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1667 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1668 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1669 		goto err;
1670 	}
1671 
1672 	/* TLS does not like anon-DH with client cert */
1673 	if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
1674 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1675 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1676 		goto err;
1677 	}
1678 
1679 	if (n < 0)
1680 		goto truncated;
1681 	CBS_init(&cert_request, s->internal->init_msg, n);
1682 
1683 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1684 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1685 		goto err;
1686 	}
1687 
1688 	/* get the certificate types */
1689 	if (!CBS_get_u8(&cert_request, &ctype_num))
1690 		goto truncated;
1691 
1692 	if (ctype_num > SSL3_CT_NUMBER)
1693 		ctype_num = SSL3_CT_NUMBER;
1694 	if (!CBS_get_bytes(&cert_request, &ctypes, ctype_num) ||
1695 	    !CBS_write_bytes(&ctypes, (uint8_t *)S3I(s)->tmp.ctype,
1696 	    sizeof(S3I(s)->tmp.ctype), NULL)) {
1697 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1698 		goto err;
1699 	}
1700 
1701 	if (SSL_USE_SIGALGS(s)) {
1702 		CBS sigalgs;
1703 
1704 		if (CBS_len(&cert_request) < 2) {
1705 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1706 			goto err;
1707 		}
1708 
1709 		/* Check we have enough room for signature algorithms and
1710 		 * following length value.
1711 		 */
1712 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1713 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1714 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1715 			goto err;
1716 		}
1717 		if (!tls1_process_sigalgs(s, &sigalgs)) {
1718 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1719 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1720 			goto err;
1721 		}
1722 	}
1723 
1724 	/* get the CA RDNs */
1725 	if (CBS_len(&cert_request) < 2) {
1726 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1727 		goto err;
1728 	}
1729 
1730 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1731 	    CBS_len(&cert_request) != 0) {
1732 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1733 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1734 		goto err;
1735 	}
1736 
1737 	while (CBS_len(&rdn_list) > 0) {
1738 		CBS rdn;
1739 
1740 		if (CBS_len(&rdn_list) < 2) {
1741 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1742 			goto err;
1743 		}
1744 
1745 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1746 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1747 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1748 			goto err;
1749 		}
1750 
1751 		q = CBS_data(&rdn);
1752 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1753 			ssl3_send_alert(s, SSL3_AL_FATAL,
1754 			    SSL_AD_DECODE_ERROR);
1755 			SSLerror(s, ERR_R_ASN1_LIB);
1756 			goto err;
1757 		}
1758 
1759 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1760 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1761 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1762 			goto err;
1763 		}
1764 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1765 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1766 			goto err;
1767 		}
1768 		xn = NULL;	/* avoid free in err block */
1769 	}
1770 
1771 	/* we should setup a certificate to return.... */
1772 	S3I(s)->tmp.cert_req = 1;
1773 	S3I(s)->tmp.ctype_num = ctype_num;
1774 	sk_X509_NAME_pop_free(S3I(s)->tmp.ca_names, X509_NAME_free);
1775 	S3I(s)->tmp.ca_names = ca_sk;
1776 	ca_sk = NULL;
1777 
1778 	ret = 1;
1779 	if (0) {
1780 truncated:
1781 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1782 	}
1783 err:
1784 	X509_NAME_free(xn);
1785 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1786 	return (ret);
1787 }
1788 
1789 static int
1790 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1791 {
1792 	return (X509_NAME_cmp(*a, *b));
1793 }
1794 
1795 int
1796 ssl3_get_new_session_ticket(SSL *s)
1797 {
1798 	int			 ok, al, ret = 0;
1799 	uint32_t		 lifetime_hint;
1800 	long			 n;
1801 	CBS			 cbs, session_ticket;
1802 
1803 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1804 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1805 	if (!ok)
1806 		return ((int)n);
1807 
1808 	if (S3I(s)->tmp.message_type == SSL3_MT_FINISHED) {
1809 		S3I(s)->tmp.reuse_message = 1;
1810 		return (1);
1811 	}
1812 	if (S3I(s)->tmp.message_type != SSL3_MT_NEWSESSION_TICKET) {
1813 		al = SSL_AD_UNEXPECTED_MESSAGE;
1814 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1815 		goto f_err;
1816 	}
1817 
1818 	if (n < 0) {
1819 		al = SSL_AD_DECODE_ERROR;
1820 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1821 		goto f_err;
1822 	}
1823 
1824 	CBS_init(&cbs, s->internal->init_msg, n);
1825 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1826 #if UINT32_MAX > LONG_MAX
1827 	    lifetime_hint > LONG_MAX ||
1828 #endif
1829 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1830 	    CBS_len(&cbs) != 0) {
1831 		al = SSL_AD_DECODE_ERROR;
1832 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1833 		goto f_err;
1834 	}
1835 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1836 
1837 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1838 	    &s->session->tlsext_ticklen)) {
1839 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1840 		goto err;
1841 	}
1842 
1843 	/*
1844 	 * There are two ways to detect a resumed ticket sesion.
1845 	 * One is to set an appropriate session ID and then the server
1846 	 * must return a match in ServerHello. This allows the normal
1847 	 * client session ID matching to work and we know much
1848 	 * earlier that the ticket has been accepted.
1849 	 *
1850 	 * The other way is to set zero length session ID when the
1851 	 * ticket is presented and rely on the handshake to determine
1852 	 * session resumption.
1853 	 *
1854 	 * We choose the former approach because this fits in with
1855 	 * assumptions elsewhere in OpenSSL. The session ID is set
1856 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1857 	 * ticket.
1858 	 */
1859 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1860 	    s->session->session_id, &s->session->session_id_length,
1861 	    EVP_sha256(), NULL);
1862 	ret = 1;
1863 	return (ret);
1864 f_err:
1865 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1866 err:
1867 	return (-1);
1868 }
1869 
1870 int
1871 ssl3_get_cert_status(SSL *s)
1872 {
1873 	CBS			 cert_status, response;
1874 	size_t			 stow_len;
1875 	int			 ok, al;
1876 	long			 n;
1877 	uint8_t			 status_type;
1878 
1879 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1880 	    SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS,
1881 	    16384, &ok);
1882 
1883 	if (!ok)
1884 		return ((int)n);
1885 
1886 	if (n < 0) {
1887 		/* need at least status type + length */
1888 		al = SSL_AD_DECODE_ERROR;
1889 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1890 		goto f_err;
1891 	}
1892 
1893 	CBS_init(&cert_status, s->internal->init_msg, n);
1894 	if (!CBS_get_u8(&cert_status, &status_type) ||
1895 	    CBS_len(&cert_status) < 3) {
1896 		/* need at least status type + length */
1897 		al = SSL_AD_DECODE_ERROR;
1898 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1899 		goto f_err;
1900 	}
1901 
1902 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1903 		al = SSL_AD_DECODE_ERROR;
1904 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1905 		goto f_err;
1906 	}
1907 
1908 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1909 	    CBS_len(&cert_status) != 0) {
1910 		al = SSL_AD_DECODE_ERROR;
1911 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1912 		goto f_err;
1913 	}
1914 
1915 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1916 	    &stow_len) || stow_len > INT_MAX) {
1917 		s->internal->tlsext_ocsp_resplen = 0;
1918  		al = SSL_AD_INTERNAL_ERROR;
1919  		SSLerror(s, ERR_R_MALLOC_FAILURE);
1920  		goto f_err;
1921  	}
1922 	s->internal->tlsext_ocsp_resplen = (int)stow_len;
1923 
1924 	if (s->ctx->internal->tlsext_status_cb) {
1925 		int ret;
1926 		ret = s->ctx->internal->tlsext_status_cb(s,
1927 		    s->ctx->internal->tlsext_status_arg);
1928 		if (ret == 0) {
1929 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1930 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1931 			goto f_err;
1932 		}
1933 		if (ret < 0) {
1934 			al = SSL_AD_INTERNAL_ERROR;
1935 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1936 			goto f_err;
1937 		}
1938 	}
1939 	return (1);
1940 f_err:
1941 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1942 	return (-1);
1943 }
1944 
1945 int
1946 ssl3_get_server_done(SSL *s)
1947 {
1948 	int	ok, ret = 0;
1949 	long	n;
1950 
1951 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1952 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1953 	    30, /* should be very small, like 0 :-) */ &ok);
1954 
1955 	if (!ok)
1956 		return ((int)n);
1957 	if (n > 0) {
1958 		/* should contain no data */
1959 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1960 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1961 		return (-1);
1962 	}
1963 	ret = 1;
1964 	return (ret);
1965 }
1966 
1967 static int
1968 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1969 {
1970 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1971 	unsigned char *enc_pms = NULL;
1972 	EVP_PKEY *pkey = NULL;
1973 	int ret = -1;
1974 	int enc_len;
1975 	CBB epms;
1976 
1977 	/*
1978 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1979 	 */
1980 
1981 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1982 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1983 	    pkey->pkey.rsa == NULL) {
1984 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1985 		goto err;
1986 	}
1987 
1988 	pms[0] = s->client_version >> 8;
1989 	pms[1] = s->client_version & 0xff;
1990 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1991 
1992 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1993 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1994 		goto err;
1995 	}
1996 
1997 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1998 	    RSA_PKCS1_PADDING);
1999 	if (enc_len <= 0) {
2000 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
2001 		goto err;
2002 	}
2003 
2004 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
2005 		goto err;
2006 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
2007 		goto err;
2008 	if (!CBB_flush(cbb))
2009 		goto err;
2010 
2011 	s->session->master_key_length =
2012 	    tls1_generate_master_secret(s,
2013 		s->session->master_key, pms, sizeof(pms));
2014 
2015 	ret = 1;
2016 
2017 err:
2018 	explicit_bzero(pms, sizeof(pms));
2019 	EVP_PKEY_free(pkey);
2020 	free(enc_pms);
2021 
2022 	return (ret);
2023 }
2024 
2025 static int
2026 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2027 {
2028 	DH *dh_srvr = NULL, *dh_clnt = NULL;
2029 	unsigned char *key = NULL;
2030 	int key_size = 0, key_len;
2031 	unsigned char *data;
2032 	int ret = -1;
2033 	CBB dh_Yc;
2034 
2035 	/* Ensure that we have an ephemeral key for DHE. */
2036 	if (sess_cert->peer_dh_tmp == NULL) {
2037 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2038 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2039 		goto err;
2040 	}
2041 	dh_srvr = sess_cert->peer_dh_tmp;
2042 
2043 	/* Generate a new random key. */
2044 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
2045 		SSLerror(s, ERR_R_DH_LIB);
2046 		goto err;
2047 	}
2048 	if (!DH_generate_key(dh_clnt)) {
2049 		SSLerror(s, ERR_R_DH_LIB);
2050 		goto err;
2051 	}
2052 	key_size = DH_size(dh_clnt);
2053 	if ((key = malloc(key_size)) == NULL) {
2054 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2055 		goto err;
2056 	}
2057 	key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt);
2058 	if (key_len <= 0) {
2059 		SSLerror(s, ERR_R_DH_LIB);
2060 		goto err;
2061 	}
2062 
2063 	/* Generate master key from the result. */
2064 	s->session->master_key_length =
2065 	    tls1_generate_master_secret(s,
2066 		s->session->master_key, key, key_len);
2067 
2068 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
2069 		goto err;
2070 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
2071 		goto err;
2072 	BN_bn2bin(dh_clnt->pub_key, data);
2073 	if (!CBB_flush(cbb))
2074 		goto err;
2075 
2076 	ret = 1;
2077 
2078 err:
2079 	DH_free(dh_clnt);
2080 	freezero(key, key_size);
2081 
2082 	return (ret);
2083 }
2084 
2085 static int
2086 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2087 {
2088 	const EC_GROUP *group = NULL;
2089 	const EC_POINT *point = NULL;
2090 	EC_KEY *ecdh = NULL;
2091 	BN_CTX *bn_ctx = NULL;
2092 	unsigned char *key = NULL;
2093 	unsigned char *data;
2094 	size_t encoded_len;
2095 	int key_size = 0, key_len;
2096 	int ret = -1;
2097 	CBB ecpoint;
2098 
2099 	if ((group = EC_KEY_get0_group(sc->peer_ecdh_tmp)) == NULL ||
2100 	    (point = EC_KEY_get0_public_key(sc->peer_ecdh_tmp)) == NULL) {
2101 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2102 		goto err;
2103 	}
2104 
2105 	if ((ecdh = EC_KEY_new()) == NULL) {
2106 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2107 		goto err;
2108 	}
2109 
2110 	if (!EC_KEY_set_group(ecdh, group)) {
2111 		SSLerror(s, ERR_R_EC_LIB);
2112 		goto err;
2113 	}
2114 
2115 	/* Generate a new ECDH key pair. */
2116 	if (!EC_KEY_generate_key(ecdh)) {
2117 		SSLerror(s, ERR_R_ECDH_LIB);
2118 		goto err;
2119 	}
2120 	if ((key_size = ECDH_size(ecdh)) <= 0) {
2121 		SSLerror(s, ERR_R_ECDH_LIB);
2122 		goto err;
2123 	}
2124 	if ((key = malloc(key_size)) == NULL) {
2125 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2126 		goto err;
2127 	}
2128 	key_len = ECDH_compute_key(key, key_size, point, ecdh, NULL);
2129 	if (key_len <= 0) {
2130 		SSLerror(s, ERR_R_ECDH_LIB);
2131 		goto err;
2132 	}
2133 
2134 	/* Generate master key from the result. */
2135 	s->session->master_key_length =
2136 	    tls1_generate_master_secret(s,
2137 		s->session->master_key, key, key_len);
2138 
2139 	encoded_len = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2140 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
2141 	if (encoded_len == 0) {
2142 		SSLerror(s, ERR_R_ECDH_LIB);
2143 		goto err;
2144 	}
2145 
2146 	if ((bn_ctx = BN_CTX_new()) == NULL) {
2147 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2148 		goto err;
2149 	}
2150 
2151 	/* Encode the public key. */
2152 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2153 		goto err;
2154 	if (!CBB_add_space(&ecpoint, &data, encoded_len))
2155 		goto err;
2156 	if (EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2157 	    POINT_CONVERSION_UNCOMPRESSED, data, encoded_len,
2158 	    bn_ctx) == 0)
2159 		goto err;
2160 	if (!CBB_flush(cbb))
2161 		goto err;
2162 
2163 	ret = 1;
2164 
2165  err:
2166 	freezero(key, key_size);
2167 
2168 	BN_CTX_free(bn_ctx);
2169 	EC_KEY_free(ecdh);
2170 
2171 	return (ret);
2172 }
2173 
2174 static int
2175 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2176 {
2177 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2178 	int ret = -1;
2179 	CBB ecpoint;
2180 
2181 	/* Generate X25519 key pair and derive shared key. */
2182 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2183 		goto err;
2184 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2185 		goto err;
2186 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2187 		goto err;
2188 	X25519_keypair(public_key, private_key);
2189 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2190 		goto err;
2191 
2192 	/* Serialize the public key. */
2193 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2194 		goto err;
2195 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2196 		goto err;
2197 	if (!CBB_flush(cbb))
2198 		goto err;
2199 
2200 	/* Generate master key from the result. */
2201 	s->session->master_key_length =
2202 	    tls1_generate_master_secret(s,
2203 		s->session->master_key, shared_key, X25519_KEY_LENGTH);
2204 
2205 	ret = 1;
2206 
2207  err:
2208 	free(public_key);
2209 	freezero(private_key, X25519_KEY_LENGTH);
2210 	freezero(shared_key, X25519_KEY_LENGTH);
2211 
2212 	return (ret);
2213 }
2214 
2215 static int
2216 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2217 {
2218 	if (sc->peer_x25519_tmp != NULL) {
2219 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2220 			goto err;
2221 	} else if (sc->peer_ecdh_tmp != NULL) {
2222 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2223 			goto err;
2224 	} else {
2225 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2226 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2227 		goto err;
2228 	}
2229 
2230 	return (1);
2231 
2232  err:
2233 	return (-1);
2234 }
2235 
2236 static int
2237 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2238 {
2239 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2240 	EVP_PKEY *pub_key = NULL;
2241 	EVP_PKEY_CTX *pkey_ctx;
2242 	X509 *peer_cert;
2243 	size_t msglen;
2244 	unsigned int md_len;
2245 	EVP_MD_CTX *ukm_hash;
2246 	int ret = -1;
2247 	int nid;
2248 	CBB gostblob;
2249 
2250 	/* Get server sertificate PKEY and create ctx from it */
2251 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2252 	if (peer_cert == NULL) {
2253 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2254 		goto err;
2255 	}
2256 
2257 	pub_key = X509_get_pubkey(peer_cert);
2258 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2259 
2260 	/*
2261 	 * If we have send a certificate, and certificate key parameters match
2262 	 * those of server certificate, use certificate key for key exchange.
2263 	 * Otherwise, generate ephemeral key pair.
2264 	 */
2265 	EVP_PKEY_encrypt_init(pkey_ctx);
2266 
2267 	/* Generate session key. */
2268 	arc4random_buf(premaster_secret, 32);
2269 
2270 	/*
2271 	 * If we have client certificate, use its secret as peer key.
2272 	 */
2273 	if (S3I(s)->tmp.cert_req && s->cert->key->privatekey) {
2274 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2275 		    s->cert->key->privatekey) <=0) {
2276 			/*
2277 			 * If there was an error - just ignore it.
2278 			 * Ephemeral key would be used.
2279 			 */
2280 			ERR_clear_error();
2281 		}
2282 	}
2283 
2284 	/*
2285 	 * Compute shared IV and store it in algorithm-specific context data.
2286 	 */
2287 	ukm_hash = EVP_MD_CTX_create();
2288 	if (ukm_hash == NULL) {
2289 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2290 		goto err;
2291 	}
2292 
2293 	if (ssl_get_algorithm2(s) & SSL_HANDSHAKE_MAC_GOST94)
2294 		nid = NID_id_GostR3411_94;
2295 	else
2296 		nid = NID_id_tc26_gost3411_2012_256;
2297 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2298 		goto err;
2299 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2300 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2301 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2302 	EVP_MD_CTX_destroy(ukm_hash);
2303 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2304 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2305 		SSLerror(s, SSL_R_LIBRARY_BUG);
2306 		goto err;
2307 	}
2308 
2309 	/*
2310 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2311 	 */
2312 	msglen = 255;
2313 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2314 	    32) < 0) {
2315 		SSLerror(s, SSL_R_LIBRARY_BUG);
2316 		goto err;
2317 	}
2318 
2319 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2320 		goto err;
2321 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2322 		goto err;
2323 	if (!CBB_flush(cbb))
2324 		goto err;
2325 
2326 	/* Check if pubkey from client certificate was used. */
2327 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2328 	    NULL) > 0) {
2329 		/* Set flag "skip certificate verify". */
2330 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2331 	}
2332 	EVP_PKEY_CTX_free(pkey_ctx);
2333 	s->session->master_key_length =
2334 	    tls1_generate_master_secret(s,
2335 		s->session->master_key, premaster_secret, 32);
2336 
2337 	ret = 1;
2338 
2339  err:
2340 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2341 	EVP_PKEY_free(pub_key);
2342 
2343 	return (ret);
2344 }
2345 
2346 int
2347 ssl3_send_client_key_exchange(SSL *s)
2348 {
2349 	SESS_CERT *sess_cert;
2350 	unsigned long alg_k;
2351 	CBB cbb, kex;
2352 
2353 	memset(&cbb, 0, sizeof(cbb));
2354 
2355 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2356 		alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2357 
2358 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2359 			ssl3_send_alert(s, SSL3_AL_FATAL,
2360 			    SSL_AD_UNEXPECTED_MESSAGE);
2361 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2362 			goto err;
2363 		}
2364 
2365 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &kex,
2366 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2367 			goto err;
2368 
2369 		if (alg_k & SSL_kRSA) {
2370 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2371 				goto err;
2372 		} else if (alg_k & SSL_kDHE) {
2373 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2374 				goto err;
2375 		} else if (alg_k & SSL_kECDHE) {
2376 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2377 				goto err;
2378 		} else if (alg_k & SSL_kGOST) {
2379 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2380 				goto err;
2381 		} else {
2382 			ssl3_send_alert(s, SSL3_AL_FATAL,
2383 			    SSL_AD_HANDSHAKE_FAILURE);
2384 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2385 			goto err;
2386 		}
2387 
2388 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2389 			goto err;
2390 
2391 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2392 	}
2393 
2394 	/* SSL3_ST_CW_KEY_EXCH_B */
2395 	return (ssl3_handshake_write(s));
2396 
2397 err:
2398 	CBB_cleanup(&cbb);
2399 
2400 	return (-1);
2401 }
2402 
2403 int
2404 ssl3_send_client_verify(SSL *s)
2405 {
2406 	unsigned char	*p;
2407 	unsigned char	 data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2408 	EVP_PKEY	*pkey;
2409 	EVP_PKEY_CTX	*pctx = NULL;
2410 	EVP_MD_CTX	 mctx;
2411 	unsigned	 u = 0;
2412 	unsigned long	 n;
2413 	int		 j;
2414 
2415 	EVP_MD_CTX_init(&mctx);
2416 
2417 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2418 		p = ssl3_handshake_msg_start(s, SSL3_MT_CERTIFICATE_VERIFY);
2419 
2420 		/*
2421 		 * Create context from key and test if sha1 is allowed as
2422 		 * digest.
2423 		 */
2424 		pkey = s->cert->key->privatekey;
2425 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2426 		EVP_PKEY_sign_init(pctx);
2427 
2428 		/* XXX - is this needed? */
2429 		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) <= 0)
2430 			ERR_clear_error();
2431 
2432 		if (!SSL_USE_SIGALGS(s)) {
2433 			if (S3I(s)->handshake_buffer) {
2434 				if (!tls1_digest_cached_records(s))
2435 					goto err;
2436 			}
2437 			if (!tls1_handshake_hash_value(s, data, sizeof(data),
2438 			    NULL))
2439 				goto err;
2440 		}
2441 
2442 		/*
2443 		 * For TLS v1.2 send signature algorithm and signature
2444 		 * using agreed digest and cached handshake records.
2445 		 */
2446 		if (SSL_USE_SIGALGS(s)) {
2447 			long hdatalen = 0;
2448 			void *hdata;
2449 			const EVP_MD *md = s->cert->key->digest;
2450 			hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer,
2451 			    &hdata);
2452 			if (hdatalen <= 0 ||
2453 			    !tls12_get_sigandhash(p, pkey, md)) {
2454 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2455 				goto err;
2456 			}
2457 			p += 2;
2458 			if (!EVP_SignInit_ex(&mctx, md, NULL) ||
2459 			    !EVP_SignUpdate(&mctx, hdata, hdatalen) ||
2460 			    !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2461 				SSLerror(s, ERR_R_EVP_LIB);
2462 				goto err;
2463 			}
2464 			s2n(u, p);
2465 			n = u + 4;
2466 			if (!tls1_digest_cached_records(s))
2467 				goto err;
2468 		} else if (pkey->type == EVP_PKEY_RSA) {
2469 			if (RSA_sign(NID_md5_sha1, data,
2470 			    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, &(p[2]),
2471 			    &u, pkey->pkey.rsa) <= 0 ) {
2472 				SSLerror(s, ERR_R_RSA_LIB);
2473 				goto err;
2474 			}
2475 			s2n(u, p);
2476 			n = u + 2;
2477 		} else if (pkey->type == EVP_PKEY_EC) {
2478 			if (!ECDSA_sign(pkey->save_type,
2479 			    &(data[MD5_DIGEST_LENGTH]),
2480 			    SHA_DIGEST_LENGTH, &(p[2]),
2481 			    (unsigned int *)&j, pkey->pkey.ec)) {
2482 				SSLerror(s, ERR_R_ECDSA_LIB);
2483 				goto err;
2484 			}
2485 			s2n(j, p);
2486 			n = j + 2;
2487 #ifndef OPENSSL_NO_GOST
2488 		} else if (pkey->type == NID_id_GostR3410_94 ||
2489 			   pkey->type == NID_id_GostR3410_2001) {
2490 			unsigned char signbuf[128];
2491 			long hdatalen = 0;
2492 			void *hdata;
2493 			const EVP_MD *md;
2494 			int nid;
2495 			size_t sigsize;
2496 
2497 			hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2498 			if (hdatalen <= 0) {
2499 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2500 				goto err;
2501 			}
2502 			if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2503 			    !(md = EVP_get_digestbynid(nid))) {
2504 				SSLerror(s, ERR_R_EVP_LIB);
2505 				goto err;
2506 			}
2507 			if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2508 			    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2509 			    !EVP_DigestFinal(&mctx, signbuf, &u) ||
2510 			    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2511 			    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_SIGN,
2512 					       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2513 					       GOST_SIG_FORMAT_RS_LE,
2514 					       NULL) <= 0) ||
2515 			    (EVP_PKEY_sign(pctx, &(p[2]), &sigsize,
2516 					   signbuf, u) <= 0)) {
2517 				SSLerror(s, ERR_R_EVP_LIB);
2518 				goto err;
2519 			}
2520 			if (!tls1_digest_cached_records(s))
2521 				goto err;
2522 			j = sigsize;
2523 			s2n(j, p);
2524 			n = j + 2;
2525 #endif
2526 		} else {
2527 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2528 			goto err;
2529 		}
2530 
2531 		S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_B;
2532 
2533 		ssl3_handshake_msg_finish(s, n);
2534 	}
2535 
2536 	EVP_MD_CTX_cleanup(&mctx);
2537 	EVP_PKEY_CTX_free(pctx);
2538 
2539 	return (ssl3_handshake_write(s));
2540 
2541 err:
2542 	EVP_MD_CTX_cleanup(&mctx);
2543 	EVP_PKEY_CTX_free(pctx);
2544 	return (-1);
2545 }
2546 
2547 int
2548 ssl3_send_client_certificate(SSL *s)
2549 {
2550 	EVP_PKEY *pkey = NULL;
2551 	X509 *x509 = NULL;
2552 	CBB cbb, client_cert;
2553 	int i;
2554 
2555 	memset(&cbb, 0, sizeof(cbb));
2556 
2557 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2558 		if ((s->cert == NULL) || (s->cert->key->x509 == NULL) ||
2559 		    (s->cert->key->privatekey == NULL))
2560 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2561 		else
2562 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2563 	}
2564 
2565 	/* We need to get a client cert */
2566 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_B) {
2567 		/*
2568 		 * If we get an error, we need to
2569 		 * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2570 		 * We then get retied later
2571 		 */
2572 		i = ssl_do_client_cert_cb(s, &x509, &pkey);
2573 		if (i < 0) {
2574 			s->internal->rwstate = SSL_X509_LOOKUP;
2575 			return (-1);
2576 		}
2577 		s->internal->rwstate = SSL_NOTHING;
2578 		if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
2579 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2580 			if (!SSL_use_certificate(s, x509) ||
2581 			    !SSL_use_PrivateKey(s, pkey))
2582 				i = 0;
2583 		} else if (i == 1) {
2584 			i = 0;
2585 			SSLerror(s, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2586 		}
2587 
2588 		X509_free(x509);
2589 		EVP_PKEY_free(pkey);
2590 		if (i == 0)
2591 			S3I(s)->tmp.cert_req = 2;
2592 
2593 		/* Ok, we have a cert */
2594 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2595 	}
2596 
2597 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_C) {
2598 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &client_cert,
2599 		    SSL3_MT_CERTIFICATE))
2600 			goto err;
2601 		if (!ssl3_output_cert_chain(s, &client_cert,
2602 		    (S3I(s)->tmp.cert_req == 2) ? NULL : s->cert->key->x509))
2603 			goto err;
2604 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2605 			goto err;
2606 
2607 		S3I(s)->hs.state = SSL3_ST_CW_CERT_D;
2608 	}
2609 
2610 	/* SSL3_ST_CW_CERT_D */
2611 	return (ssl3_handshake_write(s));
2612 
2613  err:
2614 	CBB_cleanup(&cbb);
2615 
2616 	return (0);
2617 }
2618 
2619 #define has_bits(i,m)	(((i)&(m)) == (m))
2620 
2621 int
2622 ssl3_check_cert_and_algorithm(SSL *s)
2623 {
2624 	int		 i, idx;
2625 	long		 alg_k, alg_a;
2626 	EVP_PKEY	*pkey = NULL;
2627 	SESS_CERT	*sc;
2628 	DH		*dh;
2629 
2630 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2631 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2632 
2633 	/* We don't have a certificate. */
2634 	if (alg_a & SSL_aNULL)
2635 		return (1);
2636 
2637 	sc = SSI(s)->sess_cert;
2638 	if (sc == NULL) {
2639 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2640 		goto err;
2641 	}
2642 	dh = SSI(s)->sess_cert->peer_dh_tmp;
2643 
2644 	/* This is the passed certificate. */
2645 
2646 	idx = sc->peer_cert_type;
2647 	if (idx == SSL_PKEY_ECC) {
2648 		if (ssl_check_srvr_ecc_cert_and_alg(
2649 		    sc->peer_pkeys[idx].x509, s) == 0) {
2650 			/* check failed */
2651 			SSLerror(s, SSL_R_BAD_ECC_CERT);
2652 			goto f_err;
2653 		} else {
2654 			return (1);
2655 		}
2656 	}
2657 	pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509);
2658 	i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey);
2659 	EVP_PKEY_free(pkey);
2660 
2661 	/* Check that we have a certificate if we require one. */
2662 	if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_SIGN)) {
2663 		SSLerror(s, SSL_R_MISSING_RSA_SIGNING_CERT);
2664 		goto f_err;
2665 	}
2666 	if ((alg_k & SSL_kRSA) && !has_bits(i, EVP_PK_RSA|EVP_PKT_ENC)) {
2667 		SSLerror(s, SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2668 		goto f_err;
2669 	}
2670 	if ((alg_k & SSL_kDHE) &&
2671 	    !(has_bits(i, EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) {
2672 		SSLerror(s, SSL_R_MISSING_DH_KEY);
2673 		goto f_err;
2674 	}
2675 
2676 	return (1);
2677 f_err:
2678 	ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2679 err:
2680 	return (0);
2681 }
2682 
2683 /*
2684  * Check to see if handshake is full or resumed. Usually this is just a
2685  * case of checking to see if a cache hit has occurred. In the case of
2686  * session tickets we have to check the next message to be sure.
2687  */
2688 
2689 int
2690 ssl3_check_finished(SSL *s)
2691 {
2692 	int	ok;
2693 	long	n;
2694 
2695 	/* If we have no ticket it cannot be a resumed session. */
2696 	if (!s->session->tlsext_tick)
2697 		return (1);
2698 	/* this function is called when we really expect a Certificate
2699 	 * message, so permit appropriate message length */
2700 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_A,
2701 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2702 	if (!ok)
2703 		return ((int)n);
2704 	S3I(s)->tmp.reuse_message = 1;
2705 	if ((S3I(s)->tmp.message_type == SSL3_MT_FINISHED) ||
2706 	    (S3I(s)->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2707 		return (2);
2708 
2709 	return (1);
2710 }
2711 
2712 int
2713 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2714 {
2715 	int	i = 0;
2716 
2717 #ifndef OPENSSL_NO_ENGINE
2718 	if (s->ctx->internal->client_cert_engine) {
2719 		i = ENGINE_load_ssl_client_cert(
2720 		    s->ctx->internal->client_cert_engine, s,
2721 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2722 		if (i != 0)
2723 			return (i);
2724 	}
2725 #endif
2726 	if (s->ctx->internal->client_cert_cb)
2727 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2728 	return (i);
2729 }
2730