xref: /openbsd-src/lib/libssl/ssl_srvr.c (revision 42c0683c5609fe346691c97e80c553467d6eec66)
1 /* $OpenBSD: ssl_srvr.c,v 1.17 2017/05/07 04:22:24 beck Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124 /* ====================================================================
125  * Copyright 2005 Nokia. All rights reserved.
126  *
127  * The portions of the attached software ("Contribution") is developed by
128  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
129  * license.
130  *
131  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
132  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
133  * support (see RFC 4279) to OpenSSL.
134  *
135  * No patent licenses or other rights except those expressly stated in
136  * the OpenSSL open source license shall be deemed granted or received
137  * expressly, by implication, estoppel, or otherwise.
138  *
139  * No assurances are provided by Nokia that the Contribution does not
140  * infringe the patent or other intellectual property rights of any third
141  * party or that the license provides you with all the necessary rights
142  * to make use of the Contribution.
143  *
144  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
145  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
146  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
147  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
148  * OTHERWISE.
149  */
150 
151 #include <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 				if (S3I(s)->next_proto_neg_seen)
472 					S3I(s)->hs.state = SSL3_ST_SR_NEXT_PROTO_A;
473 				else
474 					S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
475 				s->internal->init_num = 0;
476 			} else if (SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) {
477 				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
478 				s->internal->init_num = 0;
479 				if (!s->session->peer)
480 					break;
481 				/*
482 				 * For sigalgs freeze the handshake buffer
483 				 * at this point and digest cached records.
484 				 */
485 				if (!S3I(s)->handshake_buffer) {
486 					SSLerror(s, ERR_R_INTERNAL_ERROR);
487 					ret = -1;
488 					goto end;
489 				}
490 				s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
491 				if (!tls1_digest_cached_records(s)) {
492 					ret = -1;
493 					goto end;
494 				}
495 			} else {
496 				S3I(s)->hs.state = SSL3_ST_SR_CERT_VRFY_A;
497 				s->internal->init_num = 0;
498 
499 				/*
500 				 * We need to get hashes here so if there is
501 				 * a client cert, it can be verified.
502 				 */
503 				if (S3I(s)->handshake_buffer) {
504 					if (!tls1_digest_cached_records(s)) {
505 						ret = -1;
506 						goto end;
507 					}
508 				}
509 				if (!tls1_handshake_hash_value(s,
510 				    S3I(s)->tmp.cert_verify_md,
511 				    sizeof(S3I(s)->tmp.cert_verify_md),
512 				    NULL)) {
513 				        ret = -1;
514 					goto end;
515 				}
516 			}
517 			break;
518 
519 		case SSL3_ST_SR_CERT_VRFY_A:
520 		case SSL3_ST_SR_CERT_VRFY_B:
521 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
522 
523 			/* we should decide if we expected this one */
524 			ret = ssl3_get_cert_verify(s);
525 			if (ret <= 0)
526 				goto end;
527 
528 			if (S3I(s)->next_proto_neg_seen)
529 				S3I(s)->hs.state = SSL3_ST_SR_NEXT_PROTO_A;
530 			else
531 				S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
532 			s->internal->init_num = 0;
533 			break;
534 
535 		case SSL3_ST_SR_NEXT_PROTO_A:
536 		case SSL3_ST_SR_NEXT_PROTO_B:
537 			ret = ssl3_get_next_proto(s);
538 			if (ret <= 0)
539 				goto end;
540 			s->internal->init_num = 0;
541 			S3I(s)->hs.state = SSL3_ST_SR_FINISHED_A;
542 			break;
543 
544 		case SSL3_ST_SR_FINISHED_A:
545 		case SSL3_ST_SR_FINISHED_B:
546 			s->s3->flags |= SSL3_FLAGS_CCS_OK;
547 			ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
548 			    SSL3_ST_SR_FINISHED_B);
549 			if (ret <= 0)
550 				goto end;
551 			if (s->internal->hit)
552 				S3I(s)->hs.state = SSL_ST_OK;
553 			else if (s->internal->tlsext_ticket_expected)
554 				S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_A;
555 			else
556 				S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
557 			s->internal->init_num = 0;
558 			break;
559 
560 		case SSL3_ST_SW_SESSION_TICKET_A:
561 		case SSL3_ST_SW_SESSION_TICKET_B:
562 			ret = ssl3_send_newsession_ticket(s);
563 			if (ret <= 0)
564 				goto end;
565 			S3I(s)->hs.state = SSL3_ST_SW_CHANGE_A;
566 			s->internal->init_num = 0;
567 			break;
568 
569 		case SSL3_ST_SW_CERT_STATUS_A:
570 		case SSL3_ST_SW_CERT_STATUS_B:
571 			ret = ssl3_send_cert_status(s);
572 			if (ret <= 0)
573 				goto end;
574 			S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_A;
575 			s->internal->init_num = 0;
576 			break;
577 
578 
579 		case SSL3_ST_SW_CHANGE_A:
580 		case SSL3_ST_SW_CHANGE_B:
581 
582 			s->session->cipher = S3I(s)->hs.new_cipher;
583 			if (!tls1_setup_key_block(s)) {
584 				ret = -1;
585 				goto end;
586 			}
587 
588 			ret = ssl3_send_change_cipher_spec(s,
589 			    SSL3_ST_SW_CHANGE_A, SSL3_ST_SW_CHANGE_B);
590 
591 			if (ret <= 0)
592 				goto end;
593 			S3I(s)->hs.state = SSL3_ST_SW_FINISHED_A;
594 			s->internal->init_num = 0;
595 
596 			if (!tls1_change_cipher_state(
597 			    s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
598 				ret = -1;
599 				goto end;
600 			}
601 
602 			break;
603 
604 		case SSL3_ST_SW_FINISHED_A:
605 		case SSL3_ST_SW_FINISHED_B:
606 			ret = ssl3_send_finished(s,
607 			SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
608 			TLS_MD_SERVER_FINISH_CONST,
609 			TLS_MD_SERVER_FINISH_CONST_SIZE);
610 			if (ret <= 0)
611 				goto end;
612 			S3I(s)->hs.state = SSL3_ST_SW_FLUSH;
613 			if (s->internal->hit) {
614 				if (S3I(s)->next_proto_neg_seen) {
615 					s->s3->flags |= SSL3_FLAGS_CCS_OK;
616 					S3I(s)->hs.next_state =
617 					    SSL3_ST_SR_NEXT_PROTO_A;
618 				} else
619 					S3I(s)->hs.next_state =
620 					    SSL3_ST_SR_FINISHED_A;
621 			} else
622 				S3I(s)->hs.next_state = SSL_ST_OK;
623 			s->internal->init_num = 0;
624 			break;
625 
626 		case SSL_ST_OK:
627 			/* clean a few things up */
628 			tls1_cleanup_key_block(s);
629 
630 			BUF_MEM_free(s->internal->init_buf);
631 			s->internal->init_buf = NULL;
632 
633 			/* remove buffering on output */
634 			ssl_free_wbio_buffer(s);
635 
636 			s->internal->init_num = 0;
637 
638 			/* skipped if we just sent a HelloRequest */
639 			if (s->internal->renegotiate == 2) {
640 				s->internal->renegotiate = 0;
641 				s->internal->new_session = 0;
642 
643 				ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
644 
645 				s->ctx->internal->stats.sess_accept_good++;
646 				/* s->server=1; */
647 				s->internal->handshake_func = ssl3_accept;
648 
649 				if (cb != NULL)
650 					cb(s, SSL_CB_HANDSHAKE_DONE, 1);
651 			}
652 
653 			ret = 1;
654 			goto end;
655 			/* break; */
656 
657 		default:
658 			SSLerror(s, SSL_R_UNKNOWN_STATE);
659 			ret = -1;
660 			goto end;
661 			/* break; */
662 		}
663 
664 		if (!S3I(s)->tmp.reuse_message && !skip) {
665 			if (s->internal->debug) {
666 				if ((ret = BIO_flush(s->wbio)) <= 0)
667 					goto end;
668 			}
669 
670 
671 			if ((cb != NULL) && (S3I(s)->hs.state != state)) {
672 				new_state = S3I(s)->hs.state;
673 				S3I(s)->hs.state = state;
674 				cb(s, SSL_CB_ACCEPT_LOOP, 1);
675 				S3I(s)->hs.state = new_state;
676 			}
677 		}
678 		skip = 0;
679 	}
680 end:
681 	/* BIO_flush(s->wbio); */
682 
683 	s->internal->in_handshake--;
684 	if (cb != NULL)
685 		cb(s, SSL_CB_ACCEPT_EXIT, ret);
686 	return (ret);
687 }
688 
689 int
690 ssl3_send_hello_request(SSL *s)
691 {
692 	CBB cbb, hello;
693 
694 	memset(&cbb, 0, sizeof(cbb));
695 
696 	if (S3I(s)->hs.state == SSL3_ST_SW_HELLO_REQ_A) {
697 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &hello,
698 		    SSL3_MT_HELLO_REQUEST))
699 			goto err;
700 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
701 			goto err;
702 
703 		S3I(s)->hs.state = SSL3_ST_SW_HELLO_REQ_B;
704 	}
705 
706 	/* SSL3_ST_SW_HELLO_REQ_B */
707 	return (ssl3_handshake_write(s));
708 
709  err:
710 	CBB_cleanup(&cbb);
711 
712 	return (-1);
713 }
714 
715 int
716 ssl3_get_client_hello(SSL *s)
717 {
718 	CBS cbs, client_random, session_id, cookie, cipher_suites;
719 	CBS compression_methods;
720 	uint16_t client_version;
721 	uint8_t comp_method;
722 	int comp_null;
723 	int i, j, ok, al, ret = -1, cookie_valid = 0;
724 	long n;
725 	unsigned long id;
726 	unsigned char *p, *d;
727 	SSL_CIPHER *c;
728 	STACK_OF(SSL_CIPHER) *ciphers = NULL;
729 	unsigned long alg_k;
730 	const SSL_METHOD *method;
731 	uint16_t shared_version;
732 	unsigned char *end;
733 
734 	/*
735 	 * We do this so that we will respond with our native type.
736 	 * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
737 	 * This down switching should be handled by a different method.
738 	 * If we are SSLv3, we will respond with SSLv3, even if prompted with
739 	 * TLSv1.
740 	 */
741 	if (S3I(s)->hs.state == SSL3_ST_SR_CLNT_HELLO_A) {
742 		S3I(s)->hs.state = SSL3_ST_SR_CLNT_HELLO_B;
743 	}
744 
745 	s->internal->first_packet = 1;
746 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B,
747 	    SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO,
748 	    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
749 	if (!ok)
750 		return ((int)n);
751 	s->internal->first_packet = 0;
752 
753 	if (n < 0)
754 		goto err;
755 
756 	d = p = (unsigned char *)s->internal->init_msg;
757 	end = d + n;
758 
759 	CBS_init(&cbs, s->internal->init_msg, n);
760 
761 	/*
762 	 * Use version from inside client hello, not from record header.
763 	 * (may differ: see RFC 2246, Appendix E, second paragraph)
764 	 */
765 	if (!CBS_get_u16(&cbs, &client_version))
766 		goto truncated;
767 
768 	if (ssl_max_shared_version(s, client_version, &shared_version) != 1) {
769 		SSLerror(s, SSL_R_WRONG_VERSION_NUMBER);
770 		if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
771 		    !s->internal->enc_write_ctx && !s->internal->write_hash) {
772 			/*
773 			 * Similar to ssl3_get_record, send alert using remote
774 			 * version number.
775 			 */
776 			s->version = s->client_version;
777 		}
778 		al = SSL_AD_PROTOCOL_VERSION;
779 		goto f_err;
780 	}
781 	s->client_version = client_version;
782 	s->version = shared_version;
783 
784 	if ((method = tls1_get_server_method(shared_version)) == NULL)
785 		method = dtls1_get_server_method(shared_version);
786 	if (method == NULL) {
787 		SSLerror(s, ERR_R_INTERNAL_ERROR);
788 		goto err;
789 	}
790 	s->method = method;
791 
792 	if (!CBS_get_bytes(&cbs, &client_random, SSL3_RANDOM_SIZE))
793 		goto truncated;
794 	if (!CBS_get_u8_length_prefixed(&cbs, &session_id))
795 		goto truncated;
796 
797 	/*
798 	 * If we require cookies (DTLS) and this ClientHello doesn't
799 	 * contain one, just return since we do not want to
800 	 * allocate any memory yet. So check cookie length...
801 	 */
802 	if (SSL_IS_DTLS(s)) {
803 		if (!CBS_get_u8_length_prefixed(&cbs, &cookie))
804 			goto truncated;
805 		if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
806 			if (CBS_len(&cookie) == 0)
807 				return (1);
808 		}
809 	}
810 
811 	if (!CBS_write_bytes(&client_random, s->s3->client_random,
812 	    sizeof(s->s3->client_random), NULL))
813 		goto err;
814 
815 	s->internal->hit = 0;
816 
817 	/*
818 	 * Versions before 0.9.7 always allow clients to resume sessions in
819 	 * renegotiation. 0.9.7 and later allow this by default, but optionally
820 	 * ignore resumption requests with flag
821 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag
822 	 * rather than a change to default behavior so that applications
823 	 * relying on this for security won't even compile against older
824 	 * library versions).
825 	 *
826 	 * 1.0.1 and later also have a function SSL_renegotiate_abbreviated()
827 	 * to request renegotiation but not a new session (s->internal->new_session
828 	 * remains unset): for servers, this essentially just means that the
829 	 * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
830 	 * ignored.
831 	 */
832 	if ((s->internal->new_session && (s->internal->options &
833 	    SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
834 		if (!ssl_get_new_session(s, 1))
835 			goto err;
836 	} else {
837 		/* XXX - pass CBS through instead... */
838 		i = ssl_get_prev_session(s,
839 		    (unsigned char *)CBS_data(&session_id),
840 		    CBS_len(&session_id), end);
841 		if (i == 1) { /* previous session */
842 			s->internal->hit = 1;
843 		} else if (i == -1)
844 			goto err;
845 		else {
846 			/* i == 0 */
847 			if (!ssl_get_new_session(s, 1))
848 				goto err;
849 		}
850 	}
851 
852 	if (SSL_IS_DTLS(s)) {
853 		/*
854 		 * The ClientHello may contain a cookie even if the HelloVerify
855 		 * message has not been sent - make sure that it does not cause
856 		 * an overflow.
857 		 */
858 		if (CBS_len(&cookie) > sizeof(D1I(s)->rcvd_cookie)) {
859 			al = SSL_AD_DECODE_ERROR;
860 			SSLerror(s, SSL_R_COOKIE_MISMATCH);
861 			goto f_err;
862 		}
863 
864 		/* Verify the cookie if appropriate option is set. */
865 		if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
866 		    CBS_len(&cookie) > 0) {
867 			size_t cookie_len;
868 
869 			/* XXX - rcvd_cookie seems to only be used here... */
870 			if (!CBS_write_bytes(&cookie, D1I(s)->rcvd_cookie,
871 			    sizeof(D1I(s)->rcvd_cookie), &cookie_len))
872 				goto err;
873 
874 			if (s->ctx->internal->app_verify_cookie_cb != NULL) {
875 				if (s->ctx->internal->app_verify_cookie_cb(s,
876 				    D1I(s)->rcvd_cookie, cookie_len) == 0) {
877 					al = SSL_AD_HANDSHAKE_FAILURE;
878 					SSLerror(s, SSL_R_COOKIE_MISMATCH);
879 					goto f_err;
880 				}
881 				/* else cookie verification succeeded */
882 			/* XXX - can d1->cookie_len > sizeof(rcvd_cookie) ? */
883 			} else if (timingsafe_memcmp(D1I(s)->rcvd_cookie,
884 			    D1I(s)->cookie, D1I(s)->cookie_len) != 0) {
885 				/* default verification */
886 				al = SSL_AD_HANDSHAKE_FAILURE;
887 				SSLerror(s, SSL_R_COOKIE_MISMATCH);
888 				goto f_err;
889 			}
890 			cookie_valid = 1;
891 		}
892 	}
893 
894 	if (!CBS_get_u16_length_prefixed(&cbs, &cipher_suites))
895 		goto truncated;
896 
897 	/* XXX - This logic seems wrong... */
898 	if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
899 		/* we need a cipher if we are not resuming a session */
900 		al = SSL_AD_ILLEGAL_PARAMETER;
901 		SSLerror(s, SSL_R_NO_CIPHERS_SPECIFIED);
902 		goto f_err;
903 	}
904 
905 	if (CBS_len(&cipher_suites) > 0) {
906 		if ((ciphers = ssl_bytes_to_cipher_list(s,
907 		    CBS_data(&cipher_suites), CBS_len(&cipher_suites))) == NULL)
908 			goto err;
909 	}
910 
911 	/* If it is a hit, check that the cipher is in the list */
912 	if (s->internal->hit && CBS_len(&cipher_suites) > 0) {
913 		j = 0;
914 		id = s->session->cipher->id;
915 
916 		for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
917 			c = sk_SSL_CIPHER_value(ciphers, i);
918 			if (c->id == id) {
919 				j = 1;
920 				break;
921 			}
922 		}
923 		if (j == 0) {
924 			/*
925 			 * We need to have the cipher in the cipher
926 			 * list if we are asked to reuse it
927 			 */
928 			al = SSL_AD_ILLEGAL_PARAMETER;
929 			SSLerror(s, SSL_R_REQUIRED_CIPHER_MISSING);
930 			goto f_err;
931 		}
932 	}
933 
934 	if (!CBS_get_u8_length_prefixed(&cbs, &compression_methods))
935 		goto truncated;
936 
937 	comp_null = 0;
938 	while (CBS_len(&compression_methods) > 0) {
939 		if (!CBS_get_u8(&compression_methods, &comp_method))
940 			goto truncated;
941 		if (comp_method == 0)
942 			comp_null = 1;
943 	}
944 	if (comp_null == 0) {
945 		al = SSL_AD_DECODE_ERROR;
946 		SSLerror(s, SSL_R_NO_COMPRESSION_SPECIFIED);
947 		goto f_err;
948 	}
949 
950 	p = (unsigned char *)CBS_data(&cbs);
951 
952 	/* TLS extensions*/
953 	if (!ssl_parse_clienthello_tlsext(s, &p, d, n, &al)) {
954 		/* 'al' set by ssl_parse_clienthello_tlsext */
955 		SSLerror(s, SSL_R_PARSE_TLSEXT);
956 		goto f_err;
957 	}
958 	if (ssl_check_clienthello_tlsext_early(s) <= 0) {
959 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
960 		goto err;
961 	}
962 
963 	/*
964 	 * Check if we want to use external pre-shared secret for this
965 	 * handshake for not reused session only. We need to generate
966 	 * server_random before calling tls_session_secret_cb in order to allow
967 	 * SessionTicket processing to use it in key derivation.
968 	 */
969 	arc4random_buf(s->s3->server_random, SSL3_RANDOM_SIZE);
970 
971 	if (!s->internal->hit && s->internal->tls_session_secret_cb) {
972 		SSL_CIPHER *pref_cipher = NULL;
973 
974 		s->session->master_key_length = sizeof(s->session->master_key);
975 		if (s->internal->tls_session_secret_cb(s, s->session->master_key,
976 		    &s->session->master_key_length, ciphers, &pref_cipher,
977 		    s->internal->tls_session_secret_cb_arg)) {
978 			s->internal->hit = 1;
979 			s->session->ciphers = ciphers;
980 			s->session->verify_result = X509_V_OK;
981 
982 			ciphers = NULL;
983 
984 			/* check if some cipher was preferred by call back */
985 			pref_cipher = pref_cipher ? pref_cipher :
986 			    ssl3_choose_cipher(s, s->session->ciphers,
987 			    SSL_get_ciphers(s));
988 			if (pref_cipher == NULL) {
989 				al = SSL_AD_HANDSHAKE_FAILURE;
990 				SSLerror(s, SSL_R_NO_SHARED_CIPHER);
991 				goto f_err;
992 			}
993 
994 			s->session->cipher = pref_cipher;
995 
996 			sk_SSL_CIPHER_free(s->cipher_list);
997 			sk_SSL_CIPHER_free(s->internal->cipher_list_by_id);
998 
999 			s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1000 			s->internal->cipher_list_by_id =
1001 			    sk_SSL_CIPHER_dup(s->session->ciphers);
1002 		}
1003 	}
1004 
1005 	/*
1006 	 * Given s->session->ciphers and SSL_get_ciphers, we must
1007 	 * pick a cipher
1008 	 */
1009 
1010 	if (!s->internal->hit) {
1011 		sk_SSL_CIPHER_free(s->session->ciphers);
1012 		s->session->ciphers = ciphers;
1013 		if (ciphers == NULL) {
1014 			al = SSL_AD_ILLEGAL_PARAMETER;
1015 			SSLerror(s, SSL_R_NO_CIPHERS_PASSED);
1016 			goto f_err;
1017 		}
1018 		ciphers = NULL;
1019 		c = ssl3_choose_cipher(s, s->session->ciphers,
1020 		SSL_get_ciphers(s));
1021 
1022 		if (c == NULL) {
1023 			al = SSL_AD_HANDSHAKE_FAILURE;
1024 			SSLerror(s, SSL_R_NO_SHARED_CIPHER);
1025 			goto f_err;
1026 		}
1027 		S3I(s)->hs.new_cipher = c;
1028 	} else {
1029 		S3I(s)->hs.new_cipher = s->session->cipher;
1030 	}
1031 
1032 	if (!tls1_handshake_hash_init(s))
1033 		goto err;
1034 
1035 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
1036 	if (!(SSL_USE_SIGALGS(s) || (alg_k & SSL_kGOST)) ||
1037 	    !(s->verify_mode & SSL_VERIFY_PEER)) {
1038 		if (!tls1_digest_cached_records(s)) {
1039 			al = SSL_AD_INTERNAL_ERROR;
1040 			goto f_err;
1041 		}
1042 	}
1043 
1044 	/*
1045 	 * We now have the following setup.
1046 	 * client_random
1047 	 * cipher_list 		- our prefered list of ciphers
1048 	 * ciphers 		- the clients prefered list of ciphers
1049 	 * compression		- basically ignored right now
1050 	 * ssl version is set	- sslv3
1051 	 * s->session		- The ssl session has been setup.
1052 	 * s->internal->hit		- session reuse flag
1053 	 * s->hs.new_cipher	- the new cipher to use.
1054 	 */
1055 
1056 	/* Handles TLS extensions that we couldn't check earlier */
1057 	if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1058 		SSLerror(s, SSL_R_CLIENTHELLO_TLSEXT);
1059 		goto err;
1060 	}
1061 
1062 	ret = cookie_valid ? 2 : 1;
1063 
1064 	if (0) {
1065 truncated:
1066 		al = SSL_AD_DECODE_ERROR;
1067 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1068 f_err:
1069 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
1070 	}
1071 err:
1072 	sk_SSL_CIPHER_free(ciphers);
1073 
1074 	return (ret);
1075 }
1076 
1077 int
1078 ssl3_send_server_hello(SSL *s)
1079 {
1080 	unsigned char *bufend;
1081 	unsigned char *p, *d;
1082 	CBB cbb, session_id;
1083 	size_t outlen;
1084 	int sl;
1085 
1086 	memset(&cbb, 0, sizeof(cbb));
1087 
1088 	bufend = (unsigned char *)s->internal->init_buf->data + SSL3_RT_MAX_PLAIN_LENGTH;
1089 
1090 	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_HELLO_A) {
1091 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_SERVER_HELLO);
1092 
1093 		if (!CBB_init_fixed(&cbb, p, bufend - p))
1094 			goto err;
1095 
1096 		if (!CBB_add_u16(&cbb, s->version))
1097 			goto err;
1098 		if (!CBB_add_bytes(&cbb, s->s3->server_random,
1099 		    sizeof(s->s3->server_random)))
1100 			goto err;
1101 
1102 		/*
1103 		 * There are several cases for the session ID to send
1104 		 * back in the server hello:
1105 		 *
1106 		 * - For session reuse from the session cache,
1107 		 *   we send back the old session ID.
1108 		 * - If stateless session reuse (using a session ticket)
1109 		 *   is successful, we send back the client's "session ID"
1110 		 *   (which doesn't actually identify the session).
1111 		 * - If it is a new session, we send back the new
1112 		 *   session ID.
1113 		 * - However, if we want the new session to be single-use,
1114 		 *   we send back a 0-length session ID.
1115 		 *
1116 		 * s->internal->hit is non-zero in either case of session reuse,
1117 		 * so the following won't overwrite an ID that we're supposed
1118 		 * to send back.
1119 		 */
1120 		if (!(s->ctx->internal->session_cache_mode & SSL_SESS_CACHE_SERVER)
1121 		    && !s->internal->hit)
1122 			s->session->session_id_length = 0;
1123 
1124 		sl = s->session->session_id_length;
1125 		if (sl > (int)sizeof(s->session->session_id)) {
1126 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1127 			goto err;
1128 		}
1129 
1130 		if (!CBB_add_u8_length_prefixed(&cbb, &session_id))
1131 			goto err;
1132 		if (!CBB_add_bytes(&session_id, s->session->session_id, sl))
1133 			goto err;
1134 
1135 		/* Cipher suite. */
1136 		if (!CBB_add_u16(&cbb,
1137 		    ssl3_cipher_get_value(S3I(s)->hs.new_cipher)))
1138 			goto err;
1139 
1140 		/* Compression method. */
1141 		if (!CBB_add_u8(&cbb, 0))
1142 			goto err;
1143 
1144 		if (!CBB_finish(&cbb, NULL, &outlen))
1145 			goto err;
1146 
1147 		if ((p = ssl_add_serverhello_tlsext(s, p + outlen,
1148 		    bufend)) == NULL) {
1149 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1150 			goto err;
1151 		}
1152 
1153 		ssl3_handshake_msg_finish(s, p - d);
1154 	}
1155 
1156 	/* SSL3_ST_SW_SRVR_HELLO_B */
1157 	return (ssl3_handshake_write(s));
1158 
1159  err:
1160 	CBB_cleanup(&cbb);
1161 
1162 	return (-1);
1163 }
1164 
1165 int
1166 ssl3_send_server_done(SSL *s)
1167 {
1168 	CBB cbb, done;
1169 
1170 	memset(&cbb, 0, sizeof(cbb));
1171 
1172 	if (S3I(s)->hs.state == SSL3_ST_SW_SRVR_DONE_A) {
1173 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &done,
1174 		    SSL3_MT_SERVER_DONE))
1175 			goto err;
1176 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
1177 			goto err;
1178 
1179 		S3I(s)->hs.state = SSL3_ST_SW_SRVR_DONE_B;
1180 	}
1181 
1182 	/* SSL3_ST_SW_SRVR_DONE_B */
1183 	return (ssl3_handshake_write(s));
1184 
1185  err:
1186 	CBB_cleanup(&cbb);
1187 
1188 	return (-1);
1189 }
1190 
1191 int
1192 ssl3_send_server_kex_dhe(SSL *s, CBB *cbb)
1193 {
1194 	CBB dh_p, dh_g, dh_Ys;
1195 	DH *dh = NULL, *dhp;
1196 	unsigned char *data;
1197 	int al;
1198 
1199 	if (s->cert->dh_tmp_auto != 0) {
1200 		if ((dhp = ssl_get_auto_dh(s)) == NULL) {
1201 			al = SSL_AD_INTERNAL_ERROR;
1202 			SSLerror(s, ERR_R_INTERNAL_ERROR);
1203 			goto f_err;
1204 		}
1205 	} else
1206 		dhp = s->cert->dh_tmp;
1207 
1208 	if (dhp == NULL && s->cert->dh_tmp_cb != NULL)
1209 		dhp = s->cert->dh_tmp_cb(s, 0,
1210 		    SSL_C_PKEYLENGTH(S3I(s)->hs.new_cipher));
1211 
1212 	if (dhp == NULL) {
1213 		al = SSL_AD_HANDSHAKE_FAILURE;
1214 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1215 		goto f_err;
1216 	}
1217 
1218 	if (S3I(s)->tmp.dh != NULL) {
1219 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1220 		goto err;
1221 	}
1222 
1223 	if (s->cert->dh_tmp_auto != 0) {
1224 		dh = dhp;
1225 	} else if ((dh = DHparams_dup(dhp)) == NULL) {
1226 		SSLerror(s, ERR_R_DH_LIB);
1227 		goto err;
1228 	}
1229 	S3I(s)->tmp.dh = dh;
1230 	if (!DH_generate_key(dh)) {
1231 		SSLerror(s, ERR_R_DH_LIB);
1232 		goto err;
1233 	}
1234 
1235 	/*
1236 	 * Serialize the DH parameters and public key.
1237 	 */
1238 	if (!CBB_add_u16_length_prefixed(cbb, &dh_p))
1239 		goto err;
1240 	if (!CBB_add_space(&dh_p, &data, BN_num_bytes(dh->p)))
1241 		goto err;
1242 	BN_bn2bin(dh->p, data);
1243 
1244 	if (!CBB_add_u16_length_prefixed(cbb, &dh_g))
1245 		goto err;
1246 	if (!CBB_add_space(&dh_g, &data, BN_num_bytes(dh->g)))
1247 		goto err;
1248 	BN_bn2bin(dh->g, data);
1249 
1250 	if (!CBB_add_u16_length_prefixed(cbb, &dh_Ys))
1251 		goto err;
1252 	if (!CBB_add_space(&dh_Ys, &data, BN_num_bytes(dh->pub_key)))
1253 		goto err;
1254 	BN_bn2bin(dh->pub_key, data);
1255 
1256 	if (!CBB_flush(cbb))
1257 		goto err;
1258 
1259 	return (1);
1260 
1261  f_err:
1262 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1263  err:
1264 	return (-1);
1265 }
1266 
1267 static int
1268 ssl3_send_server_kex_ecdhe_ecp(SSL *s, int nid, CBB *cbb)
1269 {
1270 	CBB ecpoint;
1271 	unsigned char *data;
1272 	EC_KEY *ecdh = NULL, *ecdhp;
1273 	const EC_GROUP *group;
1274 	int encoded_len = 0;
1275 	int curve_id = 0;
1276 	BN_CTX *bn_ctx = NULL;
1277 	int al;
1278 
1279 	ecdhp = s->cert->ecdh_tmp;
1280 	if (s->cert->ecdh_tmp_auto != 0) {
1281 		if (nid != NID_undef)
1282 			ecdhp = EC_KEY_new_by_curve_name(nid);
1283 	} else if (ecdhp == NULL && s->cert->ecdh_tmp_cb != NULL) {
1284 		ecdhp = s->cert->ecdh_tmp_cb(s, 0,
1285 		    SSL_C_PKEYLENGTH(S3I(s)->hs.new_cipher));
1286 	}
1287 	if (ecdhp == NULL) {
1288 		al = SSL_AD_HANDSHAKE_FAILURE;
1289 		SSLerror(s, SSL_R_MISSING_TMP_ECDH_KEY);
1290 		goto f_err;
1291 	}
1292 
1293 	if (S3I(s)->tmp.ecdh != NULL) {
1294 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1295 		goto err;
1296 	}
1297 
1298 	/* Duplicate the ECDH structure. */
1299 	if (s->cert->ecdh_tmp_auto != 0) {
1300 		ecdh = ecdhp;
1301 	} else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1302 		SSLerror(s, ERR_R_ECDH_LIB);
1303 		goto err;
1304 	}
1305 	S3I(s)->tmp.ecdh = ecdh;
1306 
1307 	if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1308 	    (EC_KEY_get0_private_key(ecdh) == NULL) ||
1309 	    (s->internal->options & SSL_OP_SINGLE_ECDH_USE)) {
1310 		if (!EC_KEY_generate_key(ecdh)) {
1311 			SSLerror(s, ERR_R_ECDH_LIB);
1312 			goto err;
1313 		}
1314 	}
1315 
1316 	if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1317 	    (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1318 	    (EC_KEY_get0_private_key(ecdh) == NULL)) {
1319 		SSLerror(s, ERR_R_ECDH_LIB);
1320 		goto err;
1321 	}
1322 
1323 	/*
1324 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1325 	 * For supported named curves, curve_id is non-zero.
1326 	 */
1327 	if ((curve_id = tls1_ec_nid2curve_id(
1328 	    EC_GROUP_get_curve_name(group))) == 0) {
1329 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1330 		goto err;
1331 	}
1332 
1333 	/*
1334 	 * Encode the public key. First check the size of encoding and
1335 	 * allocate memory accordingly.
1336 	 */
1337 	encoded_len = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1338 	    POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
1339 	if (encoded_len == 0) {
1340 		SSLerror(s, ERR_R_ECDH_LIB);
1341 		goto err;
1342 	}
1343 	if ((bn_ctx = BN_CTX_new()) == NULL) {
1344 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1345 		goto err;
1346 	}
1347 
1348 	/*
1349 	 * Only named curves are supported in ECDH ephemeral key exchanges.
1350 	 * In this case the ServerKeyExchange message has:
1351 	 * [1 byte CurveType], [2 byte CurveName]
1352 	 * [1 byte length of encoded point], followed by
1353 	 * the actual encoded point itself.
1354 	 */
1355 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1356 		goto err;
1357 	if (!CBB_add_u16(cbb, curve_id))
1358 		goto err;
1359 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1360 		goto err;
1361 	if (!CBB_add_space(&ecpoint, &data, encoded_len))
1362 		goto err;
1363 	if (EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
1364 	    POINT_CONVERSION_UNCOMPRESSED, data, encoded_len, bn_ctx) == 0) {
1365 		SSLerror(s, ERR_R_ECDH_LIB);
1366 		goto err;
1367 	}
1368 	if (!CBB_flush(cbb))
1369 		goto err;
1370 
1371 	BN_CTX_free(bn_ctx);
1372 
1373 	return (1);
1374 
1375  f_err:
1376 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1377  err:
1378 	BN_CTX_free(bn_ctx);
1379 
1380 	return (-1);
1381 }
1382 
1383 static int
1384 ssl3_send_server_kex_ecdhe_ecx(SSL *s, int nid, CBB *cbb)
1385 {
1386 	uint8_t *public_key = NULL;
1387 	int curve_id;
1388 	CBB ecpoint;
1389 	int ret = -1;
1390 
1391 	/* Generate an X25519 key pair. */
1392 	if (S3I(s)->tmp.x25519 != NULL) {
1393 		SSLerror(s, ERR_R_INTERNAL_ERROR);
1394 		goto err;
1395 	}
1396 	if ((S3I(s)->tmp.x25519 = malloc(X25519_KEY_LENGTH)) == NULL)
1397 		goto err;
1398 	if ((public_key = malloc(X25519_KEY_LENGTH)) == NULL)
1399 		goto err;
1400 	X25519_keypair(public_key, S3I(s)->tmp.x25519);
1401 
1402 	/* Serialize public key. */
1403 	if ((curve_id = tls1_ec_nid2curve_id(nid)) == 0) {
1404 		SSLerror(s, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1405 		goto err;
1406 	}
1407 
1408 	if (!CBB_add_u8(cbb, NAMED_CURVE_TYPE))
1409 		goto err;
1410 	if (!CBB_add_u16(cbb, curve_id))
1411 		goto err;
1412 	if (!CBB_add_u8_length_prefixed(cbb, &ecpoint))
1413 		goto err;
1414 	if (!CBB_add_bytes(&ecpoint, public_key, X25519_KEY_LENGTH))
1415 		goto err;
1416 	if (!CBB_flush(cbb))
1417 		goto err;
1418 
1419 	ret = 1;
1420 
1421  err:
1422 	free(public_key);
1423 
1424 	return (ret);
1425 }
1426 
1427 static int
1428 ssl3_send_server_kex_ecdhe(SSL *s, CBB *cbb)
1429 {
1430 	int nid;
1431 
1432 	nid = tls1_get_shared_curve(s);
1433 
1434 	if (s->cert->ecdh_tmp_auto != 0 && nid == NID_X25519)
1435 		return ssl3_send_server_kex_ecdhe_ecx(s, nid, cbb);
1436 
1437 	return ssl3_send_server_kex_ecdhe_ecp(s, nid, cbb);
1438 }
1439 
1440 int
1441 ssl3_send_server_key_exchange(SSL *s)
1442 {
1443 	CBB cbb;
1444 	unsigned char *params = NULL;
1445 	size_t params_len;
1446 	unsigned char *q;
1447 	unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1448 	unsigned int u;
1449 	EVP_PKEY *pkey;
1450 	const EVP_MD *md = NULL;
1451 	unsigned char *p, *d;
1452 	int al, i, j, n, kn;
1453 	unsigned long type;
1454 	BUF_MEM *buf;
1455 	EVP_MD_CTX md_ctx;
1456 
1457 	memset(&cbb, 0, sizeof(cbb));
1458 
1459 	EVP_MD_CTX_init(&md_ctx);
1460 	if (S3I(s)->hs.state == SSL3_ST_SW_KEY_EXCH_A) {
1461 		type = S3I(s)->hs.new_cipher->algorithm_mkey;
1462 
1463 		buf = s->internal->init_buf;
1464 
1465 		if (!CBB_init(&cbb, 0))
1466 			goto err;
1467 
1468 		if (type & SSL_kDHE) {
1469 			if (ssl3_send_server_kex_dhe(s, &cbb) != 1)
1470 				goto err;
1471 		} else if (type & SSL_kECDHE) {
1472 			if (ssl3_send_server_kex_ecdhe(s, &cbb) != 1)
1473 				goto err;
1474 		} else {
1475 			al = SSL_AD_HANDSHAKE_FAILURE;
1476 			SSLerror(s, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1477 			goto f_err;
1478 		}
1479 
1480 		if (!CBB_finish(&cbb, &params, &params_len))
1481 			goto err;
1482 
1483 		if (!(S3I(s)->hs.new_cipher->algorithm_auth & SSL_aNULL)) {
1484 			if ((pkey = ssl_get_sign_pkey(
1485 			    s, S3I(s)->hs.new_cipher, &md)) == NULL) {
1486 				al = SSL_AD_DECODE_ERROR;
1487 				goto f_err;
1488 			}
1489 			kn = EVP_PKEY_size(pkey);
1490 		} else {
1491 			pkey = NULL;
1492 			kn = 0;
1493 		}
1494 
1495 		if (!BUF_MEM_grow_clean(buf, ssl3_handshake_msg_hdr_len(s) +
1496 		    params_len + kn)) {
1497 			SSLerror(s, ERR_LIB_BUF);
1498 			goto err;
1499 		}
1500 
1501 		d = p = ssl3_handshake_msg_start(s,
1502 		    SSL3_MT_SERVER_KEY_EXCHANGE);
1503 
1504 		memcpy(p, params, params_len);
1505 
1506 		free(params);
1507 		params = NULL;
1508 
1509 		n = params_len;
1510 		p += params_len;
1511 
1512 		/* not anonymous */
1513 		if (pkey != NULL) {
1514 			/*
1515 			 * n is the length of the params, they start at &(d[4])
1516 			 * and p points to the space at the end.
1517 			 */
1518 			if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
1519 				q = md_buf;
1520 				j = 0;
1521 				if (!EVP_DigestInit_ex(&md_ctx, EVP_md5_sha1(),
1522 				    NULL))
1523 					goto err;
1524 				EVP_DigestUpdate(&md_ctx, s->s3->client_random,
1525 				    SSL3_RANDOM_SIZE);
1526 				EVP_DigestUpdate(&md_ctx, s->s3->server_random,
1527 				    SSL3_RANDOM_SIZE);
1528 				EVP_DigestUpdate(&md_ctx, d, n);
1529 				EVP_DigestFinal_ex(&md_ctx, q,
1530 				    (unsigned int *)&i);
1531 				q += i;
1532 				j += i;
1533 				if (RSA_sign(NID_md5_sha1, md_buf, j,
1534 				    &(p[2]), &u, pkey->pkey.rsa) <= 0) {
1535 					SSLerror(s, ERR_R_RSA_LIB);
1536 					goto err;
1537 				}
1538 				s2n(u, p);
1539 				n += u + 2;
1540 			} else if (md) {
1541 				/* Send signature algorithm. */
1542 				if (SSL_USE_SIGALGS(s)) {
1543 					if (!tls12_get_sigandhash(p, pkey, md)) {
1544 						/* Should never happen */
1545 						al = SSL_AD_INTERNAL_ERROR;
1546 						SSLerror(s, ERR_R_INTERNAL_ERROR);
1547 						goto f_err;
1548 					}
1549 					p += 2;
1550 				}
1551 				EVP_SignInit_ex(&md_ctx, md, NULL);
1552 				EVP_SignUpdate(&md_ctx,
1553 				    s->s3->client_random,
1554 				    SSL3_RANDOM_SIZE);
1555 				EVP_SignUpdate(&md_ctx,
1556 				    s->s3->server_random,
1557 				    SSL3_RANDOM_SIZE);
1558 				EVP_SignUpdate(&md_ctx, d, n);
1559 				if (!EVP_SignFinal(&md_ctx, &p[2],
1560 					(unsigned int *)&i, pkey)) {
1561 					SSLerror(s, ERR_R_EVP_LIB);
1562 					goto err;
1563 				}
1564 				s2n(i, p);
1565 				n += i + 2;
1566 				if (SSL_USE_SIGALGS(s))
1567 					n += 2;
1568 			} else {
1569 				/* Is this error check actually needed? */
1570 				al = SSL_AD_HANDSHAKE_FAILURE;
1571 				SSLerror(s, SSL_R_UNKNOWN_PKEY_TYPE);
1572 				goto f_err;
1573 			}
1574 		}
1575 
1576 		ssl3_handshake_msg_finish(s, n);
1577 	}
1578 
1579 	S3I(s)->hs.state = SSL3_ST_SW_KEY_EXCH_B;
1580 
1581 	EVP_MD_CTX_cleanup(&md_ctx);
1582 
1583 	return (ssl3_handshake_write(s));
1584 
1585  f_err:
1586 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1587  err:
1588 	free(params);
1589 	EVP_MD_CTX_cleanup(&md_ctx);
1590 	CBB_cleanup(&cbb);
1591 
1592 	return (-1);
1593 }
1594 
1595 int
1596 ssl3_send_certificate_request(SSL *s)
1597 {
1598 	unsigned char *p, *d;
1599 	int i, j, nl, off, n;
1600 	STACK_OF(X509_NAME) *sk = NULL;
1601 	X509_NAME *name;
1602 	BUF_MEM *buf;
1603 
1604 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_REQ_A) {
1605 		buf = s->internal->init_buf;
1606 
1607 		d = p = ssl3_handshake_msg_start(s,
1608 		    SSL3_MT_CERTIFICATE_REQUEST);
1609 
1610 		/* get the list of acceptable cert types */
1611 		p++;
1612 		n = ssl3_get_req_cert_type(s, p);
1613 		d[0] = n;
1614 		p += n;
1615 		n++;
1616 
1617 		if (SSL_USE_SIGALGS(s)) {
1618 			nl = tls12_get_req_sig_algs(s, p + 2);
1619 			s2n(nl, p);
1620 			p += nl + 2;
1621 			n += nl + 2;
1622 		}
1623 
1624 		off = n;
1625 		p += 2;
1626 		n += 2;
1627 
1628 		sk = SSL_get_client_CA_list(s);
1629 		nl = 0;
1630 		if (sk != NULL) {
1631 			for (i = 0; i < sk_X509_NAME_num(sk); i++) {
1632 				name = sk_X509_NAME_value(sk, i);
1633 				j = i2d_X509_NAME(name, NULL);
1634 				if (!BUF_MEM_grow_clean(buf,
1635 				    ssl3_handshake_msg_hdr_len(s) + n + j
1636 				    + 2)) {
1637 					SSLerror(s, ERR_R_BUF_LIB);
1638 					goto err;
1639 				}
1640 				p = ssl3_handshake_msg_start(s,
1641 				    SSL3_MT_CERTIFICATE_REQUEST) + n;
1642 				s2n(j, p);
1643 				i2d_X509_NAME(name, &p);
1644 				n += 2 + j;
1645 				nl += 2 + j;
1646 			}
1647 		}
1648 		/* else no CA names */
1649 		p = ssl3_handshake_msg_start(s,
1650 		    SSL3_MT_CERTIFICATE_REQUEST) + off;
1651 		s2n(nl, p);
1652 
1653 		ssl3_handshake_msg_finish(s, n);
1654 
1655 		S3I(s)->hs.state = SSL3_ST_SW_CERT_REQ_B;
1656 	}
1657 
1658 	/* SSL3_ST_SW_CERT_REQ_B */
1659 	return (ssl3_handshake_write(s));
1660 err:
1661 	return (-1);
1662 }
1663 
1664 static int
1665 ssl3_get_client_kex_rsa(SSL *s, unsigned char *p, long n)
1666 {
1667 	unsigned char fakekey[SSL_MAX_MASTER_KEY_LENGTH];
1668 	unsigned char *d;
1669 	RSA *rsa = NULL;
1670 	EVP_PKEY *pkey = NULL;
1671 	int i, al;
1672 
1673 	d = p;
1674 
1675 	arc4random_buf(fakekey, sizeof(fakekey));
1676 	fakekey[0] = s->client_version >> 8;
1677 	fakekey[1] = s->client_version & 0xff;
1678 
1679 	pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1680 	if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) ||
1681 	    (pkey->pkey.rsa == NULL)) {
1682 		al = SSL_AD_HANDSHAKE_FAILURE;
1683 		SSLerror(s, SSL_R_MISSING_RSA_CERTIFICATE);
1684 		goto f_err;
1685 	}
1686 	rsa = pkey->pkey.rsa;
1687 
1688 	if (2 > n)
1689 		goto truncated;
1690 	n2s(p, i);
1691 	if (n != i + 2) {
1692 		SSLerror(s, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1693 		goto err;
1694 	} else
1695 		n = i;
1696 
1697 	i = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
1698 
1699 	ERR_clear_error();
1700 
1701 	al = -1;
1702 
1703 	if (i != SSL_MAX_MASTER_KEY_LENGTH) {
1704 		al = SSL_AD_DECODE_ERROR;
1705 		/* SSLerror(s, SSL_R_BAD_RSA_DECRYPT); */
1706 	}
1707 
1708 	if (p - d + 2 > n)	/* needed in the SSL3 case */
1709 		goto truncated;
1710 	if ((al == -1) && !((p[0] == (s->client_version >> 8)) &&
1711 	    (p[1] == (s->client_version & 0xff)))) {
1712 		/*
1713 		 * The premaster secret must contain the same version
1714 		 * number as the ClientHello to detect version rollback
1715 		 * attacks (strangely, the protocol does not offer such
1716 		 * protection for DH ciphersuites).
1717 		 * However, buggy clients exist that send the negotiated
1718 		 * protocol version instead if the server does not
1719 		 * support the requested protocol version.
1720 		 * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
1721 		 * clients.
1722 		 */
1723 		if (!((s->internal->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1724 		    (p[0] == (s->version >> 8)) &&
1725 		    (p[1] == (s->version & 0xff)))) {
1726 			al = SSL_AD_DECODE_ERROR;
1727 			/* SSLerror(s, SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1728 
1729 			/*
1730 			 * The Klima-Pokorny-Rosa extension of
1731 			 * Bleichenbacher's attack
1732 			 * (http://eprint.iacr.org/2003/052/) exploits
1733 			 * the version number check as a "bad version
1734 			 * oracle" -- an alert would reveal that the
1735 			 * plaintext corresponding to some ciphertext
1736 			 * made up by the adversary is properly
1737 			 * formatted except that the version number is
1738 			 * wrong.
1739 			 * To avoid such attacks, we should treat this
1740 			 * just like any other decryption error.
1741 			 */
1742 		}
1743 	}
1744 
1745 	if (al != -1) {
1746 		/*
1747 		 * Some decryption failure -- use random value instead
1748 		 * as countermeasure against Bleichenbacher's attack
1749 		 * on PKCS #1 v1.5 RSA padding (see RFC 2246,
1750 		 * section 7.4.7.1).
1751 		 */
1752 		i = SSL_MAX_MASTER_KEY_LENGTH;
1753 		p = fakekey;
1754 	}
1755 
1756 	s->session->master_key_length =
1757 	    tls1_generate_master_secret(s,
1758 	        s->session->master_key, p, i);
1759 
1760 	explicit_bzero(p, i);
1761 
1762 	return (1);
1763 truncated:
1764 	al = SSL_AD_DECODE_ERROR;
1765 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1766 f_err:
1767 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1768 err:
1769 	return (-1);
1770 }
1771 
1772 static int
1773 ssl3_get_client_kex_dhe(SSL *s, unsigned char *p, long n)
1774 {
1775 	BIGNUM *bn = NULL;
1776 	int key_size, al;
1777 	CBS cbs, dh_Yc;
1778 	DH *dh;
1779 
1780 	if (n < 0)
1781 		goto err;
1782 
1783 	CBS_init(&cbs, p, n);
1784 
1785 	if (!CBS_get_u16_length_prefixed(&cbs, &dh_Yc))
1786 		goto truncated;
1787 
1788 	if (CBS_len(&cbs) != 0)
1789 		goto truncated;
1790 
1791 	if (S3I(s)->tmp.dh == NULL) {
1792 		al = SSL_AD_HANDSHAKE_FAILURE;
1793 		SSLerror(s, SSL_R_MISSING_TMP_DH_KEY);
1794 		goto f_err;
1795 	}
1796 	dh = S3I(s)->tmp.dh;
1797 
1798 	if ((bn = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL)) == NULL) {
1799 		SSLerror(s, SSL_R_BN_LIB);
1800 		goto err;
1801 	}
1802 
1803 	key_size = DH_compute_key(p, bn, dh);
1804 	if (key_size <= 0) {
1805 		SSLerror(s, ERR_R_DH_LIB);
1806 		BN_clear_free(bn);
1807 		goto err;
1808 	}
1809 
1810 	s->session->master_key_length =
1811 	    tls1_generate_master_secret(
1812 	        s, s->session->master_key, p, key_size);
1813 
1814 	explicit_bzero(p, key_size);
1815 
1816 	DH_free(S3I(s)->tmp.dh);
1817 	S3I(s)->tmp.dh = NULL;
1818 
1819 	BN_clear_free(bn);
1820 
1821 	return (1);
1822 
1823  truncated:
1824 	al = SSL_AD_DECODE_ERROR;
1825 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
1826  f_err:
1827 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1828  err:
1829 	return (-1);
1830 }
1831 
1832 static int
1833 ssl3_get_client_kex_ecdhe_ecp(SSL *s, unsigned char *p, long n)
1834 {
1835 	EC_KEY *srvr_ecdh = NULL;
1836 	EVP_PKEY *clnt_pub_pkey = NULL;
1837 	EC_POINT *clnt_ecpoint = NULL;
1838 	BN_CTX *bn_ctx = NULL;
1839 	int i, al;
1840 
1841 	int ret = 1;
1842 	int key_size;
1843 	const EC_KEY   *tkey;
1844 	const EC_GROUP *group;
1845 	const BIGNUM *priv_key;
1846 
1847 	/* Initialize structures for server's ECDH key pair. */
1848 	if ((srvr_ecdh = EC_KEY_new()) == NULL) {
1849 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1850 		goto err;
1851 	}
1852 
1853 	/*
1854 	 * Use the ephemeral values we saved when
1855 	 * generating the ServerKeyExchange message.
1856 	 */
1857 	tkey = S3I(s)->tmp.ecdh;
1858 
1859 	group = EC_KEY_get0_group(tkey);
1860 	priv_key = EC_KEY_get0_private_key(tkey);
1861 
1862 	if (!EC_KEY_set_group(srvr_ecdh, group) ||
1863 	    !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
1864 		SSLerror(s, ERR_R_EC_LIB);
1865 		goto err;
1866 	}
1867 
1868 	/* Let's get client's public key */
1869 	if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
1870 		SSLerror(s, ERR_R_MALLOC_FAILURE);
1871 		goto err;
1872 	}
1873 
1874 	if (n == 0L) {
1875 		/* Client Publickey was in Client Certificate */
1876 		if (((clnt_pub_pkey = X509_get_pubkey(
1877 		    s->session->peer)) == NULL) ||
1878 		    (clnt_pub_pkey->type != EVP_PKEY_EC)) {
1879 			/*
1880 			 * XXX: For now, we do not support client
1881 			 * authentication using ECDH certificates
1882 			 * so this branch (n == 0L) of the code is
1883 			 * never executed. When that support is
1884 			 * added, we ought to ensure the key
1885 			 * received in the certificate is
1886 			 * authorized for key agreement.
1887 			 * ECDH_compute_key implicitly checks that
1888 			 * the two ECDH shares are for the same
1889 			 * group.
1890 			 */
1891 			al = SSL_AD_HANDSHAKE_FAILURE;
1892 			SSLerror(s, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
1893 			goto f_err;
1894 		}
1895 
1896 		if (EC_POINT_copy(clnt_ecpoint,
1897 		    EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec))
1898 		    == 0) {
1899 			SSLerror(s, ERR_R_EC_LIB);
1900 			goto err;
1901 		}
1902 		ret = 2; /* Skip certificate verify processing */
1903 	} else {
1904 		/*
1905 		 * Get client's public key from encoded point
1906 		 * in the ClientKeyExchange message.
1907 		 */
1908 		if ((bn_ctx = BN_CTX_new()) == NULL) {
1909 			SSLerror(s, ERR_R_MALLOC_FAILURE);
1910 			goto err;
1911 		}
1912 
1913 		/* Get encoded point length */
1914 		i = *p;
1915 
1916 		p += 1;
1917 		if (n != 1 + i) {
1918 			SSLerror(s, ERR_R_EC_LIB);
1919 			goto err;
1920 		}
1921 		if (EC_POINT_oct2point(group,
1922 			clnt_ecpoint, p, i, bn_ctx) == 0) {
1923 			SSLerror(s, ERR_R_EC_LIB);
1924 			goto err;
1925 		}
1926 		/*
1927 		 * p is pointing to somewhere in the buffer
1928 		 * currently, so set it to the start.
1929 		 */
1930 		p = (unsigned char *)s->internal->init_buf->data;
1931 	}
1932 
1933 	/* Compute the shared pre-master secret */
1934 	key_size = ECDH_size(srvr_ecdh);
1935 	if (key_size <= 0) {
1936 		SSLerror(s, ERR_R_ECDH_LIB);
1937 		goto err;
1938 	}
1939 	i = ECDH_compute_key(p, key_size, clnt_ecpoint, srvr_ecdh,
1940 	    NULL);
1941 	if (i <= 0) {
1942 		SSLerror(s, ERR_R_ECDH_LIB);
1943 		goto err;
1944 	}
1945 
1946 	EVP_PKEY_free(clnt_pub_pkey);
1947 	EC_POINT_free(clnt_ecpoint);
1948 	EC_KEY_free(srvr_ecdh);
1949 	BN_CTX_free(bn_ctx);
1950 	EC_KEY_free(S3I(s)->tmp.ecdh);
1951 	S3I(s)->tmp.ecdh = NULL;
1952 
1953 	/* Compute the master secret */
1954 	s->session->master_key_length =
1955 	    tls1_generate_master_secret(
1956 		s, s->session->master_key, p, i);
1957 
1958 	explicit_bzero(p, i);
1959 	return (ret);
1960 
1961  f_err:
1962 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
1963  err:
1964 	EVP_PKEY_free(clnt_pub_pkey);
1965 	EC_POINT_free(clnt_ecpoint);
1966 	EC_KEY_free(srvr_ecdh);
1967 	BN_CTX_free(bn_ctx);
1968 	return (-1);
1969 }
1970 
1971 static int
1972 ssl3_get_client_kex_ecdhe_ecx(SSL *s, unsigned char *p, long n)
1973 {
1974 	uint8_t *shared_key = NULL;
1975 	CBS cbs, ecpoint;
1976 	int ret = -1;
1977 
1978 	if (n < 0)
1979 		goto err;
1980 
1981 	CBS_init(&cbs, p, n);
1982 	if (!CBS_get_u8_length_prefixed(&cbs, &ecpoint))
1983 		goto err;
1984 	if (CBS_len(&ecpoint) != X25519_KEY_LENGTH)
1985 		goto err;
1986 
1987 	if ((shared_key = malloc(X25519_KEY_LENGTH)) == NULL)
1988 		goto err;
1989 	if (!X25519(shared_key, S3I(s)->tmp.x25519, CBS_data(&ecpoint)))
1990 		goto err;
1991 
1992 	freezero(S3I(s)->tmp.x25519, X25519_KEY_LENGTH);
1993 	S3I(s)->tmp.x25519 = NULL;
1994 
1995 	s->session->master_key_length =
1996 	    tls1_generate_master_secret(
1997 		s, s->session->master_key, shared_key, X25519_KEY_LENGTH);
1998 
1999 	ret = 1;
2000 
2001  err:
2002 	freezero(shared_key, X25519_KEY_LENGTH);
2003 
2004 	return (ret);
2005 }
2006 
2007 static int
2008 ssl3_get_client_kex_ecdhe(SSL *s, unsigned char *p, long n)
2009 {
2010         if (S3I(s)->tmp.x25519 != NULL)
2011 		return ssl3_get_client_kex_ecdhe_ecx(s, p, n);
2012 
2013 	return ssl3_get_client_kex_ecdhe_ecp(s, p, n);
2014 }
2015 
2016 static int
2017 ssl3_get_client_kex_gost(SSL *s, unsigned char *p, long n)
2018 {
2019 
2020 	EVP_PKEY_CTX *pkey_ctx;
2021 	EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2022 	unsigned char premaster_secret[32], *start;
2023 	size_t outlen = 32, inlen;
2024 	unsigned long alg_a;
2025 	int Ttag, Tclass;
2026 	long Tlen;
2027 	int al;
2028 	int ret = 0;
2029 
2030 	/* Get our certificate private key*/
2031 	alg_a = S3I(s)->hs.new_cipher->algorithm_auth;
2032 	if (alg_a & SSL_aGOST01)
2033 		pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2034 
2035 	pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2036 	EVP_PKEY_decrypt_init(pkey_ctx);
2037 	/*
2038 	 * If client certificate is present and is of the same type,
2039 	 * maybe use it for key exchange.
2040 	 * Don't mind errors from EVP_PKEY_derive_set_peer, because
2041 	 * it is completely valid to use a client certificate for
2042 	 * authorization only.
2043 	 */
2044 	client_pub_pkey = X509_get_pubkey(s->session->peer);
2045 	if (client_pub_pkey) {
2046 		if (EVP_PKEY_derive_set_peer(pkey_ctx,
2047 		    client_pub_pkey) <= 0)
2048 			ERR_clear_error();
2049 	}
2050 	if (2 > n)
2051 		goto truncated;
2052 	/* Decrypt session key */
2053 	if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag,
2054 	    &Tclass, n) != V_ASN1_CONSTRUCTED ||
2055 	    Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
2056 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2057 		goto gerr;
2058 	}
2059 	start = p;
2060 	inlen = Tlen;
2061 	if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen,
2062 	    start, inlen) <=0) {
2063 		SSLerror(s, SSL_R_DECRYPTION_FAILED);
2064 		goto gerr;
2065 	}
2066 	/* Generate master secret */
2067 	s->session->master_key_length =
2068 	    tls1_generate_master_secret(
2069 		s, s->session->master_key, premaster_secret, 32);
2070 	/* Check if pubkey from client certificate was used */
2071 	if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1,
2072 	    EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2073 		ret = 2;
2074 	else
2075 		ret = 1;
2076  gerr:
2077 	EVP_PKEY_free(client_pub_pkey);
2078 	EVP_PKEY_CTX_free(pkey_ctx);
2079 	if (ret)
2080 		return (ret);
2081 	else
2082 		goto err;
2083 
2084  truncated:
2085 	al = SSL_AD_DECODE_ERROR;
2086 	SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2087 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2088  err:
2089 	return (-1);
2090 }
2091 
2092 int
2093 ssl3_get_client_key_exchange(SSL *s)
2094 {
2095 	unsigned long alg_k;
2096 	unsigned char *p;
2097 	int al, ok;
2098 	long n;
2099 
2100 	/* 2048 maxlen is a guess.  How long a key does that permit? */
2101 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
2102 	    SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2103 	if (!ok)
2104 		return ((int)n);
2105 
2106 	p = (unsigned char *)s->internal->init_msg;
2107 
2108 	alg_k = S3I(s)->hs.new_cipher->algorithm_mkey;
2109 
2110 	if (alg_k & SSL_kRSA) {
2111 		if (ssl3_get_client_kex_rsa(s, p, n) != 1)
2112 			goto err;
2113 	} else if (alg_k & SSL_kDHE) {
2114 		if (ssl3_get_client_kex_dhe(s, p, n) != 1)
2115 			goto err;
2116 	} else if (alg_k & SSL_kECDHE) {
2117 		if (ssl3_get_client_kex_ecdhe(s, p, n) != 1)
2118 			goto err;
2119 	} else if (alg_k & SSL_kGOST) {
2120 		if (ssl3_get_client_kex_gost(s, p, n) != 1)
2121 			goto err;
2122 	} else {
2123 		al = SSL_AD_HANDSHAKE_FAILURE;
2124 		SSLerror(s, SSL_R_UNKNOWN_CIPHER_TYPE);
2125 		goto f_err;
2126 	}
2127 
2128 	return (1);
2129 
2130  f_err:
2131 	ssl3_send_alert(s, SSL3_AL_FATAL, al);
2132  err:
2133 	return (-1);
2134 }
2135 
2136 int
2137 ssl3_get_cert_verify(SSL *s)
2138 {
2139 	EVP_PKEY *pkey = NULL;
2140 	unsigned char *p;
2141 	int al, ok, ret = 0;
2142 	long n;
2143 	int type = 0, i, j;
2144 	X509 *peer;
2145 	const EVP_MD *md = NULL;
2146 	EVP_MD_CTX mctx;
2147 	EVP_MD_CTX_init(&mctx);
2148 
2149 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A,
2150 	    SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2151 	if (!ok)
2152 		return ((int)n);
2153 
2154 	if (s->session->peer != NULL) {
2155 		peer = s->session->peer;
2156 		pkey = X509_get_pubkey(peer);
2157 		type = X509_certificate_type(peer, pkey);
2158 	} else {
2159 		peer = NULL;
2160 		pkey = NULL;
2161 	}
2162 
2163 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) {
2164 		S3I(s)->tmp.reuse_message = 1;
2165 		if (peer != NULL) {
2166 			al = SSL_AD_UNEXPECTED_MESSAGE;
2167 			SSLerror(s, SSL_R_MISSING_VERIFY_MESSAGE);
2168 			goto f_err;
2169 		}
2170 		ret = 1;
2171 		goto end;
2172 	}
2173 
2174 	if (peer == NULL) {
2175 		SSLerror(s, SSL_R_NO_CLIENT_CERT_RECEIVED);
2176 		al = SSL_AD_UNEXPECTED_MESSAGE;
2177 		goto f_err;
2178 	}
2179 
2180 	if (!(type & EVP_PKT_SIGN)) {
2181 		SSLerror(s, SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2182 		al = SSL_AD_ILLEGAL_PARAMETER;
2183 		goto f_err;
2184 	}
2185 
2186 	if (S3I(s)->change_cipher_spec) {
2187 		SSLerror(s, SSL_R_CCS_RECEIVED_EARLY);
2188 		al = SSL_AD_UNEXPECTED_MESSAGE;
2189 		goto f_err;
2190 	}
2191 
2192 	/* we now have a signature that we need to verify */
2193 	p = (unsigned char *)s->internal->init_msg;
2194 	/*
2195 	 * Check for broken implementations of GOST ciphersuites.
2196 	 *
2197 	 * If key is GOST and n is exactly 64, it is a bare
2198 	 * signature without length field.
2199 	 */
2200 	if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2201 	    pkey->type == NID_id_GostR3410_2001) ) {
2202 		i = 64;
2203 	} else {
2204 		if (SSL_USE_SIGALGS(s)) {
2205 			int sigalg = tls12_get_sigid(pkey);
2206 			/* Should never happen */
2207 			if (sigalg == -1) {
2208 				SSLerror(s, ERR_R_INTERNAL_ERROR);
2209 				al = SSL_AD_INTERNAL_ERROR;
2210 				goto f_err;
2211 			}
2212 			if (2 > n)
2213 				goto truncated;
2214 			/* Check key type is consistent with signature */
2215 			if (sigalg != (int)p[1]) {
2216 				SSLerror(s, SSL_R_WRONG_SIGNATURE_TYPE);
2217 				al = SSL_AD_DECODE_ERROR;
2218 				goto f_err;
2219 			}
2220 			md = tls12_get_hash(p[0]);
2221 			if (md == NULL) {
2222 				SSLerror(s, SSL_R_UNKNOWN_DIGEST);
2223 				al = SSL_AD_DECODE_ERROR;
2224 				goto f_err;
2225 			}
2226 			p += 2;
2227 			n -= 2;
2228 		}
2229 		if (2 > n)
2230 			goto truncated;
2231 		n2s(p, i);
2232 		n -= 2;
2233 		if (i > n)
2234 			goto truncated;
2235 	}
2236 	j = EVP_PKEY_size(pkey);
2237 	if ((i > j) || (n > j) || (n <= 0)) {
2238 		SSLerror(s, SSL_R_WRONG_SIGNATURE_SIZE);
2239 		al = SSL_AD_DECODE_ERROR;
2240 		goto f_err;
2241 	}
2242 
2243 	if (SSL_USE_SIGALGS(s)) {
2244 		long hdatalen = 0;
2245 		void *hdata;
2246 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2247 		if (hdatalen <= 0) {
2248 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2249 			al = SSL_AD_INTERNAL_ERROR;
2250 			goto f_err;
2251 		}
2252 		if (!EVP_VerifyInit_ex(&mctx, md, NULL) ||
2253 		    !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2254 			SSLerror(s, ERR_R_EVP_LIB);
2255 			al = SSL_AD_INTERNAL_ERROR;
2256 			goto f_err;
2257 		}
2258 
2259 		if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2260 			al = SSL_AD_DECRYPT_ERROR;
2261 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2262 			goto f_err;
2263 		}
2264 	} else
2265 	if (pkey->type == EVP_PKEY_RSA) {
2266 		i = RSA_verify(NID_md5_sha1, S3I(s)->tmp.cert_verify_md,
2267 		    MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
2268 		    pkey->pkey.rsa);
2269 		if (i < 0) {
2270 			al = SSL_AD_DECRYPT_ERROR;
2271 			SSLerror(s, SSL_R_BAD_RSA_DECRYPT);
2272 			goto f_err;
2273 		}
2274 		if (i == 0) {
2275 			al = SSL_AD_DECRYPT_ERROR;
2276 			SSLerror(s, SSL_R_BAD_RSA_SIGNATURE);
2277 			goto f_err;
2278 		}
2279 	} else
2280 	if (pkey->type == EVP_PKEY_DSA) {
2281 		j = DSA_verify(pkey->save_type,
2282 		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2283 		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
2284 		if (j <= 0) {
2285 			/* bad signature */
2286 			al = SSL_AD_DECRYPT_ERROR;
2287 			SSLerror(s, SSL_R_BAD_DSA_SIGNATURE);
2288 			goto f_err;
2289 		}
2290 	} else
2291 	if (pkey->type == EVP_PKEY_EC) {
2292 		j = ECDSA_verify(pkey->save_type,
2293 		    &(S3I(s)->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2294 		    SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
2295 		if (j <= 0) {
2296 			/* bad signature */
2297 			al = SSL_AD_DECRYPT_ERROR;
2298 			SSLerror(s, SSL_R_BAD_ECDSA_SIGNATURE);
2299 			goto f_err;
2300 		}
2301 	} else
2302 #ifndef OPENSSL_NO_GOST
2303 	if (pkey->type == NID_id_GostR3410_94 ||
2304 	    pkey->type == NID_id_GostR3410_2001) {
2305 		long hdatalen = 0;
2306 		void *hdata;
2307 		unsigned char signature[128];
2308 		unsigned int siglen = sizeof(signature);
2309 		int nid;
2310 		EVP_PKEY_CTX *pctx;
2311 
2312 		hdatalen = BIO_get_mem_data(S3I(s)->handshake_buffer, &hdata);
2313 		if (hdatalen <= 0) {
2314 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2315 			al = SSL_AD_INTERNAL_ERROR;
2316 			goto f_err;
2317 		}
2318 		if (!EVP_PKEY_get_default_digest_nid(pkey, &nid) ||
2319 				!(md = EVP_get_digestbynid(nid))) {
2320 			SSLerror(s, ERR_R_EVP_LIB);
2321 			al = SSL_AD_INTERNAL_ERROR;
2322 			goto f_err;
2323 		}
2324 		pctx = EVP_PKEY_CTX_new(pkey, NULL);
2325 		if (!pctx) {
2326 			SSLerror(s, ERR_R_EVP_LIB);
2327 			al = SSL_AD_INTERNAL_ERROR;
2328 			goto f_err;
2329 		}
2330 		if (!EVP_DigestInit_ex(&mctx, md, NULL) ||
2331 		    !EVP_DigestUpdate(&mctx, hdata, hdatalen) ||
2332 		    !EVP_DigestFinal(&mctx, signature, &siglen) ||
2333 		    (EVP_PKEY_verify_init(pctx) <= 0) ||
2334 		    (EVP_PKEY_CTX_set_signature_md(pctx, md) <= 0) ||
2335 		    (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_VERIFY,
2336 				       EVP_PKEY_CTRL_GOST_SIG_FORMAT,
2337 				       GOST_SIG_FORMAT_RS_LE,
2338 				       NULL) <= 0)) {
2339 			SSLerror(s, ERR_R_EVP_LIB);
2340 			al = SSL_AD_INTERNAL_ERROR;
2341 			EVP_PKEY_CTX_free(pctx);
2342 			goto f_err;
2343 		}
2344 
2345 		if (EVP_PKEY_verify(pctx, p, i, signature, siglen) <= 0) {
2346 			al = SSL_AD_DECRYPT_ERROR;
2347 			SSLerror(s, SSL_R_BAD_SIGNATURE);
2348 			EVP_PKEY_CTX_free(pctx);
2349 			goto f_err;
2350 		}
2351 
2352 		EVP_PKEY_CTX_free(pctx);
2353 	} else
2354 #endif
2355 	{
2356 		SSLerror(s, ERR_R_INTERNAL_ERROR);
2357 		al = SSL_AD_UNSUPPORTED_CERTIFICATE;
2358 		goto f_err;
2359 	}
2360 
2361 
2362 	ret = 1;
2363 	if (0) {
2364 truncated:
2365 		al = SSL_AD_DECODE_ERROR;
2366 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2367 f_err:
2368 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2369 	}
2370 end:
2371 	if (S3I(s)->handshake_buffer) {
2372 		BIO_free(S3I(s)->handshake_buffer);
2373 		S3I(s)->handshake_buffer = NULL;
2374 		s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
2375 	}
2376 	EVP_MD_CTX_cleanup(&mctx);
2377 	EVP_PKEY_free(pkey);
2378 	return (ret);
2379 }
2380 
2381 int
2382 ssl3_get_client_certificate(SSL *s)
2383 {
2384 	CBS cbs, client_certs;
2385 	int i, ok, al, ret = -1;
2386 	X509 *x = NULL;
2387 	long n;
2388 	const unsigned char *q;
2389 	STACK_OF(X509) *sk = NULL;
2390 
2391 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
2392 	    -1, s->internal->max_cert_list, &ok);
2393 
2394 	if (!ok)
2395 		return ((int)n);
2396 
2397 	if (S3I(s)->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
2398 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2399 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2400 		    	SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2401 			al = SSL_AD_HANDSHAKE_FAILURE;
2402 			goto f_err;
2403 		}
2404 		/*
2405 		 * If tls asked for a client cert,
2406 		 * the client must return a 0 list.
2407 		 */
2408 		if (S3I(s)->tmp.cert_request) {
2409 			SSLerror(s, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST
2410 			    );
2411 			al = SSL_AD_UNEXPECTED_MESSAGE;
2412 			goto f_err;
2413 		}
2414 		S3I(s)->tmp.reuse_message = 1;
2415 		return (1);
2416 	}
2417 
2418 	if (S3I(s)->tmp.message_type != SSL3_MT_CERTIFICATE) {
2419 		al = SSL_AD_UNEXPECTED_MESSAGE;
2420 		SSLerror(s, SSL_R_WRONG_MESSAGE_TYPE);
2421 		goto f_err;
2422 	}
2423 
2424 	if (n < 0)
2425 		goto truncated;
2426 
2427 	CBS_init(&cbs, s->internal->init_msg, n);
2428 
2429 	if ((sk = sk_X509_new_null()) == NULL) {
2430 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2431 		goto err;
2432 	}
2433 
2434 	if (!CBS_get_u24_length_prefixed(&cbs, &client_certs) ||
2435 	    CBS_len(&cbs) != 0)
2436 		goto truncated;
2437 
2438 	while (CBS_len(&client_certs) > 0) {
2439 		CBS cert;
2440 
2441 		if (!CBS_get_u24_length_prefixed(&client_certs, &cert)) {
2442 			al = SSL_AD_DECODE_ERROR;
2443 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2444 			goto f_err;
2445 		}
2446 
2447 		q = CBS_data(&cert);
2448 		x = d2i_X509(NULL, &q, CBS_len(&cert));
2449 		if (x == NULL) {
2450 			SSLerror(s, ERR_R_ASN1_LIB);
2451 			goto err;
2452 		}
2453 		if (q != CBS_data(&cert) + CBS_len(&cert)) {
2454 			al = SSL_AD_DECODE_ERROR;
2455 			SSLerror(s, SSL_R_CERT_LENGTH_MISMATCH);
2456 			goto f_err;
2457 		}
2458 		if (!sk_X509_push(sk, x)) {
2459 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2460 			goto err;
2461 		}
2462 		x = NULL;
2463 	}
2464 
2465 	if (sk_X509_num(sk) <= 0) {
2466 		/*
2467 		 * TLS does not mind 0 certs returned.
2468 		 * Fail for TLS only if we required a certificate.
2469 		 */
2470 		if ((s->verify_mode & SSL_VERIFY_PEER) &&
2471 		    (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
2472 			SSLerror(s, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2473 			al = SSL_AD_HANDSHAKE_FAILURE;
2474 			goto f_err;
2475 		}
2476 		/* No client certificate so digest cached records */
2477 		if (S3I(s)->handshake_buffer && !tls1_digest_cached_records(s)) {
2478 			al = SSL_AD_INTERNAL_ERROR;
2479 			goto f_err;
2480 		}
2481 	} else {
2482 		i = ssl_verify_cert_chain(s, sk);
2483 		if (i <= 0) {
2484 			al = ssl_verify_alarm_type(s->verify_result);
2485 			SSLerror(s, SSL_R_NO_CERTIFICATE_RETURNED);
2486 			goto f_err;
2487 		}
2488 	}
2489 
2490 	X509_free(s->session->peer);
2491 	s->session->peer = sk_X509_shift(sk);
2492 	s->session->verify_result = s->verify_result;
2493 
2494 	/*
2495 	 * With the current implementation, sess_cert will always be NULL
2496 	 * when we arrive here
2497 	 */
2498 	if (SSI(s)->sess_cert == NULL) {
2499 		SSI(s)->sess_cert = ssl_sess_cert_new();
2500 		if (SSI(s)->sess_cert == NULL) {
2501 			SSLerror(s, ERR_R_MALLOC_FAILURE);
2502 			goto err;
2503 		}
2504 	}
2505 	sk_X509_pop_free(SSI(s)->sess_cert->cert_chain, X509_free);
2506 	SSI(s)->sess_cert->cert_chain = sk;
2507 
2508 	/*
2509 	 * Inconsistency alert: cert_chain does *not* include the
2510 	 * peer's own certificate, while we do include it in s3_clnt.c
2511 	 */
2512 
2513 	sk = NULL;
2514 
2515 	ret = 1;
2516 	if (0) {
2517 truncated:
2518 		al = SSL_AD_DECODE_ERROR;
2519 		SSLerror(s, SSL_R_BAD_PACKET_LENGTH);
2520 f_err:
2521 		ssl3_send_alert(s, SSL3_AL_FATAL, al);
2522 	}
2523 err:
2524 	X509_free(x);
2525 	sk_X509_pop_free(sk, X509_free);
2526 
2527 	return (ret);
2528 }
2529 
2530 int
2531 ssl3_send_server_certificate(SSL *s)
2532 {
2533 	CBB cbb, server_cert;
2534 	X509 *x;
2535 
2536 	/*
2537 	 * Server Certificate - RFC 5246, section 7.4.2.
2538 	 */
2539 
2540 	memset(&cbb, 0, sizeof(cbb));
2541 
2542 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_A) {
2543 		if ((x = ssl_get_server_send_cert(s)) == NULL) {
2544 			SSLerror(s, ERR_R_INTERNAL_ERROR);
2545 			return (0);
2546 		}
2547 
2548 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &server_cert,
2549 		    SSL3_MT_CERTIFICATE))
2550 			goto err;
2551 		if (!ssl3_output_cert_chain(s, &server_cert, x))
2552 			goto err;
2553 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2554 			goto err;
2555 
2556 		S3I(s)->hs.state = SSL3_ST_SW_CERT_B;
2557 	}
2558 
2559 	/* SSL3_ST_SW_CERT_B */
2560 	return (ssl3_handshake_write(s));
2561 
2562  err:
2563 	CBB_cleanup(&cbb);
2564 
2565 	return (0);
2566 }
2567 
2568 /* send a new session ticket (not necessarily for a new session) */
2569 int
2570 ssl3_send_newsession_ticket(SSL *s)
2571 {
2572 	unsigned char *d, *p, *macstart;
2573 	unsigned char *senc = NULL;
2574 	const unsigned char *const_p;
2575 	int len, slen_full, slen;
2576 	SSL_SESSION *sess;
2577 	unsigned int hlen;
2578 	EVP_CIPHER_CTX ctx;
2579 	HMAC_CTX hctx;
2580 	SSL_CTX *tctx = s->initial_ctx;
2581 	unsigned char iv[EVP_MAX_IV_LENGTH];
2582 	unsigned char key_name[16];
2583 
2584 	if (S3I(s)->hs.state == SSL3_ST_SW_SESSION_TICKET_A) {
2585 		/* get session encoding length */
2586 		slen_full = i2d_SSL_SESSION(s->session, NULL);
2587 		/*
2588 		 * Some length values are 16 bits, so forget it if session is
2589  		 * too long
2590  		 */
2591 		if (slen_full > 0xFF00)
2592 			goto err;
2593 		senc = malloc(slen_full);
2594 		if (!senc)
2595 			goto err;
2596 		p = senc;
2597 		i2d_SSL_SESSION(s->session, &p);
2598 
2599 		/*
2600 		 * Create a fresh copy (not shared with other threads) to
2601 		 * clean up
2602 		 */
2603 		const_p = senc;
2604 		sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
2605 		if (sess == NULL)
2606 			goto err;
2607 
2608 		/* ID is irrelevant for the ticket */
2609 		sess->session_id_length = 0;
2610 
2611 		slen = i2d_SSL_SESSION(sess, NULL);
2612 		if (slen > slen_full) {
2613 			/* shouldn't ever happen */
2614 			goto err;
2615 		}
2616 		p = senc;
2617 		i2d_SSL_SESSION(sess, &p);
2618 		SSL_SESSION_free(sess);
2619 
2620 		/*
2621 		 * Grow buffer if need be: the length calculation is as
2622  		 * follows 1 (size of message name) + 3 (message length
2623  		 * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
2624  		 * 16 (key name) + max_iv_len (iv length) +
2625  		 * session_length + max_enc_block_size (max encrypted session
2626  		 * length) + max_md_size (HMAC).
2627  		 */
2628 		if (!BUF_MEM_grow(s->internal->init_buf, ssl3_handshake_msg_hdr_len(s) +
2629 		    22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
2630 		    EVP_MAX_MD_SIZE + slen))
2631 			goto err;
2632 
2633 		d = p = ssl3_handshake_msg_start(s, SSL3_MT_NEWSESSION_TICKET);
2634 
2635 		EVP_CIPHER_CTX_init(&ctx);
2636 		HMAC_CTX_init(&hctx);
2637 
2638 		/*
2639 		 * Initialize HMAC and cipher contexts. If callback present
2640 		 * it does all the work otherwise use generated values
2641 		 * from parent ctx.
2642 		 */
2643 		if (tctx->internal->tlsext_ticket_key_cb) {
2644 			if (tctx->internal->tlsext_ticket_key_cb(s,
2645 			    key_name, iv, &ctx, &hctx, 1) < 0) {
2646 				EVP_CIPHER_CTX_cleanup(&ctx);
2647 				goto err;
2648 			}
2649 		} else {
2650 			arc4random_buf(iv, 16);
2651 			EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
2652 			    tctx->internal->tlsext_tick_aes_key, iv);
2653 			HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
2654 			    16, tlsext_tick_md(), NULL);
2655 			memcpy(key_name, tctx->internal->tlsext_tick_key_name, 16);
2656 		}
2657 
2658 		/*
2659 		 * Ticket lifetime hint (advisory only):
2660 		 * We leave this unspecified for resumed session
2661 		 * (for simplicity), and guess that tickets for new
2662 		 * sessions will live as long as their sessions.
2663 		 */
2664 		l2n(s->internal->hit ? 0 : s->session->timeout, p);
2665 
2666 		/* Skip ticket length for now */
2667 		p += 2;
2668 		/* Output key name */
2669 		macstart = p;
2670 		memcpy(p, key_name, 16);
2671 		p += 16;
2672 		/* output IV */
2673 		memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
2674 		p += EVP_CIPHER_CTX_iv_length(&ctx);
2675 		/* Encrypt session data */
2676 		EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
2677 		p += len;
2678 		EVP_EncryptFinal_ex(&ctx, p, &len);
2679 		p += len;
2680 		EVP_CIPHER_CTX_cleanup(&ctx);
2681 
2682 		HMAC_Update(&hctx, macstart, p - macstart);
2683 		HMAC_Final(&hctx, p, &hlen);
2684 		HMAC_CTX_cleanup(&hctx);
2685 		p += hlen;
2686 
2687 		/* Now write out lengths: p points to end of data written */
2688 		/* Total length */
2689 		len = p - d;
2690 
2691 		/* Skip ticket lifetime hint. */
2692 		p = d + 4;
2693 		s2n(len - 6, p); /* Message length */
2694 
2695 		ssl3_handshake_msg_finish(s, len);
2696 
2697 		S3I(s)->hs.state = SSL3_ST_SW_SESSION_TICKET_B;
2698 
2699 		freezero(senc, slen_full);
2700 	}
2701 
2702 	/* SSL3_ST_SW_SESSION_TICKET_B */
2703 	return (ssl3_handshake_write(s));
2704 
2705  err:
2706 	freezero(senc, slen_full);
2707 
2708 	return (-1);
2709 }
2710 
2711 int
2712 ssl3_send_cert_status(SSL *s)
2713 {
2714 	CBB cbb, certstatus, ocspresp;
2715 
2716 	memset(&cbb, 0, sizeof(cbb));
2717 
2718 	if (S3I(s)->hs.state == SSL3_ST_SW_CERT_STATUS_A) {
2719 		if (!ssl3_handshake_msg_start_cbb(s, &cbb, &certstatus,
2720 		    SSL3_MT_CERTIFICATE_STATUS))
2721 			goto err;
2722 		if (!CBB_add_u8(&certstatus, s->tlsext_status_type))
2723 			goto err;
2724 		if (!CBB_add_u24_length_prefixed(&certstatus, &ocspresp))
2725 			goto err;
2726 		if (!CBB_add_bytes(&ocspresp, s->internal->tlsext_ocsp_resp,
2727 		    s->internal->tlsext_ocsp_resplen))
2728 			goto err;
2729 		if (!ssl3_handshake_msg_finish_cbb(s, &cbb))
2730 			goto err;
2731 
2732 		S3I(s)->hs.state = SSL3_ST_SW_CERT_STATUS_B;
2733 	}
2734 
2735 	/* SSL3_ST_SW_CERT_STATUS_B */
2736 	return (ssl3_handshake_write(s));
2737 
2738  err:
2739 	CBB_cleanup(&cbb);
2740 
2741 	return (-1);
2742 }
2743 
2744 /*
2745  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
2746  * It sets the next_proto member in s if found
2747  */
2748 int
2749 ssl3_get_next_proto(SSL *s)
2750 {
2751 	CBS cbs, proto, padding;
2752 	int ok;
2753 	long n;
2754 	size_t len;
2755 
2756 	/*
2757 	 * Clients cannot send a NextProtocol message if we didn't see the
2758 	 * extension in their ClientHello
2759 	 */
2760 	if (!S3I(s)->next_proto_neg_seen) {
2761 		SSLerror(s, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
2762 		return (-1);
2763 	}
2764 
2765 	/* 514 maxlen is enough for the payload format below */
2766 	n = s->method->internal->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A,
2767 	    SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO, 514, &ok);
2768 	if (!ok)
2769 		return ((int)n);
2770 
2771 	/*
2772 	 * S3I(s)->hs.state doesn't reflect whether ChangeCipherSpec has been received
2773 	 * in this handshake, but S3I(s)->change_cipher_spec does (will be reset
2774 	 * by ssl3_get_finished).
2775 	 */
2776 	if (!S3I(s)->change_cipher_spec) {
2777 		SSLerror(s, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
2778 		return (-1);
2779 	}
2780 
2781 	if (n < 2)
2782 		return (0);
2783 	/* The body must be > 1 bytes long */
2784 
2785 	CBS_init(&cbs, s->internal->init_msg, s->internal->init_num);
2786 
2787 	/*
2788 	 * The payload looks like:
2789 	 *   uint8 proto_len;
2790 	 *   uint8 proto[proto_len];
2791 	 *   uint8 padding_len;
2792 	 *   uint8 padding[padding_len];
2793 	 */
2794 	if (!CBS_get_u8_length_prefixed(&cbs, &proto) ||
2795 	    !CBS_get_u8_length_prefixed(&cbs, &padding) ||
2796 	    CBS_len(&cbs) != 0)
2797 		return 0;
2798 
2799 	/*
2800 	 * XXX We should not NULL it, but this matches old behavior of not
2801 	 * freeing before malloc.
2802 	 */
2803 	s->internal->next_proto_negotiated = NULL;
2804 	s->internal->next_proto_negotiated_len = 0;
2805 
2806 	if (!CBS_stow(&proto, &s->internal->next_proto_negotiated, &len)) {
2807 		SSLerror(s, ERR_R_MALLOC_FAILURE);
2808 		return (0);
2809 	}
2810 	s->internal->next_proto_negotiated_len = (uint8_t)len;
2811 
2812 	return (1);
2813 }
2814