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