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