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