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