xref: /openbsd-src/lib/libssl/tls13_record_layer.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /* $OpenBSD: tls13_record_layer.c,v 1.68 2022/07/20 06:32:24 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 "tls13_internal.h"
19 #include "tls13_record.h"
20 #include "tls_content.h"
21 
22 static ssize_t tls13_record_layer_write_chunk(struct tls13_record_layer *rl,
23     uint8_t content_type, const uint8_t *buf, size_t n);
24 static ssize_t tls13_record_layer_write_record(struct tls13_record_layer *rl,
25     uint8_t content_type, const uint8_t *content, size_t content_len);
26 
27 struct tls13_record_protection {
28 	EVP_AEAD_CTX *aead_ctx;
29 	struct tls13_secret iv;
30 	struct tls13_secret nonce;
31 	uint8_t seq_num[TLS13_RECORD_SEQ_NUM_LEN];
32 };
33 
34 struct tls13_record_protection *
35 tls13_record_protection_new(void)
36 {
37 	return calloc(1, sizeof(struct tls13_record_protection));
38 }
39 
40 void
41 tls13_record_protection_clear(struct tls13_record_protection *rp)
42 {
43 	EVP_AEAD_CTX_free(rp->aead_ctx);
44 
45 	tls13_secret_cleanup(&rp->iv);
46 	tls13_secret_cleanup(&rp->nonce);
47 
48 	memset(rp, 0, sizeof(*rp));
49 }
50 
51 void
52 tls13_record_protection_free(struct tls13_record_protection *rp)
53 {
54 	if (rp == NULL)
55 		return;
56 
57 	tls13_record_protection_clear(rp);
58 
59 	freezero(rp, sizeof(struct tls13_record_protection));
60 }
61 
62 struct tls13_record_layer {
63 	uint16_t legacy_version;
64 
65 	int ccs_allowed;
66 	int ccs_seen;
67 	int ccs_sent;
68 	int handshake_completed;
69 	int legacy_alerts_allowed;
70 	int phh;
71 	int phh_retry;
72 
73 	/*
74 	 * Read and/or write channels are closed due to an alert being
75 	 * sent or received. In the case of an error alert both channels
76 	 * are closed, whereas in the case of a close notify only one
77 	 * channel is closed.
78 	 */
79 	int read_closed;
80 	int write_closed;
81 
82 	struct tls13_record *rrec;
83 
84 	struct tls13_record *wrec;
85 	uint8_t wrec_content_type;
86 	size_t wrec_appdata_len;
87 	size_t wrec_content_len;
88 
89 	/* Alert to be sent on return from current read handler. */
90 	uint8_t alert;
91 
92 	/* Pending alert messages. */
93 	uint8_t *alert_data;
94 	size_t alert_len;
95 	uint8_t alert_level;
96 	uint8_t alert_desc;
97 
98 	/* Pending post-handshake handshake messages (RFC 8446, section 4.6). */
99 	CBS phh_cbs;
100 	uint8_t *phh_data;
101 	size_t phh_len;
102 
103 	/* Content from opened records. */
104 	struct tls_content *rcontent;
105 
106 	/* Record protection. */
107 	const EVP_MD *hash;
108 	const EVP_AEAD *aead;
109 	struct tls13_record_protection *read;
110 	struct tls13_record_protection *write;
111 
112 	/* Callbacks. */
113 	struct tls13_record_layer_callbacks cb;
114 	void *cb_arg;
115 };
116 
117 static void
118 tls13_record_layer_rrec_free(struct tls13_record_layer *rl)
119 {
120 	tls13_record_free(rl->rrec);
121 	rl->rrec = NULL;
122 }
123 
124 static void
125 tls13_record_layer_wrec_free(struct tls13_record_layer *rl)
126 {
127 	tls13_record_free(rl->wrec);
128 	rl->wrec = NULL;
129 }
130 
131 struct tls13_record_layer *
132 tls13_record_layer_new(const struct tls13_record_layer_callbacks *callbacks,
133     void *cb_arg)
134 {
135 	struct tls13_record_layer *rl;
136 
137 	if ((rl = calloc(1, sizeof(struct tls13_record_layer))) == NULL)
138 		goto err;
139 
140 	if ((rl->rcontent = tls_content_new()) == NULL)
141 		goto err;
142 
143 	if ((rl->read = tls13_record_protection_new()) == NULL)
144 		goto err;
145 	if ((rl->write = tls13_record_protection_new()) == NULL)
146 		goto err;
147 
148 	rl->legacy_version = TLS1_2_VERSION;
149 	rl->cb = *callbacks;
150 	rl->cb_arg = cb_arg;
151 
152 	return rl;
153 
154  err:
155 	tls13_record_layer_free(rl);
156 
157 	return NULL;
158 }
159 
160 void
161 tls13_record_layer_free(struct tls13_record_layer *rl)
162 {
163 	if (rl == NULL)
164 		return;
165 
166 	tls13_record_layer_rrec_free(rl);
167 	tls13_record_layer_wrec_free(rl);
168 
169 	freezero(rl->alert_data, rl->alert_len);
170 	freezero(rl->phh_data, rl->phh_len);
171 
172 	tls_content_free(rl->rcontent);
173 
174 	tls13_record_protection_free(rl->read);
175 	tls13_record_protection_free(rl->write);
176 
177 	freezero(rl, sizeof(struct tls13_record_layer));
178 }
179 
180 void
181 tls13_record_layer_rcontent(struct tls13_record_layer *rl, CBS *cbs)
182 {
183 	CBS_dup(tls_content_cbs(rl->rcontent), cbs);
184 }
185 
186 static const uint8_t tls13_max_seq_num[TLS13_RECORD_SEQ_NUM_LEN] = {
187 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
188 };
189 
190 int
191 tls13_record_layer_inc_seq_num(uint8_t *seq_num)
192 {
193 	int i;
194 
195 	/* RFC 8446 section 5.3 - sequence numbers must not wrap. */
196 	if (memcmp(seq_num, tls13_max_seq_num, TLS13_RECORD_SEQ_NUM_LEN) == 0)
197 		return 0;
198 
199 	for (i = TLS13_RECORD_SEQ_NUM_LEN - 1; i >= 0; i--) {
200 		if (++seq_num[i] != 0)
201 			break;
202 	}
203 
204 	return 1;
205 }
206 
207 static int
208 tls13_record_layer_update_nonce(struct tls13_secret *nonce,
209     struct tls13_secret *iv, uint8_t *seq_num)
210 {
211 	ssize_t i, j;
212 
213 	if (nonce->len != iv->len)
214 		return 0;
215 
216 	/*
217 	 * RFC 8446 section 5.3 - sequence number is zero padded and XOR'd
218 	 * with the IV to produce a per-record nonce. The IV will also be
219 	 * at least 8-bytes in length.
220 	 */
221 	for (i = nonce->len - 1, j = TLS13_RECORD_SEQ_NUM_LEN - 1; i >= 0; i--, j--)
222 		nonce->data[i] = iv->data[i] ^ (j >= 0 ? seq_num[j] : 0);
223 
224 	return 1;
225 }
226 
227 void
228 tls13_record_layer_allow_ccs(struct tls13_record_layer *rl, int allow)
229 {
230 	rl->ccs_allowed = allow;
231 }
232 
233 void
234 tls13_record_layer_allow_legacy_alerts(struct tls13_record_layer *rl, int allow)
235 {
236 	rl->legacy_alerts_allowed = allow;
237 }
238 
239 void
240 tls13_record_layer_set_aead(struct tls13_record_layer *rl,
241     const EVP_AEAD *aead)
242 {
243 	rl->aead = aead;
244 }
245 
246 void
247 tls13_record_layer_set_hash(struct tls13_record_layer *rl,
248     const EVP_MD *hash)
249 {
250 	rl->hash = hash;
251 }
252 
253 void
254 tls13_record_layer_set_legacy_version(struct tls13_record_layer *rl,
255     uint16_t version)
256 {
257 	rl->legacy_version = version;
258 }
259 
260 void
261 tls13_record_layer_handshake_completed(struct tls13_record_layer *rl)
262 {
263 	rl->handshake_completed = 1;
264 }
265 
266 void
267 tls13_record_layer_set_retry_after_phh(struct tls13_record_layer *rl, int retry)
268 {
269 	rl->phh_retry = retry;
270 }
271 
272 static ssize_t
273 tls13_record_layer_process_alert(struct tls13_record_layer *rl)
274 {
275 	uint8_t alert_level, alert_desc;
276 	ssize_t ret = TLS13_IO_FAILURE;
277 
278 	/*
279 	 * RFC 8446 - sections 5.1 and 6.
280 	 *
281 	 * A TLSv1.3 alert record can only contain a single alert - this means
282 	 * that processing the alert must consume all of the record. The alert
283 	 * will result in one of three things - continuation (user_cancelled),
284 	 * read channel closure (close_notify) or termination (all others).
285 	 */
286 	if (tls_content_type(rl->rcontent) != SSL3_RT_ALERT)
287 		return TLS13_IO_FAILURE;
288 
289 	if (!CBS_get_u8(tls_content_cbs(rl->rcontent), &alert_level))
290 		return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
291 	if (!CBS_get_u8(tls_content_cbs(rl->rcontent), &alert_desc))
292 		return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
293 
294 	if (tls_content_remaining(rl->rcontent) != 0)
295 		return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
296 
297 	tls_content_clear(rl->rcontent);
298 
299 	/*
300 	 * Alert level is ignored for closure alerts (RFC 8446 section 6.1),
301 	 * however for error alerts (RFC 8446 section 6.2), the alert level
302 	 * must be specified as fatal.
303 	 */
304 	if (alert_desc == TLS13_ALERT_CLOSE_NOTIFY) {
305 		rl->read_closed = 1;
306 		ret = TLS13_IO_EOF;
307 	} else if (alert_desc == TLS13_ALERT_USER_CANCELED) {
308 		/* Ignored at the record layer. */
309 		ret = TLS13_IO_WANT_RETRY;
310 	} else if (alert_level == TLS13_ALERT_LEVEL_FATAL) {
311 		rl->read_closed = 1;
312 		rl->write_closed = 1;
313 		ret = TLS13_IO_ALERT;
314 	} else if (rl->legacy_alerts_allowed &&
315 	    alert_level == TLS13_ALERT_LEVEL_WARNING) {
316 		/* Ignored and not passed to the callback. */
317 		return TLS13_IO_WANT_RETRY;
318 	} else {
319 		return tls13_send_alert(rl, TLS13_ALERT_ILLEGAL_PARAMETER);
320 	}
321 
322 	rl->cb.alert_recv(alert_desc, rl->cb_arg);
323 
324 	return ret;
325 }
326 
327 static ssize_t
328 tls13_record_layer_send_alert(struct tls13_record_layer *rl)
329 {
330 	ssize_t ret;
331 
332 	/* This has to fit into a single record, per RFC 8446 section 5.1. */
333 	if ((ret = tls13_record_layer_write_record(rl, SSL3_RT_ALERT,
334 	    rl->alert_data, rl->alert_len)) != rl->alert_len) {
335 		if (ret == TLS13_IO_EOF)
336 			ret = TLS13_IO_ALERT;
337 		return ret;
338 	}
339 
340 	freezero(rl->alert_data, rl->alert_len);
341 	rl->alert_data = NULL;
342 	rl->alert_len = 0;
343 
344 	if (rl->alert_desc == TLS13_ALERT_CLOSE_NOTIFY) {
345 		rl->write_closed = 1;
346 		ret = TLS13_IO_SUCCESS;
347 	} else if (rl->alert_desc == TLS13_ALERT_USER_CANCELED) {
348 		/* Ignored at the record layer. */
349 		ret = TLS13_IO_SUCCESS;
350 	} else {
351 		rl->read_closed = 1;
352 		rl->write_closed = 1;
353 		ret = TLS13_IO_ALERT;
354 	}
355 
356 	rl->cb.alert_sent(rl->alert_desc, rl->cb_arg);
357 
358 	return ret;
359 }
360 
361 static ssize_t
362 tls13_record_layer_send_phh(struct tls13_record_layer *rl)
363 {
364 	ssize_t ret;
365 
366 	/* Push out pending post-handshake handshake messages. */
367 	if ((ret = tls13_record_layer_write_chunk(rl, SSL3_RT_HANDSHAKE,
368 	    CBS_data(&rl->phh_cbs), CBS_len(&rl->phh_cbs))) <= 0)
369 		return ret;
370 	if (!CBS_skip(&rl->phh_cbs, ret))
371 		return TLS13_IO_FAILURE;
372 	if (CBS_len(&rl->phh_cbs) != 0)
373 		return TLS13_IO_WANT_RETRY;
374 
375 	freezero(rl->phh_data, rl->phh_len);
376 	rl->phh_data = NULL;
377 	rl->phh_len = 0;
378 
379 	CBS_init(&rl->phh_cbs, rl->phh_data, rl->phh_len);
380 
381 	rl->cb.phh_sent(rl->cb_arg);
382 
383 	return TLS13_IO_SUCCESS;
384 }
385 
386 ssize_t
387 tls13_record_layer_send_pending(struct tls13_record_layer *rl)
388 {
389 	/*
390 	 * If an alert is pending, then it needs to be sent. However,
391 	 * if we're already part of the way through sending post-handshake
392 	 * handshake messages, then we need to finish that first...
393 	 */
394 
395 	if (rl->phh_data != NULL && CBS_len(&rl->phh_cbs) != rl->phh_len)
396 		return tls13_record_layer_send_phh(rl);
397 
398 	if (rl->alert_data != NULL)
399 		return tls13_record_layer_send_alert(rl);
400 
401 	if (rl->phh_data != NULL)
402 		return tls13_record_layer_send_phh(rl);
403 
404 	return TLS13_IO_SUCCESS;
405 }
406 
407 static ssize_t
408 tls13_record_layer_enqueue_alert(struct tls13_record_layer *rl,
409     uint8_t alert_level, uint8_t alert_desc)
410 {
411 	CBB cbb;
412 
413 	if (rl->alert_data != NULL)
414 		return TLS13_IO_FAILURE;
415 
416 	if (!CBB_init(&cbb, 0))
417 		goto err;
418 
419 	if (!CBB_add_u8(&cbb, alert_level))
420 		goto err;
421 	if (!CBB_add_u8(&cbb, alert_desc))
422 		goto err;
423 	if (!CBB_finish(&cbb, &rl->alert_data, &rl->alert_len))
424 		goto err;
425 
426 	rl->alert_level = alert_level;
427 	rl->alert_desc = alert_desc;
428 
429 	return tls13_record_layer_send_pending(rl);
430 
431  err:
432 	CBB_cleanup(&cbb);
433 
434 	return TLS13_IO_FAILURE;
435 }
436 
437 ssize_t
438 tls13_record_layer_phh(struct tls13_record_layer *rl, CBS *cbs)
439 {
440 	if (rl->phh_data != NULL)
441 		return TLS13_IO_FAILURE;
442 
443 	if (!CBS_stow(cbs, &rl->phh_data, &rl->phh_len))
444 		return TLS13_IO_FAILURE;
445 
446 	CBS_init(&rl->phh_cbs, rl->phh_data, rl->phh_len);
447 
448 	return tls13_record_layer_send_pending(rl);
449 }
450 
451 static int
452 tls13_record_layer_set_traffic_key(const EVP_AEAD *aead, const EVP_MD *hash,
453     struct tls13_record_protection *rp, struct tls13_secret *traffic_key)
454 {
455 	struct tls13_secret context = { .data = "", .len = 0 };
456 	struct tls13_secret key = { .data = NULL, .len = 0 };
457 	int ret = 0;
458 
459 	tls13_record_protection_clear(rp);
460 
461 	if ((rp->aead_ctx = EVP_AEAD_CTX_new()) == NULL)
462 		return 0;
463 
464 	if (!tls13_secret_init(&rp->iv, EVP_AEAD_nonce_length(aead)))
465 		goto err;
466 	if (!tls13_secret_init(&rp->nonce, EVP_AEAD_nonce_length(aead)))
467 		goto err;
468 	if (!tls13_secret_init(&key, EVP_AEAD_key_length(aead)))
469 		goto err;
470 
471 	if (!tls13_hkdf_expand_label(&rp->iv, hash, traffic_key, "iv", &context))
472 		goto err;
473 	if (!tls13_hkdf_expand_label(&key, hash, traffic_key, "key", &context))
474 		goto err;
475 
476 	if (!EVP_AEAD_CTX_init(rp->aead_ctx, aead, key.data, key.len,
477 	    EVP_AEAD_DEFAULT_TAG_LENGTH, NULL))
478 		goto err;
479 
480 	ret = 1;
481 
482  err:
483 	tls13_secret_cleanup(&key);
484 
485 	return ret;
486 }
487 
488 int
489 tls13_record_layer_set_read_traffic_key(struct tls13_record_layer *rl,
490     struct tls13_secret *read_key)
491 {
492 	return tls13_record_layer_set_traffic_key(rl->aead, rl->hash,
493 	    rl->read, read_key);
494 }
495 
496 int
497 tls13_record_layer_set_write_traffic_key(struct tls13_record_layer *rl,
498     struct tls13_secret *write_key)
499 {
500 	return tls13_record_layer_set_traffic_key(rl->aead, rl->hash,
501 	    rl->write, write_key);
502 }
503 
504 static int
505 tls13_record_layer_open_record_plaintext(struct tls13_record_layer *rl)
506 {
507 	CBS cbs;
508 
509 	if (rl->aead != NULL)
510 		return 0;
511 
512 	/*
513 	 * We're still operating in plaintext mode, so just copy the
514 	 * content from the record to the plaintext buffer.
515 	 */
516 	if (!tls13_record_content(rl->rrec, &cbs))
517 		return 0;
518 
519 	if (CBS_len(&cbs) > TLS13_RECORD_MAX_PLAINTEXT_LEN) {
520 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
521 		return 0;
522 	}
523 
524 	if (!tls_content_dup_data(rl->rcontent,
525 	    tls13_record_content_type(rl->rrec), CBS_data(&cbs), CBS_len(&cbs)))
526 		return 0;
527 
528 	return 1;
529 }
530 
531 static int
532 tls13_record_layer_open_record_protected(struct tls13_record_layer *rl)
533 {
534 	CBS header, enc_record, inner;
535 	uint8_t *content = NULL;
536 	size_t content_len = 0;
537 	uint8_t content_type;
538 	size_t out_len;
539 
540 	if (rl->aead == NULL)
541 		goto err;
542 
543 	if (!tls13_record_header(rl->rrec, &header))
544 		goto err;
545 	if (!tls13_record_content(rl->rrec, &enc_record))
546 		goto err;
547 
548 	if ((content = calloc(1, CBS_len(&enc_record))) == NULL)
549 		goto err;
550 	content_len = CBS_len(&enc_record);
551 
552 	if (!tls13_record_layer_update_nonce(&rl->read->nonce, &rl->read->iv,
553 	    rl->read->seq_num))
554 		goto err;
555 
556 	if (!EVP_AEAD_CTX_open(rl->read->aead_ctx,
557 	    content, &out_len, content_len,
558 	    rl->read->nonce.data, rl->read->nonce.len,
559 	    CBS_data(&enc_record), CBS_len(&enc_record),
560 	    CBS_data(&header), CBS_len(&header)))
561 		goto err;
562 
563 	if (out_len > TLS13_RECORD_MAX_INNER_PLAINTEXT_LEN) {
564 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
565 		goto err;
566 	}
567 
568 	if (!tls13_record_layer_inc_seq_num(rl->read->seq_num))
569 		goto err;
570 
571 	/*
572 	 * The real content type is hidden at the end of the record content and
573 	 * it may be followed by padding that consists of one or more zeroes.
574 	 * Time to hunt for that elusive content type!
575 	 */
576 	CBS_init(&inner, content, out_len);
577 	content_type = 0;
578 	while (CBS_get_last_u8(&inner, &content_type)) {
579 		if (content_type != 0)
580 			break;
581 	}
582 	if (content_type == 0) {
583 		/* Unexpected message per RFC 8446 section 5.4. */
584 		rl->alert = TLS13_ALERT_UNEXPECTED_MESSAGE;
585 		goto err;
586 	}
587 	if (CBS_len(&inner) > TLS13_RECORD_MAX_PLAINTEXT_LEN) {
588 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
589 		goto err;
590 	}
591 
592 	tls_content_set_data(rl->rcontent, content_type, CBS_data(&inner),
593 	    CBS_len(&inner));
594 
595 	return 1;
596 
597  err:
598 	freezero(content, content_len);
599 
600 	return 0;
601 }
602 
603 static int
604 tls13_record_layer_open_record(struct tls13_record_layer *rl)
605 {
606 	if (rl->handshake_completed && rl->aead == NULL)
607 		return 0;
608 
609 	if (rl->aead == NULL)
610 		return tls13_record_layer_open_record_plaintext(rl);
611 
612 	return tls13_record_layer_open_record_protected(rl);
613 }
614 
615 static int
616 tls13_record_layer_seal_record_plaintext(struct tls13_record_layer *rl,
617     uint8_t content_type, const uint8_t *content, size_t content_len)
618 {
619 	uint8_t *data = NULL;
620 	size_t data_len = 0;
621 	CBB cbb, body;
622 
623 	/*
624 	 * Allow dummy CCS messages to be sent in plaintext even when
625 	 * record protection has been engaged, as long as the handshake
626 	 * has not yet completed.
627 	 */
628 	if (rl->handshake_completed)
629 		return 0;
630 	if (rl->aead != NULL && content_type != SSL3_RT_CHANGE_CIPHER_SPEC)
631 		return 0;
632 
633 	/*
634 	 * We're still operating in plaintext mode, so just copy the
635 	 * content into the record.
636 	 */
637 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN + content_len))
638 		goto err;
639 
640 	if (!CBB_add_u8(&cbb, content_type))
641 		goto err;
642 	if (!CBB_add_u16(&cbb, rl->legacy_version))
643 		goto err;
644 	if (!CBB_add_u16_length_prefixed(&cbb, &body))
645 		goto err;
646 	if (!CBB_add_bytes(&body, content, content_len))
647 		goto err;
648 
649 	if (!CBB_finish(&cbb, &data, &data_len))
650 		goto err;
651 
652 	if (!tls13_record_set_data(rl->wrec, data, data_len))
653 		goto err;
654 
655 	rl->wrec_content_len = content_len;
656 	rl->wrec_content_type = content_type;
657 
658 	return 1;
659 
660  err:
661 	CBB_cleanup(&cbb);
662 	freezero(data, data_len);
663 
664 	return 0;
665 }
666 
667 static int
668 tls13_record_layer_seal_record_protected(struct tls13_record_layer *rl,
669     uint8_t content_type, const uint8_t *content, size_t content_len)
670 {
671 	uint8_t *data = NULL, *header = NULL, *inner = NULL;
672 	size_t data_len = 0, header_len = 0, inner_len = 0;
673 	uint8_t *enc_record;
674 	size_t enc_record_len;
675 	ssize_t ret = 0;
676 	size_t out_len;
677 	CBB cbb;
678 
679 	if (rl->aead == NULL)
680 		return 0;
681 
682 	memset(&cbb, 0, sizeof(cbb));
683 
684 	/* Build inner plaintext. */
685 	if (!CBB_init(&cbb, content_len + 1))
686 		goto err;
687 	if (!CBB_add_bytes(&cbb, content, content_len))
688 		goto err;
689 	if (!CBB_add_u8(&cbb, content_type))
690 		goto err;
691 	/* XXX - padding? */
692 	if (!CBB_finish(&cbb, &inner, &inner_len))
693 		goto err;
694 
695 	if (inner_len > TLS13_RECORD_MAX_INNER_PLAINTEXT_LEN)
696 		goto err;
697 
698 	/* XXX EVP_AEAD_max_tag_len vs EVP_AEAD_CTX_tag_len. */
699 	enc_record_len = inner_len + EVP_AEAD_max_tag_len(rl->aead);
700 	if (enc_record_len > TLS13_RECORD_MAX_CIPHERTEXT_LEN)
701 		goto err;
702 
703 	/* Build the record header. */
704 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN))
705 		goto err;
706 	if (!CBB_add_u8(&cbb, SSL3_RT_APPLICATION_DATA))
707 		goto err;
708 	if (!CBB_add_u16(&cbb, TLS1_2_VERSION))
709 		goto err;
710 	if (!CBB_add_u16(&cbb, enc_record_len))
711 		goto err;
712 	if (!CBB_finish(&cbb, &header, &header_len))
713 		goto err;
714 
715 	/* Build the actual record. */
716 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN + enc_record_len))
717 		goto err;
718 	if (!CBB_add_bytes(&cbb, header, header_len))
719 		goto err;
720 	if (!CBB_add_space(&cbb, &enc_record, enc_record_len))
721 		goto err;
722 	if (!CBB_finish(&cbb, &data, &data_len))
723 		goto err;
724 
725 	if (!tls13_record_layer_update_nonce(&rl->write->nonce,
726 	    &rl->write->iv, rl->write->seq_num))
727 		goto err;
728 
729 	/*
730 	 * XXX - consider a EVP_AEAD_CTX_seal_iov() that takes an iovec...
731 	 * this would avoid a copy since the inner would be passed as two
732 	 * separate pieces.
733 	 */
734 	if (!EVP_AEAD_CTX_seal(rl->write->aead_ctx,
735 	    enc_record, &out_len, enc_record_len,
736 	    rl->write->nonce.data, rl->write->nonce.len,
737 	    inner, inner_len, header, header_len))
738 		goto err;
739 
740 	if (out_len != enc_record_len)
741 		goto err;
742 
743 	if (!tls13_record_layer_inc_seq_num(rl->write->seq_num))
744 		goto err;
745 
746 	if (!tls13_record_set_data(rl->wrec, data, data_len))
747 		goto err;
748 
749 	rl->wrec_content_len = content_len;
750 	rl->wrec_content_type = content_type;
751 
752 	data = NULL;
753 	data_len = 0;
754 
755 	ret = 1;
756 
757  err:
758 	CBB_cleanup(&cbb);
759 
760 	freezero(data, data_len);
761 	freezero(header, header_len);
762 	freezero(inner, inner_len);
763 
764 	return ret;
765 }
766 
767 static int
768 tls13_record_layer_seal_record(struct tls13_record_layer *rl,
769     uint8_t content_type, const uint8_t *content, size_t content_len)
770 {
771 	if (rl->handshake_completed && rl->aead == NULL)
772 		return 0;
773 
774 	tls13_record_layer_wrec_free(rl);
775 
776 	if ((rl->wrec = tls13_record_new()) == NULL)
777 		return 0;
778 
779 	if (rl->aead == NULL || content_type == SSL3_RT_CHANGE_CIPHER_SPEC)
780 		return tls13_record_layer_seal_record_plaintext(rl,
781 		    content_type, content, content_len);
782 
783 	return tls13_record_layer_seal_record_protected(rl, content_type,
784 	    content, content_len);
785 }
786 
787 static ssize_t
788 tls13_record_layer_read_record(struct tls13_record_layer *rl)
789 {
790 	uint8_t content_type, ccs;
791 	ssize_t ret;
792 	CBS cbs;
793 
794 	if (rl->rrec == NULL) {
795 		if ((rl->rrec = tls13_record_new()) == NULL)
796 			goto err;
797 	}
798 
799 	if ((ret = tls13_record_recv(rl->rrec, rl->cb.wire_read, rl->cb_arg)) <= 0) {
800 		switch (ret) {
801 		case TLS13_IO_RECORD_VERSION:
802 			return tls13_send_alert(rl, TLS13_ALERT_PROTOCOL_VERSION);
803 		case TLS13_IO_RECORD_OVERFLOW:
804 			return tls13_send_alert(rl, TLS13_ALERT_RECORD_OVERFLOW);
805 		}
806 		return ret;
807 	}
808 
809 	content_type = tls13_record_content_type(rl->rrec);
810 
811 	/*
812 	 * In response to a client hello we may receive an alert in a
813 	 * record with a legacy version. Otherwise enforce that the
814 	 * legacy record version is 0x0303 per RFC 8446, section 5.1.
815 	 */
816 	if (rl->legacy_version == TLS1_2_VERSION &&
817 	    tls13_record_version(rl->rrec) != TLS1_2_VERSION &&
818 	    (content_type != SSL3_RT_ALERT || !rl->legacy_alerts_allowed))
819 		return tls13_send_alert(rl, TLS13_ALERT_PROTOCOL_VERSION);
820 
821 	/*
822 	 * Bag of hacks ahead... after the first ClientHello message has been
823 	 * sent or received and before the peer's Finished message has been
824 	 * received, we may receive an unencrypted ChangeCipherSpec record
825 	 * (see RFC 8446 section 5 and appendix D.4). This record must be
826 	 * ignored.
827 	 */
828 	if (content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
829 		if (!rl->ccs_allowed || rl->ccs_seen >= 2)
830 			return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
831 		if (!tls13_record_content(rl->rrec, &cbs))
832 			return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
833 		if (!CBS_get_u8(&cbs, &ccs))
834 			return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
835 		if (ccs != 1)
836 			return tls13_send_alert(rl, TLS13_ALERT_ILLEGAL_PARAMETER);
837 		rl->ccs_seen++;
838 		tls13_record_layer_rrec_free(rl);
839 		return TLS13_IO_WANT_RETRY;
840 	}
841 
842 	/*
843 	 * Once record protection is engaged, we should only receive
844 	 * protected application data messages (aside from the
845 	 * dummy ChangeCipherSpec messages, handled above).
846 	 */
847 	if (rl->aead != NULL && content_type != SSL3_RT_APPLICATION_DATA)
848 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
849 
850 	if (!tls13_record_layer_open_record(rl))
851 		goto err;
852 
853 	tls13_record_layer_rrec_free(rl);
854 
855 	/*
856 	 * On receiving a handshake or alert record with empty inner plaintext,
857 	 * we must terminate the connection with an unexpected_message alert.
858 	 * See RFC 8446 section 5.4.
859 	 */
860 	if (tls_content_remaining(rl->rcontent) == 0 &&
861 	    (tls_content_type(rl->rcontent) == SSL3_RT_ALERT ||
862 	     tls_content_type(rl->rcontent) == SSL3_RT_HANDSHAKE))
863 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
864 
865 	switch (tls_content_type(rl->rcontent)) {
866 	case SSL3_RT_ALERT:
867 		return tls13_record_layer_process_alert(rl);
868 
869 	case SSL3_RT_HANDSHAKE:
870 		break;
871 
872 	case SSL3_RT_APPLICATION_DATA:
873 		if (!rl->handshake_completed)
874 			return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
875 		break;
876 
877 	default:
878 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
879 	}
880 
881 	return TLS13_IO_SUCCESS;
882 
883  err:
884 	return TLS13_IO_FAILURE;
885 }
886 
887 static ssize_t
888 tls13_record_layer_pending(struct tls13_record_layer *rl, uint8_t content_type)
889 {
890 	if (tls_content_type(rl->rcontent) != content_type)
891 		return 0;
892 
893 	return tls_content_remaining(rl->rcontent);
894 }
895 
896 static ssize_t
897 tls13_record_layer_recv_phh(struct tls13_record_layer *rl)
898 {
899 	ssize_t ret = TLS13_IO_FAILURE;
900 
901 	rl->phh = 1;
902 
903 	/*
904 	 * The post handshake handshake receive callback is allowed to return:
905 	 *
906 	 * TLS13_IO_WANT_POLLIN  need more handshake data.
907 	 * TLS13_IO_WANT_POLLOUT got whole handshake message, response enqueued.
908 	 * TLS13_IO_SUCCESS	 got the whole handshake, nothing more to do.
909 	 * TLS13_IO_FAILURE	 something broke.
910 	 */
911 	if (rl->cb.phh_recv != NULL)
912 		ret = rl->cb.phh_recv(rl->cb_arg);
913 
914 	tls_content_clear(rl->rcontent);
915 
916 	/* Leave post handshake handshake mode unless we need more data. */
917 	if (ret != TLS13_IO_WANT_POLLIN)
918 		rl->phh = 0;
919 
920 	if (ret == TLS13_IO_SUCCESS) {
921 		if (rl->phh_retry)
922 			return TLS13_IO_WANT_RETRY;
923 
924 		return TLS13_IO_WANT_POLLIN;
925 	}
926 
927 	return ret;
928 }
929 
930 static ssize_t
931 tls13_record_layer_read_internal(struct tls13_record_layer *rl,
932     uint8_t content_type, uint8_t *buf, size_t n, int peek)
933 {
934 	ssize_t ret;
935 
936 	if ((ret = tls13_record_layer_send_pending(rl)) != TLS13_IO_SUCCESS)
937 		return ret;
938 
939 	if (rl->read_closed)
940 		return TLS13_IO_EOF;
941 
942 	/* If necessary, pull up the next record. */
943 	if (tls_content_remaining(rl->rcontent) == 0) {
944 		if ((ret = tls13_record_layer_read_record(rl)) <= 0)
945 			return ret;
946 
947 		/*
948 		 * We may have read a valid 0-byte application data record,
949 		 * in which case we need to read the next record.
950 		 */
951 		if (tls_content_remaining(rl->rcontent) == 0)
952 			return TLS13_IO_WANT_POLLIN;
953 	}
954 
955 	/*
956 	 * If we are in post handshake handshake mode, we must not see
957 	 * any record type that isn't a handshake until we are done.
958 	 */
959 	if (rl->phh && tls_content_type(rl->rcontent) != SSL3_RT_HANDSHAKE)
960 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
961 
962 	/*
963 	 * Handshake content can appear as post-handshake messages (yup,
964 	 * the RFC reused the same content type...), which means we can
965 	 * be trying to read application data and need to handle a
966 	 * post-handshake handshake message instead...
967 	 */
968 	if (tls_content_type(rl->rcontent) != content_type) {
969 		if (tls_content_type(rl->rcontent) == SSL3_RT_HANDSHAKE) {
970 			if (rl->handshake_completed)
971 				return tls13_record_layer_recv_phh(rl);
972 		}
973 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
974 	}
975 
976 	if (peek)
977 		return tls_content_peek(rl->rcontent, buf, n);
978 
979 	return tls_content_read(rl->rcontent, buf, n);
980 }
981 
982 static ssize_t
983 tls13_record_layer_peek(struct tls13_record_layer *rl, uint8_t content_type,
984     uint8_t *buf, size_t n)
985 {
986 	ssize_t ret;
987 
988 	do {
989 		ret = tls13_record_layer_read_internal(rl, content_type, buf, n, 1);
990 	} while (ret == TLS13_IO_WANT_RETRY);
991 
992 	if (rl->alert != 0)
993 		return tls13_send_alert(rl, rl->alert);
994 
995 	return ret;
996 }
997 
998 static ssize_t
999 tls13_record_layer_read(struct tls13_record_layer *rl, uint8_t content_type,
1000     uint8_t *buf, size_t n)
1001 {
1002 	ssize_t ret;
1003 
1004 	do {
1005 		ret = tls13_record_layer_read_internal(rl, content_type, buf, n, 0);
1006 	} while (ret == TLS13_IO_WANT_RETRY);
1007 
1008 	if (rl->alert != 0)
1009 		return tls13_send_alert(rl, rl->alert);
1010 
1011 	return ret;
1012 }
1013 
1014 static ssize_t
1015 tls13_record_layer_write_record(struct tls13_record_layer *rl,
1016     uint8_t content_type, const uint8_t *content, size_t content_len)
1017 {
1018 	ssize_t ret;
1019 
1020 	if (rl->write_closed)
1021 		return TLS13_IO_EOF;
1022 
1023 	/*
1024 	 * If we pushed out application data while handling other messages,
1025 	 * we need to return content length on the next call.
1026 	 */
1027 	if (content_type == SSL3_RT_APPLICATION_DATA &&
1028 	    rl->wrec_appdata_len != 0) {
1029 		ret = rl->wrec_appdata_len;
1030 		rl->wrec_appdata_len = 0;
1031 		return ret;
1032 	}
1033 
1034 	/* See if there is an existing record and attempt to push it out... */
1035 	if (rl->wrec != NULL) {
1036 		if ((ret = tls13_record_send(rl->wrec, rl->cb.wire_write,
1037 		    rl->cb_arg)) <= 0)
1038 			return ret;
1039 		tls13_record_layer_wrec_free(rl);
1040 
1041 		if (rl->wrec_content_type == content_type) {
1042 			ret = rl->wrec_content_len;
1043 			rl->wrec_content_len = 0;
1044 			rl->wrec_content_type = 0;
1045 			return ret;
1046 		}
1047 
1048 		/*
1049 		 * The only partial record type should be application data.
1050 		 * All other cases are handled to completion.
1051 		 */
1052 		if (rl->wrec_content_type != SSL3_RT_APPLICATION_DATA)
1053 			return TLS13_IO_FAILURE;
1054 		rl->wrec_appdata_len = rl->wrec_content_len;
1055 	}
1056 
1057 	if (content_len > TLS13_RECORD_MAX_PLAINTEXT_LEN)
1058 		goto err;
1059 
1060 	if (!tls13_record_layer_seal_record(rl, content_type, content, content_len))
1061 		goto err;
1062 
1063 	if ((ret = tls13_record_send(rl->wrec, rl->cb.wire_write, rl->cb_arg)) <= 0)
1064 		return ret;
1065 
1066 	tls13_record_layer_wrec_free(rl);
1067 
1068 	return content_len;
1069 
1070  err:
1071 	return TLS13_IO_FAILURE;
1072 }
1073 
1074 static ssize_t
1075 tls13_record_layer_write_chunk(struct tls13_record_layer *rl,
1076     uint8_t content_type, const uint8_t *buf, size_t n)
1077 {
1078 	if (n > TLS13_RECORD_MAX_PLAINTEXT_LEN)
1079 		n = TLS13_RECORD_MAX_PLAINTEXT_LEN;
1080 
1081 	return tls13_record_layer_write_record(rl, content_type, buf, n);
1082 }
1083 
1084 static ssize_t
1085 tls13_record_layer_write(struct tls13_record_layer *rl, uint8_t content_type,
1086     const uint8_t *buf, size_t n)
1087 {
1088 	ssize_t ret;
1089 
1090 	do {
1091 		ret = tls13_record_layer_send_pending(rl);
1092 	} while (ret == TLS13_IO_WANT_RETRY);
1093 	if (ret != TLS13_IO_SUCCESS)
1094 		return ret;
1095 
1096 	do {
1097 		ret = tls13_record_layer_write_chunk(rl, content_type, buf, n);
1098 	} while (ret == TLS13_IO_WANT_RETRY);
1099 
1100 	return ret;
1101 }
1102 
1103 ssize_t
1104 tls13_record_layer_flush(struct tls13_record_layer *rl)
1105 {
1106 	return rl->cb.wire_flush(rl->cb_arg);
1107 }
1108 
1109 static const uint8_t tls13_dummy_ccs[] = { 0x01 };
1110 
1111 ssize_t
1112 tls13_send_dummy_ccs(struct tls13_record_layer *rl)
1113 {
1114 	ssize_t ret;
1115 
1116 	if (rl->ccs_sent)
1117 		return TLS13_IO_FAILURE;
1118 
1119 	if ((ret = tls13_record_layer_write(rl, SSL3_RT_CHANGE_CIPHER_SPEC,
1120 	    tls13_dummy_ccs, sizeof(tls13_dummy_ccs))) <= 0)
1121 		return ret;
1122 
1123 	rl->ccs_sent = 1;
1124 
1125 	return TLS13_IO_SUCCESS;
1126 }
1127 
1128 ssize_t
1129 tls13_read_handshake_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1130 {
1131 	return tls13_record_layer_read(rl, SSL3_RT_HANDSHAKE, buf, n);
1132 }
1133 
1134 ssize_t
1135 tls13_write_handshake_data(struct tls13_record_layer *rl, const uint8_t *buf,
1136     size_t n)
1137 {
1138 	return tls13_record_layer_write(rl, SSL3_RT_HANDSHAKE, buf, n);
1139 }
1140 
1141 ssize_t
1142 tls13_pending_application_data(struct tls13_record_layer *rl)
1143 {
1144 	if (!rl->handshake_completed)
1145 		return 0;
1146 
1147 	return tls13_record_layer_pending(rl, SSL3_RT_APPLICATION_DATA);
1148 }
1149 
1150 ssize_t
1151 tls13_peek_application_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1152 {
1153 	if (!rl->handshake_completed)
1154 		return TLS13_IO_FAILURE;
1155 
1156 	return tls13_record_layer_peek(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1157 }
1158 
1159 ssize_t
1160 tls13_read_application_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1161 {
1162 	if (!rl->handshake_completed)
1163 		return TLS13_IO_FAILURE;
1164 
1165 	return tls13_record_layer_read(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1166 }
1167 
1168 ssize_t
1169 tls13_write_application_data(struct tls13_record_layer *rl, const uint8_t *buf,
1170     size_t n)
1171 {
1172 	if (!rl->handshake_completed)
1173 		return TLS13_IO_FAILURE;
1174 
1175 	return tls13_record_layer_write(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1176 }
1177 
1178 ssize_t
1179 tls13_send_alert(struct tls13_record_layer *rl, uint8_t alert_desc)
1180 {
1181 	uint8_t alert_level = TLS13_ALERT_LEVEL_FATAL;
1182 	ssize_t ret;
1183 
1184 	if (alert_desc == TLS13_ALERT_CLOSE_NOTIFY ||
1185 	    alert_desc == TLS13_ALERT_USER_CANCELED)
1186 		alert_level = TLS13_ALERT_LEVEL_WARNING;
1187 
1188 	do {
1189 		ret = tls13_record_layer_enqueue_alert(rl, alert_level,
1190 		    alert_desc);
1191 	} while (ret == TLS13_IO_WANT_RETRY);
1192 
1193 	return ret;
1194 }
1195