Skip to main content

rtci_sframe/
header.rs

1use crate::error::{Error, Result};
2
3/// The longest SFrame header: the config byte, an 8-byte KID and an 8-byte CTR.
4pub const MAX_HEADER_LEN: usize = 17;
5
6const EXTENDED_KID: u8 = 0x80;
7const EXTENDED_CTR: u8 = 0x08;
8
9/// An SFrame header (RFC 9605 section 4.3): the key id that selects the key and the counter
10/// the nonce is built from.
11///
12/// ```text
13///  0 1 2 3 4 5 6 7
14/// +-+-+-+-+-+-+-+-+------------+------------+
15/// |X|  K  |Y|  C  |   KID...   |   CTR...   |
16/// +-+-+-+-+-+-+-+-+------------+------------+
17/// ```
18///
19/// A value below 8 is carried in the config byte (`K` or `C`, with `X` or `Y` clear). A larger
20/// one follows the config byte as a big-endian integer in the fewest bytes that hold it, and
21/// the field holds that length minus one.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub struct Header {
24    /// The key id (KID).
25    pub kid: u64,
26    /// The counter (CTR).
27    pub ctr: u64,
28}
29
30/// The number of bytes a value takes after the config byte: none below 8, else its shortest
31/// big-endian form.
32const fn extension_len(value: u64) -> usize {
33    if value < 8 {
34        0
35    } else {
36        8 - (value.leading_zeros() as usize) / 8
37    }
38}
39
40/// The config-byte nibble of a value: the value itself below 8, else the extended flag and the
41/// length minus one.
42const fn nibble(value: u64) -> u8 {
43    if value < 8 {
44        value as u8
45    } else {
46        0x08 | (extension_len(value) as u8 - 1)
47    }
48}
49
50impl Header {
51    /// A header with these values.
52    #[must_use]
53    pub const fn new(kid: u64, ctr: u64) -> Self {
54        Self { kid, ctr }
55    }
56
57    /// The length in bytes of this header's encoding: 1 to 17.
58    #[must_use]
59    pub const fn encoded_len(&self) -> usize {
60        1 + extension_len(self.kid) + extension_len(self.ctr)
61    }
62
63    /// Writes the header's (minimal) encoding at the start of `out` and returns its length.
64    pub fn encode(&self, out: &mut [u8; MAX_HEADER_LEN]) -> usize {
65        let kid_len = extension_len(self.kid);
66        let ctr_len = extension_len(self.ctr);
67        out[0] = (nibble(self.kid) << 4) | nibble(self.ctr);
68        out[1..1 + kid_len].copy_from_slice(&self.kid.to_be_bytes()[8 - kid_len..]);
69        out[1 + kid_len..1 + kid_len + ctr_len]
70            .copy_from_slice(&self.ctr.to_be_bytes()[8 - ctr_len..]);
71        1 + kid_len + ctr_len
72    }
73
74    /// Appends the header's encoding to `out`.
75    pub fn encode_to(&self, out: &mut Vec<u8>) {
76        let mut buffer = [0; MAX_HEADER_LEN];
77        let len = self.encode(&mut buffer);
78        out.extend_from_slice(&buffer[..len]);
79    }
80
81    /// Parses the header at the start of `data`. Returns it with the number of bytes it takes;
82    /// the rest of `data` is the AEAD output.
83    ///
84    /// A value that is not in its shortest form is refused with
85    /// [`Error::NonMinimalHeader`]: RFC 9605 requires the shortest form of a sender, so a
86    /// conforming one never produces anything else. [`decode_lenient`](Self::decode_lenient)
87    /// accepts such headers.
88    pub fn decode(data: &[u8]) -> Result<(Self, usize)> {
89        let (header, len, minimal) = Self::parse(data)?;
90        if minimal {
91            Ok((header, len))
92        } else {
93            Err(Error::NonMinimalHeader)
94        }
95    }
96
97    /// Parses the header at the start of `data`, also when a KID or CTR is longer than it needs
98    /// to be (an extended value below 8, or leading zero bytes).
99    ///
100    /// Decryption authenticates the header bytes as they were received, so a re-encoded header
101    /// never validates; accepting the longer forms only admits a sender that does not follow
102    /// the encoding rule.
103    pub fn decode_lenient(data: &[u8]) -> Result<(Self, usize)> {
104        let (header, len, _) = Self::parse(data)?;
105        Ok((header, len))
106    }
107
108    fn parse(data: &[u8]) -> Result<(Self, usize, bool)> {
109        let Some((&config, rest)) = data.split_first() else {
110            return Err(Error::TruncatedHeader);
111        };
112        let (kid, kid_len) = field(config & EXTENDED_KID != 0, (config >> 4) & 0x07, rest)?;
113        let (ctr, ctr_len) = field(config & EXTENDED_CTR != 0, config & 0x07, &rest[kid_len..])?;
114        let minimal = extension_len(kid) == kid_len && extension_len(ctr) == ctr_len;
115        Ok((Self { kid, ctr }, 1 + kid_len + ctr_len, minimal))
116    }
117}
118
119/// One KID or CTR: inline in `bits` when not `extended`, else `bits + 1` bytes of `rest`.
120/// Returns the value and how many bytes of `rest` it took.
121fn field(extended: bool, bits: u8, rest: &[u8]) -> Result<(u64, usize)> {
122    if !extended {
123        return Ok((u64::from(bits), 0));
124    }
125    let len = usize::from(bits) + 1;
126    let Some(bytes) = rest.get(..len) else {
127        return Err(Error::TruncatedHeader);
128    };
129    let mut value = [0; 8];
130    value[8 - len..].copy_from_slice(bytes);
131    Ok((u64::from_be_bytes(value), len))
132}