1 /* $OpenBSD: tls13_client.c,v 1.67 2020/09/11 17:36:27 jsing Exp $ */
2 /*
3  * Copyright (c) 2018, 2019 Joel Sing <jsing@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include "ssl_locl.h"
19 
20 #include <openssl/ssl3.h>
21 
22 #include "bytestring.h"
23 #include "ssl_tlsext.h"
24 #include "tls13_handshake.h"
25 #include "tls13_internal.h"
26 
27 int
28 tls13_client_init(struct tls13_ctx *ctx)
29 {
30 	const uint16_t *groups;
31 	size_t groups_len;
32 	SSL *s = ctx->ssl;
33 
34 	if (!ssl_supported_version_range(s, &ctx->hs->min_version,
35 	    &ctx->hs->max_version)) {
36 		SSLerror(s, SSL_R_NO_PROTOCOLS_AVAILABLE);
37 		return 0;
38 	}
39 	s->client_version = s->version = ctx->hs->max_version;
40 
41 	tls13_record_layer_set_retry_after_phh(ctx->rl,
42 	    (s->internal->mode & SSL_MODE_AUTO_RETRY) != 0);
43 
44 	if (!ssl_get_new_session(s, 0)) /* XXX */
45 		return 0;
46 
47 	if (!tls1_transcript_init(s))
48 		return 0;
49 
50 	/* Generate a key share using our preferred group. */
51 	tls1_get_group_list(s, 0, &groups, &groups_len);
52 	if (groups_len < 1)
53 		return 0;
54 	if ((ctx->hs->key_share = tls13_key_share_new(groups[0])) == NULL)
55 		return 0;
56 	if (!tls13_key_share_generate(ctx->hs->key_share))
57 		return 0;
58 
59 	arc4random_buf(s->s3->client_random, SSL3_RANDOM_SIZE);
60 
61 	/*
62 	 * The legacy session identifier should either be set to an
63 	 * unpredictable 32-byte value or zero length... a non-zero length
64 	 * legacy session identifier triggers compatibility mode (see RFC 8446
65 	 * Appendix D.4). In the pre-TLSv1.3 case a zero length value is used.
66 	 */
67 	if (ctx->middlebox_compat && ctx->hs->max_version >= TLS1_3_VERSION) {
68 		arc4random_buf(ctx->hs->legacy_session_id,
69 		    sizeof(ctx->hs->legacy_session_id));
70 		ctx->hs->legacy_session_id_len =
71 		    sizeof(ctx->hs->legacy_session_id);
72 	}
73 
74 	return 1;
75 }
76 
77 int
78 tls13_client_connect(struct tls13_ctx *ctx)
79 {
80 	if (ctx->mode != TLS13_HS_CLIENT)
81 		return TLS13_IO_FAILURE;
82 
83 	return tls13_handshake_perform(ctx);
84 }
85 
86 static int
87 tls13_client_hello_build(struct tls13_ctx *ctx, CBB *cbb)
88 {
89 	CBB cipher_suites, compression_methods, session_id;
90 	uint16_t client_version;
91 	SSL *s = ctx->ssl;
92 
93 	/* Legacy client version is capped at TLS 1.2. */
94 	client_version = ctx->hs->max_version;
95 	if (client_version > TLS1_2_VERSION)
96 		client_version = TLS1_2_VERSION;
97 
98 	if (!CBB_add_u16(cbb, client_version))
99 		goto err;
100 	if (!CBB_add_bytes(cbb, s->s3->client_random, SSL3_RANDOM_SIZE))
101 		goto err;
102 
103 	if (!CBB_add_u8_length_prefixed(cbb, &session_id))
104 		goto err;
105 	if (!CBB_add_bytes(&session_id, ctx->hs->legacy_session_id,
106 	    ctx->hs->legacy_session_id_len))
107 		goto err;
108 
109 	if (!CBB_add_u16_length_prefixed(cbb, &cipher_suites))
110 		goto err;
111 	if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &cipher_suites)) {
112 		SSLerror(s, SSL_R_NO_CIPHERS_AVAILABLE);
113 		goto err;
114 	}
115 
116 	if (!CBB_add_u8_length_prefixed(cbb, &compression_methods))
117 		goto err;
118 	if (!CBB_add_u8(&compression_methods, 0))
119 		goto err;
120 
121 	if (!tlsext_client_build(s, SSL_TLSEXT_MSG_CH, cbb))
122 		goto err;
123 
124 	if (!CBB_flush(cbb))
125 		goto err;
126 
127 	return 1;
128 
129  err:
130 	return 0;
131 }
132 
133 int
134 tls13_client_hello_send(struct tls13_ctx *ctx, CBB *cbb)
135 {
136 	if (ctx->hs->min_version < TLS1_2_VERSION)
137 		tls13_record_layer_set_legacy_version(ctx->rl, TLS1_VERSION);
138 
139 	/* We may receive a pre-TLSv1.3 alert in response to the client hello. */
140 	tls13_record_layer_allow_legacy_alerts(ctx->rl, 1);
141 
142 	if (!tls13_client_hello_build(ctx, cbb))
143 		return 0;
144 
145 	return 1;
146 }
147 
148 int
149 tls13_client_hello_sent(struct tls13_ctx *ctx)
150 {
151 	tls13_record_layer_allow_ccs(ctx->rl, 1);
152 
153 	tls1_transcript_freeze(ctx->ssl);
154 
155 	if (ctx->middlebox_compat)
156 		ctx->send_dummy_ccs = 1;
157 
158 	return 1;
159 }
160 
161 static int
162 tls13_server_hello_is_legacy(CBS *cbs)
163 {
164 	CBS extensions_block, extensions, extension_data;
165 	uint16_t selected_version = 0;
166 	uint16_t type;
167 
168 	CBS_dup(cbs, &extensions_block);
169 
170 	if (!CBS_get_u16_length_prefixed(&extensions_block, &extensions))
171 		return 1;
172 
173 	while (CBS_len(&extensions) > 0) {
174 		if (!CBS_get_u16(&extensions, &type))
175 			return 1;
176 		if (!CBS_get_u16_length_prefixed(&extensions, &extension_data))
177 			return 1;
178 
179 		if (type != TLSEXT_TYPE_supported_versions)
180 			continue;
181 		if (!CBS_get_u16(&extension_data, &selected_version))
182 			return 1;
183 		if (CBS_len(&extension_data) != 0)
184 			return 1;
185 	}
186 
187 	return (selected_version < TLS1_3_VERSION);
188 }
189 
190 static int
191 tls13_server_hello_is_retry(CBS *cbs)
192 {
193 	CBS server_hello, server_random;
194 	uint16_t legacy_version;
195 
196 	CBS_dup(cbs, &server_hello);
197 
198 	if (!CBS_get_u16(&server_hello, &legacy_version))
199 		return 0;
200 	if (!CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE))
201 		return 0;
202 
203 	/* See if this is a HelloRetryRequest. */
204 	return CBS_mem_equal(&server_random, tls13_hello_retry_request_hash,
205 	    sizeof(tls13_hello_retry_request_hash));
206 }
207 
208 static int
209 tls13_server_hello_process(struct tls13_ctx *ctx, CBS *cbs)
210 {
211 	CBS server_random, session_id;
212 	uint16_t tlsext_msg_type = SSL_TLSEXT_MSG_SH;
213 	uint16_t cipher_suite, legacy_version;
214 	uint8_t compression_method;
215 	const SSL_CIPHER *cipher;
216 	int alert_desc;
217 	SSL *s = ctx->ssl;
218 
219 	if (!CBS_get_u16(cbs, &legacy_version))
220 		goto err;
221 	if (!CBS_get_bytes(cbs, &server_random, SSL3_RANDOM_SIZE))
222 		goto err;
223 	if (!CBS_get_u8_length_prefixed(cbs, &session_id))
224 		goto err;
225 	if (!CBS_get_u16(cbs, &cipher_suite))
226 		goto err;
227 	if (!CBS_get_u8(cbs, &compression_method))
228 		goto err;
229 
230 	if (tls13_server_hello_is_legacy(cbs)) {
231 		if (ctx->hs->max_version >= TLS1_3_VERSION) {
232 			/*
233 			 * RFC 8446 section 4.1.3, We must not downgrade if
234 			 * the server random value contains the TLS 1.2 or 1.1
235 			 * magical value.
236 			 */
237 			if (!CBS_skip(&server_random, CBS_len(&server_random) -
238 			    sizeof(tls13_downgrade_12)))
239 				goto err;
240 			if (CBS_mem_equal(&server_random, tls13_downgrade_12,
241 			    sizeof(tls13_downgrade_12)) ||
242 			    CBS_mem_equal(&server_random, tls13_downgrade_11,
243 			    sizeof(tls13_downgrade_11))) {
244 				ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
245 				goto err;
246 			}
247 		}
248 
249 		if (!CBS_skip(cbs, CBS_len(cbs)))
250 			goto err;
251 
252 		ctx->hs->use_legacy = 1;
253 		return 1;
254 	}
255 
256 	/* From here on in we know we are doing TLSv1.3. */
257 	tls13_record_layer_set_legacy_version(ctx->rl, TLS1_2_VERSION);
258 	tls13_record_layer_allow_legacy_alerts(ctx->rl, 0);
259 
260 	/* See if this is a HelloRetryRequest. */
261 	/* XXX - see if we can avoid doing this twice. */
262 	if (CBS_mem_equal(&server_random, tls13_hello_retry_request_hash,
263 	    sizeof(tls13_hello_retry_request_hash))) {
264 		tlsext_msg_type = SSL_TLSEXT_MSG_HRR;
265 		ctx->hs->hrr = 1;
266 	}
267 
268 	if (!tlsext_client_parse(s, tlsext_msg_type, cbs, &alert_desc)) {
269 		ctx->alert = alert_desc;
270 		goto err;
271 	}
272 
273 	/*
274 	 * See if a supported versions extension was returned. If it was then
275 	 * the legacy version must be set to 0x0303 (RFC 8446 section 4.1.3).
276 	 * Otherwise, fallback to the legacy version, ensuring that it is both
277 	 * within range and not TLS 1.3 or greater (which must use the
278 	 * supported version extension.
279 	 */
280 	if (ctx->hs->server_version != 0) {
281 		if (legacy_version != TLS1_2_VERSION) {
282 			ctx->alert = TLS13_ALERT_PROTOCOL_VERSION;
283 			goto err;
284 		}
285 	} else {
286 		if (legacy_version < ctx->hs->min_version ||
287 		    legacy_version > ctx->hs->max_version ||
288 		    legacy_version > TLS1_2_VERSION) {
289 			ctx->alert = TLS13_ALERT_PROTOCOL_VERSION;
290 			goto err;
291 		}
292 		ctx->hs->server_version = legacy_version;
293 	}
294 
295 	/* The session_id must match. */
296 	if (!CBS_mem_equal(&session_id, ctx->hs->legacy_session_id,
297 	    ctx->hs->legacy_session_id_len)) {
298 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
299 		goto err;
300 	}
301 
302 	/*
303 	 * Ensure that the cipher suite is one that we offered in the client
304 	 * hello and that it matches the TLS version selected.
305 	 */
306 	cipher = ssl3_get_cipher_by_value(cipher_suite);
307 	if (cipher == NULL || !ssl_cipher_in_list(SSL_get_ciphers(s), cipher)) {
308 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
309 		goto err;
310 	}
311 	if (ctx->hs->server_version == TLS1_3_VERSION &&
312 	    cipher->algorithm_ssl != SSL_TLSV1_3) {
313 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
314 		goto err;
315 	}
316 	/* XXX - move this to hs_tls13? */
317 	S3I(s)->hs.new_cipher = cipher;
318 
319 	if (compression_method != 0) {
320 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
321 		goto err;
322 	}
323 
324 	return 1;
325 
326  err:
327 	if (ctx->alert == 0)
328 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
329 
330 	return 0;
331 }
332 
333 static int
334 tls13_client_engage_record_protection(struct tls13_ctx *ctx)
335 {
336 	struct tls13_secrets *secrets;
337 	struct tls13_secret context;
338 	unsigned char buf[EVP_MAX_MD_SIZE];
339 	uint8_t *shared_key = NULL;
340 	size_t shared_key_len = 0;
341 	size_t hash_len;
342 	SSL *s = ctx->ssl;
343 	int ret = 0;
344 
345 	/* Derive the shared key and engage record protection. */
346 
347 	if (!tls13_key_share_derive(ctx->hs->key_share, &shared_key,
348 	    &shared_key_len))
349 		goto err;
350 
351 	s->session->cipher = S3I(s)->hs.new_cipher;
352 	s->session->ssl_version = ctx->hs->server_version;
353 
354 	if ((ctx->aead = tls13_cipher_aead(S3I(s)->hs.new_cipher)) == NULL)
355 		goto err;
356 	if ((ctx->hash = tls13_cipher_hash(S3I(s)->hs.new_cipher)) == NULL)
357 		goto err;
358 
359 	if ((secrets = tls13_secrets_create(ctx->hash, 0)) == NULL)
360 		goto err;
361 	ctx->hs->secrets = secrets;
362 
363 	/* XXX - pass in hash. */
364 	if (!tls1_transcript_hash_init(s))
365 		goto err;
366 	tls1_transcript_free(s);
367 	if (!tls1_transcript_hash_value(s, buf, sizeof(buf), &hash_len))
368 		goto err;
369 	context.data = buf;
370 	context.len = hash_len;
371 
372 	/* Early secrets. */
373 	if (!tls13_derive_early_secrets(secrets, secrets->zeros.data,
374 	    secrets->zeros.len, &context))
375 		goto err;
376 
377 	/* Handshake secrets. */
378 	if (!tls13_derive_handshake_secrets(ctx->hs->secrets, shared_key,
379 	    shared_key_len, &context))
380 		goto err;
381 
382 	tls13_record_layer_set_aead(ctx->rl, ctx->aead);
383 	tls13_record_layer_set_hash(ctx->rl, ctx->hash);
384 
385 	if (!tls13_record_layer_set_read_traffic_key(ctx->rl,
386 	    &secrets->server_handshake_traffic))
387 		goto err;
388 	if (!tls13_record_layer_set_write_traffic_key(ctx->rl,
389 	    &secrets->client_handshake_traffic))
390 		goto err;
391 
392 	ret = 1;
393 
394  err:
395 	freezero(shared_key, shared_key_len);
396 
397 	return ret;
398 }
399 
400 int
401 tls13_server_hello_retry_request_recv(struct tls13_ctx *ctx, CBS *cbs)
402 {
403 	/*
404 	 * The state machine has no way of knowing if we're going to receive a
405 	 * HelloRetryRequest or a ServerHello. As such, we have to handle
406 	 * this case here and hand off to the appropriate function.
407 	 */
408 	if (!tls13_server_hello_is_retry(cbs)) {
409 		ctx->handshake_stage.hs_type |= WITHOUT_HRR;
410 		return tls13_server_hello_recv(ctx, cbs);
411 	}
412 
413 	if (!tls13_server_hello_process(ctx, cbs))
414 		return 0;
415 
416 	/*
417 	 * This may have been a TLSv1.2 or earlier ServerHello that just happened
418 	 * to have matching server random...
419 	 */
420 	if (ctx->hs->use_legacy)
421 		return tls13_use_legacy_client(ctx);
422 
423 	if (!ctx->hs->hrr)
424 		return 0;
425 
426 	if (!tls13_synthetic_handshake_message(ctx))
427 		return 0;
428 	if (!tls13_handshake_msg_record(ctx))
429 		return 0;
430 
431 	ctx->hs->hrr = 0;
432 
433 	return 1;
434 }
435 
436 int
437 tls13_client_hello_retry_send(struct tls13_ctx *ctx, CBB *cbb)
438 {
439 	/*
440 	 * Ensure that the server supported group is one that we listed in our
441 	 * supported groups and is not the same as the key share we previously
442 	 * offered.
443 	 */
444 	if (!tls1_check_curve(ctx->ssl, ctx->hs->server_group))
445 		return 0; /* XXX alert */
446 	if (ctx->hs->server_group == tls13_key_share_group(ctx->hs->key_share))
447 		return 0; /* XXX alert */
448 
449 	/* Switch to new key share. */
450 	tls13_key_share_free(ctx->hs->key_share);
451 	if ((ctx->hs->key_share =
452 	    tls13_key_share_new(ctx->hs->server_group)) == NULL)
453 		return 0;
454 	if (!tls13_key_share_generate(ctx->hs->key_share))
455 		return 0;
456 
457 	if (!tls13_client_hello_build(ctx, cbb))
458 		return 0;
459 
460 	return 1;
461 }
462 
463 int
464 tls13_server_hello_recv(struct tls13_ctx *ctx, CBS *cbs)
465 {
466 	SSL *s = ctx->ssl;
467 
468 	/*
469 	 * We may have received a legacy (pre-TLSv1.3) ServerHello or a TLSv1.3
470 	 * ServerHello. HelloRetryRequests have already been handled.
471 	 */
472 	if (!tls13_server_hello_process(ctx, cbs))
473 		return 0;
474 
475 	if (ctx->handshake_stage.hs_type & WITHOUT_HRR) {
476 		tls1_transcript_unfreeze(s);
477 		if (!tls13_handshake_msg_record(ctx))
478 			return 0;
479 	}
480 
481 	if (ctx->hs->use_legacy) {
482 		if (!(ctx->handshake_stage.hs_type & WITHOUT_HRR))
483 			return 0;
484 		return tls13_use_legacy_client(ctx);
485 	}
486 
487 	if (ctx->hs->hrr) {
488 		/* The server has sent two HelloRetryRequests. */
489 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
490 		return 0;
491 	}
492 
493 	if (!tls13_client_engage_record_protection(ctx))
494 		return 0;
495 
496 	ctx->handshake_stage.hs_type |= NEGOTIATED;
497 
498 	return 1;
499 }
500 
501 int
502 tls13_server_encrypted_extensions_recv(struct tls13_ctx *ctx, CBS *cbs)
503 {
504 	int alert_desc;
505 
506 	if (!tlsext_client_parse(ctx->ssl, SSL_TLSEXT_MSG_EE, cbs, &alert_desc)) {
507 		ctx->alert = alert_desc;
508 		goto err;
509 	}
510 
511 	return 1;
512 
513  err:
514 	if (ctx->alert == 0)
515 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
516 
517 	return 0;
518 }
519 
520 int
521 tls13_server_certificate_request_recv(struct tls13_ctx *ctx, CBS *cbs)
522 {
523 	CBS cert_request_context;
524 	int alert_desc;
525 
526 	/*
527 	 * Thanks to poor state design in the RFC, this function can be called
528 	 * when we actually have a certificate message instead of a certificate
529 	 * request... in that case we call the certificate handler after
530 	 * switching state, to avoid advancing state.
531 	 */
532 	if (tls13_handshake_msg_type(ctx->hs_msg) == TLS13_MT_CERTIFICATE) {
533 		ctx->handshake_stage.hs_type |= WITHOUT_CR;
534 		return tls13_server_certificate_recv(ctx, cbs);
535 	}
536 
537 	if (!CBS_get_u8_length_prefixed(cbs, &cert_request_context))
538 		goto err;
539 	if (CBS_len(&cert_request_context) != 0)
540 		goto err;
541 
542 	if (!tlsext_client_parse(ctx->ssl, SSL_TLSEXT_MSG_CR, cbs, &alert_desc)) {
543 		ctx->alert = alert_desc;
544 		goto err;
545 	}
546 
547 	return 1;
548 
549  err:
550 	if (ctx->alert == 0)
551 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
552 
553 	return 0;
554 }
555 
556 int
557 tls13_server_certificate_recv(struct tls13_ctx *ctx, CBS *cbs)
558 {
559 	CBS cert_request_context, cert_list, cert_data;
560 	struct stack_st_X509 *certs = NULL;
561 	SSL *s = ctx->ssl;
562 	X509 *cert = NULL;
563 	EVP_PKEY *pkey;
564 	const uint8_t *p;
565 	int cert_idx, alert_desc;
566 	int ret = 0;
567 
568 	if ((certs = sk_X509_new_null()) == NULL)
569 		goto err;
570 
571 	if (!CBS_get_u8_length_prefixed(cbs, &cert_request_context))
572 		goto err;
573 	if (CBS_len(&cert_request_context) != 0)
574 		goto err;
575 	if (!CBS_get_u24_length_prefixed(cbs, &cert_list))
576 		goto err;
577 
578 	while (CBS_len(&cert_list) > 0) {
579 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert_data))
580 			goto err;
581 
582 		if (!tlsext_client_parse(ctx->ssl, SSL_TLSEXT_MSG_CT,
583 		    &cert_list, &alert_desc)) {
584 			ctx->alert = alert_desc;
585 			goto err;
586 		}
587 
588 		p = CBS_data(&cert_data);
589 		if ((cert = d2i_X509(NULL, &p, CBS_len(&cert_data))) == NULL)
590 			goto err;
591 		if (p != CBS_data(&cert_data) + CBS_len(&cert_data))
592 			goto err;
593 
594 		if (!sk_X509_push(certs, cert))
595 			goto err;
596 
597 		cert = NULL;
598 	}
599 
600 	/* A server must always provide a non-empty certificate list. */
601 	if (sk_X509_num(certs) < 1) {
602 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
603 		tls13_set_errorx(ctx, TLS13_ERR_NO_PEER_CERTIFICATE, 0,
604 		    "peer failed to provide a certificate", NULL);
605 		goto err;
606 	}
607 
608 	/*
609 	 * At this stage we still have no proof of possession. As such, it would
610 	 * be preferable to keep the chain and verify once we have successfully
611 	 * processed the CertificateVerify message.
612 	 */
613 	if (ssl_verify_cert_chain(s, certs) <= 0 &&
614 	    s->verify_mode != SSL_VERIFY_NONE) {
615 		ctx->alert = ssl_verify_alarm_type(s->verify_result);
616 		tls13_set_errorx(ctx, TLS13_ERR_VERIFY_FAILED, 0,
617 		    "failed to verify peer certificate", NULL);
618 		goto err;
619 	}
620 	ERR_clear_error();
621 
622 	cert = sk_X509_value(certs, 0);
623 	X509_up_ref(cert);
624 
625 	if ((pkey = X509_get0_pubkey(cert)) == NULL)
626 		goto err;
627 	if (EVP_PKEY_missing_parameters(pkey))
628 		goto err;
629 	if ((cert_idx = ssl_cert_type(cert, pkey)) < 0)
630 		goto err;
631 
632 	ssl_sess_cert_free(SSI(s)->sess_cert);
633 	if ((SSI(s)->sess_cert = ssl_sess_cert_new()) == NULL)
634 		goto err;
635 
636 	SSI(s)->sess_cert->cert_chain = certs;
637 	certs = NULL;
638 
639 	X509_up_ref(cert);
640 	SSI(s)->sess_cert->peer_pkeys[cert_idx].x509 = cert;
641 	SSI(s)->sess_cert->peer_key = &(SSI(s)->sess_cert->peer_pkeys[cert_idx]);
642 
643 	X509_free(s->session->peer);
644 
645 	X509_up_ref(cert);
646 	s->session->peer = cert;
647 	s->session->verify_result = s->verify_result;
648 
649 	if (ctx->ocsp_status_recv_cb != NULL &&
650 	    !ctx->ocsp_status_recv_cb(ctx))
651 		goto err;
652 
653 	ret = 1;
654 
655  err:
656 	sk_X509_pop_free(certs, X509_free);
657 	X509_free(cert);
658 
659 	return ret;
660 }
661 
662 int
663 tls13_server_certificate_verify_recv(struct tls13_ctx *ctx, CBS *cbs)
664 {
665 	const struct ssl_sigalg *sigalg;
666 	uint16_t signature_scheme;
667 	uint8_t *sig_content = NULL;
668 	size_t sig_content_len;
669 	EVP_MD_CTX *mdctx = NULL;
670 	EVP_PKEY_CTX *pctx;
671 	EVP_PKEY *pkey;
672 	X509 *cert;
673 	CBS signature;
674 	CBB cbb;
675 	int ret = 0;
676 
677 	memset(&cbb, 0, sizeof(cbb));
678 
679 	if (!CBS_get_u16(cbs, &signature_scheme))
680 		goto err;
681 	if (!CBS_get_u16_length_prefixed(cbs, &signature))
682 		goto err;
683 
684 	if ((sigalg = ssl_sigalg(signature_scheme, tls13_sigalgs,
685 	    tls13_sigalgs_len)) == NULL)
686 		goto err;
687 
688 	if (!CBB_init(&cbb, 0))
689 		goto err;
690 	if (!CBB_add_bytes(&cbb, tls13_cert_verify_pad,
691 	    sizeof(tls13_cert_verify_pad)))
692 		goto err;
693 	if (!CBB_add_bytes(&cbb, tls13_cert_server_verify_context,
694 	    strlen(tls13_cert_server_verify_context)))
695 		goto err;
696 	if (!CBB_add_u8(&cbb, 0))
697 		goto err;
698 	if (!CBB_add_bytes(&cbb, ctx->hs->transcript_hash,
699 	    ctx->hs->transcript_hash_len))
700 		goto err;
701 	if (!CBB_finish(&cbb, &sig_content, &sig_content_len))
702 		goto err;
703 
704 	if ((cert = ctx->ssl->session->peer) == NULL)
705 		goto err;
706 	if ((pkey = X509_get0_pubkey(cert)) == NULL)
707 		goto err;
708 	if (!ssl_sigalg_pkey_ok(sigalg, pkey, 1))
709 		goto err;
710 
711 	if (CBS_len(&signature) > EVP_PKEY_size(pkey))
712 		goto err;
713 
714 	if ((mdctx = EVP_MD_CTX_new()) == NULL)
715 		goto err;
716 	if (!EVP_DigestVerifyInit(mdctx, &pctx, sigalg->md(), NULL, pkey))
717 		goto err;
718 	if (sigalg->flags & SIGALG_FLAG_RSA_PSS) {
719 		if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING))
720 			goto err;
721 		if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))
722 			goto err;
723 	}
724 	if (!EVP_DigestVerifyUpdate(mdctx, sig_content, sig_content_len)) {
725 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
726 		goto err;
727 	}
728 	if (EVP_DigestVerifyFinal(mdctx, CBS_data(&signature),
729 	    CBS_len(&signature)) <= 0) {
730 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
731 		goto err;
732 	}
733 
734 	ret = 1;
735 
736  err:
737 	if (!ret && ctx->alert == 0)
738 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
739 	CBB_cleanup(&cbb);
740 	EVP_MD_CTX_free(mdctx);
741 	free(sig_content);
742 
743 	return ret;
744 }
745 
746 int
747 tls13_server_finished_recv(struct tls13_ctx *ctx, CBS *cbs)
748 {
749 	struct tls13_secrets *secrets = ctx->hs->secrets;
750 	struct tls13_secret context = { .data = "", .len = 0 };
751 	struct tls13_secret finished_key;
752 	uint8_t transcript_hash[EVP_MAX_MD_SIZE];
753 	size_t transcript_hash_len;
754 	uint8_t *verify_data = NULL;
755 	size_t verify_data_len;
756 	uint8_t key[EVP_MAX_MD_SIZE];
757 	HMAC_CTX *hmac_ctx = NULL;
758 	unsigned int hlen;
759 	int ret = 0;
760 
761 	/*
762 	 * Verify server finished.
763 	 */
764 	finished_key.data = key;
765 	finished_key.len = EVP_MD_size(ctx->hash);
766 
767 	if (!tls13_hkdf_expand_label(&finished_key, ctx->hash,
768 	    &secrets->server_handshake_traffic, "finished",
769 	    &context))
770 		goto err;
771 
772 	if ((hmac_ctx = HMAC_CTX_new()) == NULL)
773 		goto err;
774 	if (!HMAC_Init_ex(hmac_ctx, finished_key.data, finished_key.len,
775 	    ctx->hash, NULL))
776 		goto err;
777 	if (!HMAC_Update(hmac_ctx, ctx->hs->transcript_hash,
778 	    ctx->hs->transcript_hash_len))
779 		goto err;
780 	verify_data_len = HMAC_size(hmac_ctx);
781 	if ((verify_data = calloc(1, verify_data_len)) == NULL)
782 		goto err;
783 	if (!HMAC_Final(hmac_ctx, verify_data, &hlen))
784 		goto err;
785 	if (hlen != verify_data_len)
786 		goto err;
787 
788 	if (!CBS_mem_equal(cbs, verify_data, verify_data_len)) {
789 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
790 		goto err;
791 	}
792 
793 	if (!CBS_skip(cbs, verify_data_len))
794 		goto err;
795 
796 	/*
797 	 * Derive application traffic keys.
798 	 */
799 	if (!tls1_transcript_hash_value(ctx->ssl, transcript_hash,
800 	    sizeof(transcript_hash), &transcript_hash_len))
801 		goto err;
802 
803 	context.data = transcript_hash;
804 	context.len = transcript_hash_len;
805 
806 	if (!tls13_derive_application_secrets(secrets, &context))
807 		goto err;
808 
809 	/*
810 	 * Any records following the server finished message must be encrypted
811 	 * using the server application traffic keys.
812 	 */
813 	if (!tls13_record_layer_set_read_traffic_key(ctx->rl,
814 	    &secrets->server_application_traffic))
815 		goto err;
816 
817 	tls13_record_layer_allow_ccs(ctx->rl, 0);
818 
819 	ret = 1;
820 
821  err:
822 	HMAC_CTX_free(hmac_ctx);
823 	free(verify_data);
824 
825 	return ret;
826 }
827 
828 static int
829 tls13_client_check_certificate(struct tls13_ctx *ctx, CERT_PKEY *cpk,
830     int *ok, const struct ssl_sigalg **out_sigalg)
831 {
832 	const struct ssl_sigalg *sigalg;
833 	SSL *s = ctx->ssl;
834 
835 	*ok = 0;
836 	*out_sigalg = NULL;
837 
838 	if (cpk->x509 == NULL || cpk->privatekey == NULL)
839 		goto done;
840 
841 	if ((sigalg = ssl_sigalg_select(s, cpk->privatekey)) == NULL)
842 		goto done;
843 
844 	*ok = 1;
845 	*out_sigalg = sigalg;
846 
847  done:
848 	return 1;
849 }
850 
851 static int
852 tls13_client_select_certificate(struct tls13_ctx *ctx, CERT_PKEY **out_cpk,
853     const struct ssl_sigalg **out_sigalg)
854 {
855 	SSL *s = ctx->ssl;
856 	const struct ssl_sigalg *sigalg;
857 	CERT_PKEY *cpk;
858 	int cert_ok;
859 
860 	*out_cpk = NULL;
861 	*out_sigalg = NULL;
862 
863 	/*
864 	 * XXX - RFC 8446, 4.4.2.3: the server can communicate preferences
865 	 * with the certificate_authorities (4.2.4) and oid_filters (4.2.5)
866 	 * extensions. We should honor the former and must apply the latter.
867 	 */
868 
869 	cpk = &s->cert->pkeys[SSL_PKEY_ECC];
870 	if (!tls13_client_check_certificate(ctx, cpk, &cert_ok, &sigalg))
871 		return 0;
872 	if (cert_ok)
873 		goto done;
874 
875 	cpk = &s->cert->pkeys[SSL_PKEY_RSA];
876 	if (!tls13_client_check_certificate(ctx, cpk, &cert_ok, &sigalg))
877 		return 0;
878 	if (cert_ok)
879 		goto done;
880 
881 	cpk = NULL;
882 	sigalg = NULL;
883 
884  done:
885 	*out_cpk = cpk;
886 	*out_sigalg = sigalg;
887 
888 	return 1;
889 }
890 
891 int
892 tls13_client_certificate_send(struct tls13_ctx *ctx, CBB *cbb)
893 {
894 	SSL *s = ctx->ssl;
895 	CBB cert_request_context, cert_list;
896 	const struct ssl_sigalg *sigalg;
897 	STACK_OF(X509) *chain;
898 	CERT_PKEY *cpk;
899 	X509 *cert;
900 	int i, ret = 0;
901 
902 	if (!tls13_client_select_certificate(ctx, &cpk, &sigalg))
903 		goto err;
904 
905 	ctx->hs->cpk = cpk;
906 	ctx->hs->sigalg = sigalg;
907 
908 	if (!CBB_add_u8_length_prefixed(cbb, &cert_request_context))
909 		goto err;
910 	if (!CBB_add_u24_length_prefixed(cbb, &cert_list))
911 		goto err;
912 
913 	/* No certificate selected. */
914 	if (cpk == NULL)
915 		goto done;
916 
917 	if ((chain = cpk->chain) == NULL)
918 	       chain = s->ctx->extra_certs;
919 
920 	if (!tls13_cert_add(ctx, &cert_list, cpk->x509, tlsext_client_build))
921 		goto err;
922 
923 	for (i = 0; i < sk_X509_num(chain); i++) {
924 		cert = sk_X509_value(chain, i);
925 		if (!tls13_cert_add(ctx, &cert_list, cert, tlsext_client_build))
926 			goto err;
927 	}
928 
929 	ctx->handshake_stage.hs_type |= WITH_CCV;
930  done:
931 	if (!CBB_flush(cbb))
932 		goto err;
933 
934 	ret = 1;
935 
936  err:
937 	return ret;
938 }
939 
940 int
941 tls13_client_certificate_verify_send(struct tls13_ctx *ctx, CBB *cbb)
942 {
943 	const struct ssl_sigalg *sigalg;
944 	uint8_t *sig = NULL, *sig_content = NULL;
945 	size_t sig_len, sig_content_len;
946 	EVP_MD_CTX *mdctx = NULL;
947 	EVP_PKEY_CTX *pctx;
948 	EVP_PKEY *pkey;
949 	const CERT_PKEY *cpk;
950 	CBB sig_cbb;
951 	int ret = 0;
952 
953 	memset(&sig_cbb, 0, sizeof(sig_cbb));
954 
955 	if ((cpk = ctx->hs->cpk) == NULL)
956 		goto err;
957 	if ((sigalg = ctx->hs->sigalg) == NULL)
958 		goto err;
959 	pkey = cpk->privatekey;
960 
961 	if (!CBB_init(&sig_cbb, 0))
962 		goto err;
963 	if (!CBB_add_bytes(&sig_cbb, tls13_cert_verify_pad,
964 	    sizeof(tls13_cert_verify_pad)))
965 		goto err;
966 	if (!CBB_add_bytes(&sig_cbb, tls13_cert_client_verify_context,
967 	    strlen(tls13_cert_client_verify_context)))
968 		goto err;
969 	if (!CBB_add_u8(&sig_cbb, 0))
970 		goto err;
971 	if (!CBB_add_bytes(&sig_cbb, ctx->hs->transcript_hash,
972 	    ctx->hs->transcript_hash_len))
973 		goto err;
974 	if (!CBB_finish(&sig_cbb, &sig_content, &sig_content_len))
975 		goto err;
976 
977 	if ((mdctx = EVP_MD_CTX_new()) == NULL)
978 		goto err;
979 	if (!EVP_DigestSignInit(mdctx, &pctx, sigalg->md(), NULL, pkey))
980 		goto err;
981 	if (sigalg->flags & SIGALG_FLAG_RSA_PSS) {
982 		if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING))
983 			goto err;
984 		if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))
985 			goto err;
986 	}
987 	if (!EVP_DigestSignUpdate(mdctx, sig_content, sig_content_len))
988 		goto err;
989 	if (EVP_DigestSignFinal(mdctx, NULL, &sig_len) <= 0)
990 		goto err;
991 	if ((sig = calloc(1, sig_len)) == NULL)
992 		goto err;
993 	if (EVP_DigestSignFinal(mdctx, sig, &sig_len) <= 0)
994 		goto err;
995 
996 	if (!CBB_add_u16(cbb, sigalg->value))
997 		goto err;
998 	if (!CBB_add_u16_length_prefixed(cbb, &sig_cbb))
999 		goto err;
1000 	if (!CBB_add_bytes(&sig_cbb, sig, sig_len))
1001 		goto err;
1002 
1003 	if (!CBB_flush(cbb))
1004 		goto err;
1005 
1006 	ret = 1;
1007 
1008  err:
1009 	if (!ret && ctx->alert == 0)
1010 		ctx->alert = TLS13_ALERT_INTERNAL_ERROR;
1011 
1012 	CBB_cleanup(&sig_cbb);
1013 	EVP_MD_CTX_free(mdctx);
1014 	free(sig_content);
1015 	free(sig);
1016 
1017 	return ret;
1018 }
1019 
1020 int
1021 tls13_client_end_of_early_data_send(struct tls13_ctx *ctx, CBB *cbb)
1022 {
1023 	return 0;
1024 }
1025 
1026 int
1027 tls13_client_finished_send(struct tls13_ctx *ctx, CBB *cbb)
1028 {
1029 	struct tls13_secrets *secrets = ctx->hs->secrets;
1030 	struct tls13_secret context = { .data = "", .len = 0 };
1031 	struct tls13_secret finished_key;
1032 	uint8_t transcript_hash[EVP_MAX_MD_SIZE];
1033 	size_t transcript_hash_len;
1034 	uint8_t key[EVP_MAX_MD_SIZE];
1035 	uint8_t *verify_data;
1036 	size_t hmac_len;
1037 	unsigned int hlen;
1038 	HMAC_CTX *hmac_ctx = NULL;
1039 	int ret = 0;
1040 
1041 	finished_key.data = key;
1042 	finished_key.len = EVP_MD_size(ctx->hash);
1043 
1044 	if (!tls13_hkdf_expand_label(&finished_key, ctx->hash,
1045 	    &secrets->client_handshake_traffic, "finished",
1046 	    &context))
1047 		goto err;
1048 
1049 	if (!tls1_transcript_hash_value(ctx->ssl, transcript_hash,
1050 	    sizeof(transcript_hash), &transcript_hash_len))
1051 		goto err;
1052 
1053 	if ((hmac_ctx = HMAC_CTX_new()) == NULL)
1054 		goto err;
1055 	if (!HMAC_Init_ex(hmac_ctx, finished_key.data, finished_key.len,
1056 	    ctx->hash, NULL))
1057 		goto err;
1058 	if (!HMAC_Update(hmac_ctx, transcript_hash, transcript_hash_len))
1059 		goto err;
1060 
1061 	hmac_len = HMAC_size(hmac_ctx);
1062 	if (!CBB_add_space(cbb, &verify_data, hmac_len))
1063 		goto err;
1064 	if (!HMAC_Final(hmac_ctx, verify_data, &hlen))
1065 		goto err;
1066 	if (hlen != hmac_len)
1067 		goto err;
1068 
1069 	ret = 1;
1070 
1071  err:
1072 	HMAC_CTX_free(hmac_ctx);
1073 
1074 	return ret;
1075 }
1076 
1077 int
1078 tls13_client_finished_sent(struct tls13_ctx *ctx)
1079 {
1080 	struct tls13_secrets *secrets = ctx->hs->secrets;
1081 
1082 	/*
1083 	 * Any records following the client finished message must be encrypted
1084 	 * using the client application traffic keys.
1085 	 */
1086 	return tls13_record_layer_set_write_traffic_key(ctx->rl,
1087 	    &secrets->client_application_traffic);
1088 }
1089