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