Skip to main content

pb_mapper_core/
codec.rs

1use ring::aead::{
2    AES_256_GCM, Aad, BoundKey, NONCE_LEN, Nonce, NonceSequence, OpeningKey, SealingKey, Tag,
3    UnboundKey,
4};
5
6type RingResult<T> = Result<T, ring::error::Unspecified>;
7
8/// A nonce is a direction prefix, then a big-endian message counter.
9const PREFIX_LEN: usize = 4;
10const COUNTER_LEN: usize = size_of::<u64>();
11const _: () = assert!(
12    PREFIX_LEN + COUNTER_LEN == NONCE_LEN,
13    "a nonce is a 4-byte direction prefix and a big-endian 64-bit counter"
14);
15
16/// How many messages a legacy codec seals or opens under one key: it predates
17/// the 64-bit counter of data v2, whose limit is `u64::MAX`.
18const LEGACY_LIMIT: u64 = u32::MAX as u64;
19
20/// The next message's counter, and the count at which the key is spent.
21struct Counter {
22    next: u64,
23    limit: u64,
24}
25
26impl Counter {
27    fn advance(&mut self) -> RingResult<()> {
28        if self.next >= self.limit {
29            return Err(ring::error::Unspecified);
30        }
31        self.next += 1;
32        Ok(())
33    }
34
35    fn to_bytes(&self) -> [u8; COUNTER_LEN] {
36        self.next.to_be_bytes()
37    }
38}
39
40/// The nonces of one key in one direction.
41///
42/// Neither `Clone` nor `Copy`: a copy would hand out the same nonces again
43/// under the same key.
44struct CounterNonceSequence {
45    counter: Counter,
46    nonce: [u8; NONCE_LEN],
47}
48
49impl Default for CounterNonceSequence {
50    /// The legacy sequence: no prefix, and [`LEGACY_LIMIT`] messages.
51    fn default() -> Self {
52        Self {
53            counter: Counter {
54                next: 0,
55                limit: LEGACY_LIMIT,
56            },
57            nonce: [0; NONCE_LEN],
58        }
59    }
60}
61
62impl CounterNonceSequence {
63    /// A data-v2 sequence: a direction prefix and a full 64-bit counter.
64    fn data_v2(prefix: [u8; PREFIX_LEN]) -> Self {
65        let mut nonce = [0; NONCE_LEN];
66        nonce[..PREFIX_LEN].copy_from_slice(&prefix);
67        Self {
68            counter: Counter {
69                next: 0,
70                limit: u64::MAX,
71            },
72            nonce,
73        }
74    }
75}
76
77impl NonceSequence for CounterNonceSequence {
78    // called once for each seal operation
79    fn advance(&mut self) -> RingResult<Nonce> {
80        self.nonce[PREFIX_LEN..].copy_from_slice(&self.counter.to_bytes());
81        self.counter.advance()?;
82        Ok(Nonce::assume_unique_for_key(self.nonce))
83    }
84}
85
86#[derive(Debug)]
87pub struct Aes256GcmEnCodec {
88    seal: SealingKey<CounterNonceSequence>,
89}
90
91impl Aes256GcmEnCodec {
92    /// Construct a negotiated data-v2 codec with a directional nonce prefix and a
93    /// checked 64-bit counter. Legacy constructors retain their 32-bit limit.
94    /// Peers sharing a key must use disjoint prefixes for opposite directions.
95    pub fn try_new_data_v2(key: &[u8], prefix: [u8; 4]) -> RingResult<Self> {
96        Ok(Self {
97            seal: SealingKey::new(
98                UnboundKey::new(&AES_256_GCM, key)?,
99                CounterNonceSequence::data_v2(prefix),
100            ),
101        })
102    }
103
104    pub fn try_new(key: &[u8]) -> RingResult<Self> {
105        Ok(Self {
106            seal: SealingKey::new(
107                UnboundKey::new(&AES_256_GCM, key)?,
108                CounterNonceSequence::default(),
109            ),
110        })
111    }
112}
113
114impl Encryptor for Aes256GcmEnCodec {
115    fn encrypt(&mut self, data: &mut [u8]) -> RingResult<Tag> {
116        self.seal.seal_in_place_separate_tag(Aad::empty(), data)
117    }
118}
119
120#[derive(Debug)]
121pub struct Aes256GcmDeCodec {
122    open: OpeningKey<CounterNonceSequence>,
123}
124
125impl Aes256GcmDeCodec {
126    /// Construct the receiving half of a negotiated data-v2 codec.
127    pub fn try_new_data_v2(key: &[u8], prefix: [u8; 4]) -> RingResult<Self> {
128        Ok(Self {
129            open: OpeningKey::new(
130                UnboundKey::new(&AES_256_GCM, key)?,
131                CounterNonceSequence::data_v2(prefix),
132            ),
133        })
134    }
135
136    pub fn try_new(key: &[u8]) -> RingResult<Self> {
137        Ok(Self {
138            open: OpeningKey::new(
139                UnboundKey::new(&AES_256_GCM, key)?,
140                CounterNonceSequence::default(),
141            ),
142        })
143    }
144}
145
146impl Decryptor for Aes256GcmDeCodec {
147    fn decrypt<'a>(&mut self, data: &'a mut [u8]) -> RingResult<&'a mut [u8]> {
148        self.open.open_in_place(Aad::empty(), data)
149    }
150}
151
152/// Seals each message in place under the next nonce, returning its tag.
153pub trait Encryptor: 'static {
154    fn encrypt(&mut self, data: &mut [u8]) -> RingResult<Tag>;
155}
156
157/// Opens each message (ciphertext followed by its tag) in place under the
158/// next nonce, returning the plaintext.
159pub trait Decryptor {
160    fn decrypt<'a>(&mut self, data: &'a mut [u8]) -> RingResult<&'a mut [u8]>;
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn legacy_nonces_keep_their_bytes_and_both_counter_widths_fail_closed() {
169        for limit in [u64::from(u32::MAX), u64::MAX] {
170            let mut seq = CounterNonceSequence {
171                counter: Counter {
172                    next: limit - 1,
173                    limit,
174                },
175                nonce: [0; 12],
176            };
177            let nonce = seq.advance().unwrap();
178            assert_eq!(&nonce.as_ref()[..4], &[0; 4]);
179            assert_eq!(&nonce.as_ref()[4..], &(limit - 1).to_be_bytes());
180            assert!(seq.advance().is_err());
181            assert!(seq.advance().is_err());
182        }
183        let mut seq = CounterNonceSequence::default();
184        assert_eq!(seq.advance().unwrap().as_ref(), &[0; 12]);
185        assert_eq!(
186            seq.advance().unwrap().as_ref(),
187            &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
188        );
189    }
190
191    /// Which limit each constructor picks, and where the data-v2 prefix goes.
192    #[test]
193    fn legacy_and_data_v2_sequences_pick_their_prefix_and_limit() {
194        let legacy = CounterNonceSequence::default();
195        assert_eq!(legacy.counter.limit, u64::from(u32::MAX));
196        let mut v2 = CounterNonceSequence::data_v2([0, 0, 0, 1]);
197        assert_eq!(v2.counter.limit, u64::MAX);
198        assert_eq!(
199            v2.advance().unwrap().as_ref(),
200            &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
201        );
202    }
203
204    #[test]
205    fn a_sealed_message_opens_with_the_same_key() {
206        const KEY: [u8; 32] = [0x42; 32];
207        let plaintext = b"pb-mapper frame";
208        let mut seal = Aes256GcmEnCodec::try_new(&KEY).unwrap();
209        let mut open = Aes256GcmDeCodec::try_new(&KEY).unwrap();
210        for _ in 0..2 {
211            let mut message = plaintext.to_vec();
212            let tag = seal.encrypt(&mut message).unwrap();
213            assert_ne!(message, plaintext);
214            message.extend_from_slice(tag.as_ref());
215            assert_eq!(open.decrypt(&mut message).unwrap(), plaintext);
216        }
217    }
218}