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