xref: /openbsd/lib/libssl/ssl_clnt.c (revision 6f40fd34)
1 /* $OpenBSD: ssl_clnt.c,v 1.14 2017/05/07 04:22:24 beck 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 = S3I(s)->hs.state;
197 
198 		switch (S3I(s)->hs.state) {
199 		case SSL_ST_RENEGOTIATE:
200 			s->internal->renegotiate = 1;
201 			S3I(s)->hs.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 			S3I(s)->hs.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 			S3I(s)->hs.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 				S3I(s)->hs.state = SSL3_ST_CR_FINISHED_A;
271 				if (s->internal->tlsext_ticket_expected) {
272 					/* receive renewed session ticket */
273 					S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
274 				}
275 			} else
276 				S3I(s)->hs.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 					S3I(s)->hs.state = SSL3_ST_CR_SESSION_TICKET_A;
289 				else
290 					S3I(s)->hs.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)->hs.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 					S3I(s)->hs.state = SSL3_ST_CR_CERT_STATUS_A;
302 				else
303 					S3I(s)->hs.state = SSL3_ST_CR_KEY_EXCH_A;
304 			} else {
305 				skip = 1;
306 				S3I(s)->hs.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 			S3I(s)->hs.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 			S3I(s)->hs.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 				S3I(s)->hs.state = SSL3_ST_CW_CERT_A;
345 			else
346 				S3I(s)->hs.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 			S3I(s)->hs.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 				S3I(s)->hs.state = SSL3_ST_CW_CERT_VRFY_A;
385 			} else {
386 				S3I(s)->hs.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 				S3I(s)->hs.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 			S3I(s)->hs.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 				S3I(s)->hs.state = SSL3_ST_CW_NEXT_PROTO_A;
416 			else
417 				S3I(s)->hs.state = SSL3_ST_CW_FINISHED_A;
418 			s->internal->init_num = 0;
419 
420 			s->session->cipher = S3I(s)->hs.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 			S3I(s)->hs.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 			S3I(s)->hs.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)->hs.next_state = SSL_ST_OK;
457 				if (s->s3->flags &
458 				    SSL3_FLAGS_DELAY_CLIENT_FINISHED) {
459 					S3I(s)->hs.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)->hs.next_state =
467 					    SSL3_ST_CR_SESSION_TICKET_A;
468 				else
469 
470 				S3I(s)->hs.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 			S3I(s)->hs.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 			S3I(s)->hs.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 				S3I(s)->hs.state = SSL3_ST_CW_CHANGE_A;
503 			else
504 				S3I(s)->hs.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 			S3I(s)->hs.state = S3I(s)->hs.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) && (S3I(s)->hs.state != state)) {
567 				new_state = S3I(s)->hs.state;
568 				S3I(s)->hs.state = state;
569 				cb(s, SSL_CB_CONNECT_LOOP, 1);
570 				S3I(s)->hs.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 (S3I(s)->hs.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 		S3I(s)->hs.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)->hs.new_cipher = cipher;
903 
904 	if (!tls1_handshake_hash_init(s))
905 		goto err;
906 
907 	/*
908 	 * Don't digest cached records if no sigalgs: we may need them for
909 	 * client authentication.
910 	 */
911 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
912 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) &&
913 	    !tls1_digest_cached_records(s)) {
914 		al = SSL_AD_INTERNAL_ERROR;
915 		goto f_err;
916 	}
917 
918 	if (!CBS_get_u8(&cbs, &compression_method))
919 		goto truncated;
920 
921 	if (compression_method != 0) {
922 		al = SSL_AD_ILLEGAL_PARAMETER;
923 		SSLerror(s, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
924 		goto f_err;
925 	}
926 
927 	/* TLS extensions. */
928 	p = (unsigned char *)CBS_data(&cbs);
929 	if (!ssl_parse_serverhello_tlsext(s, &p, CBS_len(&cbs), &al)) {
930 		/* 'al' set by ssl_parse_serverhello_tlsext */
931 		SSLerror(s, SSL_R_PARSE_TLSEXT);
932 		goto f_err;
933 	}
934 	if (ssl_check_serverhello_tlsext(s) <= 0) {
935 		SSLerror(s, SSL_R_SERVERHELLO_TLSEXT);
936 		goto err;
937 	}
938 
939 	/* See if any data remains... */
940 	if (p - CBS_data(&cbs) != CBS_len(&cbs))
941 		goto truncated;
942 
943 	return (1);
944 
945 truncated:
946 	/* wrong packet length */
947 	al = SSL_AD_DECODE_ERROR;
948 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
949 f_err:
950 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
951 err:
952 	return (-1);
953 }
954 
955 int
956 ssl3_get_server_certificate(SSL *s)
957 {
958 	int			 al, i, ok, ret = -1;
959 	long			 n;
960 	CBS			 cbs, cert_list;
961 	X509			*x = NULL;
962 	const unsigned char	*q;
963 	STACK_OF(X509)		*sk = NULL;
964 	SESS_CERT		*sc;
965 	EVP_PKEY		*pkey = NULL;
966 
967 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_A,
968 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
969 
970 	if (!ok)
971 		return ((int)n);
972 
973 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) {
974 		S3I(s)->tmp.reuse_message = 1;
975 		return (1);
976 	}
977 
978 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
979 		al = SSL_AD_UNEXPECTED_MESSAGE;
980 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
981 		goto f_err;
982 	}
983 
984 
985 	if ((sk = sk_X509_new_null()) == NULL) {
986 		SSLerror(s, ERR_R_MALLOC_FAILURE);
987 		goto err;
988 	}
989 
990 	if (n < 0)
991 		goto truncated;
992 
993 	CBS_init(&cbs, s->internal->init_msg, n);
994 	if (CBS_len(&cbs) < 3)
995 		goto truncated;
996 
997 	if (!CBS_get_u24_length_prefixed(&cbs, &cert_list) ||
998 	    CBS_len(&cbs) != 0) {
999 		al = SSL_AD_DECODE_ERROR;
1000 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1001 		goto f_err;
1002 	}
1003 
1004 	while (CBS_len(&cert_list) > 0) {
1005 		CBS cert;
1006 
1007 		if (CBS_len(&cert_list) < 3)
1008 			goto truncated;
1009 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert)) {
1010 			al = SSL_AD_DECODE_ERROR;
1011 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1012 			goto f_err;
1013 		}
1014 
1015 		q = CBS_data(&cert);
1016 		x = d2i_X509(NULL, &q, CBS_len(&cert));
1017 		if (x == NULL) {
1018 			al = SSL_AD_BAD_CERTIFICATE;
1019 			SSLerror(s, ERR_R_ASN1_LIB);
1020 			goto f_err;
1021 		}
1022 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
1023 			al = SSL_AD_DECODE_ERROR;
1024 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
1025 			goto f_err;
1026 		}
1027 		if (!sk_X509_push(sk, x)) {
1028 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1029 			goto err;
1030 		}
1031 		x = NULL;
1032 	}
1033 
1034 	i = ssl_verify_cert_chain(s, sk);
1035 	if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)) {
1036 		al = ssl_verify_alarm_type(s->verify_result);
1037 		SSLerror(s, SSL_R_CERTIFICATE_VERIFY_FAILED);
1038 		goto f_err;
1039 
1040 	}
1041 	ERR_clear_error(); /* but we keep s->verify_result */
1042 
1043 	sc = ssl_sess_cert_new();
1044 	if (sc == NULL)
1045 		goto err;
1046 	ssl_sess_cert_free(SSI(s)->sess_cert);
1047 	SSI(s)->sess_cert = sc;
1048 
1049 	sc->cert_chain = sk;
1050 	/*
1051 	 * Inconsistency alert: cert_chain does include the peer's
1052 	 * certificate, which we don't include in s3_srvr.c
1053 	 */
1054 	x = sk_X509_value(sk, 0);
1055 	sk = NULL;
1056 	/* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1057 
1058 	pkey = X509_get_pubkey(x);
1059 
1060 	if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
1061 		x = NULL;
1062 		al = SSL3_AL_FATAL;
1063 		SSLerror(s, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1064 		goto f_err;
1065 	}
1066 
1067 	i = ssl_cert_type(x, pkey);
1068 	if (i < 0) {
1069 		x = NULL;
1070 		al = SSL3_AL_FATAL;
1071 		SSLerror(s, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1072 		goto f_err;
1073 	}
1074 
1075 	sc->peer_cert_type = i;
1076 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1077 	/*
1078 	 * Why would the following ever happen?
1079 	 * We just created sc a couple of lines ago.
1080 	 */
1081 	X509_free(sc->peer_pkeys[i].x509);
1082 	sc->peer_pkeys[i].x509 = x;
1083 	sc->peer_key = &(sc->peer_pkeys[i]);
1084 
1085 	X509_free(s->session->peer);
1086 	CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
1087 	s->session->peer = x;
1088 	s->session->verify_result = s->verify_result;
1089 
1090 	x = NULL;
1091 	ret = 1;
1092 
1093 	if (0) {
1094 truncated:
1095 		/* wrong packet length */
1096 		al = SSL_AD_DECODE_ERROR;
1097 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1098 f_err:
1099 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1100 	}
1101 err:
1102 	EVP_PKEY_free(pkey);
1103 	X509_free(x);
1104 	sk_X509_pop_free(sk, X509_free);
1105 
1106 	return (ret);
1107 }
1108 
1109 static int
1110 ssl3_get_server_kex_dhe(SSL *s, EVP_PKEY **pkey, unsigned char **pp, long *nn)
1111 {
1112 	CBS cbs, dhp, dhg, dhpk;
1113 	BN_CTX *bn_ctx = NULL;
1114 	SESS_CERT *sc = NULL;
1115 	DH *dh = NULL;
1116 	long alg_a;
1117 	int al;
1118 
1119 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1120 	sc = SSI(s)->sess_cert;
1121 
1122 	if (*nn < 0)
1123 		goto err;
1124 
1125 	CBS_init(&cbs, *pp, *nn);
1126 
1127 	if ((dh = DH_new()) == NULL) {
1128 		SSLerror(s, ERR_R_DH_LIB);
1129 		goto err;
1130 	}
1131 
1132 	if (!CBS_get_u16_length_prefixed(&cbs, &dhp))
1133 		goto truncated;
1134 	if ((dh->p = BN_bin2bn(CBS_data(&dhp), CBS_len(&dhp), NULL)) == NULL) {
1135 		SSLerror(s, ERR_R_BN_LIB);
1136 		goto err;
1137 	}
1138 
1139 	if (!CBS_get_u16_length_prefixed(&cbs, &dhg))
1140 		goto truncated;
1141 	if ((dh->g = BN_bin2bn(CBS_data(&dhg), CBS_len(&dhg), NULL)) == NULL) {
1142 		SSLerror(s, ERR_R_BN_LIB);
1143 		goto err;
1144 	}
1145 
1146 	if (!CBS_get_u16_length_prefixed(&cbs, &dhpk))
1147 		goto truncated;
1148 	if ((dh->pub_key = BN_bin2bn(CBS_data(&dhpk), CBS_len(&dhpk),
1149 	    NULL)) == NULL) {
1150 		SSLerror(s, ERR_R_BN_LIB);
1151 		goto err;
1152 	}
1153 
1154 	/*
1155 	 * Check the strength of the DH key just constructed.
1156 	 * Discard keys weaker than 1024 bits.
1157 	 */
1158 	if (DH_size(dh) < 1024 / 8) {
1159 		SSLerror(s, SSL_R_BAD_DH_P_LENGTH);
1160 		goto err;
1161 	}
1162 
1163 	if (alg_a & SSL_aRSA)
1164 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1165 	else if (alg_a & SSL_aDSS)
1166 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1167 	else
1168 		/* XXX - Anonymous DH, so no certificate or pkey. */
1169 		*pkey = NULL;
1170 
1171 	sc->peer_dh_tmp = dh;
1172 
1173 	*nn = CBS_len(&cbs);
1174 	*pp = (unsigned char *)CBS_data(&cbs);
1175 
1176 	return (1);
1177 
1178  truncated:
1179 	al = SSL_AD_DECODE_ERROR;
1180 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1181 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1182 
1183  err:
1184 	DH_free(dh);
1185 	BN_CTX_free(bn_ctx);
1186 
1187 	return (-1);
1188 }
1189 
1190 static int
1191 ssl3_get_server_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1192 {
1193 	const EC_GROUP *group;
1194 	EC_GROUP *ngroup = NULL;
1195 	EC_POINT *point = NULL;
1196 	BN_CTX *bn_ctx = NULL;
1197 	EC_KEY *ecdh = NULL;
1198 	int ret = -1;
1199 
1200 	/*
1201 	 * Extract the server's ephemeral ECDH public key.
1202 	 */
1203 
1204 	if ((ecdh = EC_KEY_new()) == NULL) {
1205 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1206 		goto err;
1207 	}
1208 
1209 	if ((ngroup = EC_GROUP_new_by_curve_name(nid)) == NULL) {
1210 		SSLerror(s, ERR_R_EC_LIB);
1211 		goto err;
1212 	}
1213 	if (EC_KEY_set_group(ecdh, ngroup) == 0) {
1214 		SSLerror(s, ERR_R_EC_LIB);
1215 		goto err;
1216 	}
1217 
1218 	group = EC_KEY_get0_group(ecdh);
1219 
1220 	if ((point = EC_POINT_new(group)) == NULL ||
1221 	    (bn_ctx = BN_CTX_new()) == NULL) {
1222 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1223 		goto err;
1224 	}
1225 
1226 	if (EC_POINT_oct2point(group, point, CBS_data(public),
1227 	    CBS_len(public), bn_ctx) == 0) {
1228 		SSLerror(s, SSL_R_BAD_ECPOINT);
1229 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1230 		goto err;
1231 	}
1232 
1233 	EC_KEY_set_public_key(ecdh, point);
1234 	sc->peer_ecdh_tmp = ecdh;
1235 	ecdh = NULL;
1236 
1237 	ret = 1;
1238 
1239  err:
1240 	BN_CTX_free(bn_ctx);
1241 	EC_GROUP_free(ngroup);
1242 	EC_POINT_free(point);
1243 	EC_KEY_free(ecdh);
1244 
1245 	return (ret);
1246 }
1247 
1248 static int
1249 ssl3_get_server_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, int nid, CBS *public)
1250 {
1251 	size_t outlen;
1252 
1253 	if (nid != NID_X25519) {
1254 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1255 		goto err;
1256 	}
1257 
1258 	if (CBS_len(public) != X25519_KEY_LENGTH) {
1259 		SSLerror(s, SSL_R_BAD_ECPOINT);
1260 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1261 		goto err;
1262 	}
1263 
1264 	if (!CBS_stow(public, &sc->peer_x25519_tmp, &outlen)) {
1265 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1266 		goto err;
1267 	}
1268 
1269 	return (1);
1270 
1271  err:
1272 	return (-1);
1273 }
1274 
1275 static int
1276 ssl3_get_server_kex_ecdhe(SSL *s, EVP_PKEY **pkey, unsigned char **pp, long *nn)
1277 {
1278 	CBS cbs, public;
1279 	uint8_t curve_type;
1280 	uint16_t curve_id;
1281 	SESS_CERT *sc;
1282 	long alg_a;
1283 	int nid;
1284 	int al;
1285 
1286 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1287 	sc = SSI(s)->sess_cert;
1288 
1289 	if (*nn < 0)
1290 		goto err;
1291 
1292 	CBS_init(&cbs, *pp, *nn);
1293 
1294 	/* Only named curves are supported. */
1295 	if (!CBS_get_u8(&cbs, &curve_type) ||
1296 	    curve_type != NAMED_CURVE_TYPE ||
1297 	    !CBS_get_u16(&cbs, &curve_id)) {
1298 		al = SSL_AD_DECODE_ERROR;
1299 		SSLerror(s, SSL_R_LENGTH_TOO_SHORT);
1300 		goto f_err;
1301 	}
1302 
1303 	/*
1304 	 * Check that the curve is one of our preferences - if it is not,
1305 	 * the server has sent us an invalid curve.
1306 	 */
1307 	if (tls1_check_curve(s, curve_id) != 1) {
1308 		al = SSL_AD_DECODE_ERROR;
1309 		SSLerror(s, SSL_R_WRONG_CURVE);
1310 		goto f_err;
1311 	}
1312 
1313 	if ((nid = tls1_ec_curve_id2nid(curve_id)) == 0) {
1314 		al = SSL_AD_INTERNAL_ERROR;
1315 		SSLerror(s, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1316 		goto f_err;
1317 	}
1318 
1319 	if (!CBS_get_u8_length_prefixed(&cbs, &public))
1320 		goto truncated;
1321 
1322 	if (nid == NID_X25519) {
1323 		if (ssl3_get_server_kex_ecdhe_ecx(s, sc, nid, &public) != 1)
1324 			goto err;
1325 	} else {
1326 		if (ssl3_get_server_kex_ecdhe_ecp(s, sc, nid, &public) != 1)
1327 			goto err;
1328 	}
1329 
1330 	/*
1331 	 * The ECC/TLS specification does not mention the use of DSA to sign
1332 	 * ECParameters in the server key exchange message. We do support RSA
1333 	 * and ECDSA.
1334 	 */
1335 	if (alg_a & SSL_aRSA)
1336 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1337 	else if (alg_a & SSL_aECDSA)
1338 		*pkey = X509_get_pubkey(sc->peer_pkeys[SSL_PKEY_ECC].x509);
1339 	else
1340 		/* XXX - Anonymous ECDH, so no certificate or pkey. */
1341 		*pkey = NULL;
1342 
1343 	*nn = CBS_len(&cbs);
1344 	*pp = (unsigned char *)CBS_data(&cbs);
1345 
1346 	return (1);
1347 
1348  truncated:
1349 	al = SSL_AD_DECODE_ERROR;
1350 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1351 
1352  f_err:
1353 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1354 
1355  err:
1356 	return (-1);
1357 }
1358 
1359 int
1360 ssl3_get_server_key_exchange(SSL *s)
1361 {
1362 	unsigned char	*q, md_buf[EVP_MAX_MD_SIZE*2];
1363 	EVP_MD_CTX	 md_ctx;
1364 	unsigned char	*param, *p;
1365 	int		 al, i, j, param_len, ok;
1366 	long		 n, alg_k, alg_a;
1367 	EVP_PKEY	*pkey = NULL;
1368 	const		 EVP_MD *md = NULL;
1369 	RSA		*rsa = NULL;
1370 
1371 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1372 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1373 
1374 	/*
1375 	 * Use same message size as in ssl3_get_certificate_request()
1376 	 * as ServerKeyExchange message may be skipped.
1377 	 */
1378 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
1379 	    SSL3_ST_CR_KEY_EXCH_B, -1, s->internal->max_cert_list, &ok);
1380 	if (!ok)
1381 		return ((int)n);
1382 
1383 	EVP_MD_CTX_init(&md_ctx);
1384 
1385 	if (S3I(s)->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
1386 		/*
1387 		 * Do not skip server key exchange if this cipher suite uses
1388 		 * ephemeral keys.
1389 		 */
1390 		if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
1391 			SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1392 			al = SSL_AD_UNEXPECTED_MESSAGE;
1393 			goto f_err;
1394 		}
1395 
1396 		S3I(s)->tmp.reuse_message = 1;
1397 		EVP_MD_CTX_cleanup(&md_ctx);
1398 		return (1);
1399 	}
1400 
1401 	if (SSI(s)->sess_cert != NULL) {
1402 		DH_free(SSI(s)->sess_cert->peer_dh_tmp);
1403 		SSI(s)->sess_cert->peer_dh_tmp = NULL;
1404 
1405 		EC_KEY_free(SSI(s)->sess_cert->peer_ecdh_tmp);
1406 		SSI(s)->sess_cert->peer_ecdh_tmp = NULL;
1407 
1408 		free(SSI(s)->sess_cert->peer_x25519_tmp);
1409 		SSI(s)->sess_cert->peer_x25519_tmp = NULL;
1410 	} else {
1411 		SSI(s)->sess_cert = ssl_sess_cert_new();
1412 		if (SSI(s)->sess_cert == NULL)
1413 			goto err;
1414 	}
1415 
1416 	param = p = (unsigned char *)s->internal->init_msg;
1417 	param_len = n;
1418 
1419 	if (alg_k & SSL_kDHE) {
1420 		if (ssl3_get_server_kex_dhe(s, &pkey, &p, &n) != 1)
1421 			goto err;
1422 	} else if (alg_k & SSL_kECDHE) {
1423 		if (ssl3_get_server_kex_ecdhe(s, &pkey, &p, &n) != 1)
1424 			goto err;
1425 	} else if (alg_k != 0) {
1426 		al = SSL_AD_UNEXPECTED_MESSAGE;
1427 		SSLerror(s, SSL_R_UNEXPECTED_MESSAGE);
1428 			goto f_err;
1429 	}
1430 
1431 	param_len = param_len - n;
1432 
1433 	/* if it was signed, check the signature */
1434 	if (pkey != NULL) {
1435 		if (SSL_USE_SIGALGS(s)) {
1436 			int sigalg = tls12_get_sigid(pkey);
1437 			/* Should never happen */
1438 			if (sigalg == -1) {
1439 				SSLerror(s, ERR_R_INTERNAL_ERROR);
1440 				goto err;
1441 			}
1442 			/*
1443 			 * Check key type is consistent
1444 			 * with signature
1445 			 */
1446 			if (2 > n)
1447 				goto truncated;
1448 			if (sigalg != (int)p[1]) {
1449 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
1450 				al = SSL_AD_DECODE_ERROR;
1451 				goto f_err;
1452 			}
1453 			md = tls12_get_hash(p[0]);
1454 			if (md == NULL) {
1455 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
1456 				al = SSL_AD_DECODE_ERROR;
1457 				goto f_err;
1458 			}
1459 			p += 2;
1460 			n -= 2;
1461 		} else
1462 			md = EVP_sha1();
1463 
1464 		if (2 > n)
1465 			goto truncated;
1466 		n2s(p, i);
1467 		n -= 2;
1468 		j = EVP_PKEY_size(pkey);
1469 
1470 		if (i != n || n > j) {
1471 			/* wrong packet length */
1472 			al = SSL_AD_DECODE_ERROR;
1473 			SSLerror(s, SSL_R_WRONG_SIGNATURE_LENGTH);
1474 			goto f_err;
1475 		}
1476 
1477 		if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1478 			j = 0;
1479 			q = md_buf;
1480 			if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(), NULL)) {
1481 				al = SSL_AD_INTERNAL_ERROR;
1482 				goto f_err;
1483 			}
1484 			EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1485 			    SSL3_RANDOM_SIZE);
1486 			EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1487 			    SSL3_RANDOM_SIZE);
1488 			EVP_DigestUpdate(&md_ctx, param, param_len);
1489 			EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
1490 			q += i;
1491 			j += i;
1492 			i = RSA_verify(NID_md5_sha1, md_buf, j,
1493 			    p, n, pkey->pkey.rsa);
1494 			if (i < 0) {
1495 				al = SSL_AD_DECRYPT_ERROR;
1496 				SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
1497 				goto f_err;
1498 			}
1499 			if (i == 0) {
1500 				/* bad signature */
1501 				al = SSL_AD_DECRYPT_ERROR;
1502 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1503 				goto f_err;
1504 			}
1505 		} else {
1506 			EVP_VerifyInit_ex(&md_ctx, md, NULL);
1507 			EVP_VerifyUpdate(&md_ctx, s->s3->client_random,
1508 			    SSL3_RANDOM_SIZE);
1509 			EVP_VerifyUpdate(&md_ctx, s->s3->server_random,
1510 			    SSL3_RANDOM_SIZE);
1511 			EVP_VerifyUpdate(&md_ctx, param, param_len);
1512 			if (EVP_VerifyFinal(&md_ctx, p,(int)n, pkey) <= 0) {
1513 				/* bad signature */
1514 				al = SSL_AD_DECRYPT_ERROR;
1515 				SSLerror(s, SSL_R_BAD_SIGNATURE);
1516 				goto f_err;
1517 			}
1518 		}
1519 	} else {
1520 		/* aNULL does not need public keys. */
1521 		if (!(alg_a & SSL_aNULL)) {
1522 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1523 			goto err;
1524 		}
1525 		/* still data left over */
1526 		if (n != 0) {
1527 			al = SSL_AD_DECODE_ERROR;
1528 			SSLerror(s, SSL_R_EXTRA_DATA_IN_MESSAGE);
1529 			goto f_err;
1530 		}
1531 	}
1532 
1533 	EVP_PKEY_free(pkey);
1534 	EVP_MD_CTX_cleanup(&md_ctx);
1535 
1536 	return (1);
1537 
1538  truncated:
1539 	/* wrong packet length */
1540 	al = SSL_AD_DECODE_ERROR;
1541 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1542 
1543  f_err:
1544 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1545 
1546  err:
1547 	EVP_PKEY_free(pkey);
1548 	RSA_free(rsa);
1549 	EVP_MD_CTX_cleanup(&md_ctx);
1550 
1551 	return (-1);
1552 }
1553 
1554 int
1555 ssl3_get_certificate_request(SSL *s)
1556 {
1557 	int			 ok, ret = 0;
1558 	long		 	 n;
1559 	uint8_t			 ctype_num;
1560 	CBS			 cert_request, ctypes, rdn_list;
1561 	X509_NAME		*xn = NULL;
1562 	const unsigned char	*q;
1563 	STACK_OF(X509_NAME)	*ca_sk = NULL;
1564 
1565 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
1566 	    SSL3_ST_CR_CERT_REQ_B, -1, s->internal->max_cert_list, &ok);
1567 
1568 	if (!ok)
1569 		return ((int)n);
1570 
1571 	S3I(s)->tmp.cert_req = 0;
1572 
1573 	if (S3I(s)->tmp.message_type == SSL3_MT_SERVER_DONE) {
1574 		S3I(s)->tmp.reuse_message = 1;
1575 		/*
1576 		 * If we get here we don't need any cached handshake records
1577 		 * as we wont be doing client auth.
1578 		 */
1579 		if (S3I(s)->handshake_buffer) {
1580 			if (!tls1_digest_cached_records(s))
1581 				goto err;
1582 		}
1583 		return (1);
1584 	}
1585 
1586 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
1587 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1588 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
1589 		goto err;
1590 	}
1591 
1592 	/* TLS does not like anon-DH with client cert */
1593 	if (S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL) {
1594 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
1595 		SSLerror(s, SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1596 		goto err;
1597 	}
1598 
1599 	if (n < 0)
1600 		goto truncated;
1601 	CBS_init(&cert_request, s->internal->init_msg, n);
1602 
1603 	if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
1604 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1605 		goto err;
1606 	}
1607 
1608 	/* get the certificate types */
1609 	if (!CBS_get_u8(&cert_request, &ctype_num))
1610 		goto truncated;
1611 
1612 	if (ctype_num > SSL3_CT_NUMBER)
1613 		ctype_num = SSL3_CT_NUMBER;
1614 	if (!CBS_get_bytes(&cert_request, &ctypes, ctype_num) ||
1615 	    !CBS_write_bytes(&ctypes, (uint8_t *)S3I(s)->tmp.ctype,
1616 	    sizeof(S3I(s)->tmp.ctype), NULL)) {
1617 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1618 		goto err;
1619 	}
1620 
1621 	if (SSL_USE_SIGALGS(s)) {
1622 		CBS sigalgs;
1623 
1624 		if (CBS_len(&cert_request) < 2) {
1625 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1626 			goto err;
1627 		}
1628 
1629 		/* Check we have enough room for signature algorithms and
1630 		 * following length value.
1631 		 */
1632 		if (!CBS_get_u16_length_prefixed(&cert_request, &sigalgs)) {
1633 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1634 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1635 			goto err;
1636 		}
1637 		if ((CBS_len(&sigalgs) & 1) ||
1638 		    !tls1_process_sigalgs(s, CBS_data(&sigalgs),
1639 		    CBS_len(&sigalgs))) {
1640 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1641 			SSLerror(s, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
1642 			goto err;
1643 		}
1644 	}
1645 
1646 	/* get the CA RDNs */
1647 	if (CBS_len(&cert_request) < 2) {
1648 		SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1649 		goto err;
1650 	}
1651 
1652 	if (!CBS_get_u16_length_prefixed(&cert_request, &rdn_list) ||
1653 	    CBS_len(&cert_request) != 0) {
1654 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1655 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1656 		goto err;
1657 	}
1658 
1659 	while (CBS_len(&rdn_list) > 0) {
1660 		CBS rdn;
1661 
1662 		if (CBS_len(&rdn_list) < 2) {
1663 			SSLerror(s, SSL_R_DATA_LENGTH_TOO_LONG);
1664 			goto err;
1665 		}
1666 
1667 		if (!CBS_get_u16_length_prefixed(&rdn_list, &rdn)) {
1668 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1669 			SSLerror(s, SSL_R_CA_DN_TOO_LONG);
1670 			goto err;
1671 		}
1672 
1673 		q = CBS_data(&rdn);
1674 		if ((xn = d2i_X509_NAME(NULL, &q, CBS_len(&rdn))) == NULL) {
1675 			ssl3_send_alert(s, SSL3_AL_FATAL,
1676 			    SSL_AD_DECODE_ERROR);
1677 			SSLerror(s, ERR_R_ASN1_LIB);
1678 			goto err;
1679 		}
1680 
1681 		if (q != CBS_data(&rdn) + CBS_len(&rdn)) {
1682 			ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1683 			SSLerror(s, SSL_R_CA_DN_LENGTH_MISMATCH);
1684 			goto err;
1685 		}
1686 		if (!sk_X509_NAME_push(ca_sk, xn)) {
1687 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1688 			goto err;
1689 		}
1690 		xn = NULL;	/* avoid free in err block */
1691 	}
1692 
1693 	/* we should setup a certificate to return.... */
1694 	S3I(s)->tmp.cert_req = 1;
1695 	S3I(s)->tmp.ctype_num = ctype_num;
1696 	sk_X509_NAME_pop_free(S3I(s)->tmp.ca_names, X509_NAME_free);
1697 	S3I(s)->tmp.ca_names = ca_sk;
1698 	ca_sk = NULL;
1699 
1700 	ret = 1;
1701 	if (0) {
1702 truncated:
1703 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1704 	}
1705 err:
1706 	X509_NAME_free(xn);
1707 	sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
1708 	return (ret);
1709 }
1710 
1711 static int
1712 ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1713 {
1714 	return (X509_NAME_cmp(*a, *b));
1715 }
1716 
1717 int
1718 ssl3_get_new_session_ticket(SSL *s)
1719 {
1720 	int			 ok, al, ret = 0;
1721 	uint32_t		 lifetime_hint;
1722 	long			 n;
1723 	CBS			 cbs, session_ticket;
1724 
1725 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A,
1726 	    SSL3_ST_CR_SESSION_TICKET_B, -1, 16384, &ok);
1727 	if (!ok)
1728 		return ((int)n);
1729 
1730 	if (S3I(s)->tmp.message_type == SSL3_MT_FINISHED) {
1731 		S3I(s)->tmp.reuse_message = 1;
1732 		return (1);
1733 	}
1734 	if (S3I(s)->tmp.message_type != SSL3_MT_NEWSESSION_TICKET) {
1735 		al = SSL_AD_UNEXPECTED_MESSAGE;
1736 		SSLerror(s, SSL_R_BAD_MESSAGE_TYPE);
1737 		goto f_err;
1738 	}
1739 
1740 	if (n < 0) {
1741 		al = SSL_AD_DECODE_ERROR;
1742 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1743 		goto f_err;
1744 	}
1745 
1746 	CBS_init(&cbs, s->internal->init_msg, n);
1747 	if (!CBS_get_u32(&cbs, &lifetime_hint) ||
1748 #if UINT32_MAX > LONG_MAX
1749 	    lifetime_hint > LONG_MAX ||
1750 #endif
1751 	    !CBS_get_u16_length_prefixed(&cbs, &session_ticket) ||
1752 	    CBS_len(&cbs) != 0) {
1753 		al = SSL_AD_DECODE_ERROR;
1754 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1755 		goto f_err;
1756 	}
1757 	s->session->tlsext_tick_lifetime_hint = (long)lifetime_hint;
1758 
1759 	if (!CBS_stow(&session_ticket, &s->session->tlsext_tick,
1760 	    &s->session->tlsext_ticklen)) {
1761 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1762 		goto err;
1763 	}
1764 
1765 	/*
1766 	 * There are two ways to detect a resumed ticket sesion.
1767 	 * One is to set an appropriate session ID and then the server
1768 	 * must return a match in ServerHello. This allows the normal
1769 	 * client session ID matching to work and we know much
1770 	 * earlier that the ticket has been accepted.
1771 	 *
1772 	 * The other way is to set zero length session ID when the
1773 	 * ticket is presented and rely on the handshake to determine
1774 	 * session resumption.
1775 	 *
1776 	 * We choose the former approach because this fits in with
1777 	 * assumptions elsewhere in OpenSSL. The session ID is set
1778 	 * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1779 	 * ticket.
1780 	 */
1781 	EVP_Digest(CBS_data(&session_ticket), CBS_len(&session_ticket),
1782 	    s->session->session_id, &s->session->session_id_length,
1783 	    EVP_sha256(), NULL);
1784 	ret = 1;
1785 	return (ret);
1786 f_err:
1787 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1788 err:
1789 	return (-1);
1790 }
1791 
1792 int
1793 ssl3_get_cert_status(SSL *s)
1794 {
1795 	CBS			 cert_status, response;
1796 	size_t			 stow_len;
1797 	int			 ok, al;
1798 	long			 n;
1799 	uint8_t			 status_type;
1800 
1801 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A,
1802 	    SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS,
1803 	    16384, &ok);
1804 
1805 	if (!ok)
1806 		return ((int)n);
1807 
1808 	if (n < 0) {
1809 		/* need at least status type + length */
1810 		al = SSL_AD_DECODE_ERROR;
1811 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1812 		goto f_err;
1813 	}
1814 
1815 	CBS_init(&cert_status, s->internal->init_msg, n);
1816 	if (!CBS_get_u8(&cert_status, &status_type) ||
1817 	    CBS_len(&cert_status) < 3) {
1818 		/* need at least status type + length */
1819 		al = SSL_AD_DECODE_ERROR;
1820 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1821 		goto f_err;
1822 	}
1823 
1824 	if (status_type != TLSEXT_STATUSTYPE_ocsp) {
1825 		al = SSL_AD_DECODE_ERROR;
1826 		SSLerror(s, SSL_R_UNSUPPORTED_STATUS_TYPE);
1827 		goto f_err;
1828 	}
1829 
1830 	if (!CBS_get_u24_length_prefixed(&cert_status, &response) ||
1831 	    CBS_len(&cert_status) != 0) {
1832 		al = SSL_AD_DECODE_ERROR;
1833 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1834 		goto f_err;
1835 	}
1836 
1837 	if (!CBS_stow(&response, &s->internal->tlsext_ocsp_resp,
1838 	    &stow_len) || stow_len > INT_MAX) {
1839 		s->internal->tlsext_ocsp_resplen = 0;
1840  		al = SSL_AD_INTERNAL_ERROR;
1841  		SSLerror(s, ERR_R_MALLOC_FAILURE);
1842  		goto f_err;
1843  	}
1844 	s->internal->tlsext_ocsp_resplen = (int)stow_len;
1845 
1846 	if (s->ctx->internal->tlsext_status_cb) {
1847 		int ret;
1848 		ret = s->ctx->internal->tlsext_status_cb(s,
1849 		    s->ctx->internal->tlsext_status_arg);
1850 		if (ret == 0) {
1851 			al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1852 			SSLerror(s, SSL_R_INVALID_STATUS_RESPONSE);
1853 			goto f_err;
1854 		}
1855 		if (ret < 0) {
1856 			al = SSL_AD_INTERNAL_ERROR;
1857 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1858 			goto f_err;
1859 		}
1860 	}
1861 	return (1);
1862 f_err:
1863 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1864 	return (-1);
1865 }
1866 
1867 int
1868 ssl3_get_server_done(SSL *s)
1869 {
1870 	int	ok, ret = 0;
1871 	long	n;
1872 
1873 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
1874 	    SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
1875 	    30, /* should be very small, like 0 :-) */ &ok);
1876 
1877 	if (!ok)
1878 		return ((int)n);
1879 	if (n > 0) {
1880 		/* should contain no data */
1881 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
1882 		SSLerror(s, SSL_R_LENGTH_MISMATCH);
1883 		return (-1);
1884 	}
1885 	ret = 1;
1886 	return (ret);
1887 }
1888 
1889 static int
1890 ssl3_send_client_kex_rsa(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1891 {
1892 	unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH];
1893 	unsigned char *enc_pms = NULL;
1894 	EVP_PKEY *pkey = NULL;
1895 	int ret = -1;
1896 	int enc_len;
1897 	CBB epms;
1898 
1899 	/*
1900 	 * RSA-Encrypted Premaster Secret Message - RFC 5246 section 7.4.7.1.
1901 	 */
1902 
1903 	pkey = X509_get_pubkey(sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1904 	if (pkey == NULL || pkey->type != EVP_PKEY_RSA ||
1905 	    pkey->pkey.rsa == NULL) {
1906 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1907 		goto err;
1908 	}
1909 
1910 	pms[0] = s->client_version >> 8;
1911 	pms[1] = s->client_version & 0xff;
1912 	arc4random_buf(&pms[2], sizeof(pms) - 2);
1913 
1914 	if ((enc_pms = malloc(RSA_size(pkey->pkey.rsa))) == NULL) {
1915 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1916 		goto err;
1917 	}
1918 
1919 	enc_len = RSA_public_encrypt(sizeof(pms), pms, enc_pms, pkey->pkey.rsa,
1920 	    RSA_PKCS1_PADDING);
1921 	if (enc_len <= 0) {
1922 		SSLerror(s, SSL_R_BAD_RSA_ENCRYPT);
1923 		goto err;
1924 	}
1925 
1926 	if (!CBB_add_u16_length_prefixed(cbb, &epms))
1927 		goto err;
1928 	if (!CBB_add_bytes(&epms, enc_pms, enc_len))
1929 		goto err;
1930 	if (!CBB_flush(cbb))
1931 		goto err;
1932 
1933 	s->session->master_key_length =
1934 	    tls1_generate_master_secret(s,
1935 		s->session->master_key, pms, sizeof(pms));
1936 
1937 	ret = 1;
1938 
1939 err:
1940 	explicit_bzero(pms, sizeof(pms));
1941 	EVP_PKEY_free(pkey);
1942 	free(enc_pms);
1943 
1944 	return (ret);
1945 }
1946 
1947 static int
1948 ssl3_send_client_kex_dhe(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
1949 {
1950 	DH *dh_srvr = NULL, *dh_clnt = NULL;
1951 	unsigned char *key = NULL;
1952 	int key_size = 0, key_len;
1953 	unsigned char *data;
1954 	int ret = -1;
1955 	CBB dh_Yc;
1956 
1957 	/* Ensure that we have an ephemeral key for DHE. */
1958 	if (sess_cert->peer_dh_tmp == NULL) {
1959 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
1960 		SSLerror(s, SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
1961 		goto err;
1962 	}
1963 	dh_srvr = sess_cert->peer_dh_tmp;
1964 
1965 	/* Generate a new random key. */
1966 	if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) {
1967 		SSLerror(s, ERR_R_DH_LIB);
1968 		goto err;
1969 	}
1970 	if (!DH_generate_key(dh_clnt)) {
1971 		SSLerror(s, ERR_R_DH_LIB);
1972 		goto err;
1973 	}
1974 	key_size = DH_size(dh_clnt);
1975 	if ((key = malloc(key_size)) == NULL) {
1976 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1977 		goto err;
1978 	}
1979 	key_len = DH_compute_key(key, dh_srvr->pub_key, dh_clnt);
1980 	if (key_len <= 0) {
1981 		SSLerror(s, ERR_R_DH_LIB);
1982 		goto err;
1983 	}
1984 
1985 	/* Generate master key from the result. */
1986 	s->session->master_key_length =
1987 	    tls1_generate_master_secret(s,
1988 		s->session->master_key, key, key_len);
1989 
1990 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Yc))
1991 		goto err;
1992 	if (!CBB_add_space(&dh_Yc, &data, BN_num_bytes(dh_clnt->pub_key)))
1993 		goto err;
1994 	BN_bn2bin(dh_clnt->pub_key, data);
1995 	if (!CBB_flush(cbb))
1996 		goto err;
1997 
1998 	ret = 1;
1999 
2000 err:
2001 	DH_free(dh_clnt);
2002 	freezero(key, key_size);
2003 
2004 	return (ret);
2005 }
2006 
2007 static int
2008 ssl3_send_client_kex_ecdhe_ecp(SSL *s, SESS_CERT *sc, CBB *cbb)
2009 {
2010 	const EC_GROUP *group = NULL;
2011 	const EC_POINT *point = NULL;
2012 	EC_KEY *ecdh = NULL;
2013 	BN_CTX *bn_ctx = NULL;
2014 	unsigned char *key = NULL;
2015 	unsigned char *data;
2016 	size_t encoded_len;
2017 	int key_size = 0, key_len;
2018 	int ret = -1;
2019 	CBB ecpoint;
2020 
2021 	if ((group = EC_KEY_get0_group(sc->peer_ecdh_tmp)) == NULL ||
2022 	    (point = EC_KEY_get0_public_key(sc->peer_ecdh_tmp)) == NULL) {
2023 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2024 		goto err;
2025 	}
2026 
2027 	if ((ecdh = EC_KEY_new()) == NULL) {
2028 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2029 		goto err;
2030 	}
2031 
2032 	if (!EC_KEY_set_group(ecdh, group)) {
2033 		SSLerror(s, ERR_R_EC_LIB);
2034 		goto err;
2035 	}
2036 
2037 	/* Generate a new ECDH key pair. */
2038 	if (!(EC_KEY_generate_key(ecdh))) {
2039 		SSLerror(s, ERR_R_ECDH_LIB);
2040 		goto err;
2041 	}
2042 	if ((key_size = ECDH_size(ecdh)) <= 0) {
2043 		SSLerror(s, ERR_R_ECDH_LIB);
2044 		goto err;
2045 	}
2046 	if ((key = malloc(key_size)) == NULL) {
2047 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2048 	}
2049 	key_len = ECDH_compute_key(key, key_size, point, ecdh, NULL);
2050 	if (key_len <= 0) {
2051 		SSLerror(s, ERR_R_ECDH_LIB);
2052 		goto err;
2053 	}
2054 
2055 	/* Generate master key from the result. */
2056 	s->session->master_key_length =
2057 	    tls1_generate_master_secret(s,
2058 		s->session->master_key, key, key_len);
2059 
2060 	encoded_len = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2061 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
2062 	if (encoded_len == 0) {
2063 		SSLerror(s, ERR_R_ECDH_LIB);
2064 		goto err;
2065 	}
2066 
2067 	if ((bn_ctx = BN_CTX_new()) == NULL) {
2068 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2069 		goto err;
2070 	}
2071 
2072 	/* Encode the public key. */
2073 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2074 		goto err;
2075 	if (!CBB_add_space(&ecpoint, &data, encoded_len))
2076 		goto err;
2077 	if (EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
2078 	    POINT_CONVERSION_UNCOMPRESSED, data, encoded_len,
2079 	    bn_ctx) == 0)
2080 		goto err;
2081 	if (!CBB_flush(cbb))
2082 		goto err;
2083 
2084 	ret = 1;
2085 
2086  err:
2087 	freezero(key, key_size);
2088 
2089 	BN_CTX_free(bn_ctx);
2090 	EC_KEY_free(ecdh);
2091 
2092 	return (ret);
2093 }
2094 
2095 static int
2096 ssl3_send_client_kex_ecdhe_ecx(SSL *s, SESS_CERT *sc, CBB *cbb)
2097 {
2098 	uint8_t *public_key = NULL, *private_key = NULL, *shared_key = NULL;
2099 	int ret = -1;
2100 	CBB ecpoint;
2101 
2102 	/* Generate X25519 key pair and derive shared key. */
2103 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
2104 		goto err;
2105 	if ((private_key = malloc(X25519_KEY_LENGTH)) == NULL)
2106 		goto err;
2107 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
2108 		goto err;
2109 	X25519_keypair(public_key, private_key);
2110 	if (!X25519(shared_key, private_key, sc->peer_x25519_tmp))
2111 		goto err;
2112 
2113 	/* Serialize the public key. */
2114 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
2115 		goto err;
2116 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
2117 		goto err;
2118 	if (!CBB_flush(cbb))
2119 		goto err;
2120 
2121 	/* Generate master key from the result. */
2122 	s->session->master_key_length =
2123 	    tls1_generate_master_secret(s,
2124 		s->session->master_key, shared_key, X25519_KEY_LENGTH);
2125 
2126 	ret = 1;
2127 
2128  err:
2129 	free(public_key);
2130 	freezero(private_key, X25519_KEY_LENGTH);
2131 	freezero(shared_key, X25519_KEY_LENGTH);
2132 
2133 	return (ret);
2134 }
2135 
2136 static int
2137 ssl3_send_client_kex_ecdhe(SSL *s, SESS_CERT *sc, CBB *cbb)
2138 {
2139 	if (sc->peer_x25519_tmp != NULL) {
2140 		if (ssl3_send_client_kex_ecdhe_ecx(s, sc, cbb) != 1)
2141 			goto err;
2142 	} else if (sc->peer_ecdh_tmp != NULL) {
2143 		if (ssl3_send_client_kex_ecdhe_ecp(s, sc, cbb) != 1)
2144 			goto err;
2145 	} else {
2146 		ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
2147 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2148 		goto err;
2149 	}
2150 
2151 	return (1);
2152 
2153  err:
2154 	return (-1);
2155 }
2156 
2157 static int
2158 ssl3_send_client_kex_gost(SSL *s, SESS_CERT *sess_cert, CBB *cbb)
2159 {
2160 	unsigned char premaster_secret[32], shared_ukm[32], tmp[256];
2161 	EVP_PKEY *pub_key = NULL;
2162 	EVP_PKEY_CTX *pkey_ctx;
2163 	X509 *peer_cert;
2164 	size_t msglen;
2165 	unsigned int md_len;
2166 	EVP_MD_CTX *ukm_hash;
2167 	int ret = -1;
2168 	int nid;
2169 	CBB gostblob;
2170 
2171 	/* Get server sertificate PKEY and create ctx from it */
2172 	peer_cert = sess_cert->peer_pkeys[SSL_PKEY_GOST01].x509;
2173 	if (peer_cert == NULL) {
2174 		SSLerror(s, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2175 		goto err;
2176 	}
2177 
2178 	pub_key = X509_get_pubkey(peer_cert);
2179 	pkey_ctx = EVP_PKEY_CTX_new(pub_key, NULL);
2180 
2181 	/*
2182 	 * If we have send a certificate, and certificate key parameters match
2183 	 * those of server certificate, use certificate key for key exchange.
2184 	 * Otherwise, generate ephemeral key pair.
2185 	 */
2186 	EVP_PKEY_encrypt_init(pkey_ctx);
2187 
2188 	/* Generate session key. */
2189 	arc4random_buf(premaster_secret, 32);
2190 
2191 	/*
2192 	 * If we have client certificate, use its secret as peer key.
2193 	 */
2194 	if (S3I(s)->tmp.cert_req && s->cert->key->privatekey) {
2195 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2196 		    s->cert->key->privatekey) <=0) {
2197 			/*
2198 			 * If there was an error - just ignore it.
2199 			 * Ephemeral key would be used.
2200 			 */
2201 			ERR_clear_error();
2202 		}
2203 	}
2204 
2205 	/*
2206 	 * Compute shared IV and store it in algorithm-specific context data.
2207 	 */
2208 	ukm_hash = EVP_MD_CTX_create();
2209 	if (ukm_hash == NULL) {
2210 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2211 		goto err;
2212 	}
2213 
2214 	if (ssl_get_algorithm2(s) & SSL_HANDSHAKE_MAC_GOST94)
2215 		nid = NID_id_GostR3411_94;
2216 	else
2217 		nid = NID_id_tc26_gost3411_2012_256;
2218 	if (!EVP_DigestInit(ukm_hash, EVP_get_digestbynid(nid)))
2219 		goto err;
2220 	EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE);
2221 	EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE);
2222 	EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2223 	EVP_MD_CTX_destroy(ukm_hash);
2224 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
2225 	    EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {
2226 		SSLerror(s, SSL_R_LIBRARY_BUG);
2227 		goto err;
2228 	}
2229 
2230 	/*
2231 	 * Make GOST keytransport blob message, encapsulate it into sequence.
2232 	 */
2233 	msglen = 255;
2234 	if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret,
2235 	    32) < 0) {
2236 		SSLerror(s, SSL_R_LIBRARY_BUG);
2237 		goto err;
2238 	}
2239 
2240 	if (!CBB_add_asn1(cbb, &gostblob, CBS_ASN1_SEQUENCE))
2241 		goto err;
2242 	if (!CBB_add_bytes(&gostblob, tmp, msglen))
2243 		goto err;
2244 	if (!CBB_flush(cbb))
2245 		goto err;
2246 
2247 	/* Check if pubkey from client certificate was used. */
2248 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
2249 	    NULL) > 0) {
2250 		/* Set flag "skip certificate verify". */
2251 		s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2252 	}
2253 	EVP_PKEY_CTX_free(pkey_ctx);
2254 	s->session->master_key_length =
2255 	    tls1_generate_master_secret(s,
2256 		s->session->master_key, premaster_secret, 32);
2257 
2258 	ret = 1;
2259 
2260  err:
2261 	explicit_bzero(premaster_secret, sizeof(premaster_secret));
2262 	EVP_PKEY_free(pub_key);
2263 
2264 	return (ret);
2265 }
2266 
2267 int
2268 ssl3_send_client_key_exchange(SSL *s)
2269 {
2270 	SESS_CERT *sess_cert;
2271 	unsigned long alg_k;
2272 	CBB cbb, kex;
2273 
2274 	memset(&cbb, 0, sizeof(cbb));
2275 
2276 	if (S3I(s)->hs.state == SSL3_ST_CW_KEY_EXCH_A) {
2277 		alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2278 
2279 		if ((sess_cert = SSI(s)->sess_cert) == NULL) {
2280 			ssl3_send_alert(s, SSL3_AL_FATAL,
2281 			    SSL_AD_UNEXPECTED_MESSAGE);
2282 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2283 			goto err;
2284 		}
2285 
2286 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &kex,
2287 		    SSL3_MT_CLIENT_KEY_EXCHANGE))
2288 			goto err;
2289 
2290 		if (alg_k & SSL_kRSA) {
2291 			if (ssl3_send_client_kex_rsa(s, sess_cert, &kex) != 1)
2292 				goto err;
2293 		} else if (alg_k & SSL_kDHE) {
2294 			if (ssl3_send_client_kex_dhe(s, sess_cert, &kex) != 1)
2295 				goto err;
2296 		} else if (alg_k & SSL_kECDHE) {
2297 			if (ssl3_send_client_kex_ecdhe(s, sess_cert, &kex) != 1)
2298 				goto err;
2299 		} else if (alg_k & SSL_kGOST) {
2300 			if (ssl3_send_client_kex_gost(s, sess_cert, &kex) != 1)
2301 				goto err;
2302 		} else {
2303 			ssl3_send_alert(s, SSL3_AL_FATAL,
2304 			    SSL_AD_HANDSHAKE_FAILURE);
2305 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2306 			goto err;
2307 		}
2308 
2309 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2310 			goto err;
2311 
2312 		S3I(s)->hs.state = SSL3_ST_CW_KEY_EXCH_B;
2313 	}
2314 
2315 	/* SSL3_ST_CW_KEY_EXCH_B */
2316 	return (ssl3_handshake_write(s));
2317 
2318 err:
2319 	CBB_cleanup(&cbb);
2320 
2321 	return (-1);
2322 }
2323 
2324 int
2325 ssl3_send_client_verify(SSL *s)
2326 {
2327 	unsigned char	*p;
2328 	unsigned char	 data[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
2329 	EVP_PKEY	*pkey;
2330 	EVP_PKEY_CTX	*pctx = NULL;
2331 	EVP_MD_CTX	 mctx;
2332 	unsigned	 u = 0;
2333 	unsigned long	 n;
2334 	int		 j;
2335 
2336 	EVP_MD_CTX_init(&mctx);
2337 
2338 	if (S3I(s)->hs.state == SSL3_ST_CW_CERT_VRFY_A) {
2339 		p = ssl3_handshake_msg_start(s, SSL3_MT_CERTIFICATE_VERIFY);
2340 
2341 		/*
2342 		 * Create context from key and test if sha1 is allowed as
2343 		 * digest.
2344 		 */
2345 		pkey = s->cert->key->privatekey;
2346 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2347 		EVP_PKEY_sign_init(pctx);
2348 
2349 		/* XXX - is this needed? */
2350 		if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1()) <= 0)
2351 			ERR_clear_error();
2352 
2353 		if (!SSL_USE_SIGALGS(s)) {
2354 			if (S3I(s)->handshake_buffer) {
2355 				if (!tls1_digest_cached_records(s))
2356 					goto err;
2357 			}
2358 			if (!tls1_handshake_hash_value(s, data, sizeof(data),
2359 			    NULL))
2360 				goto err;
2361 		}
2362 
2363 		/*
2364 		 * For TLS v1.2 send signature algorithm and signature
2365 		 * using agreed digest and cached handshake records.
2366 		 */
2367 		if (SSL_USE_SIGALGS(s)) {
2368 			long hdatalen = 0;
2369 			void *hdata;
2370 			const EVP_MD *md = s->cert->key->digest;
2371 			hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer,
2372 			    &hdata);
2373 			if (hdatalen <= 0 ||
2374 			    !tls12_get_sigandhash(p, pkey, md)) {
2375 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2376 				goto err;
2377 			}
2378 			p += 2;
2379 			if (!EVP_SignInit_ex(&mctx, md, NULL) ||
2380 			    !EVP_SignUpdate(&mctx, hdata, hdatalen) ||
2381 			    !EVP_SignFinal(&mctx, p + 2, &u, pkey)) {
2382 				SSLerror(s, ERR_R_EVP_LIB);
2383 				goto err;
2384 			}
2385 			s2n(u, p);
2386 			n = u + 4;
2387 			if (!tls1_digest_cached_records(s))
2388 				goto err;
2389 		} else if (pkey->type == EVP_PKEY_RSA) {
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 		S3I(s)->hs.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 (S3I(s)->hs.state == SSL3_ST_CW_CERT_A) {
2489 		if ((s->cert == NULL) || (s->cert->key->x509 == NULL) ||
2490 		    (s->cert->key->privatekey == NULL))
2491 			S3I(s)->hs.state = SSL3_ST_CW_CERT_B;
2492 		else
2493 			S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2494 	}
2495 
2496 	/* We need to get a client cert */
2497 	if (S3I(s)->hs.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 			S3I(s)->hs.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 		S3I(s)->hs.state = SSL3_ST_CW_CERT_C;
2526 	}
2527 
2528 	if (S3I(s)->hs.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 		S3I(s)->hs.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)->hs.new_cipher->algorithm_mkey;
2562 	alg_a = S3I(s)->hs.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 	CBB cbb, nextproto, npn, padding;
2623 	size_t pad_len;
2624 	uint8_t *pad;
2625 
2626 	memset(&cbb, 0, sizeof(cbb));
2627 
2628 	if (S3I(s)->hs.state == SSL3_ST_CW_NEXT_PROTO_A) {
2629 		pad_len = 32 - ((s->internal->next_proto_negotiated_len + 2) % 32);
2630 
2631 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &nextproto,
2632 		    SSL3_MT_NEXT_PROTO))
2633 			goto err;
2634 		if (!CBB_add_u8_length_prefixed(&nextproto, &npn))
2635 			goto err;
2636 		if (!CBB_add_bytes(&npn, s->internal->next_proto_negotiated,
2637 		    s->internal->next_proto_negotiated_len))
2638 			goto err;
2639 		if (!CBB_add_u8_length_prefixed(&nextproto, &padding))
2640 			goto err;
2641 		if (!CBB_add_space(&padding, &pad, pad_len))
2642 			goto err;
2643 		memset(pad, 0, pad_len);
2644 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2645 			goto err;
2646 
2647 		S3I(s)->hs.state = SSL3_ST_CW_NEXT_PROTO_B;
2648 	}
2649 
2650 	return (ssl3_handshake_write(s));
2651 
2652  err:
2653 	CBB_cleanup(&cbb);
2654 
2655 	return (-1);
2656 }
2657 
2658 /*
2659  * Check to see if handshake is full or resumed. Usually this is just a
2660  * case of checking to see if a cache hit has occurred. In the case of
2661  * session tickets we have to check the next message to be sure.
2662  */
2663 
2664 int
2665 ssl3_check_finished(SSL *s)
2666 {
2667 	int	ok;
2668 	long	n;
2669 
2670 	/* If we have no ticket it cannot be a resumed session. */
2671 	if (!s->session->tlsext_tick)
2672 		return (1);
2673 	/* this function is called when we really expect a Certificate
2674 	 * message, so permit appropriate message length */
2675 	n = s->method->internal->ssl_get_message(s, SSL3_ST_CR_CERT_A,
2676 	    SSL3_ST_CR_CERT_B, -1, s->internal->max_cert_list, &ok);
2677 	if (!ok)
2678 		return ((int)n);
2679 	S3I(s)->tmp.reuse_message = 1;
2680 	if ((S3I(s)->tmp.message_type == SSL3_MT_FINISHED) ||
2681 	    (S3I(s)->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2682 		return (2);
2683 
2684 	return (1);
2685 }
2686 
2687 int
2688 ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2689 {
2690 	int	i = 0;
2691 
2692 #ifndef OPENSSL_NO_ENGINE
2693 	if (s->ctx->internal->client_cert_engine) {
2694 		i = ENGINE_load_ssl_client_cert(
2695 		    s->ctx->internal->client_cert_engine, s,
2696 		    SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL);
2697 		if (i != 0)
2698 			return (i);
2699 	}
2700 #endif
2701 	if (s->ctx->internal->client_cert_cb)
2702 		i = s->ctx->internal->client_cert_cb(s, px509, ppkey);
2703 	return (i);
2704 }
2705