noxtls 0.2.12

TLS/DTLS protocol and connection state machine for the noxtls Rust stack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Copyright (c) 2019-2026, Argenox Technologies LLC
// All rights reserved.
//
// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
//
// This file is part of the NoxTLS Library.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation; version 2 of the License.
//
// Alternatively, this file may be used under the terms of a commercial
// license from Argenox Technologies LLC.
//
// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
// CONTACT: info@argenox.com

//! TLS 1.3 server-direction record seal/open helpers (server writes, client reads).

use super::*;

impl Connection {
    /// Seals outbound application or handshake data using installed server traffic keys.
    ///
    /// # Arguments
    ///
    /// * `plaintext` — Bytes to encrypt and authenticate.
    /// * `aad` — Additional authenticated data bound to the AEAD operation.
    ///
    /// # Returns
    ///
    /// On success, a [`ProtectedRecord`] sealed with the server write key and IV.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when handshake state, suite, or key material is invalid.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_seal_server_record(
        &mut self,
        plaintext: &[u8],
        aad: &[u8],
    ) -> Result<ProtectedRecord> {
        let handshake_seal_allowed = self.version.uses_tls13_handshake_semantics()
            && self.tls_role == TlsRole::Server
            && self.state == HandshakeState::KeysDerived;
        if self.state != HandshakeState::Finished && !handshake_seal_allowed {
            return Err(Error::StateError(
                "cannot seal server record before handshake completion or tls13 server handshake flight",
            ));
        }
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        if self.server_sequence == u64::MAX {
            return Err(Error::StateError("server record sequence exhausted"));
        }
        let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
            "cipher suite must be selected before sealing server records",
        ))?;
        let key = self
            .server_write_key
            .ok_or(Error::StateError("server write key is not installed"))?;
        let iv = self
            .server_write_iv
            .ok_or(Error::StateError("server write iv is not installed"))?;
        let nonce = noxtls_build_record_nonce(&iv, self.server_sequence);
        let (ciphertext, tag) =
            Self::noxtls_aead_encrypt_for_suite(suite, &key, &nonce, aad, plaintext)?;
        let record = ProtectedRecord {
            sequence: self.server_sequence,
            ciphertext,
            tag,
        };
        self.server_sequence = self.server_sequence.wrapping_add(1);
        Ok(record)
    }

    /// Opens inbound data sealed by the TLS peer using installed client traffic keys.
    ///
    /// # Arguments
    ///
    /// * `record` — Protected record received from the client.
    /// * `aad` — Additional authenticated data used when the peer sealed the record.
    ///
    /// # Returns
    ///
    /// On success, decrypted plaintext bytes.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] on authentication failure, sequence mismatch, or invalid state.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_open_client_record(
        &mut self,
        record: &ProtectedRecord,
        aad: &[u8],
    ) -> Result<Vec<u8>> {
        let tls13_handshake_open_allowed = self.version.uses_tls13_handshake_semantics()
            && self.tls_role == TlsRole::Server
            && self.state == HandshakeState::KeysDerived;
        if self.state != HandshakeState::Finished && !tls13_handshake_open_allowed {
            return Err(Error::StateError(
                "cannot open client record before handshake completion or tls13 server handshake flight",
            ));
        }
        if self.client_sequence == u64::MAX {
            return Err(Error::StateError("client record sequence exhausted"));
        }
        if record.sequence != self.client_sequence {
            return Err(Error::StateError(
                "unexpected client record sequence number",
            ));
        }
        let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
            "cipher suite must be selected before opening client records",
        ))?;
        let key = self
            .client_write_key
            .ok_or(Error::StateError("client write key is not installed"))?;
        let iv = self
            .client_write_iv
            .ok_or(Error::StateError("client write iv is not installed"))?;
        let nonce = noxtls_build_record_nonce(&iv, record.sequence);
        let plaintext = Self::noxtls_aead_decrypt_for_suite(
            suite,
            &key,
            &nonce,
            aad,
            &record.ciphertext,
            &record.tag,
        )?;
        let plaintext_limit = if self.version.uses_tls13_handshake_semantics() {
            self.max_record_plaintext_len.saturating_add(1)
        } else {
            self.max_record_plaintext_len
        };
        if plaintext.len() > plaintext_limit {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        self.client_sequence = self.client_sequence.wrapping_add(1);
        Ok(plaintext)
    }

    /// Opens one TLS 1.2 record sent by the client using client write keys.
    pub fn noxtls_open_client_tls12_record_packet(
        &mut self,
        packet: &[u8],
    ) -> Result<(RecordContentType, Vec<u8>)> {
        self.noxtls_ensure_tls12_wire_mode()?;
        let sequence = self.client_sequence;
        let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
            "cipher suite must be selected before opening client tls12 record packet",
        ))?;
        if suite.noxtls_tls12_cbc_key_len().is_some() {
            return self.noxtls_open_client_tls12_cbc_record_packet(packet, sequence, suite);
        }
        if suite.noxtls_tls12_chacha20_poly1305_key_len().is_some() {
            return self
                .noxtls_open_client_tls12_chacha20_poly1305_record_packet(packet, sequence, suite);
        }
        let (record, content_type, explicit_nonce) =
            self.noxtls_decode_tls12_record_packet(packet, sequence)?;
        let key = self
            .client_write_key
            .ok_or(Error::StateError("client write key is not installed"))?;
        let iv = self
            .client_write_iv
            .ok_or(Error::StateError("client write iv is not installed"))?;
        let nonce = Self::noxtls_build_tls12_aead_nonce(&iv, &explicit_nonce);
        let aad =
            self.noxtls_build_tls12_record_aad(sequence, content_type, record.ciphertext.len())?;
        let plaintext = Self::noxtls_aead_decrypt_for_suite(
            suite,
            &key,
            &nonce,
            &aad,
            &record.ciphertext,
            &record.tag,
        )?;
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        self.client_sequence = self.client_sequence.wrapping_add(1);
        Ok((content_type, plaintext))
    }

    /// Seals one TLS 1.2 record from the server using server write keys.
    pub fn noxtls_seal_server_tls12_record_packet(
        &mut self,
        plaintext: &[u8],
        content_type: RecordContentType,
    ) -> Result<Vec<u8>> {
        self.noxtls_ensure_tls12_wire_mode()?;
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        if self.server_sequence == u64::MAX {
            return Err(Error::StateError("server record sequence exhausted"));
        }
        let sequence = self.server_sequence;
        let suite = self.noxtls_selected_cipher_suite.ok_or(Error::StateError(
            "cipher suite must be selected before sealing server tls12 record packet",
        ))?;
        if suite.noxtls_tls12_cbc_key_len().is_some() {
            return self.noxtls_seal_server_tls12_cbc_record_packet(
                plaintext,
                content_type,
                sequence,
                suite,
            );
        }
        if suite.noxtls_tls12_chacha20_poly1305_key_len().is_some() {
            return self.noxtls_seal_server_tls12_chacha20_poly1305_record_packet(
                plaintext,
                content_type,
                sequence,
                suite,
            );
        }
        let key = self
            .server_write_key
            .ok_or(Error::StateError("server write key is not installed"))?;
        let iv = self
            .server_write_iv
            .ok_or(Error::StateError("server write iv is not installed"))?;
        let explicit_nonce = sequence.to_be_bytes();
        let nonce = Self::noxtls_build_tls12_aead_nonce(&iv, &explicit_nonce);
        let aad = self.noxtls_build_tls12_record_aad(sequence, content_type, plaintext.len())?;
        let (ciphertext, tag) =
            Self::noxtls_aead_encrypt_for_suite(suite, &key, &nonce, &aad, plaintext)?;
        let record = ProtectedRecord {
            sequence,
            ciphertext,
            tag,
        };
        self.server_sequence = self.server_sequence.wrapping_add(1);
        self.noxtls_encode_tls12_record_packet(&record, content_type, &explicit_nonce)
    }

    fn noxtls_open_client_tls12_cbc_record_packet(
        &mut self,
        packet: &[u8],
        sequence: u64,
        suite: CipherSuite,
    ) -> Result<(RecordContentType, Vec<u8>)> {
        let (content_type_u8, version, payload) = noxtls_decode_tls12_ciphertext_record(packet)?;
        let strict_version = noxtls_legacy_wire_version(self.version);
        let legacy_compat_ok = self.tls12_allow_legacy_record_versions
            && (version == [0x03, 0x01] || version == [0x03, 0x02]);
        if version != strict_version && !legacy_compat_ok {
            return Err(Error::ParseFailure(
                "tls12 record has invalid legacy version",
            ));
        }
        let content_type = RecordContentType::from_u8(content_type_u8)
            .ok_or(Error::ParseFailure("unknown tls12 record content type"))?;
        let key_len = suite.noxtls_tls12_cbc_key_len().ok_or(Error::StateError(
            "tls 1.2 cbc suite must define traffic key length",
        ))?;
        if payload.len() < 32 || (payload.len() - 16) % 16 != 0 {
            return Err(Error::ParseFailure("invalid tls12 cbc record length"));
        }
        let mut explicit_iv = [0_u8; 16];
        explicit_iv.copy_from_slice(&payload[..16]);
        let key = self
            .client_write_key
            .ok_or(Error::StateError("client write key is not installed"))?;
        let mac_key = self
            .tls12_client_write_mac_key
            .ok_or(Error::StateError("client write mac key is not installed"))?;
        let cipher = AesCipher::noxtls_new(&key[..key_len])?;
        let plaintext_mac_padding = noxtls_aes_cbc_decrypt(&cipher, &explicit_iv, &payload[16..])?;
        let Some(&padding_len_u8) = plaintext_mac_padding.last() else {
            return Err(Error::CryptoFailure("tls12 cbc record missing padding"));
        };
        let padding_total = usize::from(padding_len_u8) + 1;
        if padding_total > plaintext_mac_padding.len() {
            return Err(Error::CryptoFailure("tls12 cbc padding exceeds plaintext"));
        }
        let padding_start = plaintext_mac_padding.len() - padding_total;
        if plaintext_mac_padding[padding_start..]
            .iter()
            .any(|byte| *byte != padding_len_u8)
        {
            return Err(Error::CryptoFailure("invalid tls12 cbc padding"));
        }
        if padding_start < 20 {
            return Err(Error::CryptoFailure("tls12 cbc record missing mac"));
        }
        let mac_start = padding_start - 20;
        let plaintext = &plaintext_mac_padding[..mac_start];
        let received_mac = &plaintext_mac_padding[mac_start..padding_start];
        let expected_mac =
            Self::noxtls_tls12_cbc_hmac_sha1(&mac_key, sequence, content_type, plaintext)?;
        if !noxtls_constant_time_eq(received_mac, &expected_mac) {
            return Err(Error::CryptoFailure("tls12 cbc record mac mismatch"));
        }
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        self.client_sequence = self.client_sequence.wrapping_add(1);
        Ok((content_type, plaintext.to_vec()))
    }

    fn noxtls_seal_server_tls12_cbc_record_packet(
        &mut self,
        plaintext: &[u8],
        content_type: RecordContentType,
        sequence: u64,
        suite: CipherSuite,
    ) -> Result<Vec<u8>> {
        let key_len = suite.noxtls_tls12_cbc_key_len().ok_or(Error::StateError(
            "tls 1.2 cbc suite must define traffic key length",
        ))?;
        let key = self
            .server_write_key
            .ok_or(Error::StateError("server write key is not installed"))?;
        let mac_key = self
            .tls12_server_write_mac_key
            .ok_or(Error::StateError("server write mac key is not installed"))?;
        let mut explicit_iv = [0_u8; 16];
        explicit_iv[..8].copy_from_slice(&sequence.to_be_bytes());
        explicit_iv[8..].copy_from_slice(&(!sequence).to_be_bytes());
        let mac = Self::noxtls_tls12_cbc_hmac_sha1(&mac_key, sequence, content_type, plaintext)?;
        let mut plain = Vec::with_capacity(plaintext.len() + mac.len() + 16);
        plain.extend_from_slice(plaintext);
        plain.extend_from_slice(&mac);
        let padding_len = 15 - (plain.len() % 16);
        plain.extend(core::iter::repeat(padding_len as u8).take(padding_len + 1));
        let cipher = AesCipher::noxtls_new(&key[..key_len])?;
        let ciphertext = noxtls_aes_cbc_encrypt(&cipher, &explicit_iv, &plain)?;
        let mut payload = Vec::with_capacity(16 + ciphertext.len());
        payload.extend_from_slice(&explicit_iv);
        payload.extend_from_slice(&ciphertext);
        self.server_sequence = self.server_sequence.wrapping_add(1);
        noxtls_encode_tls12_ciphertext_record(
            content_type.to_u8(),
            noxtls_legacy_wire_version(self.version),
            &payload,
        )
    }

    fn noxtls_tls12_cbc_hmac_sha1(
        mac_key: &[u8; 20],
        sequence: u64,
        content_type: RecordContentType,
        plaintext: &[u8],
    ) -> Result<[u8; 20]> {
        if plaintext.len() > usize::from(u16::MAX) {
            return Err(Error::InvalidLength(
                "tls12 cbc plaintext length exceeds u16",
            ));
        }
        let mut mac_input = Vec::with_capacity(13 + plaintext.len());
        mac_input.extend_from_slice(&sequence.to_be_bytes());
        mac_input.push(content_type.to_u8());
        mac_input.extend_from_slice(&[0x03, 0x03]);
        mac_input.extend_from_slice(&(plaintext.len() as u16).to_be_bytes());
        mac_input.extend_from_slice(plaintext);
        Ok(noxtls_hmac_sha1(mac_key, &mac_input))
    }

    fn noxtls_open_client_tls12_chacha20_poly1305_record_packet(
        &mut self,
        packet: &[u8],
        sequence: u64,
        suite: CipherSuite,
    ) -> Result<(RecordContentType, Vec<u8>)> {
        let (content_type_u8, version, payload) = noxtls_decode_tls12_ciphertext_record(packet)?;
        let strict_version = noxtls_legacy_wire_version(self.version);
        let legacy_compat_ok = self.tls12_allow_legacy_record_versions
            && (version == [0x03, 0x01] || version == [0x03, 0x02]);
        if version != strict_version && !legacy_compat_ok {
            return Err(Error::ParseFailure(
                "tls12 record has invalid legacy version",
            ));
        }
        let content_type = RecordContentType::from_u8(content_type_u8)
            .ok_or(Error::ParseFailure("unknown tls12 record content type"))?;
        suite
            .noxtls_tls12_chacha20_poly1305_key_len()
            .ok_or(Error::StateError(
                "tls 1.2 chacha20 suite must define traffic key length",
            ))?;
        if payload.len() < 16 {
            return Err(Error::ParseFailure(
                "tls12 chacha20-poly1305 record payload too short",
            ));
        }
        let tag_offset = payload.len() - 16;
        let ciphertext = &payload[..tag_offset];
        let mut tag = [0_u8; 16];
        tag.copy_from_slice(&payload[tag_offset..]);
        let key = self
            .client_write_key
            .ok_or(Error::StateError("client write key is not installed"))?;
        let iv = self
            .client_write_iv
            .ok_or(Error::StateError("client write iv is not installed"))?;
        let nonce = Self::noxtls_build_tls12_chacha20_poly1305_nonce(&iv, sequence);
        let aad = self.noxtls_build_tls12_record_aad(sequence, content_type, ciphertext.len())?;
        let plaintext = noxtls_chacha20_poly1305_decrypt(&key, &nonce, &aad, ciphertext, &tag)?;
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        self.client_sequence = self.client_sequence.wrapping_add(1);
        Ok((content_type, plaintext))
    }

    fn noxtls_seal_server_tls12_chacha20_poly1305_record_packet(
        &mut self,
        plaintext: &[u8],
        content_type: RecordContentType,
        sequence: u64,
        suite: CipherSuite,
    ) -> Result<Vec<u8>> {
        suite
            .noxtls_tls12_chacha20_poly1305_key_len()
            .ok_or(Error::StateError(
                "tls 1.2 chacha20 suite must define traffic key length",
            ))?;
        let key = self
            .server_write_key
            .ok_or(Error::StateError("server write key is not installed"))?;
        let iv = self
            .server_write_iv
            .ok_or(Error::StateError("server write iv is not installed"))?;
        let nonce = Self::noxtls_build_tls12_chacha20_poly1305_nonce(&iv, sequence);
        let aad = self.noxtls_build_tls12_record_aad(sequence, content_type, plaintext.len())?;
        let (ciphertext, tag) = noxtls_chacha20_poly1305_encrypt(&key, &nonce, &aad, plaintext)?;
        let mut payload = Vec::with_capacity(ciphertext.len() + tag.len());
        payload.extend_from_slice(&ciphertext);
        payload.extend_from_slice(&tag);
        self.server_sequence = self.server_sequence.wrapping_add(1);
        noxtls_encode_tls12_ciphertext_record(
            content_type.to_u8(),
            noxtls_legacy_wire_version(self.version),
            &payload,
        )
    }

    pub(super) fn noxtls_build_tls12_chacha20_poly1305_nonce(
        fixed_iv: &[u8; 12],
        sequence: u64,
    ) -> [u8; 12] {
        let mut padded_sequence = [0_u8; 12];
        padded_sequence[4..].copy_from_slice(&sequence.to_be_bytes());
        let mut nonce = [0_u8; 12];
        for i in 0..12 {
            nonce[i] = fixed_iv[i] ^ padded_sequence[i];
        }
        nonce
    }

    /// Seals one TLS 1.3 inner record using server traffic keys.
    ///
    /// # Arguments
    ///
    /// * `content` — Inner plaintext content bytes.
    /// * `content_type` — TLSInnerPlaintext content type byte.
    /// * `aad` — Record header bytes used as AEAD additional data.
    /// * `padding_len` — Number of trailing zero padding bytes.
    ///
    /// # Returns
    ///
    /// On success, a protected record using the server write key.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when called outside TLS 1.3 or when seal preconditions fail.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_seal_server_tls13_inner_record(
        &mut self,
        content: &[u8],
        content_type: u8,
        aad: &[u8],
        padding_len: usize,
    ) -> Result<ProtectedRecord> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 inner plaintext records require TLS 1.3 connection",
            ));
        }
        let inner = noxtls_encode_tls13_inner_plaintext(content, content_type, padding_len);
        self.noxtls_seal_server_record(&inner, aad)
    }

    /// Opens one TLS 1.3 inner record sealed by the client and decodes TLSInnerPlaintext.
    ///
    /// # Arguments
    ///
    /// * `record` — Protected record received from the client.
    /// * `aad` — Record header bytes used as AEAD additional data.
    ///
    /// # Returns
    ///
    /// On success, `(content, content_type)` extracted from the inner plaintext.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when decryption or inner-plaintext parsing fails.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_open_client_tls13_inner_record(
        &mut self,
        record: &ProtectedRecord,
        aad: &[u8],
    ) -> Result<(Vec<u8>, u8)> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 inner plaintext records require TLS 1.3 connection",
            ));
        }
        let inner = self.noxtls_open_client_record(record, aad)?;
        noxtls_decode_tls13_inner_plaintext(&inner)
    }

    /// Seals one TLS 1.3 wire record packet using server traffic keys.
    ///
    /// # Arguments
    ///
    /// * `content` — Inner plaintext content bytes.
    /// * `content_type` — TLSInnerPlaintext content type byte.
    /// * `aad` — Record header bytes used as AEAD additional data.
    /// * `padding_len` — Number of trailing zero padding bytes.
    ///
    /// # Returns
    ///
    /// On success, serialized TLSCiphertext packet bytes.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when called outside TLS 1.3 or when seal preconditions fail.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_seal_server_tls13_record_packet(
        &mut self,
        content: &[u8],
        content_type: u8,
        aad: &[u8],
        padding_len: usize,
    ) -> Result<Vec<u8>> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 record packets require TLS 1.3 connection",
            ));
        }
        let record =
            self.noxtls_seal_server_tls13_inner_record(content, content_type, aad, padding_len)?;
        self.noxtls_encode_tls13_record_packet(&record)
    }

    /// Opens one inbound TLS 1.3 wire record packet sealed by the client.
    ///
    /// # Arguments
    ///
    /// * `packet` — Serialized TLSCiphertext packet bytes from the client.
    /// * `aad` — Record header bytes used as AEAD additional data.
    ///
    /// # Returns
    ///
    /// On success, `(content, content_type)` decoded from the inner plaintext.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when decryption or packet framing fails.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_open_client_tls13_record_packet(
        &mut self,
        packet: &[u8],
        aad: &[u8],
    ) -> Result<(Vec<u8>, u8)> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 record packets require TLS 1.3 connection",
            ));
        }
        let record = self.noxtls_decode_tls13_record_packet(packet, self.client_sequence)?;
        self.noxtls_open_client_tls13_inner_record(&record, aad)
    }

    /// Encrypts plaintext with the negotiated suite using the provided key and nonce.
    ///
    /// # Arguments
    ///
    /// * `suite` — Negotiated AEAD cipher suite.
    /// * `key` — Up to 32 bytes of key material; AES suites use a prefix slice.
    /// * `nonce` — 12-byte record nonce.
    /// * `aad` — Additional authenticated data.
    /// * `plaintext` — Plaintext bytes to protect.
    ///
    /// # Returns
    ///
    /// On success, `(ciphertext, tag)` for the protected payload.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when cipher construction or AEAD encryption fails.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub(super) fn noxtls_aead_encrypt_for_suite(
        suite: CipherSuite,
        key: &[u8; 32],
        nonce: &[u8; 12],
        aad: &[u8],
        plaintext: &[u8],
    ) -> Result<(Vec<u8>, [u8; 16])> {
        match suite {
            CipherSuite::TlsChacha20Poly1305Sha256 => {
                noxtls_chacha20_poly1305_encrypt(key, nonce, aad, plaintext)
            }
            CipherSuite::TlsAes128GcmSha256 | CipherSuite::TlsAes256GcmSha384 => {
                let key_len = suite
                    .noxtls_tls13_traffic_key_len()
                    .ok_or(Error::StateError(
                        "tls 1.3 aes suites must define traffic key length",
                    ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_gcm_encrypt(&cipher, nonce, aad, plaintext)
            }
            CipherSuite::TlsEcdheRsaWithAes128GcmSha256
            | CipherSuite::TlsEcdheRsaWithAes256GcmSha384
            | CipherSuite::TlsEcdheEcdsaWithAes128GcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes256GcmSha384
            | CipherSuite::TlsDheRsaWithAes128GcmSha256
            | CipherSuite::TlsDheRsaWithAes256GcmSha384
            | CipherSuite::TlsRsaWithAes128GcmSha256
            | CipherSuite::TlsRsaWithAes256GcmSha384 => {
                let key_len = suite.noxtls_tls12_aead_key_len().ok_or(Error::StateError(
                    "tls 1.2 aes-gcm suites must define traffic key length",
                ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_gcm_encrypt(&cipher, nonce, aad, plaintext)
            }
            CipherSuite::TlsEcdheEcdsaWithAes128CcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes256CcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes128Ccm8Sha256
            | CipherSuite::TlsEcdheEcdsaWithAes256Ccm8Sha256
            | CipherSuite::TlsRsaWithAes128CcmSha256
            | CipherSuite::TlsRsaWithAes256CcmSha256
            | CipherSuite::TlsRsaWithAes128Ccm8Sha256
            | CipherSuite::TlsRsaWithAes256Ccm8Sha256
            | CipherSuite::TlsDheRsaWithAes128CcmSha256
            | CipherSuite::TlsDheRsaWithAes256CcmSha256
            | CipherSuite::TlsDheRsaWithAes128Ccm8Sha256
            | CipherSuite::TlsDheRsaWithAes256Ccm8Sha256
            | CipherSuite::TlsPskWithAes128Ccm8Sha256
            | CipherSuite::TlsEcjpakeWithAes128Ccm8Sha256 => {
                let key_len = suite.noxtls_tls12_aead_key_len().ok_or(Error::StateError(
                    "tls 1.2 aes-ccm suites must define traffic key length",
                ))?;
                let tag_len = suite.noxtls_tls12_aead_tag_len().ok_or(Error::StateError(
                    "tls 1.2 aes-ccm suites must define tag length",
                ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_ccm_encrypt_with_tag_len(&cipher, nonce, aad, plaintext, tag_len)
            }
            CipherSuite::TlsEcdheRsaWithAes128CbcSha | CipherSuite::TlsRsaWithAes128CbcSha => Err(
                Error::UnsupportedFeature("tls 1.2 cbc uses block record protection"),
            ),
            CipherSuite::TlsEcdheRsaWithChacha20Poly1305Sha256
            | CipherSuite::TlsEcdheEcdsaWithChacha20Poly1305Sha256
            | CipherSuite::TlsDheRsaWithChacha20Poly1305Sha256 => Err(Error::UnsupportedFeature(
                "tls 1.2 chacha20-poly1305 uses tls12 nonce record protection",
            )),
        }
    }

    /// Decrypts ciphertext with the negotiated suite using the provided key and nonce.
    ///
    /// # Arguments
    ///
    /// * `suite` — Negotiated AEAD cipher suite.
    /// * `key` — Up to 32 bytes of key material; AES suites use a prefix slice.
    /// * `nonce` — 12-byte record nonce.
    /// * `aad` — Additional authenticated data.
    /// * `ciphertext` — Protected ciphertext bytes.
    /// * `tag` — 16-byte authentication tag.
    ///
    /// # Returns
    ///
    /// On success, decrypted plaintext bytes.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when authentication or cipher operations fail.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub(super) fn noxtls_aead_decrypt_for_suite(
        suite: CipherSuite,
        key: &[u8; 32],
        nonce: &[u8; 12],
        aad: &[u8],
        ciphertext: &[u8],
        tag: &[u8; 16],
    ) -> Result<Vec<u8>> {
        match suite {
            CipherSuite::TlsChacha20Poly1305Sha256 => {
                noxtls_chacha20_poly1305_decrypt(key, nonce, aad, ciphertext, tag)
            }
            CipherSuite::TlsAes128GcmSha256 | CipherSuite::TlsAes256GcmSha384 => {
                let key_len = suite
                    .noxtls_tls13_traffic_key_len()
                    .ok_or(Error::StateError(
                        "tls 1.3 aes suites must define traffic key length",
                    ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_gcm_decrypt(&cipher, nonce, aad, ciphertext, tag)
            }
            CipherSuite::TlsEcdheRsaWithAes128GcmSha256
            | CipherSuite::TlsEcdheRsaWithAes256GcmSha384
            | CipherSuite::TlsEcdheEcdsaWithAes128GcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes256GcmSha384
            | CipherSuite::TlsDheRsaWithAes128GcmSha256
            | CipherSuite::TlsDheRsaWithAes256GcmSha384
            | CipherSuite::TlsRsaWithAes128GcmSha256
            | CipherSuite::TlsRsaWithAes256GcmSha384 => {
                let key_len = suite.noxtls_tls12_aead_key_len().ok_or(Error::StateError(
                    "tls 1.2 aes-gcm suites must define traffic key length",
                ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_gcm_decrypt(&cipher, nonce, aad, ciphertext, tag)
            }
            CipherSuite::TlsEcdheEcdsaWithAes128CcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes256CcmSha256
            | CipherSuite::TlsEcdheEcdsaWithAes128Ccm8Sha256
            | CipherSuite::TlsEcdheEcdsaWithAes256Ccm8Sha256
            | CipherSuite::TlsRsaWithAes128CcmSha256
            | CipherSuite::TlsRsaWithAes256CcmSha256
            | CipherSuite::TlsRsaWithAes128Ccm8Sha256
            | CipherSuite::TlsRsaWithAes256Ccm8Sha256
            | CipherSuite::TlsDheRsaWithAes128CcmSha256
            | CipherSuite::TlsDheRsaWithAes256CcmSha256
            | CipherSuite::TlsDheRsaWithAes128Ccm8Sha256
            | CipherSuite::TlsDheRsaWithAes256Ccm8Sha256
            | CipherSuite::TlsPskWithAes128Ccm8Sha256
            | CipherSuite::TlsEcjpakeWithAes128Ccm8Sha256 => {
                let key_len = suite.noxtls_tls12_aead_key_len().ok_or(Error::StateError(
                    "tls 1.2 aes-ccm suites must define traffic key length",
                ))?;
                let tag_len = suite.noxtls_tls12_aead_tag_len().ok_or(Error::StateError(
                    "tls 1.2 aes-ccm suites must define tag length",
                ))?;
                let cipher = AesCipher::noxtls_new(&key[..key_len])?;
                noxtls_aes_ccm_decrypt_with_tag_len(&cipher, nonce, aad, ciphertext, tag, tag_len)
            }
            CipherSuite::TlsEcdheRsaWithAes128CbcSha | CipherSuite::TlsRsaWithAes128CbcSha => Err(
                Error::UnsupportedFeature("tls 1.2 cbc uses block record protection"),
            ),
            CipherSuite::TlsEcdheRsaWithChacha20Poly1305Sha256
            | CipherSuite::TlsEcdheEcdsaWithChacha20Poly1305Sha256
            | CipherSuite::TlsDheRsaWithChacha20Poly1305Sha256 => Err(Error::UnsupportedFeature(
                "tls 1.2 chacha20-poly1305 uses tls12 nonce record protection",
            )),
        }
    }
}