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