xref: /openbsd-src/lib/libssl/tls13_record_layer.c (revision 824adb5411e4389b29bae28eba5c2c2bbd147f34)
1 /* $OpenBSD: tls13_record_layer.c,v 1.64 2021/09/16 19:25:30 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_cleanup(&rp->aead_ctx);
44 
45 	tls13_secret_cleanup(&rp->iv);
46 	tls13_secret_cleanup(&rp->nonce);
47 
48 	memset(rp->seq_num, 0, sizeof(rp->seq_num));
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 (!tls13_secret_init(&rp->iv, EVP_AEAD_nonce_length(aead)))
462 		goto err;
463 	if (!tls13_secret_init(&rp->nonce, EVP_AEAD_nonce_length(aead)))
464 		goto err;
465 	if (!tls13_secret_init(&key, EVP_AEAD_key_length(aead)))
466 		goto err;
467 
468 	if (!tls13_hkdf_expand_label(&rp->iv, hash, traffic_key, "iv", &context))
469 		goto err;
470 	if (!tls13_hkdf_expand_label(&key, hash, traffic_key, "key", &context))
471 		goto err;
472 
473 	if (!EVP_AEAD_CTX_init(&rp->aead_ctx, aead, key.data, key.len,
474 	    EVP_AEAD_DEFAULT_TAG_LENGTH, NULL))
475 		goto err;
476 
477 	ret = 1;
478 
479  err:
480 	tls13_secret_cleanup(&key);
481 
482 	return ret;
483 }
484 
485 int
486 tls13_record_layer_set_read_traffic_key(struct tls13_record_layer *rl,
487     struct tls13_secret *read_key)
488 {
489 	return tls13_record_layer_set_traffic_key(rl->aead, rl->hash,
490 	    rl->read, read_key);
491 }
492 
493 int
494 tls13_record_layer_set_write_traffic_key(struct tls13_record_layer *rl,
495     struct tls13_secret *write_key)
496 {
497 	return tls13_record_layer_set_traffic_key(rl->aead, rl->hash,
498 	    rl->write, write_key);
499 }
500 
501 static int
502 tls13_record_layer_open_record_plaintext(struct tls13_record_layer *rl)
503 {
504 	CBS cbs;
505 
506 	if (rl->aead != NULL)
507 		return 0;
508 
509 	/*
510 	 * We're still operating in plaintext mode, so just copy the
511 	 * content from the record to the plaintext buffer.
512 	 */
513 	if (!tls13_record_content(rl->rrec, &cbs))
514 		return 0;
515 
516 	if (CBS_len(&cbs) > TLS13_RECORD_MAX_PLAINTEXT_LEN) {
517 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
518 		return 0;
519 	}
520 
521 	if (!tls_content_dup_data(rl->rcontent,
522 	    tls13_record_content_type(rl->rrec), CBS_data(&cbs), CBS_len(&cbs)))
523 		return 0;
524 
525 	return 1;
526 }
527 
528 static int
529 tls13_record_layer_open_record_protected(struct tls13_record_layer *rl)
530 {
531 	CBS header, enc_record;
532 	ssize_t inner_len;
533 	uint8_t *content = NULL;
534 	size_t content_len = 0;
535 	uint8_t content_type;
536 	size_t out_len;
537 
538 	if (rl->aead == NULL)
539 		goto err;
540 
541 	if (!tls13_record_header(rl->rrec, &header))
542 		goto err;
543 	if (!tls13_record_content(rl->rrec, &enc_record))
544 		goto err;
545 
546 	if ((content = calloc(1, CBS_len(&enc_record))) == NULL)
547 		goto err;
548 	content_len = CBS_len(&enc_record);
549 
550 	if (!tls13_record_layer_update_nonce(&rl->read->nonce, &rl->read->iv,
551 	    rl->read->seq_num))
552 		goto err;
553 
554 	if (!EVP_AEAD_CTX_open(&rl->read->aead_ctx,
555 	    content, &out_len, content_len,
556 	    rl->read->nonce.data, rl->read->nonce.len,
557 	    CBS_data(&enc_record), CBS_len(&enc_record),
558 	    CBS_data(&header), CBS_len(&header)))
559 		goto err;
560 
561 	if (out_len > TLS13_RECORD_MAX_INNER_PLAINTEXT_LEN) {
562 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
563 		goto err;
564 	}
565 
566 	if (!tls13_record_layer_inc_seq_num(rl->read->seq_num))
567 		goto err;
568 
569 	/*
570 	 * The real content type is hidden at the end of the record content and
571 	 * it may be followed by padding that consists of one or more zeroes.
572 	 * Time to hunt for that elusive content type!
573 	 */
574 	/* XXX - CBS from end? CBS_get_end_u8()? */
575 	inner_len = out_len - 1;
576 	while (inner_len >= 0 && content[inner_len] == 0)
577 		inner_len--;
578 	if (inner_len < 0) {
579 		/* Unexpected message per RFC 8446 section 5.4. */
580 		rl->alert = TLS13_ALERT_UNEXPECTED_MESSAGE;
581 		goto err;
582 	}
583 	if (inner_len > TLS13_RECORD_MAX_PLAINTEXT_LEN) {
584 		rl->alert = TLS13_ALERT_RECORD_OVERFLOW;
585 		goto err;
586 	}
587 	content_type = content[inner_len];
588 
589 	tls_content_set_data(rl->rcontent, content_type, content, inner_len);
590 
591 	return 1;
592 
593  err:
594 	freezero(content, content_len);
595 
596 	return 0;
597 }
598 
599 static int
600 tls13_record_layer_open_record(struct tls13_record_layer *rl)
601 {
602 	if (rl->handshake_completed && rl->aead == NULL)
603 		return 0;
604 
605 	if (rl->aead == NULL)
606 		return tls13_record_layer_open_record_plaintext(rl);
607 
608 	return tls13_record_layer_open_record_protected(rl);
609 }
610 
611 static int
612 tls13_record_layer_seal_record_plaintext(struct tls13_record_layer *rl,
613     uint8_t content_type, const uint8_t *content, size_t content_len)
614 {
615 	uint8_t *data = NULL;
616 	size_t data_len = 0;
617 	CBB cbb, body;
618 
619 	/*
620 	 * Allow dummy CCS messages to be sent in plaintext even when
621 	 * record protection has been engaged, as long as the handshake
622 	 * has not yet completed.
623 	 */
624 	if (rl->handshake_completed)
625 		return 0;
626 	if (rl->aead != NULL && content_type != SSL3_RT_CHANGE_CIPHER_SPEC)
627 		return 0;
628 
629 	/*
630 	 * We're still operating in plaintext mode, so just copy the
631 	 * content into the record.
632 	 */
633 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN + content_len))
634 		goto err;
635 
636 	if (!CBB_add_u8(&cbb, content_type))
637 		goto err;
638 	if (!CBB_add_u16(&cbb, rl->legacy_version))
639 		goto err;
640 	if (!CBB_add_u16_length_prefixed(&cbb, &body))
641 		goto err;
642 	if (!CBB_add_bytes(&body, content, content_len))
643 		goto err;
644 
645 	if (!CBB_finish(&cbb, &data, &data_len))
646 		goto err;
647 
648 	if (!tls13_record_set_data(rl->wrec, data, data_len))
649 		goto err;
650 
651 	rl->wrec_content_len = content_len;
652 	rl->wrec_content_type = content_type;
653 
654 	return 1;
655 
656  err:
657 	CBB_cleanup(&cbb);
658 	freezero(data, data_len);
659 
660 	return 0;
661 }
662 
663 static int
664 tls13_record_layer_seal_record_protected(struct tls13_record_layer *rl,
665     uint8_t content_type, const uint8_t *content, size_t content_len)
666 {
667 	uint8_t *data = NULL, *header = NULL, *inner = NULL;
668 	size_t data_len = 0, header_len = 0, inner_len = 0;
669 	uint8_t *enc_record;
670 	size_t enc_record_len;
671 	ssize_t ret = 0;
672 	size_t out_len;
673 	CBB cbb;
674 
675 	if (rl->aead == NULL)
676 		return 0;
677 
678 	memset(&cbb, 0, sizeof(cbb));
679 
680 	/* Build inner plaintext. */
681 	if (!CBB_init(&cbb, content_len + 1))
682 		goto err;
683 	if (!CBB_add_bytes(&cbb, content, content_len))
684 		goto err;
685 	if (!CBB_add_u8(&cbb, content_type))
686 		goto err;
687 	/* XXX - padding? */
688 	if (!CBB_finish(&cbb, &inner, &inner_len))
689 		goto err;
690 
691 	if (inner_len > TLS13_RECORD_MAX_INNER_PLAINTEXT_LEN)
692 		goto err;
693 
694 	/* XXX EVP_AEAD_max_tag_len vs EVP_AEAD_CTX_tag_len. */
695 	enc_record_len = inner_len + EVP_AEAD_max_tag_len(rl->aead);
696 	if (enc_record_len > TLS13_RECORD_MAX_CIPHERTEXT_LEN)
697 		goto err;
698 
699 	/* Build the record header. */
700 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN))
701 		goto err;
702 	if (!CBB_add_u8(&cbb, SSL3_RT_APPLICATION_DATA))
703 		goto err;
704 	if (!CBB_add_u16(&cbb, TLS1_2_VERSION))
705 		goto err;
706 	if (!CBB_add_u16(&cbb, enc_record_len))
707 		goto err;
708 	if (!CBB_finish(&cbb, &header, &header_len))
709 		goto err;
710 
711 	/* Build the actual record. */
712 	if (!CBB_init(&cbb, TLS13_RECORD_HEADER_LEN + enc_record_len))
713 		goto err;
714 	if (!CBB_add_bytes(&cbb, header, header_len))
715 		goto err;
716 	if (!CBB_add_space(&cbb, &enc_record, enc_record_len))
717 		goto err;
718 	if (!CBB_finish(&cbb, &data, &data_len))
719 		goto err;
720 
721 	if (!tls13_record_layer_update_nonce(&rl->write->nonce,
722 	    &rl->write->iv, rl->write->seq_num))
723 		goto err;
724 
725 	/*
726 	 * XXX - consider a EVP_AEAD_CTX_seal_iov() that takes an iovec...
727 	 * this would avoid a copy since the inner would be passed as two
728 	 * separate pieces.
729 	 */
730 	if (!EVP_AEAD_CTX_seal(&rl->write->aead_ctx,
731 	    enc_record, &out_len, enc_record_len,
732 	    rl->write->nonce.data, rl->write->nonce.len,
733 	    inner, inner_len, header, header_len))
734 		goto err;
735 
736 	if (out_len != enc_record_len)
737 		goto err;
738 
739 	if (!tls13_record_layer_inc_seq_num(rl->write->seq_num))
740 		goto err;
741 
742 	if (!tls13_record_set_data(rl->wrec, data, data_len))
743 		goto err;
744 
745 	rl->wrec_content_len = content_len;
746 	rl->wrec_content_type = content_type;
747 
748 	data = NULL;
749 	data_len = 0;
750 
751 	ret = 1;
752 
753  err:
754 	CBB_cleanup(&cbb);
755 
756 	freezero(data, data_len);
757 	freezero(header, header_len);
758 	freezero(inner, inner_len);
759 
760 	return ret;
761 }
762 
763 static int
764 tls13_record_layer_seal_record(struct tls13_record_layer *rl,
765     uint8_t content_type, const uint8_t *content, size_t content_len)
766 {
767 	if (rl->handshake_completed && rl->aead == NULL)
768 		return 0;
769 
770 	tls13_record_layer_wrec_free(rl);
771 
772 	if ((rl->wrec = tls13_record_new()) == NULL)
773 		return 0;
774 
775 	if (rl->aead == NULL || content_type == SSL3_RT_CHANGE_CIPHER_SPEC)
776 		return tls13_record_layer_seal_record_plaintext(rl,
777 		    content_type, content, content_len);
778 
779 	return tls13_record_layer_seal_record_protected(rl, content_type,
780 	    content, content_len);
781 }
782 
783 static ssize_t
784 tls13_record_layer_read_record(struct tls13_record_layer *rl)
785 {
786 	uint8_t content_type, ccs;
787 	ssize_t ret;
788 	CBS cbs;
789 
790 	if (rl->rrec == NULL) {
791 		if ((rl->rrec = tls13_record_new()) == NULL)
792 			goto err;
793 	}
794 
795 	if ((ret = tls13_record_recv(rl->rrec, rl->cb.wire_read, rl->cb_arg)) <= 0) {
796 		switch (ret) {
797 		case TLS13_IO_RECORD_VERSION:
798 			return tls13_send_alert(rl, TLS13_ALERT_PROTOCOL_VERSION);
799 		case TLS13_IO_RECORD_OVERFLOW:
800 			return tls13_send_alert(rl, TLS13_ALERT_RECORD_OVERFLOW);
801 		}
802 		return ret;
803 	}
804 
805 	content_type = tls13_record_content_type(rl->rrec);
806 
807 	/*
808 	 * In response to a client hello we may receive an alert in a
809 	 * record with a legacy version. Otherwise enforce that the
810 	 * legacy record version is 0x0303 per RFC 8446, section 5.1.
811 	 */
812 	if (rl->legacy_version == TLS1_2_VERSION &&
813 	    tls13_record_version(rl->rrec) != TLS1_2_VERSION &&
814 	    (content_type != SSL3_RT_ALERT || !rl->legacy_alerts_allowed))
815 		return tls13_send_alert(rl, TLS13_ALERT_PROTOCOL_VERSION);
816 
817 	/*
818 	 * Bag of hacks ahead... after the first ClientHello message has been
819 	 * sent or received and before the peer's Finished message has been
820 	 * received, we may receive an unencrypted ChangeCipherSpec record
821 	 * (see RFC 8446 section 5 and appendix D.4). This record must be
822 	 * ignored.
823 	 */
824 	if (content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
825 		if (!rl->ccs_allowed || rl->ccs_seen >= 2)
826 			return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
827 		if (!tls13_record_content(rl->rrec, &cbs))
828 			return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
829 		if (!CBS_get_u8(&cbs, &ccs))
830 			return tls13_send_alert(rl, TLS13_ALERT_DECODE_ERROR);
831 		if (ccs != 1)
832 			return tls13_send_alert(rl, TLS13_ALERT_ILLEGAL_PARAMETER);
833 		rl->ccs_seen++;
834 		tls13_record_layer_rrec_free(rl);
835 		return TLS13_IO_WANT_RETRY;
836 	}
837 
838 	/*
839 	 * Once record protection is engaged, we should only receive
840 	 * protected application data messages (aside from the
841 	 * dummy ChangeCipherSpec messages, handled above).
842 	 */
843 	if (rl->aead != NULL && content_type != SSL3_RT_APPLICATION_DATA)
844 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
845 
846 	if (!tls13_record_layer_open_record(rl))
847 		goto err;
848 
849 	tls13_record_layer_rrec_free(rl);
850 
851 	/*
852 	 * On receiving a handshake or alert record with empty inner plaintext,
853 	 * we must terminate the connection with an unexpected_message alert.
854 	 * See RFC 8446 section 5.4.
855 	 */
856 	if (tls_content_remaining(rl->rcontent) == 0 &&
857 	    (tls_content_type(rl->rcontent) == SSL3_RT_ALERT ||
858 	     tls_content_type(rl->rcontent) == SSL3_RT_HANDSHAKE))
859 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
860 
861 	switch (tls_content_type(rl->rcontent)) {
862 	case SSL3_RT_ALERT:
863 		return tls13_record_layer_process_alert(rl);
864 
865 	case SSL3_RT_HANDSHAKE:
866 		break;
867 
868 	case SSL3_RT_APPLICATION_DATA:
869 		if (!rl->handshake_completed)
870 			return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
871 		break;
872 
873 	default:
874 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
875 	}
876 
877 	return TLS13_IO_SUCCESS;
878 
879  err:
880 	return TLS13_IO_FAILURE;
881 }
882 
883 static ssize_t
884 tls13_record_layer_pending(struct tls13_record_layer *rl, uint8_t content_type)
885 {
886 	if (tls_content_type(rl->rcontent) != content_type)
887 		return 0;
888 
889 	return tls_content_remaining(rl->rcontent);
890 }
891 
892 static ssize_t
893 tls13_record_layer_recv_phh(struct tls13_record_layer *rl)
894 {
895 	ssize_t ret = TLS13_IO_FAILURE;
896 
897 	rl->phh = 1;
898 
899 	/*
900 	 * The post handshake handshake receive callback is allowed to return:
901 	 *
902 	 * TLS13_IO_WANT_POLLIN  need more handshake data.
903 	 * TLS13_IO_WANT_POLLOUT got whole handshake message, response enqueued.
904 	 * TLS13_IO_SUCCESS	 got the whole handshake, nothing more to do.
905 	 * TLS13_IO_FAILURE	 something broke.
906 	 */
907 	if (rl->cb.phh_recv != NULL)
908 		ret = rl->cb.phh_recv(rl->cb_arg, tls_content_cbs(rl->rcontent));
909 
910 	tls_content_clear(rl->rcontent);
911 
912 	/* Leave post handshake handshake mode unless we need more data. */
913 	if (ret != TLS13_IO_WANT_POLLIN)
914 		rl->phh = 0;
915 
916 	if (ret == TLS13_IO_SUCCESS) {
917 		if (rl->phh_retry)
918 			return TLS13_IO_WANT_RETRY;
919 
920 		return TLS13_IO_WANT_POLLIN;
921 	}
922 
923 	return ret;
924 }
925 
926 static ssize_t
927 tls13_record_layer_read_internal(struct tls13_record_layer *rl,
928     uint8_t content_type, uint8_t *buf, size_t n, int peek)
929 {
930 	ssize_t ret;
931 
932 	if ((ret = tls13_record_layer_send_pending(rl)) != TLS13_IO_SUCCESS)
933 		return ret;
934 
935 	if (rl->read_closed)
936 		return TLS13_IO_EOF;
937 
938 	/* If necessary, pull up the next record. */
939 	if (tls_content_remaining(rl->rcontent) == 0) {
940 		if ((ret = tls13_record_layer_read_record(rl)) <= 0)
941 			return ret;
942 
943 		/*
944 		 * We may have read a valid 0-byte application data record,
945 		 * in which case we need to read the next record.
946 		 */
947 		if (tls_content_remaining(rl->rcontent) == 0)
948 			return TLS13_IO_WANT_POLLIN;
949 	}
950 
951 	/*
952 	 * If we are in post handshake handshake mode, we must not see
953 	 * any record type that isn't a handshake until we are done.
954 	 */
955 	if (rl->phh && tls_content_type(rl->rcontent) != SSL3_RT_HANDSHAKE)
956 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
957 
958 	/*
959 	 * Handshake content can appear as post-handshake messages (yup,
960 	 * the RFC reused the same content type...), which means we can
961 	 * be trying to read application data and need to handle a
962 	 * post-handshake handshake message instead...
963 	 */
964 	if (tls_content_type(rl->rcontent) != content_type) {
965 		if (tls_content_type(rl->rcontent) == SSL3_RT_HANDSHAKE) {
966 			if (rl->handshake_completed)
967 				return tls13_record_layer_recv_phh(rl);
968 		}
969 		return tls13_send_alert(rl, TLS13_ALERT_UNEXPECTED_MESSAGE);
970 	}
971 
972 	if (peek)
973 		return tls_content_peek(rl->rcontent, buf, n);
974 
975 	return tls_content_read(rl->rcontent, buf, n);
976 }
977 
978 static ssize_t
979 tls13_record_layer_peek(struct tls13_record_layer *rl, uint8_t content_type,
980     uint8_t *buf, size_t n)
981 {
982 	ssize_t ret;
983 
984 	do {
985 		ret = tls13_record_layer_read_internal(rl, content_type, buf, n, 1);
986 	} while (ret == TLS13_IO_WANT_RETRY);
987 
988 	if (rl->alert != 0)
989 		return tls13_send_alert(rl, rl->alert);
990 
991 	return ret;
992 }
993 
994 static ssize_t
995 tls13_record_layer_read(struct tls13_record_layer *rl, uint8_t content_type,
996     uint8_t *buf, size_t n)
997 {
998 	ssize_t ret;
999 
1000 	do {
1001 		ret = tls13_record_layer_read_internal(rl, content_type, buf, n, 0);
1002 	} while (ret == TLS13_IO_WANT_RETRY);
1003 
1004 	if (rl->alert != 0)
1005 		return tls13_send_alert(rl, rl->alert);
1006 
1007 	return ret;
1008 }
1009 
1010 static ssize_t
1011 tls13_record_layer_write_record(struct tls13_record_layer *rl,
1012     uint8_t content_type, const uint8_t *content, size_t content_len)
1013 {
1014 	ssize_t ret;
1015 
1016 	if (rl->write_closed)
1017 		return TLS13_IO_EOF;
1018 
1019 	/*
1020 	 * If we pushed out application data while handling other messages,
1021 	 * we need to return content length on the next call.
1022 	 */
1023 	if (content_type == SSL3_RT_APPLICATION_DATA &&
1024 	    rl->wrec_appdata_len != 0) {
1025 		ret = rl->wrec_appdata_len;
1026 		rl->wrec_appdata_len = 0;
1027 		return ret;
1028 	}
1029 
1030 	/* See if there is an existing record and attempt to push it out... */
1031 	if (rl->wrec != NULL) {
1032 		if ((ret = tls13_record_send(rl->wrec, rl->cb.wire_write,
1033 		    rl->cb_arg)) <= 0)
1034 			return ret;
1035 		tls13_record_layer_wrec_free(rl);
1036 
1037 		if (rl->wrec_content_type == content_type) {
1038 			ret = rl->wrec_content_len;
1039 			rl->wrec_content_len = 0;
1040 			rl->wrec_content_type = 0;
1041 			return ret;
1042 		}
1043 
1044 		/*
1045 		 * The only partial record type should be application data.
1046 		 * All other cases are handled to completion.
1047 		 */
1048 		if (rl->wrec_content_type != SSL3_RT_APPLICATION_DATA)
1049 			return TLS13_IO_FAILURE;
1050 		rl->wrec_appdata_len = rl->wrec_content_len;
1051 	}
1052 
1053 	if (content_len > TLS13_RECORD_MAX_PLAINTEXT_LEN)
1054 		goto err;
1055 
1056 	if (!tls13_record_layer_seal_record(rl, content_type, content, content_len))
1057 		goto err;
1058 
1059 	if ((ret = tls13_record_send(rl->wrec, rl->cb.wire_write, rl->cb_arg)) <= 0)
1060 		return ret;
1061 
1062 	tls13_record_layer_wrec_free(rl);
1063 
1064 	return content_len;
1065 
1066  err:
1067 	return TLS13_IO_FAILURE;
1068 }
1069 
1070 static ssize_t
1071 tls13_record_layer_write_chunk(struct tls13_record_layer *rl,
1072     uint8_t content_type, const uint8_t *buf, size_t n)
1073 {
1074 	if (n > TLS13_RECORD_MAX_PLAINTEXT_LEN)
1075 		n = TLS13_RECORD_MAX_PLAINTEXT_LEN;
1076 
1077 	return tls13_record_layer_write_record(rl, content_type, buf, n);
1078 }
1079 
1080 static ssize_t
1081 tls13_record_layer_write(struct tls13_record_layer *rl, uint8_t content_type,
1082     const uint8_t *buf, size_t n)
1083 {
1084 	ssize_t ret;
1085 
1086 	do {
1087 		ret = tls13_record_layer_send_pending(rl);
1088 	} while (ret == TLS13_IO_WANT_RETRY);
1089 	if (ret != TLS13_IO_SUCCESS)
1090 		return ret;
1091 
1092 	do {
1093 		ret = tls13_record_layer_write_chunk(rl, content_type, buf, n);
1094 	} while (ret == TLS13_IO_WANT_RETRY);
1095 
1096 	return ret;
1097 }
1098 
1099 ssize_t
1100 tls13_record_layer_flush(struct tls13_record_layer *rl)
1101 {
1102 	return rl->cb.wire_flush(rl->cb_arg);
1103 }
1104 
1105 static const uint8_t tls13_dummy_ccs[] = { 0x01 };
1106 
1107 ssize_t
1108 tls13_send_dummy_ccs(struct tls13_record_layer *rl)
1109 {
1110 	ssize_t ret;
1111 
1112 	if (rl->ccs_sent)
1113 		return TLS13_IO_FAILURE;
1114 
1115 	if ((ret = tls13_record_layer_write(rl, SSL3_RT_CHANGE_CIPHER_SPEC,
1116 	    tls13_dummy_ccs, sizeof(tls13_dummy_ccs))) <= 0)
1117 		return ret;
1118 
1119 	rl->ccs_sent = 1;
1120 
1121 	return TLS13_IO_SUCCESS;
1122 }
1123 
1124 ssize_t
1125 tls13_read_handshake_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1126 {
1127 	return tls13_record_layer_read(rl, SSL3_RT_HANDSHAKE, buf, n);
1128 }
1129 
1130 ssize_t
1131 tls13_write_handshake_data(struct tls13_record_layer *rl, const uint8_t *buf,
1132     size_t n)
1133 {
1134 	return tls13_record_layer_write(rl, SSL3_RT_HANDSHAKE, buf, n);
1135 }
1136 
1137 ssize_t
1138 tls13_pending_application_data(struct tls13_record_layer *rl)
1139 {
1140 	if (!rl->handshake_completed)
1141 		return 0;
1142 
1143 	return tls13_record_layer_pending(rl, SSL3_RT_APPLICATION_DATA);
1144 }
1145 
1146 ssize_t
1147 tls13_peek_application_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1148 {
1149 	if (!rl->handshake_completed)
1150 		return TLS13_IO_FAILURE;
1151 
1152 	return tls13_record_layer_peek(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1153 }
1154 
1155 ssize_t
1156 tls13_read_application_data(struct tls13_record_layer *rl, uint8_t *buf, size_t n)
1157 {
1158 	if (!rl->handshake_completed)
1159 		return TLS13_IO_FAILURE;
1160 
1161 	return tls13_record_layer_read(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1162 }
1163 
1164 ssize_t
1165 tls13_write_application_data(struct tls13_record_layer *rl, const uint8_t *buf,
1166     size_t n)
1167 {
1168 	if (!rl->handshake_completed)
1169 		return TLS13_IO_FAILURE;
1170 
1171 	return tls13_record_layer_write(rl, SSL3_RT_APPLICATION_DATA, buf, n);
1172 }
1173 
1174 ssize_t
1175 tls13_send_alert(struct tls13_record_layer *rl, uint8_t alert_desc)
1176 {
1177 	uint8_t alert_level = TLS13_ALERT_LEVEL_FATAL;
1178 	ssize_t ret;
1179 
1180 	if (alert_desc == TLS13_ALERT_CLOSE_NOTIFY ||
1181 	    alert_desc == TLS13_ALERT_USER_CANCELED)
1182 		alert_level = TLS13_ALERT_LEVEL_WARNING;
1183 
1184 	do {
1185 		ret = tls13_record_layer_enqueue_alert(rl, alert_level,
1186 		    alert_desc);
1187 	} while (ret == TLS13_IO_WANT_RETRY);
1188 
1189 	return ret;
1190 }
1191