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