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