xref: /openbsd-src/lib/libssl/tls13_client.c (revision c020cf82e0cc147236f01a8dca7052034cf9d30d)
1 /* $OpenBSD: tls13_client.c,v 1.65 2020/06/04 18:41:42 tb 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, cbb, SSL_TLSEXT_MSG_CH))
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, cbs, &alert_desc, tlsext_msg_type)) {
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 ||
308 	    sk_SSL_CIPHER_find(ssl_get_ciphers_by_id(s), cipher) < 0) {
309 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
310 		goto err;
311 	}
312 	if (ctx->hs->server_version == TLS1_3_VERSION &&
313 	    cipher->algorithm_ssl != SSL_TLSV1_3) {
314 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
315 		goto err;
316 	}
317 	/* XXX - move this to hs_tls13? */
318 	S3I(s)->hs.new_cipher = cipher;
319 
320 	if (compression_method != 0) {
321 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
322 		goto err;
323 	}
324 
325 	return 1;
326 
327  err:
328 	if (ctx->alert == 0)
329 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
330 
331 	return 0;
332 }
333 
334 static int
335 tls13_client_engage_record_protection(struct tls13_ctx *ctx)
336 {
337 	struct tls13_secrets *secrets;
338 	struct tls13_secret context;
339 	unsigned char buf[EVP_MAX_MD_SIZE];
340 	uint8_t *shared_key = NULL;
341 	size_t shared_key_len = 0;
342 	size_t hash_len;
343 	SSL *s = ctx->ssl;
344 	int ret = 0;
345 
346 	/* Derive the shared key and engage record protection. */
347 
348 	if (!tls13_key_share_derive(ctx->hs->key_share, &shared_key,
349 	    &shared_key_len))
350 		goto err;
351 
352 	s->session->cipher = S3I(s)->hs.new_cipher;
353 	s->session->ssl_version = ctx->hs->server_version;
354 
355 	if ((ctx->aead = tls13_cipher_aead(S3I(s)->hs.new_cipher)) == NULL)
356 		goto err;
357 	if ((ctx->hash = tls13_cipher_hash(S3I(s)->hs.new_cipher)) == NULL)
358 		goto err;
359 
360 	if ((secrets = tls13_secrets_create(ctx->hash, 0)) == NULL)
361 		goto err;
362 	ctx->hs->secrets = secrets;
363 
364 	/* XXX - pass in hash. */
365 	if (!tls1_transcript_hash_init(s))
366 		goto err;
367 	tls1_transcript_free(s);
368 	if (!tls1_transcript_hash_value(s, buf, sizeof(buf), &hash_len))
369 		goto err;
370 	context.data = buf;
371 	context.len = hash_len;
372 
373 	/* Early secrets. */
374 	if (!tls13_derive_early_secrets(secrets, secrets->zeros.data,
375 	    secrets->zeros.len, &context))
376 		goto err;
377 
378 	/* Handshake secrets. */
379 	if (!tls13_derive_handshake_secrets(ctx->hs->secrets, shared_key,
380 	    shared_key_len, &context))
381 		goto err;
382 
383 	tls13_record_layer_set_aead(ctx->rl, ctx->aead);
384 	tls13_record_layer_set_hash(ctx->rl, ctx->hash);
385 
386 	if (!tls13_record_layer_set_read_traffic_key(ctx->rl,
387 	    &secrets->server_handshake_traffic))
388 		goto err;
389 	if (!tls13_record_layer_set_write_traffic_key(ctx->rl,
390 	    &secrets->client_handshake_traffic))
391 		goto err;
392 
393 	ret = 1;
394 
395  err:
396 	freezero(shared_key, shared_key_len);
397 
398 	return ret;
399 }
400 
401 int
402 tls13_server_hello_retry_request_recv(struct tls13_ctx *ctx, CBS *cbs)
403 {
404 	/*
405 	 * The state machine has no way of knowing if we're going to receive a
406 	 * HelloRetryRequest or a ServerHello. As such, we have to handle
407 	 * this case here and hand off to the appropriate function.
408 	 */
409 	if (!tls13_server_hello_is_retry(cbs)) {
410 		ctx->handshake_stage.hs_type |= WITHOUT_HRR;
411 		return tls13_server_hello_recv(ctx, cbs);
412 	}
413 
414 	if (!tls13_server_hello_process(ctx, cbs))
415 		return 0;
416 
417 	/*
418 	 * This may have been a TLSv1.2 or earlier ServerHello that just happened
419 	 * to have matching server random...
420 	 */
421 	if (ctx->hs->use_legacy)
422 		return tls13_use_legacy_client(ctx);
423 
424 	if (!ctx->hs->hrr)
425 		return 0;
426 
427 	if (!tls13_synthetic_handshake_message(ctx))
428 		return 0;
429 	if (!tls13_handshake_msg_record(ctx))
430 		return 0;
431 
432 	ctx->hs->hrr = 0;
433 
434 	return 1;
435 }
436 
437 int
438 tls13_client_hello_retry_send(struct tls13_ctx *ctx, CBB *cbb)
439 {
440 	/*
441 	 * Ensure that the server supported group is one that we listed in our
442 	 * supported groups and is not the same as the key share we previously
443 	 * offered.
444 	 */
445 	if (!tls1_check_curve(ctx->ssl, ctx->hs->server_group))
446 		return 0; /* XXX alert */
447 	if (ctx->hs->server_group == tls13_key_share_group(ctx->hs->key_share))
448 		return 0; /* XXX alert */
449 
450 	/* Switch to new key share. */
451 	tls13_key_share_free(ctx->hs->key_share);
452 	if ((ctx->hs->key_share =
453 	    tls13_key_share_new(ctx->hs->server_group)) == NULL)
454 		return 0;
455 	if (!tls13_key_share_generate(ctx->hs->key_share))
456 		return 0;
457 
458 	if (!tls13_client_hello_build(ctx, cbb))
459 		return 0;
460 
461 	return 1;
462 }
463 
464 int
465 tls13_server_hello_recv(struct tls13_ctx *ctx, CBS *cbs)
466 {
467 	SSL *s = ctx->ssl;
468 
469 	/*
470 	 * We may have received a legacy (pre-TLSv1.3) ServerHello or a TLSv1.3
471 	 * ServerHello. HelloRetryRequests have already been handled.
472 	 */
473 	if (!tls13_server_hello_process(ctx, cbs))
474 		return 0;
475 
476 	if (ctx->handshake_stage.hs_type & WITHOUT_HRR) {
477 		tls1_transcript_unfreeze(s);
478 		if (!tls13_handshake_msg_record(ctx))
479 			return 0;
480 	}
481 
482 	if (ctx->hs->use_legacy) {
483 		if (!(ctx->handshake_stage.hs_type & WITHOUT_HRR))
484 			return 0;
485 		return tls13_use_legacy_client(ctx);
486 	}
487 
488 	if (ctx->hs->hrr) {
489 		/* The server has sent two HelloRetryRequests. */
490 		ctx->alert = TLS13_ALERT_ILLEGAL_PARAMETER;
491 		return 0;
492 	}
493 
494 	if (!tls13_client_engage_record_protection(ctx))
495 		return 0;
496 
497 	ctx->handshake_stage.hs_type |= NEGOTIATED;
498 
499 	return 1;
500 }
501 
502 int
503 tls13_server_encrypted_extensions_recv(struct tls13_ctx *ctx, CBS *cbs)
504 {
505 	int alert_desc;
506 
507 	if (!tlsext_client_parse(ctx->ssl, cbs, &alert_desc, SSL_TLSEXT_MSG_EE)) {
508 		ctx->alert = alert_desc;
509 		goto err;
510 	}
511 
512 	return 1;
513 
514  err:
515 	if (ctx->alert == 0)
516 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
517 
518 	return 0;
519 }
520 
521 int
522 tls13_server_certificate_request_recv(struct tls13_ctx *ctx, CBS *cbs)
523 {
524 	CBS cert_request_context;
525 	int alert_desc;
526 
527 	/*
528 	 * Thanks to poor state design in the RFC, this function can be called
529 	 * when we actually have a certificate message instead of a certificate
530 	 * request... in that case we call the certificate handler after
531 	 * switching state, to avoid advancing state.
532 	 */
533 	if (tls13_handshake_msg_type(ctx->hs_msg) == TLS13_MT_CERTIFICATE) {
534 		ctx->handshake_stage.hs_type |= WITHOUT_CR;
535 		return tls13_server_certificate_recv(ctx, cbs);
536 	}
537 
538 	if (!CBS_get_u8_length_prefixed(cbs, &cert_request_context))
539 		goto err;
540 	if (CBS_len(&cert_request_context) != 0)
541 		goto err;
542 
543 	if (!tlsext_client_parse(ctx->ssl, cbs, &alert_desc, SSL_TLSEXT_MSG_CR)) {
544 		ctx->alert = alert_desc;
545 		goto err;
546 	}
547 
548 	return 1;
549 
550  err:
551 	if (ctx->alert == 0)
552 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
553 
554 	return 0;
555 }
556 
557 int
558 tls13_server_certificate_recv(struct tls13_ctx *ctx, CBS *cbs)
559 {
560 	CBS cert_request_context, cert_list, cert_data;
561 	struct stack_st_X509 *certs = NULL;
562 	SSL *s = ctx->ssl;
563 	X509 *cert = NULL;
564 	EVP_PKEY *pkey;
565 	const uint8_t *p;
566 	int cert_idx, alert_desc;
567 	int ret = 0;
568 
569 	if ((certs = sk_X509_new_null()) == NULL)
570 		goto err;
571 
572 	if (!CBS_get_u8_length_prefixed(cbs, &cert_request_context))
573 		goto err;
574 	if (CBS_len(&cert_request_context) != 0)
575 		goto err;
576 	if (!CBS_get_u24_length_prefixed(cbs, &cert_list))
577 		goto err;
578 
579 	while (CBS_len(&cert_list) > 0) {
580 		if (!CBS_get_u24_length_prefixed(&cert_list, &cert_data))
581 			goto err;
582 
583 		if (!tlsext_client_parse(ctx->ssl, &cert_list, &alert_desc,
584 		    SSL_TLSEXT_MSG_CT)) {
585 			ctx->alert = alert_desc;
586 			goto err;
587 		}
588 
589 		p = CBS_data(&cert_data);
590 		if ((cert = d2i_X509(NULL, &p, CBS_len(&cert_data))) == NULL)
591 			goto err;
592 		if (p != CBS_data(&cert_data) + CBS_len(&cert_data))
593 			goto err;
594 
595 		if (!sk_X509_push(certs, cert))
596 			goto err;
597 
598 		cert = NULL;
599 	}
600 
601 	/* A server must always provide a non-empty certificate list. */
602 	if (sk_X509_num(certs) < 1) {
603 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
604 		tls13_set_errorx(ctx, TLS13_ERR_NO_PEER_CERTIFICATE, 0,
605 		    "peer failed to provide a certificate", NULL);
606 		goto err;
607 	}
608 
609 	/*
610 	 * At this stage we still have no proof of possession. As such, it would
611 	 * be preferable to keep the chain and verify once we have successfully
612 	 * processed the CertificateVerify message.
613 	 */
614 	if (ssl_verify_cert_chain(s, certs) <= 0 &&
615 	    s->verify_mode != SSL_VERIFY_NONE) {
616 		ctx->alert = ssl_verify_alarm_type(s->verify_result);
617 		tls13_set_errorx(ctx, TLS13_ERR_VERIFY_FAILED, 0,
618 		    "failed to verify peer certificate", NULL);
619 		goto err;
620 	}
621 	ERR_clear_error();
622 
623 	cert = sk_X509_value(certs, 0);
624 	X509_up_ref(cert);
625 
626 	if ((pkey = X509_get0_pubkey(cert)) == NULL)
627 		goto err;
628 	if (EVP_PKEY_missing_parameters(pkey))
629 		goto err;
630 	if ((cert_idx = ssl_cert_type(cert, pkey)) < 0)
631 		goto err;
632 
633 	ssl_sess_cert_free(SSI(s)->sess_cert);
634 	if ((SSI(s)->sess_cert = ssl_sess_cert_new()) == NULL)
635 		goto err;
636 
637 	SSI(s)->sess_cert->cert_chain = certs;
638 	certs = NULL;
639 
640 	X509_up_ref(cert);
641 	SSI(s)->sess_cert->peer_pkeys[cert_idx].x509 = cert;
642 	SSI(s)->sess_cert->peer_key = &(SSI(s)->sess_cert->peer_pkeys[cert_idx]);
643 
644 	X509_free(s->session->peer);
645 
646 	X509_up_ref(cert);
647 	s->session->peer = cert;
648 	s->session->verify_result = s->verify_result;
649 
650 	if (ctx->ocsp_status_recv_cb != NULL &&
651 	    !ctx->ocsp_status_recv_cb(ctx))
652 		goto err;
653 
654 	ret = 1;
655 
656  err:
657 	sk_X509_pop_free(certs, X509_free);
658 	X509_free(cert);
659 
660 	return ret;
661 }
662 
663 int
664 tls13_server_certificate_verify_recv(struct tls13_ctx *ctx, CBS *cbs)
665 {
666 	const struct ssl_sigalg *sigalg;
667 	uint16_t signature_scheme;
668 	uint8_t *sig_content = NULL;
669 	size_t sig_content_len;
670 	EVP_MD_CTX *mdctx = NULL;
671 	EVP_PKEY_CTX *pctx;
672 	EVP_PKEY *pkey;
673 	X509 *cert;
674 	CBS signature;
675 	CBB cbb;
676 	int ret = 0;
677 
678 	memset(&cbb, 0, sizeof(cbb));
679 
680 	if (!CBS_get_u16(cbs, &signature_scheme))
681 		goto err;
682 	if (!CBS_get_u16_length_prefixed(cbs, &signature))
683 		goto err;
684 
685 	if ((sigalg = ssl_sigalg(signature_scheme, tls13_sigalgs,
686 	    tls13_sigalgs_len)) == NULL)
687 		goto err;
688 
689 	if (!CBB_init(&cbb, 0))
690 		goto err;
691 	if (!CBB_add_bytes(&cbb, tls13_cert_verify_pad,
692 	    sizeof(tls13_cert_verify_pad)))
693 		goto err;
694 	if (!CBB_add_bytes(&cbb, tls13_cert_server_verify_context,
695 	    strlen(tls13_cert_server_verify_context)))
696 		goto err;
697 	if (!CBB_add_u8(&cbb, 0))
698 		goto err;
699 	if (!CBB_add_bytes(&cbb, ctx->hs->transcript_hash,
700 	    ctx->hs->transcript_hash_len))
701 		goto err;
702 	if (!CBB_finish(&cbb, &sig_content, &sig_content_len))
703 		goto err;
704 
705 	if ((cert = ctx->ssl->session->peer) == NULL)
706 		goto err;
707 	if ((pkey = X509_get0_pubkey(cert)) == NULL)
708 		goto err;
709 	if (!ssl_sigalg_pkey_ok(sigalg, pkey, 1))
710 		goto err;
711 
712 	if (CBS_len(&signature) > EVP_PKEY_size(pkey))
713 		goto err;
714 
715 	if ((mdctx = EVP_MD_CTX_new()) == NULL)
716 		goto err;
717 	if (!EVP_DigestVerifyInit(mdctx, &pctx, sigalg->md(), NULL, pkey))
718 		goto err;
719 	if (sigalg->flags & SIGALG_FLAG_RSA_PSS) {
720 		if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING))
721 			goto err;
722 		if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))
723 			goto err;
724 	}
725 	if (!EVP_DigestVerifyUpdate(mdctx, sig_content, sig_content_len)) {
726 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
727 		goto err;
728 	}
729 	if (EVP_DigestVerifyFinal(mdctx, CBS_data(&signature),
730 	    CBS_len(&signature)) <= 0) {
731 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
732 		goto err;
733 	}
734 
735 	ret = 1;
736 
737  err:
738 	if (!ret && ctx->alert == 0)
739 		ctx->alert = TLS13_ALERT_DECODE_ERROR;
740 	CBB_cleanup(&cbb);
741 	EVP_MD_CTX_free(mdctx);
742 	free(sig_content);
743 
744 	return ret;
745 }
746 
747 int
748 tls13_server_finished_recv(struct tls13_ctx *ctx, CBS *cbs)
749 {
750 	struct tls13_secrets *secrets = ctx->hs->secrets;
751 	struct tls13_secret context = { .data = "", .len = 0 };
752 	struct tls13_secret finished_key;
753 	uint8_t transcript_hash[EVP_MAX_MD_SIZE];
754 	size_t transcript_hash_len;
755 	uint8_t *verify_data = NULL;
756 	size_t verify_data_len;
757 	uint8_t key[EVP_MAX_MD_SIZE];
758 	HMAC_CTX *hmac_ctx = NULL;
759 	unsigned int hlen;
760 	int ret = 0;
761 
762 	/*
763 	 * Verify server finished.
764 	 */
765 	finished_key.data = key;
766 	finished_key.len = EVP_MD_size(ctx->hash);
767 
768 	if (!tls13_hkdf_expand_label(&finished_key, ctx->hash,
769 	    &secrets->server_handshake_traffic, "finished",
770 	    &context))
771 		goto err;
772 
773 	if ((hmac_ctx = HMAC_CTX_new()) == NULL)
774 		goto err;
775 	if (!HMAC_Init_ex(hmac_ctx, finished_key.data, finished_key.len,
776 	    ctx->hash, NULL))
777 		goto err;
778 	if (!HMAC_Update(hmac_ctx, ctx->hs->transcript_hash,
779 	    ctx->hs->transcript_hash_len))
780 		goto err;
781 	verify_data_len = HMAC_size(hmac_ctx);
782 	if ((verify_data = calloc(1, verify_data_len)) == NULL)
783 		goto err;
784 	if (!HMAC_Final(hmac_ctx, verify_data, &hlen))
785 		goto err;
786 	if (hlen != verify_data_len)
787 		goto err;
788 
789 	if (!CBS_mem_equal(cbs, verify_data, verify_data_len)) {
790 		ctx->alert = TLS13_ALERT_DECRYPT_ERROR;
791 		goto err;
792 	}
793 
794 	if (!CBS_skip(cbs, verify_data_len))
795 		goto err;
796 
797 	/*
798 	 * Derive application traffic keys.
799 	 */
800 	if (!tls1_transcript_hash_value(ctx->ssl, transcript_hash,
801 	    sizeof(transcript_hash), &transcript_hash_len))
802 		goto err;
803 
804 	context.data = transcript_hash;
805 	context.len = transcript_hash_len;
806 
807 	if (!tls13_derive_application_secrets(secrets, &context))
808 		goto err;
809 
810 	/*
811 	 * Any records following the server finished message must be encrypted
812 	 * using the server application traffic keys.
813 	 */
814 	if (!tls13_record_layer_set_read_traffic_key(ctx->rl,
815 	    &secrets->server_application_traffic))
816 		goto err;
817 
818 	tls13_record_layer_allow_ccs(ctx->rl, 0);
819 
820 	ret = 1;
821 
822  err:
823 	HMAC_CTX_free(hmac_ctx);
824 	free(verify_data);
825 
826 	return ret;
827 }
828 
829 static int
830 tls13_client_check_certificate(struct tls13_ctx *ctx, CERT_PKEY *cpk,
831     int *ok, const struct ssl_sigalg **out_sigalg)
832 {
833 	const struct ssl_sigalg *sigalg;
834 	SSL *s = ctx->ssl;
835 
836 	*ok = 0;
837 	*out_sigalg = NULL;
838 
839 	if (cpk->x509 == NULL || cpk->privatekey == NULL)
840 		goto done;
841 
842 	if ((sigalg = ssl_sigalg_select(s, cpk->privatekey)) == NULL)
843 		goto done;
844 
845 	*ok = 1;
846 	*out_sigalg = sigalg;
847 
848  done:
849 	return 1;
850 }
851 
852 static int
853 tls13_client_select_certificate(struct tls13_ctx *ctx, CERT_PKEY **out_cpk,
854     const struct ssl_sigalg **out_sigalg)
855 {
856 	SSL *s = ctx->ssl;
857 	const struct ssl_sigalg *sigalg;
858 	CERT_PKEY *cpk;
859 	int cert_ok;
860 
861 	*out_cpk = NULL;
862 	*out_sigalg = NULL;
863 
864 	/*
865 	 * XXX - RFC 8446, 4.4.2.3: the server can communicate preferences
866 	 * with the certificate_authorities (4.2.4) and oid_filters (4.2.5)
867 	 * extensions. We should honor the former and must apply the latter.
868 	 */
869 
870 	cpk = &s->cert->pkeys[SSL_PKEY_ECC];
871 	if (!tls13_client_check_certificate(ctx, cpk, &cert_ok, &sigalg))
872 		return 0;
873 	if (cert_ok)
874 		goto done;
875 
876 	cpk = &s->cert->pkeys[SSL_PKEY_RSA];
877 	if (!tls13_client_check_certificate(ctx, cpk, &cert_ok, &sigalg))
878 		return 0;
879 	if (cert_ok)
880 		goto done;
881 
882 	cpk = NULL;
883 	sigalg = NULL;
884 
885  done:
886 	*out_cpk = cpk;
887 	*out_sigalg = sigalg;
888 
889 	return 1;
890 }
891 
892 int
893 tls13_client_certificate_send(struct tls13_ctx *ctx, CBB *cbb)
894 {
895 	SSL *s = ctx->ssl;
896 	CBB cert_request_context, cert_list;
897 	const struct ssl_sigalg *sigalg;
898 	STACK_OF(X509) *chain;
899 	CERT_PKEY *cpk;
900 	X509 *cert;
901 	int i, ret = 0;
902 
903 	if (!tls13_client_select_certificate(ctx, &cpk, &sigalg))
904 		goto err;
905 
906 	ctx->hs->cpk = cpk;
907 	ctx->hs->sigalg = sigalg;
908 
909 	if (!CBB_add_u8_length_prefixed(cbb, &cert_request_context))
910 		goto err;
911 	if (!CBB_add_u24_length_prefixed(cbb, &cert_list))
912 		goto err;
913 
914 	/* No certificate selected. */
915 	if (cpk == NULL)
916 		goto done;
917 
918 	if ((chain = cpk->chain) == NULL)
919 	       chain = s->ctx->extra_certs;
920 
921 	if (!tls13_cert_add(ctx, &cert_list, cpk->x509, tlsext_client_build))
922 		goto err;
923 
924 	for (i = 0; i < sk_X509_num(chain); i++) {
925 		cert = sk_X509_value(chain, i);
926 		if (!tls13_cert_add(ctx, &cert_list, cert, tlsext_client_build))
927 			goto err;
928 	}
929 
930 	ctx->handshake_stage.hs_type |= WITH_CCV;
931  done:
932 	if (!CBB_flush(cbb))
933 		goto err;
934 
935 	ret = 1;
936 
937  err:
938 	return ret;
939 }
940 
941 int
942 tls13_client_certificate_verify_send(struct tls13_ctx *ctx, CBB *cbb)
943 {
944 	const struct ssl_sigalg *sigalg;
945 	uint8_t *sig = NULL, *sig_content = NULL;
946 	size_t sig_len, sig_content_len;
947 	EVP_MD_CTX *mdctx = NULL;
948 	EVP_PKEY_CTX *pctx;
949 	EVP_PKEY *pkey;
950 	const CERT_PKEY *cpk;
951 	CBB sig_cbb;
952 	int ret = 0;
953 
954 	memset(&sig_cbb, 0, sizeof(sig_cbb));
955 
956 	if ((cpk = ctx->hs->cpk) == NULL)
957 		goto err;
958 	if ((sigalg = ctx->hs->sigalg) == NULL)
959 		goto err;
960 	pkey = cpk->privatekey;
961 
962 	if (!CBB_init(&sig_cbb, 0))
963 		goto err;
964 	if (!CBB_add_bytes(&sig_cbb, tls13_cert_verify_pad,
965 	    sizeof(tls13_cert_verify_pad)))
966 		goto err;
967 	if (!CBB_add_bytes(&sig_cbb, tls13_cert_client_verify_context,
968 	    strlen(tls13_cert_client_verify_context)))
969 		goto err;
970 	if (!CBB_add_u8(&sig_cbb, 0))
971 		goto err;
972 	if (!CBB_add_bytes(&sig_cbb, ctx->hs->transcript_hash,
973 	    ctx->hs->transcript_hash_len))
974 		goto err;
975 	if (!CBB_finish(&sig_cbb, &sig_content, &sig_content_len))
976 		goto err;
977 
978 	if ((mdctx = EVP_MD_CTX_new()) == NULL)
979 		goto err;
980 	if (!EVP_DigestSignInit(mdctx, &pctx, sigalg->md(), NULL, pkey))
981 		goto err;
982 	if (sigalg->flags & SIGALG_FLAG_RSA_PSS) {
983 		if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING))
984 			goto err;
985 		if (!EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1))
986 			goto err;
987 	}
988 	if (!EVP_DigestSignUpdate(mdctx, sig_content, sig_content_len))
989 		goto err;
990 	if (EVP_DigestSignFinal(mdctx, NULL, &sig_len) <= 0)
991 		goto err;
992 	if ((sig = calloc(1, sig_len)) == NULL)
993 		goto err;
994 	if (EVP_DigestSignFinal(mdctx, sig, &sig_len) <= 0)
995 		goto err;
996 
997 	if (!CBB_add_u16(cbb, sigalg->value))
998 		goto err;
999 	if (!CBB_add_u16_length_prefixed(cbb, &sig_cbb))
1000 		goto err;
1001 	if (!CBB_add_bytes(&sig_cbb, sig, sig_len))
1002 		goto err;
1003 
1004 	if (!CBB_flush(cbb))
1005 		goto err;
1006 
1007 	ret = 1;
1008 
1009  err:
1010 	if (!ret && ctx->alert == 0)
1011 		ctx->alert = TLS13_ALERT_INTERNAL_ERROR;
1012 
1013 	CBB_cleanup(&sig_cbb);
1014 	EVP_MD_CTX_free(mdctx);
1015 	free(sig_content);
1016 	free(sig);
1017 
1018 	return ret;
1019 }
1020 
1021 int
1022 tls13_client_end_of_early_data_send(struct tls13_ctx *ctx, CBB *cbb)
1023 {
1024 	return 0;
1025 }
1026 
1027 int
1028 tls13_client_finished_send(struct tls13_ctx *ctx, CBB *cbb)
1029 {
1030 	struct tls13_secrets *secrets = ctx->hs->secrets;
1031 	struct tls13_secret context = { .data = "", .len = 0 };
1032 	struct tls13_secret finished_key;
1033 	uint8_t transcript_hash[EVP_MAX_MD_SIZE];
1034 	size_t transcript_hash_len;
1035 	uint8_t key[EVP_MAX_MD_SIZE];
1036 	uint8_t *verify_data;
1037 	size_t hmac_len;
1038 	unsigned int hlen;
1039 	HMAC_CTX *hmac_ctx = NULL;
1040 	int ret = 0;
1041 
1042 	finished_key.data = key;
1043 	finished_key.len = EVP_MD_size(ctx->hash);
1044 
1045 	if (!tls13_hkdf_expand_label(&finished_key, ctx->hash,
1046 	    &secrets->client_handshake_traffic, "finished",
1047 	    &context))
1048 		goto err;
1049 
1050 	if (!tls1_transcript_hash_value(ctx->ssl, transcript_hash,
1051 	    sizeof(transcript_hash), &transcript_hash_len))
1052 		goto err;
1053 
1054 	if ((hmac_ctx = HMAC_CTX_new()) == NULL)
1055 		goto err;
1056 	if (!HMAC_Init_ex(hmac_ctx, finished_key.data, finished_key.len,
1057 	    ctx->hash, NULL))
1058 		goto err;
1059 	if (!HMAC_Update(hmac_ctx, transcript_hash, transcript_hash_len))
1060 		goto err;
1061 
1062 	hmac_len = HMAC_size(hmac_ctx);
1063 	if (!CBB_add_space(cbb, &verify_data, hmac_len))
1064 		goto err;
1065 	if (!HMAC_Final(hmac_ctx, verify_data, &hlen))
1066 		goto err;
1067 	if (hlen != hmac_len)
1068 		goto err;
1069 
1070 	ret = 1;
1071 
1072  err:
1073 	HMAC_CTX_free(hmac_ctx);
1074 
1075 	return ret;
1076 }
1077 
1078 int
1079 tls13_client_finished_sent(struct tls13_ctx *ctx)
1080 {
1081 	struct tls13_secrets *secrets = ctx->hs->secrets;
1082 
1083 	/*
1084 	 * Any records following the client finished message must be encrypted
1085 	 * using the client application traffic keys.
1086 	 */
1087 	return tls13_record_layer_set_write_traffic_key(ctx->rl,
1088 	    &secrets->client_application_traffic);
1089 }
1090