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