xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision f763167468dba5339ed4b14b7ecaca2a397ab0f6)
1 /* $OpenBSD: ssl_srvr.c,v 1.22 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 <stdio.h>
152 
153 #include "ssl_locl.h"
154 
155 #include <openssl/bn.h>
156 #include <openssl/buffer.h>
157 #include <openssl/curve25519.h>
158 #include <openssl/evp.h>
159 #include <openssl/dh.h>
160 #ifndef OPENSSL_NO_GOST
161 #include <openssl/gost.h>
162 #endif
163 #include <openssl/hmac.h>
164 #include <openssl/md5.h>
165 #include <openssl/objects.h>
166 #include <openssl/x509.h>
167 
168 #include "bytestring.h"
169 
170 int
171 ssl3_accept(SSL *s)
172 {
173 	unsigned long alg_k;
174 	void (*cb)(const SSL *ssl, int type, int val) = NULL;
175 	int ret = -1;
176 	int new_state, state, skip = 0;
177 
178 	ERR_clear_error();
179 	errno = 0;
180 
181 	if (s->internal->info_callback != NULL)
182 		cb = s->internal->info_callback;
183 	else if (s->ctx->internal->info_callback != NULL)
184 		cb = s->ctx->internal->info_callback;
185 
186 	/* init things to blank */
187 	s->internal->in_handshake++;
188 	if (!SSL_in_init(s) || SSL_in_before(s))
189 		SSL_clear(s);
190 
191 	if (s->cert == NULL) {
192 		SSLerror(s, SSL_R_NO_CERTIFICATE_SET);
193 		ret = -1;
194 		goto end;
195 	}
196 
197 	for (;;) {
198 		state = S3I(s)->hs.state;
199 
200 		switch (S3I(s)->hs.state) {
201 		case SSL_ST_RENEGOTIATE:
202 			s->internal->renegotiate = 1;
203 			/* S3I(s)->hs.state=SSL_ST_ACCEPT; */
204 
205 		case SSL_ST_BEFORE:
206 		case SSL_ST_ACCEPT:
207 		case SSL_ST_BEFORE|SSL_ST_ACCEPT:
208 		case SSL_ST_OK|SSL_ST_ACCEPT:
209 
210 			s->server = 1;
211 			if (cb != NULL)
212 				cb(s, SSL_CB_HANDSHAKE_START, 1);
213 
214 			if ((s->version >> 8) != 3) {
215 				SSLerror(s, ERR_R_INTERNAL_ERROR);
216 				ret = -1;
217 				goto end;
218 			}
219 			s->internal->type = SSL_ST_ACCEPT;
220 
221 			if (!ssl3_setup_init_buffer(s)) {
222 				ret = -1;
223 				goto end;
224 			}
225 			if (!ssl3_setup_buffers(s)) {
226 				ret = -1;
227 				goto end;
228 			}
229 
230 			s->internal->init_num = 0;
231 
232 			if (S3I(s)->hs.state != SSL_ST_RENEGOTIATE) {
233 				/*
234 				 * Ok, we now need to push on a buffering BIO
235 				 * so that the output is sent in a way that
236 				 * TCP likes :-)
237 				 */
238 				if (!ssl_init_wbio_buffer(s, 1)) {
239 					ret = -1;
240 					goto end;
241 				}
242 
243 				if (!tls1_init_finished_mac(s)) {
244 					ret = -1;
245 					goto end;
246 				}
247 
248 				S3I(s)->hs.state = SSL3_ST_SR_CLNT_HELLO_A;
249 				s->ctx->internal->stats.sess_accept++;
250 			} else if (!S3I(s)->send_connection_binding) {
251 				/*
252 				 * Server attempting to renegotiate with
253 				 * client that doesn't support secure
254 				 * renegotiation.
255 				 */
256 				SSLerror(s, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
257 				ssl3_send_alert(s, SSL3_AL_FATAL,
258 				    SSL_AD_HANDSHAKE_FAILURE);
259 				ret = -1;
260 				goto end;
261 			} else {
262 				/*
263 				 * S3I(s)->hs.state == SSL_ST_RENEGOTIATE,
264 				 * we will just send a HelloRequest
265 				 */
266 				s->ctx->internal->stats.sess_accept_renegotiate++;
267 				S3I(s)->hs.state = SSL3_ST_SW_HELLO_REQ_A;
268 			}
269 			break;
270 
271 		case SSL3_ST_SW_HELLO_REQ_A:
272 		case SSL3_ST_SW_HELLO_REQ_B:
273 
274 			s->internal->shutdown = 0;
275 			ret = ssl3_send_hello_request(s);
276 			if (ret <= 0)
277 				goto end;
278 			S3I(s)->hs.next_state = SSL3_ST_SW_HELLO_REQ_C;
279 			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
280 			s->internal->init_num = 0;
281 
282 			if (!tls1_init_finished_mac(s)) {
283 				ret = -1;
284 				goto end;
285 			}
286 			break;
287 
288 		case SSL3_ST_SW_HELLO_REQ_C:
289 			S3I(s)->hs.state = SSL_ST_OK;
290 			break;
291 
292 		case SSL3_ST_SR_CLNT_HELLO_A:
293 		case SSL3_ST_SR_CLNT_HELLO_B:
294 		case SSL3_ST_SR_CLNT_HELLO_C:
295 
296 			s->internal->shutdown = 0;
297 			if (s->internal->rwstate != SSL_X509_LOOKUP) {
298 				ret = ssl3_get_client_hello(s);
299 				if (ret <= 0)
300 					goto end;
301 			}
302 
303 			s->internal->renegotiate = 2;
304 			S3I(s)->hs.state = SSL3_ST_SW_SRVR_HELLO_A;
305 			s->internal->init_num = 0;
306 			break;
307 
308 		case SSL3_ST_SW_SRVR_HELLO_A:
309 		case SSL3_ST_SW_SRVR_HELLO_B:
310 			ret = ssl3_send_server_hello(s);
311 			if (ret <= 0)
312 				goto end;
313 			if (s->internal->hit) {
314 				if (s->internal->tlsext_ticket_expected)
315 					S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_A;
316 				else
317 					S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
318 			}
319 			else
320 				S3I(s)->hs.state = SSL3_ST_SW_CERT_A;
321 			s->internal->init_num = 0;
322 			break;
323 
324 		case SSL3_ST_SW_CERT_A:
325 		case SSL3_ST_SW_CERT_B:
326 			/* Check if it is anon DH or anon ECDH. */
327 			if (!(S3I(s)->hs.new_cipher->algorithm_auth &
328 			    SSL_aNULL)) {
329 				ret = ssl3_send_server_certificate(s);
330 				if (ret <= 0)
331 					goto end;
332 				if (s->internal->tlsext_status_expected)
333 					S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_A;
334 				else
335 					S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
336 			} else {
337 				skip = 1;
338 				S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
339 			}
340 			s->internal->init_num = 0;
341 			break;
342 
343 		case SSL3_ST_SW_KEY_EXCH_A:
344 		case SSL3_ST_SW_KEY_EXCH_B:
345 			alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
346 
347 			/*
348 			 * Only send if using a DH key exchange.
349 			 *
350 			 * For ECC ciphersuites, we send a ServerKeyExchange
351 			 * message only if the cipher suite is ECDHE. In other
352 			 * cases, the server certificate contains the server's
353 			 * public key for key exchange.
354 			 */
355 			if (alg_k & (SSL_kDHE|SSL_kECDHE)) {
356 				ret = ssl3_send_server_key_exchange(s);
357 				if (ret <= 0)
358 					goto end;
359 			} else
360 				skip = 1;
361 
362 			S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_A;
363 			s->internal->init_num = 0;
364 			break;
365 
366 		case SSL3_ST_SW_CERT_REQ_A:
367 		case SSL3_ST_SW_CERT_REQ_B:
368 			/*
369 			 * Determine whether or not we need to request a
370 			 * certificate.
371 			 *
372 			 * Do not request a certificate if:
373 			 *
374 			 * - We did not ask for it (SSL_VERIFY_PEER is unset).
375 			 *
376 			 * - SSL_VERIFY_CLIENT_ONCE is set and we are
377 			 *   renegotiating.
378 			 *
379 			 * - We are using an anonymous ciphersuites
380 			 *   (see section "Certificate request" in SSL 3 drafts
381 			 *   and in RFC 2246) ... except when the application
382 			 *   insists on verification (against the specs, but
383 			 *   s3_clnt.c accepts this for SSL 3).
384 			 */
385 			if (!(s->verify_mode & SSL_VERIFY_PEER) ||
386 			    ((s->session->peer != NULL) &&
387 			     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
388 			    ((S3I(s)->hs.new_cipher->algorithm_auth &
389 			     SSL_aNULL) && !(s->verify_mode &
390 			     SSL_VERIFY_FAIL_IF_NO_PEER_CERT))) {
391 				/* No cert request */
392 				skip = 1;
393 				S3I(s)->tmp.cert_request = 0;
394 				S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_A;
395 				if (S3I(s)->handshake_buffer) {
396 					if (!tls1_digest_cached_records(s)) {
397 						ret = -1;
398 						goto end;
399 					}
400 				}
401 			} else {
402 				S3I(s)->tmp.cert_request = 1;
403 				ret = ssl3_send_certificate_request(s);
404 				if (ret <= 0)
405 					goto end;
406 				S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_A;
407 				s->internal->init_num = 0;
408 			}
409 			break;
410 
411 		case SSL3_ST_SW_SRVR_DONE_A:
412 		case SSL3_ST_SW_SRVR_DONE_B:
413 			ret = ssl3_send_server_done(s);
414 			if (ret <= 0)
415 				goto end;
416 			S3I(s)->hs.next_state = SSL3_ST_SR_CERT_A;
417 			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
418 			s->internal->init_num = 0;
419 			break;
420 
421 		case SSL3_ST_SW_FLUSH:
422 
423 			/*
424 			 * This code originally checked to see if
425 			 * any data was pending using BIO_CTRL_INFO
426 			 * and then flushed. This caused problems
427 			 * as documented in PR#1939. The proposed
428 			 * fix doesn't completely resolve this issue
429 			 * as buggy implementations of BIO_CTRL_PENDING
430 			 * still exist. So instead we just flush
431 			 * unconditionally.
432 			 */
433 
434 			s->internal->rwstate = SSL_WRITING;
435 			if (BIO_flush(s->wbio) <= 0) {
436 				ret = -1;
437 				goto end;
438 			}
439 			s->internal->rwstate = SSL_NOTHING;
440 
441 			S3I(s)->hs.state = S3I(s)->hs.next_state;
442 			break;
443 
444 		case SSL3_ST_SR_CERT_A:
445 		case SSL3_ST_SR_CERT_B:
446 			if (S3I(s)->tmp.cert_request) {
447 				ret = ssl3_get_client_certificate(s);
448 				if (ret <= 0)
449 					goto end;
450 			}
451 			s->internal->init_num = 0;
452 			S3I(s)->hs.state = SSL3_ST_SR_KEY_EXCH_A;
453 			break;
454 
455 		case SSL3_ST_SR_KEY_EXCH_A:
456 		case SSL3_ST_SR_KEY_EXCH_B:
457 			ret = ssl3_get_client_key_exchange(s);
458 			if (ret <= 0)
459 				goto end;
460 			alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
461 			if (ret == 2) {
462 				/*
463 				 * For the ECDH ciphersuites when
464 				 * the client sends its ECDH pub key in
465 				 * a certificate, the CertificateVerify
466 				 * message is not sent.
467 				 * Also for GOST ciphersuites when
468 				 * the client uses its key from the certificate
469 				 * for key exchange.
470 				 */
471 				S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
472 				s->internal->init_num = 0;
473 			} else if (SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) {
474 				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
475 				s->internal->init_num = 0;
476 				if (!s->session->peer)
477 					break;
478 				/*
479 				 * For sigalgs freeze the handshake buffer
480 				 * at this point and digest cached records.
481 				 */
482 				if (!S3I(s)->handshake_buffer) {
483 					SSLerror(s, ERR_R_INTERNAL_ERROR);
484 					ret = -1;
485 					goto end;
486 				}
487 				s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
488 				if (!tls1_digest_cached_records(s)) {
489 					ret = -1;
490 					goto end;
491 				}
492 			} else {
493 				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
494 				s->internal->init_num = 0;
495 
496 				/*
497 				 * We need to get hashes here so if there is
498 				 * a client cert, it can be verified.
499 				 */
500 				if (S3I(s)->handshake_buffer) {
501 					if (!tls1_digest_cached_records(s)) {
502 						ret = -1;
503 						goto end;
504 					}
505 				}
506 				if (!tls1_handshake_hash_value(s,
507 				    S3I(s)->tmp.cert_verify_md,
508 				    sizeof(S3I(s)->tmp.cert_verify_md),
509 				    NULL)) {
510 				        ret = -1;
511 					goto end;
512 				}
513 			}
514 			break;
515 
516 		case SSL3_ST_SR_CERT_VRFY_A:
517 		case SSL3_ST_SR_CERT_VRFY_B:
518 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
519 
520 			/* we should decide if we expected this one */
521 			ret = ssl3_get_cert_verify(s);
522 			if (ret <= 0)
523 				goto end;
524 
525 			S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
526 			s->internal->init_num = 0;
527 			break;
528 
529 		case SSL3_ST_SR_FINISHED_A:
530 		case SSL3_ST_SR_FINISHED_B:
531 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
532 			ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
533 			    SSL3_ST_SR_FINISHED_B);
534 			if (ret <= 0)
535 				goto end;
536 			if (s->internal->hit)
537 				S3I(s)->hs.state = SSL_ST_OK;
538 			else if (s->internal->tlsext_ticket_expected)
539 				S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_A;
540 			else
541 				S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
542 			s->internal->init_num = 0;
543 			break;
544 
545 		case SSL3_ST_SW_SESSION_TICKET_A:
546 		case SSL3_ST_SW_SESSION_TICKET_B:
547 			ret = ssl3_send_newsession_ticket(s);
548 			if (ret <= 0)
549 				goto end;
550 			S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
551 			s->internal->init_num = 0;
552 			break;
553 
554 		case SSL3_ST_SW_CERT_STATUS_A:
555 		case SSL3_ST_SW_CERT_STATUS_B:
556 			ret = ssl3_send_cert_status(s);
557 			if (ret <= 0)
558 				goto end;
559 			S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
560 			s->internal->init_num = 0;
561 			break;
562 
563 
564 		case SSL3_ST_SW_CHANGE_A:
565 		case SSL3_ST_SW_CHANGE_B:
566 
567 			s->session->cipher = S3I(s)->hs.new_cipher;
568 			if (!tls1_setup_key_block(s)) {
569 				ret = -1;
570 				goto end;
571 			}
572 
573 			ret = ssl3_send_change_cipher_spec(s,
574 			    SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B);
575 
576 			if (ret <= 0)
577 				goto end;
578 			S3I(s)->hs.state = SSL3_ST_SW_FINISHED_A;
579 			s->internal->init_num = 0;
580 
581 			if (!tls1_change_cipher_state(
582 			    s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
583 				ret = -1;
584 				goto end;
585 			}
586 
587 			break;
588 
589 		case SSL3_ST_SW_FINISHED_A:
590 		case SSL3_ST_SW_FINISHED_B:
591 			ret = ssl3_send_finished(s,
592 			SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
593 			TLS_MD_SERVER_FINISH_CONST,
594 			TLS_MD_SERVER_FINISH_CONST_SIZE);
595 			if (ret <= 0)
596 				goto end;
597 			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
598 			if (s->internal->hit)
599 				S3I(s)->hs.next_state = SSL3_ST_SR_FINISHED_A;
600 			else
601 				S3I(s)->hs.next_state = SSL_ST_OK;
602 			s->internal->init_num = 0;
603 			break;
604 
605 		case SSL_ST_OK:
606 			/* clean a few things up */
607 			tls1_cleanup_key_block(s);
608 
609 			BUF_MEM_free(s->internal->init_buf);
610 			s->internal->init_buf = NULL;
611 
612 			/* remove buffering on output */
613 			ssl_free_wbio_buffer(s);
614 
615 			s->internal->init_num = 0;
616 
617 			/* skipped if we just sent a HelloRequest */
618 			if (s->internal->renegotiate == 2) {
619 				s->internal->renegotiate = 0;
620 				s->internal->new_session = 0;
621 
622 				ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
623 
624 				s->ctx->internal->stats.sess_accept_good++;
625 				/* s->server=1; */
626 				s->internal->handshake_func = ssl3_accept;
627 
628 				if (cb != NULL)
629 					cb(s, SSL_CB_HANDSHAKE_DONE, 1);
630 			}
631 
632 			ret = 1;
633 			goto end;
634 			/* break; */
635 
636 		default:
637 			SSLerror(s, SSL_R_UNKNOWN_STATE);
638 			ret = -1;
639 			goto end;
640 			/* break; */
641 		}
642 
643 		if (!S3I(s)->tmp.reuse_message && !skip) {
644 			if (s->internal->debug) {
645 				if ((ret = BIO_flush(s->wbio)) <= 0)
646 					goto end;
647 			}
648 
649 
650 			if ((cb != NULL) && (S3I(s)->hs.state != state)) {
651 				new_state = S3I(s)->hs.state;
652 				S3I(s)->hs.state = state;
653 				cb(s, SSL_CB_ACCEPT_LOOP, 1);
654 				S3I(s)->hs.state = new_state;
655 			}
656 		}
657 		skip = 0;
658 	}
659 end:
660 	/* BIO_flush(s->wbio); */
661 
662 	s->internal->in_handshake--;
663 	if (cb != NULL)
664 		cb(s, SSL_CB_ACCEPT_EXIT, ret);
665 	return (ret);
666 }
667 
668 int
669 ssl3_send_hello_request(SSL *s)
670 {
671 	CBB cbb, hello;
672 
673 	memset(&cbb, 0, sizeof(cbb));
674 
675 	if (S3I(s)->hs.state == SSL3_ST_SW_HELLO_REQ_A) {
676 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &hello,
677 		    SSL3_MT_HELLO_REQUEST))
678 			goto err;
679 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
680 			goto err;
681 
682 		S3I(s)->hs.state = SSL3_ST_SW_HELLO_REQ_B;
683 	}
684 
685 	/* SSL3_ST_SW_HELLO_REQ_B */
686 	return (ssl3_handshake_write(s));
687 
688  err:
689 	CBB_cleanup(&cbb);
690 
691 	return (-1);
692 }
693 
694 int
695 ssl3_get_client_hello(SSL *s)
696 {
697 	CBS cbs, client_random, session_id, cookie, cipher_suites;
698 	CBS compression_methods;
699 	uint16_t client_version;
700 	uint8_t comp_method;
701 	int comp_null;
702 	int i, j, ok, al, ret = -1, cookie_valid = 0;
703 	long n;
704 	unsigned long id;
705 	unsigned char *p, *d;
706 	SSL_CIPHER *c;
707 	STACK_OF(SSL_CIPHER) *ciphers = NULL;
708 	unsigned long alg_k;
709 	const SSL_METHOD *method;
710 	uint16_t shared_version;
711 	unsigned char *end;
712 
713 	/*
714 	 * We do this so that we will respond with our native type.
715 	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
716 	 * This down switching should be handled by a different method.
717 	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
718 	 * TLSv1.
719 	 */
720 	if (S3I(s)->hs.state == SSL3_ST_SR_CLNT_HELLO_A) {
721 		S3I(s)->hs.state = SSL3_ST_SR_CLNT_HELLO_B;
722 	}
723 
724 	s->internal->first_packet = 1;
725 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
726 	    SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
727 	    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
728 	if (!ok)
729 		return ((int)n);
730 	s->internal->first_packet = 0;
731 
732 	if (n < 0)
733 		goto err;
734 
735 	d = p = (unsigned char *)s->internal->init_msg;
736 	end = d + n;
737 
738 	CBS_init(&cbs, s->internal->init_msg, n);
739 
740 	/*
741 	 * Use version from inside client hello, not from record header.
742 	 * (may differ: see RFC 2246, Appendix E, second paragraph)
743 	 */
744 	if (!CBS_get_u16(&cbs, &client_version))
745 		goto truncated;
746 
747 	if (ssl_max_shared_version(s, client_version, &shared_version) != 1) {
748 		SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
749 		if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
750 		    !s->internal->enc_write_ctx && !s->internal->write_hash) {
751 			/*
752 			 * Similar to ssl3_get_record, send alert using remote
753 			 * version number.
754 			 */
755 			s->version = s->client_version;
756 		}
757 		al = SSL_AD_PROTOCOL_VERSION;
758 		goto f_err;
759 	}
760 	s->client_version = client_version;
761 	s->version = shared_version;
762 
763 	if ((method = tls1_get_server_method(shared_version)) == NULL)
764 		method = dtls1_get_server_method(shared_version);
765 	if (method == NULL) {
766 		SSLerror(s, ERR_R_INTERNAL_ERROR);
767 		goto err;
768 	}
769 	s->method = method;
770 
771 	if (!CBS_get_bytes(&cbs, &client_random, SSL3_RANDOM_SIZE))
772 		goto truncated;
773 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
774 		goto truncated;
775 
776 	/*
777 	 * If we require cookies (DTLS) and this ClientHello doesn't
778 	 * contain one, just return since we do not want to
779 	 * allocate any memory yet. So check cookie length...
780 	 */
781 	if (SSL_IS_DTLS(s)) {
782 		if (!CBS_get_u8_length_prefixed(&cbs, &cookie))
783 			goto truncated;
784 		if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
785 			if (CBS_len(&cookie) == 0)
786 				return (1);
787 		}
788 	}
789 
790 	if (!CBS_write_bytes(&client_random, s->s3->client_random,
791 	    sizeof(s->s3->client_random), NULL))
792 		goto err;
793 
794 	s->internal->hit = 0;
795 
796 	/*
797 	 * Versions before 0.9.7 always allow clients to resume sessions in
798 	 * renegotiation. 0.9.7 and later allow this by default, but optionally
799 	 * ignore resumption requests with flag
800 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
801 	 * rather than a change to default behavior so that applications
802 	 * relying on this for security won't even compile against older
803 	 * library versions).
804 	 *
805 	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
806 	 * to request renegotiation but not a new session (s->internal->new_session
807 	 * remains unset): for servers, this essentially just means that the
808 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
809 	 * ignored.
810 	 */
811 	if ((s->internal->new_session && (s->internal->options &
812 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
813 		if (!ssl_get_new_session(s, 1))
814 			goto err;
815 	} else {
816 		/* XXX - pass CBS through instead... */
817 		i = ssl_get_prev_session(s,
818 		    (unsigned char *)CBS_data(&session_id),
819 		    CBS_len(&session_id), end);
820 		if (i == 1) { /* previous session */
821 			s->internal->hit = 1;
822 		} else if (i == -1)
823 			goto err;
824 		else {
825 			/* i == 0 */
826 			if (!ssl_get_new_session(s, 1))
827 				goto err;
828 		}
829 	}
830 
831 	if (SSL_IS_DTLS(s)) {
832 		/*
833 		 * The ClientHello may contain a cookie even if the HelloVerify
834 		 * message has not been sent - make sure that it does not cause
835 		 * an overflow.
836 		 */
837 		if (CBS_len(&cookie) > sizeof(D1I(s)->rcvd_cookie)) {
838 			al = SSL_AD_DECODE_ERROR;
839 			SSLerror(s, SSL_R_COOKIE_MISMATCH);
840 			goto f_err;
841 		}
842 
843 		/* Verify the cookie if appropriate option is set. */
844 		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
845 		    CBS_len(&cookie) > 0) {
846 			size_t cookie_len;
847 
848 			/* XXX - rcvd_cookie seems to only be used here... */
849 			if (!CBS_write_bytes(&cookie, D1I(s)->rcvd_cookie,
850 			    sizeof(D1I(s)->rcvd_cookie), &cookie_len))
851 				goto err;
852 
853 			if (s->ctx->internal->app_verify_cookie_cb != NULL) {
854 				if (s->ctx->internal->app_verify_cookie_cb(s,
855 				    D1I(s)->rcvd_cookie, cookie_len) == 0) {
856 					al = SSL_AD_HANDSHAKE_FAILURE;
857 					SSLerror(s, SSL_R_COOKIE_MISMATCH);
858 					goto f_err;
859 				}
860 				/* else cookie verification succeeded */
861 			/* XXX - can d1->cookie_len > sizeof(rcvd_cookie) ? */
862 			} else if (timingsafe_memcmp(D1I(s)->rcvd_cookie,
863 			    D1I(s)->cookie, D1I(s)->cookie_len) != 0) {
864 				/* default verification */
865 				al = SSL_AD_HANDSHAKE_FAILURE;
866 				SSLerror(s, SSL_R_COOKIE_MISMATCH);
867 				goto f_err;
868 			}
869 			cookie_valid = 1;
870 		}
871 	}
872 
873 	if (!CBS_get_u16_length_prefixed(&cbs, &cipher_suites))
874 		goto truncated;
875 
876 	/* XXX - This logic seems wrong... */
877 	if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
878 		/* we need a cipher if we are not resuming a session */
879 		al = SSL_AD_ILLEGAL_PARAMETER;
880 		SSLerror(s, SSL_R_NO_CIPHERS_SPECIFIED);
881 		goto f_err;
882 	}
883 
884 	if (CBS_len(&cipher_suites) > 0) {
885 		if ((ciphers = ssl_bytes_to_cipher_list(s,
886 		    CBS_data(&cipher_suites), CBS_len(&cipher_suites))) == NULL)
887 			goto err;
888 	}
889 
890 	/* If it is a hit, check that the cipher is in the list */
891 	if (s->internal->hit && CBS_len(&cipher_suites) > 0) {
892 		j = 0;
893 		id = s->session->cipher->id;
894 
895 		for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
896 			c = sk_SSL_CIPHER_value(ciphers, i);
897 			if (c->id == id) {
898 				j = 1;
899 				break;
900 			}
901 		}
902 		if (j == 0) {
903 			/*
904 			 * We need to have the cipher in the cipher
905 			 * list if we are asked to reuse it
906 			 */
907 			al = SSL_AD_ILLEGAL_PARAMETER;
908 			SSLerror(s, SSL_R_REQUIRED_CIPHER_MISSING);
909 			goto f_err;
910 		}
911 	}
912 
913 	if (!CBS_get_u8_length_prefixed(&cbs, &compression_methods))
914 		goto truncated;
915 
916 	comp_null = 0;
917 	while (CBS_len(&compression_methods) > 0) {
918 		if (!CBS_get_u8(&compression_methods, &comp_method))
919 			goto truncated;
920 		if (comp_method == 0)
921 			comp_null = 1;
922 	}
923 	if (comp_null == 0) {
924 		al = SSL_AD_DECODE_ERROR;
925 		SSLerror(s, SSL_R_NO_COMPRESSION_SPECIFIED);
926 		goto f_err;
927 	}
928 
929 	p = (unsigned char *)CBS_data(&cbs);
930 
931 	/* TLS extensions*/
932 	if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
933 		/* 'al' set by ssl_parse_clienthello_tlsext */
934 		SSLerror(s, SSL_R_PARSE_TLSEXT);
935 		goto f_err;
936 	}
937 	if (ssl_check_clienthello_tlsext_early(s) <= 0) {
938 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
939 		goto err;
940 	}
941 
942 	/*
943 	 * Check if we want to use external pre-shared secret for this
944 	 * handshake for not reused session only. We need to generate
945 	 * server_random before calling tls_session_secret_cb in order to allow
946 	 * SessionTicket processing to use it in key derivation.
947 	 */
948 	arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
949 
950 	if (!s->internal->hit && s->internal->tls_session_secret_cb) {
951 		SSL_CIPHER *pref_cipher = NULL;
952 
953 		s->session->master_key_length = sizeof(s->session->master_key);
954 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
955 		    &s->session->master_key_length, ciphers, &pref_cipher,
956 		    s->internal->tls_session_secret_cb_arg)) {
957 			s->internal->hit = 1;
958 			s->session->ciphers = ciphers;
959 			s->session->verify_result = X509_V_OK;
960 
961 			ciphers = NULL;
962 
963 			/* check if some cipher was preferred by call back */
964 			pref_cipher = pref_cipher ? pref_cipher :
965 			    ssl3_choose_cipher(s, s->session->ciphers,
966 			    SSL_get_ciphers(s));
967 			if (pref_cipher == NULL) {
968 				al = SSL_AD_HANDSHAKE_FAILURE;
969 				SSLerror(s, SSL_R_NO_SHARED_CIPHER);
970 				goto f_err;
971 			}
972 
973 			s->session->cipher = pref_cipher;
974 
975 			sk_SSL_CIPHER_free(s->cipher_list);
976 			sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
977 
978 			s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
979 			s->internal->cipher_list_by_id =
980 			    sk_SSL_CIPHER_dup(s->session->ciphers);
981 		}
982 	}
983 
984 	/*
985 	 * Given s->session->ciphers and SSL_get_ciphers, we must
986 	 * pick a cipher
987 	 */
988 
989 	if (!s->internal->hit) {
990 		sk_SSL_CIPHER_free(s->session->ciphers);
991 		s->session->ciphers = ciphers;
992 		if (ciphers == NULL) {
993 			al = SSL_AD_ILLEGAL_PARAMETER;
994 			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
995 			goto f_err;
996 		}
997 		ciphers = NULL;
998 		c = ssl3_choose_cipher(s, s->session->ciphers,
999 		SSL_get_ciphers(s));
1000 
1001 		if (c == NULL) {
1002 			al = SSL_AD_HANDSHAKE_FAILURE;
1003 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1004 			goto f_err;
1005 		}
1006 		S3I(s)->hs.new_cipher = c;
1007 	} else {
1008 		S3I(s)->hs.new_cipher = s->session->cipher;
1009 	}
1010 
1011 	if (!tls1_handshake_hash_init(s))
1012 		goto err;
1013 
1014 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1015 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1016 	    !(s->verify_mode & SSL_VERIFY_PEER)) {
1017 		if (!tls1_digest_cached_records(s)) {
1018 			al = SSL_AD_INTERNAL_ERROR;
1019 			goto f_err;
1020 		}
1021 	}
1022 
1023 	/*
1024 	 * We now have the following setup.
1025 	 * client_random
1026 	 * cipher_list 		- our prefered list of ciphers
1027 	 * ciphers 		- the clients prefered list of ciphers
1028 	 * compression		- basically ignored right now
1029 	 * ssl version is set	- sslv3
1030 	 * s->session		- The ssl session has been setup.
1031 	 * s->internal->hit		- session reuse flag
1032 	 * s->hs.new_cipher	- the new cipher to use.
1033 	 */
1034 
1035 	/* Handles TLS extensions that we couldn't check earlier */
1036 	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1037 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1038 		goto err;
1039 	}
1040 
1041 	ret = cookie_valid ? 2 : 1;
1042 
1043 	if (0) {
1044 truncated:
1045 		al = SSL_AD_DECODE_ERROR;
1046 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1047 f_err:
1048 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1049 	}
1050 err:
1051 	sk_SSL_CIPHER_free(ciphers);
1052 
1053 	return (ret);
1054 }
1055 
1056 int
1057 ssl3_send_server_hello(SSL *s)
1058 {
1059 	unsigned char *bufend;
1060 	unsigned char *p, *d;
1061 	CBB cbb, session_id;
1062 	size_t outlen;
1063 	int sl;
1064 
1065 	memset(&cbb, 0, sizeof(cbb));
1066 
1067 	bufend = (unsigned char *)s->internal->init_buf->data + SSL3_RT_MAX_PLAIN_LENGTH;
1068 
1069 	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
1070 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_SERVER_HELLO);
1071 
1072 		if (!CBB_init_fixed(&cbb, p, bufend - p))
1073 			goto err;
1074 
1075 		if (!CBB_add_u16(&cbb, s->version))
1076 			goto err;
1077 		if (!CBB_add_bytes(&cbb, s->s3->server_random,
1078 		    sizeof(s->s3->server_random)))
1079 			goto err;
1080 
1081 		/*
1082 		 * There are several cases for the session ID to send
1083 		 * back in the server hello:
1084 		 *
1085 		 * - For session reuse from the session cache,
1086 		 *   we send back the old session ID.
1087 		 * - If stateless session reuse (using a session ticket)
1088 		 *   is successful, we send back the client's "session ID"
1089 		 *   (which doesn't actually identify the session).
1090 		 * - If it is a new session, we send back the new
1091 		 *   session ID.
1092 		 * - However, if we want the new session to be single-use,
1093 		 *   we send back a 0-length session ID.
1094 		 *
1095 		 * s->internal->hit is non-zero in either case of session reuse,
1096 		 * so the following won't overwrite an ID that we're supposed
1097 		 * to send back.
1098 		 */
1099 		if (!(s->ctx->internal->session_cache_mode & SSL_SESS_CACHE_SERVER)
1100 		    && !s->internal->hit)
1101 			s->session->session_id_length = 0;
1102 
1103 		sl = s->session->session_id_length;
1104 		if (sl > (int)sizeof(s->session->session_id)) {
1105 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1106 			goto err;
1107 		}
1108 
1109 		if (!CBB_add_u8_length_prefixed(&cbb, &session_id))
1110 			goto err;
1111 		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1112 			goto err;
1113 
1114 		/* Cipher suite. */
1115 		if (!CBB_add_u16(&cbb,
1116 		    ssl3_cipher_get_value(S3I(s)->hs.new_cipher)))
1117 			goto err;
1118 
1119 		/* Compression method. */
1120 		if (!CBB_add_u8(&cbb, 0))
1121 			goto err;
1122 
1123 		if (!CBB_finish(&cbb, NULL, &outlen))
1124 			goto err;
1125 
1126 		if ((p = ssl_add_serverhello_tlsext(s, p + outlen,
1127 		    bufend)) == NULL) {
1128 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1129 			goto err;
1130 		}
1131 
1132 		ssl3_handshake_msg_finish(s, p - d);
1133 	}
1134 
1135 	/* SSL3_ST_SW_SRVR_HELLO_B */
1136 	return (ssl3_handshake_write(s));
1137 
1138  err:
1139 	CBB_cleanup(&cbb);
1140 
1141 	return (-1);
1142 }
1143 
1144 int
1145 ssl3_send_server_done(SSL *s)
1146 {
1147 	CBB cbb, done;
1148 
1149 	memset(&cbb, 0, sizeof(cbb));
1150 
1151 	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_DONE_A) {
1152 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &done,
1153 		    SSL3_MT_SERVER_DONE))
1154 			goto err;
1155 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1156 			goto err;
1157 
1158 		S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_B;
1159 	}
1160 
1161 	/* SSL3_ST_SW_SRVR_DONE_B */
1162 	return (ssl3_handshake_write(s));
1163 
1164  err:
1165 	CBB_cleanup(&cbb);
1166 
1167 	return (-1);
1168 }
1169 
1170 int
1171 ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1172 {
1173 	CBB dh_p, dh_g, dh_Ys;
1174 	DH *dh = NULL, *dhp;
1175 	unsigned char *data;
1176 	int al;
1177 
1178 	if (s->cert->dh_tmp_auto != 0) {
1179 		if ((dhp = ssl_get_auto_dh(s)) == NULL) {
1180 			al = SSL_AD_INTERNAL_ERROR;
1181 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1182 			goto f_err;
1183 		}
1184 	} else
1185 		dhp = s->cert->dh_tmp;
1186 
1187 	if (dhp == NULL && s->cert->dh_tmp_cb != NULL)
1188 		dhp = s->cert->dh_tmp_cb(s, 0,
1189 		    SSL_C_PKEYLENGTH(S3I(s)->hs.new_cipher));
1190 
1191 	if (dhp == NULL) {
1192 		al = SSL_AD_HANDSHAKE_FAILURE;
1193 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1194 		goto f_err;
1195 	}
1196 
1197 	if (S3I(s)->tmp.dh != NULL) {
1198 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1199 		goto err;
1200 	}
1201 
1202 	if (s->cert->dh_tmp_auto != 0) {
1203 		dh = dhp;
1204 	} else if ((dh = DHparams_dup(dhp)) == NULL) {
1205 		SSLerror(s, ERR_R_DH_LIB);
1206 		goto err;
1207 	}
1208 	S3I(s)->tmp.dh = dh;
1209 	if (!DH_generate_key(dh)) {
1210 		SSLerror(s, ERR_R_DH_LIB);
1211 		goto err;
1212 	}
1213 
1214 	/*
1215 	 * Serialize the DH parameters and public key.
1216 	 */
1217 	if (!CBB_add_u16_length_prefixed(cbb, &dh_p))
1218 		goto err;
1219 	if (!CBB_add_space(&dh_p, &data, BN_num_bytes(dh->p)))
1220 		goto err;
1221 	BN_bn2bin(dh->p, data);
1222 
1223 	if (!CBB_add_u16_length_prefixed(cbb, &dh_g))
1224 		goto err;
1225 	if (!CBB_add_space(&dh_g, &data, BN_num_bytes(dh->g)))
1226 		goto err;
1227 	BN_bn2bin(dh->g, data);
1228 
1229 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Ys))
1230 		goto err;
1231 	if (!CBB_add_space(&dh_Ys, &data, BN_num_bytes(dh->pub_key)))
1232 		goto err;
1233 	BN_bn2bin(dh->pub_key, data);
1234 
1235 	if (!CBB_flush(cbb))
1236 		goto err;
1237 
1238 	return (1);
1239 
1240  f_err:
1241 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1242  err:
1243 	return (-1);
1244 }
1245 
1246 static int
1247 ssl3_send_server_kex_ecdhe_ecp(SSL *s, int nid, CBB *cbb)
1248 {
1249 	const EC_GROUP *group;
1250 	const EC_POINT *pubkey;
1251 	unsigned char *data;
1252 	int encoded_len = 0;
1253 	int curve_id = 0;
1254 	BN_CTX *bn_ctx = NULL;
1255 	EC_KEY *ecdh;
1256 	CBB ecpoint;
1257 	int al;
1258 
1259 	/*
1260 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1261 	 * For supported named curves, curve_id is non-zero.
1262 	 */
1263 	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1264 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1265 		goto err;
1266 	}
1267 
1268 	if (S3I(s)->tmp.ecdh != NULL) {
1269 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1270 		goto err;
1271 	}
1272 
1273 	if ((S3I(s)->tmp.ecdh = EC_KEY_new_by_curve_name(nid)) == NULL) {
1274 		al = SSL_AD_HANDSHAKE_FAILURE;
1275 		SSLerror(s, SSL_R_MISSING_TMP_ECDH_KEY);
1276 		goto f_err;
1277 	}
1278 	ecdh = S3I(s)->tmp.ecdh;
1279 
1280 	if (!EC_KEY_generate_key(ecdh)) {
1281 		SSLerror(s, ERR_R_ECDH_LIB);
1282 		goto err;
1283 	}
1284 	if ((group = EC_KEY_get0_group(ecdh)) == NULL ||
1285 	    (pubkey = EC_KEY_get0_public_key(ecdh)) == NULL ||
1286 	    EC_KEY_get0_private_key(ecdh) == NULL) {
1287 		SSLerror(s, ERR_R_ECDH_LIB);
1288 		goto err;
1289 	}
1290 
1291 	/*
1292 	 * Encode the public key.
1293 	 */
1294 	encoded_len = EC_POINT_point2oct(group, pubkey,
1295 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
1296 	if (encoded_len == 0) {
1297 		SSLerror(s, ERR_R_ECDH_LIB);
1298 		goto err;
1299 	}
1300 	if ((bn_ctx = BN_CTX_new()) == NULL) {
1301 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1302 		goto err;
1303 	}
1304 
1305 	/*
1306 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1307 	 * In this case the ServerKeyExchange message has:
1308 	 * [1 byte CurveType], [2 byte CurveName]
1309 	 * [1 byte length of encoded point], followed by
1310 	 * the actual encoded point itself.
1311 	 */
1312 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1313 		goto err;
1314 	if (!CBB_add_u16(cbb, curve_id))
1315 		goto err;
1316 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1317 		goto err;
1318 	if (!CBB_add_space(&ecpoint, &data, encoded_len))
1319 		goto err;
1320 	if (EC_POINT_point2oct(group, pubkey, POINT_CONVERSION_UNCOMPRESSED,
1321 	    data, encoded_len, bn_ctx) == 0) {
1322 		SSLerror(s, ERR_R_ECDH_LIB);
1323 		goto err;
1324 	}
1325 	if (!CBB_flush(cbb))
1326 		goto err;
1327 
1328 	BN_CTX_free(bn_ctx);
1329 
1330 	return (1);
1331 
1332  f_err:
1333 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1334  err:
1335 	BN_CTX_free(bn_ctx);
1336 
1337 	return (-1);
1338 }
1339 
1340 static int
1341 ssl3_send_server_kex_ecdhe_ecx(SSL *s, int nid, CBB *cbb)
1342 {
1343 	uint8_t *public_key = NULL;
1344 	int curve_id;
1345 	CBB ecpoint;
1346 	int ret = -1;
1347 
1348 	/* Generate an X25519 key pair. */
1349 	if (S3I(s)->tmp.x25519 != NULL) {
1350 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1351 		goto err;
1352 	}
1353 	if ((S3I(s)->tmp.x25519 = malloc(X25519_KEY_LENGTH)) == NULL)
1354 		goto err;
1355 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
1356 		goto err;
1357 	X25519_keypair(public_key, S3I(s)->tmp.x25519);
1358 
1359 	/* Serialize public key. */
1360 	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1361 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1362 		goto err;
1363 	}
1364 
1365 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1366 		goto err;
1367 	if (!CBB_add_u16(cbb, curve_id))
1368 		goto err;
1369 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1370 		goto err;
1371 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
1372 		goto err;
1373 	if (!CBB_flush(cbb))
1374 		goto err;
1375 
1376 	ret = 1;
1377 
1378  err:
1379 	free(public_key);
1380 
1381 	return (ret);
1382 }
1383 
1384 static int
1385 ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1386 {
1387 	int nid;
1388 
1389 	nid = tls1_get_shared_curve(s);
1390 
1391 	if (nid == NID_X25519)
1392 		return ssl3_send_server_kex_ecdhe_ecx(s, nid, cbb);
1393 
1394 	return ssl3_send_server_kex_ecdhe_ecp(s, nid, cbb);
1395 }
1396 
1397 int
1398 ssl3_send_server_key_exchange(SSL *s)
1399 {
1400 	CBB cbb;
1401 	unsigned char *params = NULL;
1402 	size_t params_len;
1403 	unsigned char *q;
1404 	unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1405 	unsigned int u;
1406 	EVP_PKEY *pkey;
1407 	const EVP_MD *md = NULL;
1408 	unsigned char *p, *d;
1409 	int al, i, j, n, kn;
1410 	unsigned long type;
1411 	BUF_MEM *buf;
1412 	EVP_MD_CTX md_ctx;
1413 
1414 	memset(&cbb, 0, sizeof(cbb));
1415 
1416 	EVP_MD_CTX_init(&md_ctx);
1417 	if (S3I(s)->hs.state == SSL3_ST_SW_KEY_EXCH_A) {
1418 		type = S3I(s)->hs.new_cipher->algorithm_mkey;
1419 
1420 		buf = s->internal->init_buf;
1421 
1422 		if (!CBB_init(&cbb, 0))
1423 			goto err;
1424 
1425 		if (type & SSL_kDHE) {
1426 			if (ssl3_send_server_kex_dhe(s, &cbb) != 1)
1427 				goto err;
1428 		} else if (type & SSL_kECDHE) {
1429 			if (ssl3_send_server_kex_ecdhe(s, &cbb) != 1)
1430 				goto err;
1431 		} else {
1432 			al = SSL_AD_HANDSHAKE_FAILURE;
1433 			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1434 			goto f_err;
1435 		}
1436 
1437 		if (!CBB_finish(&cbb, &params, &params_len))
1438 			goto err;
1439 
1440 		if (!(S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL)) {
1441 			if ((pkey = ssl_get_sign_pkey(
1442 			    s, S3I(s)->hs.new_cipher, &md)) == NULL) {
1443 				al = SSL_AD_DECODE_ERROR;
1444 				goto f_err;
1445 			}
1446 			kn = EVP_PKEY_size(pkey);
1447 		} else {
1448 			pkey = NULL;
1449 			kn = 0;
1450 		}
1451 
1452 		if (!BUF_MEM_grow_clean(buf, ssl3_handshake_msg_hdr_len(s) +
1453 		    params_len + kn)) {
1454 			SSLerror(s, ERR_LIB_BUF);
1455 			goto err;
1456 		}
1457 
1458 		d = p = ssl3_handshake_msg_start(s,
1459 		    SSL3_MT_SERVER_KEY_EXCHANGE);
1460 
1461 		memcpy(p, params, params_len);
1462 
1463 		free(params);
1464 		params = NULL;
1465 
1466 		n = params_len;
1467 		p += params_len;
1468 
1469 		/* not anonymous */
1470 		if (pkey != NULL) {
1471 			/*
1472 			 * n is the length of the params, they start at &(d[4])
1473 			 * and p points to the space at the end.
1474 			 */
1475 			if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1476 				q = md_buf;
1477 				j = 0;
1478 				if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(),
1479 				    NULL))
1480 					goto err;
1481 				EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1482 				    SSL3_RANDOM_SIZE);
1483 				EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1484 				    SSL3_RANDOM_SIZE);
1485 				EVP_DigestUpdate(&md_ctx, d, n);
1486 				EVP_DigestFinal_ex(&md_ctx, q,
1487 				    (unsigned int *)&i);
1488 				q += i;
1489 				j += i;
1490 				if (RSA_sign(NID_md5_sha1, md_buf, j,
1491 				    &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1492 					SSLerror(s, ERR_R_RSA_LIB);
1493 					goto err;
1494 				}
1495 				s2n(u, p);
1496 				n += u + 2;
1497 			} else if (md) {
1498 				/* Send signature algorithm. */
1499 				if (SSL_USE_SIGALGS(s)) {
1500 					if (!tls12_get_sigandhash(p, pkey, md)) {
1501 						/* Should never happen */
1502 						al = SSL_AD_INTERNAL_ERROR;
1503 						SSLerror(s, ERR_R_INTERNAL_ERROR);
1504 						goto f_err;
1505 					}
1506 					p += 2;
1507 				}
1508 				EVP_SignInit_ex(&md_ctx, md, NULL);
1509 				EVP_SignUpdate(&md_ctx,
1510 				    s->s3->client_random,
1511 				    SSL3_RANDOM_SIZE);
1512 				EVP_SignUpdate(&md_ctx,
1513 				    s->s3->server_random,
1514 				    SSL3_RANDOM_SIZE);
1515 				EVP_SignUpdate(&md_ctx, d, n);
1516 				if (!EVP_SignFinal(&md_ctx, &p[2],
1517 					(unsigned int *)&i, pkey)) {
1518 					SSLerror(s, ERR_R_EVP_LIB);
1519 					goto err;
1520 				}
1521 				s2n(i, p);
1522 				n += i + 2;
1523 				if (SSL_USE_SIGALGS(s))
1524 					n += 2;
1525 			} else {
1526 				/* Is this error check actually needed? */
1527 				al = SSL_AD_HANDSHAKE_FAILURE;
1528 				SSLerror(s, SSL_R_UNKNOWN_PKEY_TYPE);
1529 				goto f_err;
1530 			}
1531 		}
1532 
1533 		ssl3_handshake_msg_finish(s, n);
1534 	}
1535 
1536 	S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1537 
1538 	EVP_MD_CTX_cleanup(&md_ctx);
1539 
1540 	return (ssl3_handshake_write(s));
1541 
1542  f_err:
1543 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1544  err:
1545 	free(params);
1546 	EVP_MD_CTX_cleanup(&md_ctx);
1547 	CBB_cleanup(&cbb);
1548 
1549 	return (-1);
1550 }
1551 
1552 int
1553 ssl3_send_certificate_request(SSL *s)
1554 {
1555 	CBB cbb, cert_request, cert_types, sigalgs, cert_auth, dn;
1556 	STACK_OF(X509_NAME) *sk = NULL;
1557 	X509_NAME *name;
1558 	int i;
1559 
1560 	/*
1561 	 * Certificate Request - RFC 5246 section 7.4.4.
1562 	 */
1563 
1564 	memset(&cbb, 0, sizeof(cbb));
1565 
1566 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1567 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &cert_request,
1568 		    SSL3_MT_CERTIFICATE_REQUEST))
1569 			goto err;
1570 
1571 		if (!CBB_add_u8_length_prefixed(&cert_request, &cert_types))
1572 			goto err;
1573 		if (!ssl3_get_req_cert_types(s, &cert_types))
1574 			goto err;
1575 
1576 		if (SSL_USE_SIGALGS(s)) {
1577 			unsigned char *sigalgs_data;
1578 			size_t sigalgs_len;
1579 
1580 			tls12_get_req_sig_algs(s, &sigalgs_data, &sigalgs_len);
1581 
1582 			if (!CBB_add_u16_length_prefixed(&cert_request, &sigalgs))
1583 				goto err;
1584 			if (!CBB_add_bytes(&sigalgs, sigalgs_data, sigalgs_len))
1585 				goto err;
1586 		}
1587 
1588 		if (!CBB_add_u16_length_prefixed(&cert_request, &cert_auth))
1589 			goto err;
1590 
1591 		sk = SSL_get_client_CA_list(s);
1592 		for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1593 			unsigned char *name_data;
1594 			size_t name_len;
1595 
1596 			name = sk_X509_NAME_value(sk, i);
1597 			name_len = i2d_X509_NAME(name, NULL);
1598 
1599 			if (!CBB_add_u16_length_prefixed(&cert_auth, &dn))
1600 				goto err;
1601 			if (!CBB_add_space(&dn, &name_data, name_len))
1602 				goto err;
1603 			if (i2d_X509_NAME(name, &name_data) != name_len)
1604 				goto err;
1605 		}
1606 
1607 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1608 			goto err;
1609 
1610 		S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_B;
1611 	}
1612 
1613 	/* SSL3_ST_SW_CERT_REQ_B */
1614 	return (ssl3_handshake_write(s));
1615 
1616  err:
1617 	CBB_cleanup(&cbb);
1618 
1619 	return (-1);
1620 }
1621 
1622 static int
1623 ssl3_get_client_kex_rsa(SSL *s, unsigned char *p, long n)
1624 {
1625 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1626 	unsigned char *d;
1627 	RSA *rsa = NULL;
1628 	EVP_PKEY *pkey = NULL;
1629 	int i, al;
1630 
1631 	d = p;
1632 
1633 	arc4random_buf(fakekey, sizeof(fakekey));
1634 	fakekey[0] = s->client_version >> 8;
1635 	fakekey[1] = s->client_version & 0xff;
1636 
1637 	pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1638 	if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1639 	    (pkey->pkey.rsa == NULL)) {
1640 		al = SSL_AD_HANDSHAKE_FAILURE;
1641 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1642 		goto f_err;
1643 	}
1644 	rsa = pkey->pkey.rsa;
1645 
1646 	if (2 > n)
1647 		goto truncated;
1648 	n2s(p, i);
1649 	if (n != i + 2) {
1650 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1651 		goto err;
1652 	} else
1653 		n = i;
1654 
1655 	i = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1656 
1657 	ERR_clear_error();
1658 
1659 	al = -1;
1660 
1661 	if (i != SSL_MAX_MASTER_KEY_LENGTH) {
1662 		al = SSL_AD_DECODE_ERROR;
1663 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1664 	}
1665 
1666 	if (p - d + 2 > n)	/* needed in the SSL3 case */
1667 		goto truncated;
1668 	if ((al == -1) && !((p[0] == (s->client_version >> 8)) &&
1669 	    (p[1] == (s->client_version & 0xff)))) {
1670 		/*
1671 		 * The premaster secret must contain the same version
1672 		 * number as the ClientHello to detect version rollback
1673 		 * attacks (strangely, the protocol does not offer such
1674 		 * protection for DH ciphersuites).
1675 		 * However, buggy clients exist that send the negotiated
1676 		 * protocol version instead if the server does not
1677 		 * support the requested protocol version.
1678 		 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1679 		 * clients.
1680 		 */
1681 		if (!((s->internal->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1682 		    (p[0] == (s->version >> 8)) &&
1683 		    (p[1] == (s->version & 0xff)))) {
1684 			al = SSL_AD_DECODE_ERROR;
1685 			/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1686 
1687 			/*
1688 			 * The Klima-Pokorny-Rosa extension of
1689 			 * Bleichenbacher's attack
1690 			 * (http://eprint.iacr.org/2003/052/) exploits
1691 			 * the version number check as a "bad version
1692 			 * oracle" -- an alert would reveal that the
1693 			 * plaintext corresponding to some ciphertext
1694 			 * made up by the adversary is properly
1695 			 * formatted except that the version number is
1696 			 * wrong.
1697 			 * To avoid such attacks, we should treat this
1698 			 * just like any other decryption error.
1699 			 */
1700 		}
1701 	}
1702 
1703 	if (al != -1) {
1704 		/*
1705 		 * Some decryption failure -- use random value instead
1706 		 * as countermeasure against Bleichenbacher's attack
1707 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1708 		 * section 7.4.7.1).
1709 		 */
1710 		i = SSL_MAX_MASTER_KEY_LENGTH;
1711 		p = fakekey;
1712 	}
1713 
1714 	s->session->master_key_length =
1715 	    tls1_generate_master_secret(s,
1716 	        s->session->master_key, p, i);
1717 
1718 	explicit_bzero(p, i);
1719 
1720 	return (1);
1721 truncated:
1722 	al = SSL_AD_DECODE_ERROR;
1723 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1724 f_err:
1725 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1726 err:
1727 	return (-1);
1728 }
1729 
1730 static int
1731 ssl3_get_client_kex_dhe(SSL *s, unsigned char *p, long n)
1732 {
1733 	BIGNUM *bn = NULL;
1734 	int key_size, al;
1735 	CBS cbs, dh_Yc;
1736 	DH *dh;
1737 
1738 	if (n < 0)
1739 		goto err;
1740 
1741 	CBS_init(&cbs, p, n);
1742 
1743 	if (!CBS_get_u16_length_prefixed(&cbs, &dh_Yc))
1744 		goto truncated;
1745 
1746 	if (CBS_len(&cbs) != 0)
1747 		goto truncated;
1748 
1749 	if (S3I(s)->tmp.dh == NULL) {
1750 		al = SSL_AD_HANDSHAKE_FAILURE;
1751 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1752 		goto f_err;
1753 	}
1754 	dh = S3I(s)->tmp.dh;
1755 
1756 	if ((bn = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL)) == NULL) {
1757 		SSLerror(s, SSL_R_BN_LIB);
1758 		goto err;
1759 	}
1760 
1761 	key_size = DH_compute_key(p, bn, dh);
1762 	if (key_size <= 0) {
1763 		SSLerror(s, ERR_R_DH_LIB);
1764 		BN_clear_free(bn);
1765 		goto err;
1766 	}
1767 
1768 	s->session->master_key_length =
1769 	    tls1_generate_master_secret(
1770 	        s, s->session->master_key, p, key_size);
1771 
1772 	explicit_bzero(p, key_size);
1773 
1774 	DH_free(S3I(s)->tmp.dh);
1775 	S3I(s)->tmp.dh = NULL;
1776 
1777 	BN_clear_free(bn);
1778 
1779 	return (1);
1780 
1781  truncated:
1782 	al = SSL_AD_DECODE_ERROR;
1783 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1784  f_err:
1785 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1786  err:
1787 	return (-1);
1788 }
1789 
1790 static int
1791 ssl3_get_client_kex_ecdhe_ecp(SSL *s, unsigned char *p, long n)
1792 {
1793 	EC_KEY *srvr_ecdh = NULL;
1794 	EVP_PKEY *clnt_pub_pkey = NULL;
1795 	EC_POINT *clnt_ecpoint = NULL;
1796 	BN_CTX *bn_ctx = NULL;
1797 	int i, al;
1798 
1799 	int ret = 1;
1800 	int key_size;
1801 	const EC_KEY   *tkey;
1802 	const EC_GROUP *group;
1803 	const BIGNUM *priv_key;
1804 
1805 	/* Initialize structures for server's ECDH key pair. */
1806 	if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1807 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1808 		goto err;
1809 	}
1810 
1811 	/*
1812 	 * Use the ephemeral values we saved when
1813 	 * generating the ServerKeyExchange message.
1814 	 */
1815 	tkey = S3I(s)->tmp.ecdh;
1816 
1817 	group = EC_KEY_get0_group(tkey);
1818 	priv_key = EC_KEY_get0_private_key(tkey);
1819 
1820 	if (!EC_KEY_set_group(srvr_ecdh, group) ||
1821 	    !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1822 		SSLerror(s, ERR_R_EC_LIB);
1823 		goto err;
1824 	}
1825 
1826 	/* Let's get client's public key */
1827 	if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1828 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1829 		goto err;
1830 	}
1831 
1832 	if (n == 0L) {
1833 		/* Client Publickey was in Client Certificate */
1834 		if (((clnt_pub_pkey = X509_get_pubkey(
1835 		    s->session->peer)) == NULL) ||
1836 		    (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1837 			/*
1838 			 * XXX: For now, we do not support client
1839 			 * authentication using ECDH certificates
1840 			 * so this branch (n == 0L) of the code is
1841 			 * never executed. When that support is
1842 			 * added, we ought to ensure the key
1843 			 * received in the certificate is
1844 			 * authorized for key agreement.
1845 			 * ECDH_compute_key implicitly checks that
1846 			 * the two ECDH shares are for the same
1847 			 * group.
1848 			 */
1849 			al = SSL_AD_HANDSHAKE_FAILURE;
1850 			SSLerror(s, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1851 			goto f_err;
1852 		}
1853 
1854 		if (EC_POINT_copy(clnt_ecpoint,
1855 		    EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec))
1856 		    == 0) {
1857 			SSLerror(s, ERR_R_EC_LIB);
1858 			goto err;
1859 		}
1860 		ret = 2; /* Skip certificate verify processing */
1861 	} else {
1862 		/*
1863 		 * Get client's public key from encoded point
1864 		 * in the ClientKeyExchange message.
1865 		 */
1866 		if ((bn_ctx = BN_CTX_new()) == NULL) {
1867 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1868 			goto err;
1869 		}
1870 
1871 		/* Get encoded point length */
1872 		i = *p;
1873 
1874 		p += 1;
1875 		if (n != 1 + i) {
1876 			SSLerror(s, ERR_R_EC_LIB);
1877 			goto err;
1878 		}
1879 		if (EC_POINT_oct2point(group,
1880 			clnt_ecpoint, p, i, bn_ctx) == 0) {
1881 			SSLerror(s, ERR_R_EC_LIB);
1882 			goto err;
1883 		}
1884 		/*
1885 		 * p is pointing to somewhere in the buffer
1886 		 * currently, so set it to the start.
1887 		 */
1888 		p = (unsigned char *)s->internal->init_buf->data;
1889 	}
1890 
1891 	/* Compute the shared pre-master secret */
1892 	key_size = ECDH_size(srvr_ecdh);
1893 	if (key_size <= 0) {
1894 		SSLerror(s, ERR_R_ECDH_LIB);
1895 		goto err;
1896 	}
1897 	i = ECDH_compute_key(p, key_size, clnt_ecpoint, srvr_ecdh,
1898 	    NULL);
1899 	if (i <= 0) {
1900 		SSLerror(s, ERR_R_ECDH_LIB);
1901 		goto err;
1902 	}
1903 
1904 	EVP_PKEY_free(clnt_pub_pkey);
1905 	EC_POINT_free(clnt_ecpoint);
1906 	EC_KEY_free(srvr_ecdh);
1907 	BN_CTX_free(bn_ctx);
1908 	EC_KEY_free(S3I(s)->tmp.ecdh);
1909 	S3I(s)->tmp.ecdh = NULL;
1910 
1911 	/* Compute the master secret */
1912 	s->session->master_key_length =
1913 	    tls1_generate_master_secret(
1914 		s, s->session->master_key, p, i);
1915 
1916 	explicit_bzero(p, i);
1917 	return (ret);
1918 
1919  f_err:
1920 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1921  err:
1922 	EVP_PKEY_free(clnt_pub_pkey);
1923 	EC_POINT_free(clnt_ecpoint);
1924 	EC_KEY_free(srvr_ecdh);
1925 	BN_CTX_free(bn_ctx);
1926 	return (-1);
1927 }
1928 
1929 static int
1930 ssl3_get_client_kex_ecdhe_ecx(SSL *s, unsigned char *p, long n)
1931 {
1932 	uint8_t *shared_key = NULL;
1933 	CBS cbs, ecpoint;
1934 	int ret = -1;
1935 
1936 	if (n < 0)
1937 		goto err;
1938 
1939 	CBS_init(&cbs, p, n);
1940 	if (!CBS_get_u8_length_prefixed(&cbs, &ecpoint))
1941 		goto err;
1942 	if (CBS_len(&ecpoint) != X25519_KEY_LENGTH)
1943 		goto err;
1944 
1945 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
1946 		goto err;
1947 	if (!X25519(shared_key, S3I(s)->tmp.x25519, CBS_data(&ecpoint)))
1948 		goto err;
1949 
1950 	freezero(S3I(s)->tmp.x25519, X25519_KEY_LENGTH);
1951 	S3I(s)->tmp.x25519 = NULL;
1952 
1953 	s->session->master_key_length =
1954 	    tls1_generate_master_secret(
1955 		s, s->session->master_key, shared_key, X25519_KEY_LENGTH);
1956 
1957 	ret = 1;
1958 
1959  err:
1960 	freezero(shared_key, X25519_KEY_LENGTH);
1961 
1962 	return (ret);
1963 }
1964 
1965 static int
1966 ssl3_get_client_kex_ecdhe(SSL *s, unsigned char *p, long n)
1967 {
1968         if (S3I(s)->tmp.x25519 != NULL)
1969 		return ssl3_get_client_kex_ecdhe_ecx(s, p, n);
1970 
1971 	return ssl3_get_client_kex_ecdhe_ecp(s, p, n);
1972 }
1973 
1974 static int
1975 ssl3_get_client_kex_gost(SSL *s, unsigned char *p, long n)
1976 {
1977 
1978 	EVP_PKEY_CTX *pkey_ctx;
1979 	EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
1980 	unsigned char premaster_secret[32], *start;
1981 	size_t outlen = 32, inlen;
1982 	unsigned long alg_a;
1983 	int Ttag, Tclass;
1984 	long Tlen;
1985 	int al;
1986 	int ret = 0;
1987 
1988 	/* Get our certificate private key*/
1989 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
1990 	if (alg_a & SSL_aGOST01)
1991 		pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
1992 
1993 	pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
1994 	EVP_PKEY_decrypt_init(pkey_ctx);
1995 	/*
1996 	 * If client certificate is present and is of the same type,
1997 	 * maybe use it for key exchange.
1998 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
1999 	 * it is completely valid to use a client certificate for
2000 	 * authorization only.
2001 	 */
2002 	client_pub_pkey = X509_get_pubkey(s->session->peer);
2003 	if (client_pub_pkey) {
2004 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2005 		    client_pub_pkey) <= 0)
2006 			ERR_clear_error();
2007 	}
2008 	if (2 > n)
2009 		goto truncated;
2010 	/* Decrypt session key */
2011 	if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag,
2012 	    &Tclass, n) != V_ASN1_CONSTRUCTED ||
2013 	    Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
2014 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2015 		goto gerr;
2016 	}
2017 	start = p;
2018 	inlen = Tlen;
2019 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
2020 	    start, inlen) <=0) {
2021 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2022 		goto gerr;
2023 	}
2024 	/* Generate master secret */
2025 	s->session->master_key_length =
2026 	    tls1_generate_master_secret(
2027 		s, s->session->master_key, premaster_secret, 32);
2028 	/* Check if pubkey from client certificate was used */
2029 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
2030 	    EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2031 		ret = 2;
2032 	else
2033 		ret = 1;
2034  gerr:
2035 	EVP_PKEY_free(client_pub_pkey);
2036 	EVP_PKEY_CTX_free(pkey_ctx);
2037 	if (ret)
2038 		return (ret);
2039 	else
2040 		goto err;
2041 
2042  truncated:
2043 	al = SSL_AD_DECODE_ERROR;
2044 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2045 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2046  err:
2047 	return (-1);
2048 }
2049 
2050 int
2051 ssl3_get_client_key_exchange(SSL *s)
2052 {
2053 	unsigned long alg_k;
2054 	unsigned char *p;
2055 	int al, ok;
2056 	long n;
2057 
2058 	/* 2048 maxlen is a guess.  How long a key does that permit? */
2059 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
2060 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2061 	if (!ok)
2062 		return ((int)n);
2063 
2064 	p = (unsigned char *)s->internal->init_msg;
2065 
2066 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2067 
2068 	if (alg_k & SSL_kRSA) {
2069 		if (ssl3_get_client_kex_rsa(s, p, n) != 1)
2070 			goto err;
2071 	} else if (alg_k & SSL_kDHE) {
2072 		if (ssl3_get_client_kex_dhe(s, p, n) != 1)
2073 			goto err;
2074 	} else if (alg_k & SSL_kECDHE) {
2075 		if (ssl3_get_client_kex_ecdhe(s, p, n) != 1)
2076 			goto err;
2077 	} else if (alg_k & SSL_kGOST) {
2078 		if (ssl3_get_client_kex_gost(s, p, n) != 1)
2079 			goto err;
2080 	} else {
2081 		al = SSL_AD_HANDSHAKE_FAILURE;
2082 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
2083 		goto f_err;
2084 	}
2085 
2086 	return (1);
2087 
2088  f_err:
2089 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2090  err:
2091 	return (-1);
2092 }
2093 
2094 int
2095 ssl3_get_cert_verify(SSL *s)
2096 {
2097 	EVP_PKEY *pkey = NULL;
2098 	unsigned char *p;
2099 	int al, ok, ret = 0;
2100 	long n;
2101 	int type = 0, i, j;
2102 	X509 *peer;
2103 	const EVP_MD *md = NULL;
2104 	EVP_MD_CTX mctx;
2105 	EVP_MD_CTX_init(&mctx);
2106 
2107 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2108 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2109 	if (!ok)
2110 		return ((int)n);
2111 
2112 	if (s->session->peer != NULL) {
2113 		peer = s->session->peer;
2114 		pkey = X509_get_pubkey(peer);
2115 		type = X509_certificate_type(peer, pkey);
2116 	} else {
2117 		peer = NULL;
2118 		pkey = NULL;
2119 	}
2120 
2121 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2122 		S3I(s)->tmp.reuse_message = 1;
2123 		if (peer != NULL) {
2124 			al = SSL_AD_UNEXPECTED_MESSAGE;
2125 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
2126 			goto f_err;
2127 		}
2128 		ret = 1;
2129 		goto end;
2130 	}
2131 
2132 	if (peer == NULL) {
2133 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
2134 		al = SSL_AD_UNEXPECTED_MESSAGE;
2135 		goto f_err;
2136 	}
2137 
2138 	if (!(type & EVP_PKT_SIGN)) {
2139 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2140 		al = SSL_AD_ILLEGAL_PARAMETER;
2141 		goto f_err;
2142 	}
2143 
2144 	if (S3I(s)->change_cipher_spec) {
2145 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2146 		al = SSL_AD_UNEXPECTED_MESSAGE;
2147 		goto f_err;
2148 	}
2149 
2150 	/* we now have a signature that we need to verify */
2151 	p = (unsigned char *)s->internal->init_msg;
2152 	/*
2153 	 * Check for broken implementations of GOST ciphersuites.
2154 	 *
2155 	 * If key is GOST and n is exactly 64, it is a bare
2156 	 * signature without length field.
2157 	 */
2158 	if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2159 	    pkey->type == NID_id_GostR3410_2001) ) {
2160 		i = 64;
2161 	} else {
2162 		if (SSL_USE_SIGALGS(s)) {
2163 			int sigalg = tls12_get_sigid(pkey);
2164 			/* Should never happen */
2165 			if (sigalg == -1) {
2166 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2167 				al = SSL_AD_INTERNAL_ERROR;
2168 				goto f_err;
2169 			}
2170 			if (2 > n)
2171 				goto truncated;
2172 			/* Check key type is consistent with signature */
2173 			if (sigalg != (int)p[1]) {
2174 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
2175 				al = SSL_AD_DECODE_ERROR;
2176 				goto f_err;
2177 			}
2178 			md = tls12_get_hash(p[0]);
2179 			if (md == NULL) {
2180 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
2181 				al = SSL_AD_DECODE_ERROR;
2182 				goto f_err;
2183 			}
2184 			p += 2;
2185 			n -= 2;
2186 		}
2187 		if (2 > n)
2188 			goto truncated;
2189 		n2s(p, i);
2190 		n -= 2;
2191 		if (i > n)
2192 			goto truncated;
2193 	}
2194 	j = EVP_PKEY_size(pkey);
2195 	if ((i > j) || (n > j) || (n <= 0)) {
2196 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2197 		al = SSL_AD_DECODE_ERROR;
2198 		goto f_err;
2199 	}
2200 
2201 	if (SSL_USE_SIGALGS(s)) {
2202 		long hdatalen = 0;
2203 		void *hdata;
2204 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2205 		if (hdatalen <= 0) {
2206 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2207 			al = SSL_AD_INTERNAL_ERROR;
2208 			goto f_err;
2209 		}
2210 		if (!EVP_VerifyInit_ex(&mctx, md, NULL) ||
2211 		    !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2212 			SSLerror(s, ERR_R_EVP_LIB);
2213 			al = SSL_AD_INTERNAL_ERROR;
2214 			goto f_err;
2215 		}
2216 
2217 		if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2218 			al = SSL_AD_DECRYPT_ERROR;
2219 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2220 			goto f_err;
2221 		}
2222 	} else
2223 	if (pkey->type == EVP_PKEY_RSA) {
2224 		i = RSA_verify(NID_md5_sha1, S3I(s)->tmp.cert_verify_md,
2225 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2226 		    pkey->pkey.rsa);
2227 		if (i < 0) {
2228 			al = SSL_AD_DECRYPT_ERROR;
2229 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2230 			goto f_err;
2231 		}
2232 		if (i == 0) {
2233 			al = SSL_AD_DECRYPT_ERROR;
2234 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2235 			goto f_err;
2236 		}
2237 	} else
2238 	if (pkey->type == EVP_PKEY_EC) {
2239 		j = ECDSA_verify(pkey->save_type,
2240 		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2241 		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2242 		if (j <= 0) {
2243 			/* bad signature */
2244 			al = SSL_AD_DECRYPT_ERROR;
2245 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2246 			goto f_err;
2247 		}
2248 	} else
2249 #ifndef OPENSSL_NO_GOST
2250 	if (pkey->type == NID_id_GostR3410_94 ||
2251 	    pkey->type == NID_id_GostR3410_2001) {
2252 		long hdatalen = 0;
2253 		void *hdata;
2254 		unsigned char signature[128];
2255 		unsigned int siglen = sizeof(signature);
2256 		int nid;
2257 		EVP_PKEY_CTX *pctx;
2258 
2259 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2260 		if (hdatalen <= 0) {
2261 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2262 			al = SSL_AD_INTERNAL_ERROR;
2263 			goto f_err;
2264 		}
2265 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2266 				!(md = EVP_get_digestbynid(nid))) {
2267 			SSLerror(s, ERR_R_EVP_LIB);
2268 			al = SSL_AD_INTERNAL_ERROR;
2269 			goto f_err;
2270 		}
2271 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2272 		if (!pctx) {
2273 			SSLerror(s, ERR_R_EVP_LIB);
2274 			al = SSL_AD_INTERNAL_ERROR;
2275 			goto f_err;
2276 		}
2277 		if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2278 		    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2279 		    !EVP_DigestFinal(&mctx, signature, &siglen) ||
2280 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2281 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2282 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2283 				       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2284 				       GOST_SIG_FORMAT_RS_LE,
2285 				       NULL) <= 0)) {
2286 			SSLerror(s, ERR_R_EVP_LIB);
2287 			al = SSL_AD_INTERNAL_ERROR;
2288 			EVP_PKEY_CTX_free(pctx);
2289 			goto f_err;
2290 		}
2291 
2292 		if (EVP_PKEY_verify(pctx, p, i, signature, siglen) <= 0) {
2293 			al = SSL_AD_DECRYPT_ERROR;
2294 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2295 			EVP_PKEY_CTX_free(pctx);
2296 			goto f_err;
2297 		}
2298 
2299 		EVP_PKEY_CTX_free(pctx);
2300 	} else
2301 #endif
2302 	{
2303 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2304 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2305 		goto f_err;
2306 	}
2307 
2308 
2309 	ret = 1;
2310 	if (0) {
2311 truncated:
2312 		al = SSL_AD_DECODE_ERROR;
2313 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2314 f_err:
2315 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2316 	}
2317 end:
2318 	if (S3I(s)->handshake_buffer) {
2319 		BIO_free(S3I(s)->handshake_buffer);
2320 		S3I(s)->handshake_buffer = NULL;
2321 		s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2322 	}
2323 	EVP_MD_CTX_cleanup(&mctx);
2324 	EVP_PKEY_free(pkey);
2325 	return (ret);
2326 }
2327 
2328 int
2329 ssl3_get_client_certificate(SSL *s)
2330 {
2331 	CBS cbs, client_certs;
2332 	int i, ok, al, ret = -1;
2333 	X509 *x = NULL;
2334 	long n;
2335 	const unsigned char *q;
2336 	STACK_OF(X509) *sk = NULL;
2337 
2338 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2339 	    -1, s->internal->max_cert_list, &ok);
2340 
2341 	if (!ok)
2342 		return ((int)n);
2343 
2344 	if (S3I(s)->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2345 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2346 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2347 		    	SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2348 			al = SSL_AD_HANDSHAKE_FAILURE;
2349 			goto f_err;
2350 		}
2351 		/*
2352 		 * If tls asked for a client cert,
2353 		 * the client must return a 0 list.
2354 		 */
2355 		if (S3I(s)->tmp.cert_request) {
2356 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2357 			    );
2358 			al = SSL_AD_UNEXPECTED_MESSAGE;
2359 			goto f_err;
2360 		}
2361 		S3I(s)->tmp.reuse_message = 1;
2362 		return (1);
2363 	}
2364 
2365 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
2366 		al = SSL_AD_UNEXPECTED_MESSAGE;
2367 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2368 		goto f_err;
2369 	}
2370 
2371 	if (n < 0)
2372 		goto truncated;
2373 
2374 	CBS_init(&cbs, s->internal->init_msg, n);
2375 
2376 	if ((sk = sk_X509_new_null()) == NULL) {
2377 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2378 		goto err;
2379 	}
2380 
2381 	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2382 	    CBS_len(&cbs) != 0)
2383 		goto truncated;
2384 
2385 	while (CBS_len(&client_certs) > 0) {
2386 		CBS cert;
2387 
2388 		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2389 			al = SSL_AD_DECODE_ERROR;
2390 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2391 			goto f_err;
2392 		}
2393 
2394 		q = CBS_data(&cert);
2395 		x = d2i_X509(NULL, &q, CBS_len(&cert));
2396 		if (x == NULL) {
2397 			SSLerror(s, ERR_R_ASN1_LIB);
2398 			goto err;
2399 		}
2400 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2401 			al = SSL_AD_DECODE_ERROR;
2402 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2403 			goto f_err;
2404 		}
2405 		if (!sk_X509_push(sk, x)) {
2406 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2407 			goto err;
2408 		}
2409 		x = NULL;
2410 	}
2411 
2412 	if (sk_X509_num(sk) <= 0) {
2413 		/*
2414 		 * TLS does not mind 0 certs returned.
2415 		 * Fail for TLS only if we required a certificate.
2416 		 */
2417 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2418 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2419 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2420 			al = SSL_AD_HANDSHAKE_FAILURE;
2421 			goto f_err;
2422 		}
2423 		/* No client certificate so digest cached records */
2424 		if (S3I(s)->handshake_buffer && !tls1_digest_cached_records(s)) {
2425 			al = SSL_AD_INTERNAL_ERROR;
2426 			goto f_err;
2427 		}
2428 	} else {
2429 		i = ssl_verify_cert_chain(s, sk);
2430 		if (i <= 0) {
2431 			al = ssl_verify_alarm_type(s->verify_result);
2432 			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2433 			goto f_err;
2434 		}
2435 	}
2436 
2437 	X509_free(s->session->peer);
2438 	s->session->peer = sk_X509_shift(sk);
2439 	s->session->verify_result = s->verify_result;
2440 
2441 	/*
2442 	 * With the current implementation, sess_cert will always be NULL
2443 	 * when we arrive here
2444 	 */
2445 	if (SSI(s)->sess_cert == NULL) {
2446 		SSI(s)->sess_cert = ssl_sess_cert_new();
2447 		if (SSI(s)->sess_cert == NULL) {
2448 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2449 			goto err;
2450 		}
2451 	}
2452 	sk_X509_pop_free(SSI(s)->sess_cert->cert_chain, X509_free);
2453 	SSI(s)->sess_cert->cert_chain = sk;
2454 
2455 	/*
2456 	 * Inconsistency alert: cert_chain does *not* include the
2457 	 * peer's own certificate, while we do include it in s3_clnt.c
2458 	 */
2459 
2460 	sk = NULL;
2461 
2462 	ret = 1;
2463 	if (0) {
2464 truncated:
2465 		al = SSL_AD_DECODE_ERROR;
2466 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2467 f_err:
2468 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2469 	}
2470 err:
2471 	X509_free(x);
2472 	sk_X509_pop_free(sk, X509_free);
2473 
2474 	return (ret);
2475 }
2476 
2477 int
2478 ssl3_send_server_certificate(SSL *s)
2479 {
2480 	CBB cbb, server_cert;
2481 	X509 *x;
2482 
2483 	/*
2484 	 * Server Certificate - RFC 5246, section 7.4.2.
2485 	 */
2486 
2487 	memset(&cbb, 0, sizeof(cbb));
2488 
2489 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_A) {
2490 		if ((x = ssl_get_server_send_cert(s)) == NULL) {
2491 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2492 			return (0);
2493 		}
2494 
2495 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &server_cert,
2496 		    SSL3_MT_CERTIFICATE))
2497 			goto err;
2498 		if (!ssl3_output_cert_chain(s, &server_cert, x))
2499 			goto err;
2500 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2501 			goto err;
2502 
2503 		S3I(s)->hs.state = SSL3_ST_SW_CERT_B;
2504 	}
2505 
2506 	/* SSL3_ST_SW_CERT_B */
2507 	return (ssl3_handshake_write(s));
2508 
2509  err:
2510 	CBB_cleanup(&cbb);
2511 
2512 	return (0);
2513 }
2514 
2515 /* send a new session ticket (not necessarily for a new session) */
2516 int
2517 ssl3_send_newsession_ticket(SSL *s)
2518 {
2519 	unsigned char *d, *p, *macstart;
2520 	unsigned char *senc = NULL;
2521 	const unsigned char *const_p;
2522 	int len, slen_full, slen;
2523 	SSL_SESSION *sess;
2524 	unsigned int hlen;
2525 	EVP_CIPHER_CTX ctx;
2526 	HMAC_CTX hctx;
2527 	SSL_CTX *tctx = s->initial_ctx;
2528 	unsigned char iv[EVP_MAX_IV_LENGTH];
2529 	unsigned char key_name[16];
2530 
2531 	if (S3I(s)->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2532 		/* get session encoding length */
2533 		slen_full = i2d_SSL_SESSION(s->session, NULL);
2534 		/*
2535 		 * Some length values are 16 bits, so forget it if session is
2536  		 * too long
2537  		 */
2538 		if (slen_full > 0xFF00)
2539 			goto err;
2540 		senc = malloc(slen_full);
2541 		if (!senc)
2542 			goto err;
2543 		p = senc;
2544 		i2d_SSL_SESSION(s->session, &p);
2545 
2546 		/*
2547 		 * Create a fresh copy (not shared with other threads) to
2548 		 * clean up
2549 		 */
2550 		const_p = senc;
2551 		sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2552 		if (sess == NULL)
2553 			goto err;
2554 
2555 		/* ID is irrelevant for the ticket */
2556 		sess->session_id_length = 0;
2557 
2558 		slen = i2d_SSL_SESSION(sess, NULL);
2559 		if (slen > slen_full) {
2560 			/* shouldn't ever happen */
2561 			goto err;
2562 		}
2563 		p = senc;
2564 		i2d_SSL_SESSION(sess, &p);
2565 		SSL_SESSION_free(sess);
2566 
2567 		/*
2568 		 * Grow buffer if need be: the length calculation is as
2569  		 * follows 1 (size of message name) + 3 (message length
2570  		 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2571  		 * 16 (key name) + max_iv_len (iv length) +
2572  		 * session_length + max_enc_block_size (max encrypted session
2573  		 * length) + max_md_size (HMAC).
2574  		 */
2575 		if (!BUF_MEM_grow(s->internal->init_buf, ssl3_handshake_msg_hdr_len(s) +
2576 		    22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2577 		    EVP_MAX_MD_SIZE + slen))
2578 			goto err;
2579 
2580 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_NEWSESSION_TICKET);
2581 
2582 		EVP_CIPHER_CTX_init(&ctx);
2583 		HMAC_CTX_init(&hctx);
2584 
2585 		/*
2586 		 * Initialize HMAC and cipher contexts. If callback present
2587 		 * it does all the work otherwise use generated values
2588 		 * from parent ctx.
2589 		 */
2590 		if (tctx->internal->tlsext_ticket_key_cb) {
2591 			if (tctx->internal->tlsext_ticket_key_cb(s,
2592 			    key_name, iv, &ctx, &hctx, 1) < 0) {
2593 				EVP_CIPHER_CTX_cleanup(&ctx);
2594 				goto err;
2595 			}
2596 		} else {
2597 			arc4random_buf(iv, 16);
2598 			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2599 			    tctx->internal->tlsext_tick_aes_key, iv);
2600 			HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
2601 			    16, tlsext_tick_md(), NULL);
2602 			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2603 		}
2604 
2605 		/*
2606 		 * Ticket lifetime hint (advisory only):
2607 		 * We leave this unspecified for resumed session
2608 		 * (for simplicity), and guess that tickets for new
2609 		 * sessions will live as long as their sessions.
2610 		 */
2611 		l2n(s->internal->hit ? 0 : s->session->timeout, p);
2612 
2613 		/* Skip ticket length for now */
2614 		p += 2;
2615 		/* Output key name */
2616 		macstart = p;
2617 		memcpy(p, key_name, 16);
2618 		p += 16;
2619 		/* output IV */
2620 		memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2621 		p += EVP_CIPHER_CTX_iv_length(&ctx);
2622 		/* Encrypt session data */
2623 		EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2624 		p += len;
2625 		EVP_EncryptFinal_ex(&ctx, p, &len);
2626 		p += len;
2627 		EVP_CIPHER_CTX_cleanup(&ctx);
2628 
2629 		HMAC_Update(&hctx, macstart, p - macstart);
2630 		HMAC_Final(&hctx, p, &hlen);
2631 		HMAC_CTX_cleanup(&hctx);
2632 		p += hlen;
2633 
2634 		/* Now write out lengths: p points to end of data written */
2635 		/* Total length */
2636 		len = p - d;
2637 
2638 		/* Skip ticket lifetime hint. */
2639 		p = d + 4;
2640 		s2n(len - 6, p); /* Message length */
2641 
2642 		ssl3_handshake_msg_finish(s, len);
2643 
2644 		S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2645 
2646 		freezero(senc, slen_full);
2647 	}
2648 
2649 	/* SSL3_ST_SW_SESSION_TICKET_B */
2650 	return (ssl3_handshake_write(s));
2651 
2652  err:
2653 	freezero(senc, slen_full);
2654 
2655 	return (-1);
2656 }
2657 
2658 int
2659 ssl3_send_cert_status(SSL *s)
2660 {
2661 	CBB cbb, certstatus, ocspresp;
2662 
2663 	memset(&cbb, 0, sizeof(cbb));
2664 
2665 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2666 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &certstatus,
2667 		    SSL3_MT_CERTIFICATE_STATUS))
2668 			goto err;
2669 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2670 			goto err;
2671 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2672 			goto err;
2673 		if (!CBB_add_bytes(&ocspresp, s->internal->tlsext_ocsp_resp,
2674 		    s->internal->tlsext_ocsp_resplen))
2675 			goto err;
2676 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2677 			goto err;
2678 
2679 		S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2680 	}
2681 
2682 	/* SSL3_ST_SW_CERT_STATUS_B */
2683 	return (ssl3_handshake_write(s));
2684 
2685  err:
2686 	CBB_cleanup(&cbb);
2687 
2688 	return (-1);
2689 }
2690