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