Skip to main content

dlms_cosem_kit/security/
keys.rs

1//! Keys, and the things that name them.
2
3use core::fmt;
4
5/// The eight-byte identity of a DLMS peer.
6///
7/// A system title is not a secret, but it is half of every nonce: reusing one across
8/// two devices that share a key makes their nonces collide, which for GCM is a
9/// key-recovery event rather than a privacy one.
10#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
11pub struct SystemTitle(pub [u8; 8]);
12
13impl SystemTitle {
14    /// From the eight bytes.
15    #[must_use]
16    pub const fn new(bytes: [u8; 8]) -> Self {
17        Self(bytes)
18    }
19
20    /// From a slice that must be exactly eight bytes.
21    pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
22        let arr: [u8; 8] = bytes
23            .try_into()
24            .map_err(|_| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?;
25        Ok(Self(arr))
26    }
27
28    /// The bytes.
29    #[must_use]
30    pub const fn as_bytes(&self) -> &[u8; 8] {
31        &self.0
32    }
33
34    /// The three-character manufacturer identifier, when it is printable ASCII.
35    #[must_use]
36    pub fn manufacturer(&self) -> Option<&str> {
37        core::str::from_utf8(&self.0[..3]).ok().filter(|s| s.is_ascii())
38    }
39}
40
41impl fmt::Debug for SystemTitle {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.write_str("SystemTitle(")?;
44        for b in &self.0 {
45            write!(f, "{b:02X}")?;
46        }
47        f.write_str(")")
48    }
49}
50
51impl fmt::Display for SystemTitle {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        for b in &self.0 {
54            write!(f, "{b:02X}")?;
55        }
56        Ok(())
57    }
58}
59
60/// What a key is for.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub enum KeyUsage {
63    /// The global unicast encryption key, which protects ordinary traffic.
64    GlobalUnicastEncryption,
65    /// The global broadcast encryption key, used for messages to many meters at once.
66    GlobalBroadcastEncryption,
67    /// The authentication key, which is authenticated data rather than a cipher key.
68    Authentication,
69    /// The key-encrypting key, under which other keys are wrapped for transport.
70    KeyEncrypting,
71    /// The key negotiated for this association only, carried in the InitiateRequest.
72    Dedicated,
73}
74
75impl KeyUsage {
76    /// The `Key-Id` this usage has in `general-ciphering`'s identified-key form.
77    ///
78    /// `Key-Id` is an enumeration of exactly two values — `global-unicast-encryption-key`
79    /// (0) and `global-broadcast-encryption-key` (1). Every other usage answers `None`
80    /// rather than inventing a number: the authentication key in particular is *never* an
81    /// identified key, because identified-key names the key that deciphers the content
82    /// and the authentication key never does that.
83    #[must_use]
84    pub const fn key_id(self) -> Option<u8> {
85        match self {
86            Self::GlobalUnicastEncryption => Some(0),
87            Self::GlobalBroadcastEncryption => Some(1),
88            Self::Authentication | Self::KeyEncrypting | Self::Dedicated => None,
89        }
90    }
91}
92
93/// A reference to a key, without the key.
94///
95/// A provider resolves this to material it holds — bytes in memory, a slot in a secure
96/// element, a handle in an HSM.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum KeyRef<'a> {
99    /// One of the well-known keys of this association.
100    Usage(KeyUsage),
101    /// Raw bytes supplied by the caller, for one operation.
102    Raw(&'a [u8]),
103}
104
105impl From<KeyUsage> for KeyRef<'_> {
106    fn from(u: KeyUsage) -> Self {
107        Self::Usage(u)
108    }
109}
110
111/// A symmetric key: 16 bytes for suites 0 and 1, 32 for suite 2.
112///
113/// Fixed capacity, so it needs no allocator. `Debug` prints `[REDACTED]`, so a
114/// structured log or a `defmt` trace of anything containing a key cannot leak it by
115/// accident.
116///
117/// The bytes are cleared on drop **when the `crypto` feature is on**, which is what
118/// brings in `zeroize`. Without it there is no way to clear them that the optimiser is
119/// obliged to keep — a plain `fill(0)` on a value about to die is exactly the store a
120/// compiler is allowed to delete — so the crate does not pretend to. Any build that
121/// handles real keys has `crypto` on, because `suite0` implies it.
122///
123/// The length is carried rather than fixed by a type parameter because the suite decides
124/// it and the suite arrives on the wire. A ring that could only hold 128-bit keys made
125/// suite 2 unreachable through [`KeyRef::Usage`] — the only form the protection layer
126/// uses — however completely the provider implemented AES-256.
127#[derive(Clone, PartialEq, Eq)]
128pub struct Key {
129    buf: [u8; Self::MAX_LEN],
130    len: u8,
131}
132
133impl Key {
134    /// The longest key this can hold: 256 bits, which is suite 2's.
135    pub const MAX_LEN: usize = 32;
136
137    /// A 128-bit key, the size suites 0 and 1 use.
138    #[must_use]
139    pub const fn new(bytes: [u8; 16]) -> Self {
140        let mut buf = [0u8; Self::MAX_LEN];
141        let mut i = 0;
142        while i < 16 {
143            buf[i] = bytes[i];
144            i += 1;
145        }
146        Self { buf, len: 16 }
147    }
148
149    /// A 256-bit key, the size suite 2 uses.
150    #[must_use]
151    pub const fn new_256(bytes: [u8; 32]) -> Self {
152        Self { buf: bytes, len: 32 }
153    }
154
155    /// A key from a slice that must be 16 or 32 bytes long.
156    ///
157    /// Any other length is refused rather than padded: a key silently zero-extended to
158    /// the cipher's block size is a key nobody chose.
159    ///
160    /// # Errors
161    /// [`crate::codec::ErrorKind::InvalidLength`] for any length but 16 or 32.
162    pub fn from_slice(bytes: &[u8]) -> crate::codec::Result<Self> {
163        if bytes.len() != 16 && bytes.len() != 32 {
164            return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
165        }
166        let mut buf = [0u8; Self::MAX_LEN];
167        buf.get_mut(..bytes.len())
168            .ok_or_else(|| crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0))?
169            .copy_from_slice(bytes);
170        Ok(Self { buf, len: bytes.len() as u8 })
171    }
172
173    /// The bytes. Every call site is a place a key could escape, so there is exactly one
174    /// and it is named.
175    #[must_use]
176    pub fn expose(&self) -> &[u8] {
177        self.buf.get(..usize::from(self.len)).unwrap_or(&[])
178    }
179
180    /// How many bytes the key has.
181    #[must_use]
182    pub const fn len(&self) -> usize {
183        self.len as usize
184    }
185
186    /// Always false; a key has at least sixteen bytes.
187    #[must_use]
188    pub const fn is_empty(&self) -> bool {
189        false
190    }
191}
192
193impl fmt::Debug for Key {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        f.write_str("[REDACTED]")
196    }
197}
198
199#[cfg(feature = "crypto")]
200impl Drop for Key {
201    fn drop(&mut self) {
202        use zeroize::Zeroize;
203        self.buf.zeroize();
204    }
205}
206
207impl From<[u8; 16]> for Key {
208    fn from(v: [u8; 16]) -> Self {
209        Self::new(v)
210    }
211}
212
213impl From<[u8; 32]> for Key {
214    fn from(v: [u8; 32]) -> Self {
215        Self::new_256(v)
216    }
217}
218
219/// A variable-length credential: an LLS password, or an HLS shared secret.
220///
221/// Fixed capacity, so it needs no allocator, and 64 bytes because that is the longest
222/// challenge the Blue Book allows. Like [`Key`] it prints as `[REDACTED]`, and clears
223/// itself when dropped under the same condition and for the same reason.
224#[derive(Clone, PartialEq, Eq)]
225pub struct Secret {
226    buf: [u8; Self::MAX_LEN],
227    len: u8,
228}
229
230impl Secret {
231    /// The longest secret this can hold.
232    pub const MAX_LEN: usize = 64;
233
234    /// Copy `bytes` into a secret.
235    ///
236    /// # Errors
237    /// [`crate::codec::ErrorKind::InvalidLength`] when `bytes` is longer than
238    /// [`Secret::MAX_LEN`].
239    pub fn new(bytes: &[u8]) -> crate::codec::Result<Self> {
240        if bytes.len() > Self::MAX_LEN {
241            return Err(crate::codec::Error::new(crate::codec::ErrorKind::InvalidLength, 0));
242        }
243        let mut buf = [0u8; Self::MAX_LEN];
244        buf[..bytes.len()].copy_from_slice(bytes);
245        Ok(Self { buf, len: bytes.len() as u8 })
246    }
247
248    /// The bytes. Every call site is a place a secret could escape, so there is exactly
249    /// one and it is named.
250    #[must_use]
251    pub fn expose(&self) -> &[u8] {
252        &self.buf[..usize::from(self.len)]
253    }
254}
255
256impl fmt::Debug for Secret {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        f.write_str("[REDACTED]")
259    }
260}
261
262#[cfg(feature = "crypto")]
263impl Drop for Secret {
264    fn drop(&mut self) {
265        use zeroize::Zeroize;
266        self.buf.zeroize();
267    }
268}
269
270/// The symmetric keys of one association.
271///
272/// Every entry is a [`Key`], so one ring serves suite 0, suite 1 and suite 2 without the
273/// caller choosing a width at compile time.
274#[derive(Debug, Clone, Default)]
275pub struct KeyRing {
276    /// Global unicast encryption key.
277    pub guek: Option<Key>,
278    /// Global broadcast encryption key.
279    pub gbek: Option<Key>,
280    /// Authentication key. Authenticated as additional data, never used as a cipher key.
281    pub gak: Option<Key>,
282    /// Key-encrypting key, also called the master key.
283    pub kek: Option<Key>,
284    /// The key for this association only, delivered inside the ciphered
285    /// InitiateRequest. Dropped when the association is released.
286    pub dedicated: Option<Key>,
287}
288
289impl KeyRing {
290    /// A ring with the two 128-bit keys an ordinary suite-0 association needs.
291    #[must_use]
292    pub const fn new(guek: [u8; 16], gak: [u8; 16]) -> Self {
293        Self { guek: Some(Key::new(guek)), gak: Some(Key::new(gak)), gbek: None, kek: None, dedicated: None }
294    }
295
296    /// A ring with the two 256-bit keys a suite-2 association needs.
297    #[must_use]
298    pub const fn new_256(guek: [u8; 32], gak: [u8; 32]) -> Self {
299        Self {
300            guek: Some(Key::new_256(guek)),
301            gak: Some(Key::new_256(gak)),
302            gbek: None,
303            kek: None,
304            dedicated: None,
305        }
306    }
307
308    /// The key for a usage, if the ring holds it.
309    #[must_use]
310    pub fn get(&self, usage: KeyUsage) -> Option<&[u8]> {
311        let slot = match usage {
312            KeyUsage::GlobalUnicastEncryption => self.guek.as_ref(),
313            KeyUsage::GlobalBroadcastEncryption => self.gbek.as_ref(),
314            KeyUsage::Authentication => self.gak.as_ref(),
315            KeyUsage::KeyEncrypting => self.kek.as_ref(),
316            KeyUsage::Dedicated => self.dedicated.as_ref(),
317        };
318        slot.map(Key::expose)
319    }
320
321    /// Install a key for a usage.
322    pub fn set(&mut self, usage: KeyUsage, key: Key) {
323        match usage {
324            KeyUsage::GlobalUnicastEncryption => self.guek = Some(key),
325            KeyUsage::GlobalBroadcastEncryption => self.gbek = Some(key),
326            KeyUsage::Authentication => self.gak = Some(key),
327            KeyUsage::KeyEncrypting => self.kek = Some(key),
328            KeyUsage::Dedicated => self.dedicated = Some(key),
329        }
330    }
331
332    /// Install the dedicated key for an association.
333    pub fn set_dedicated(&mut self, key: Key) {
334        self.dedicated = Some(key);
335    }
336
337    /// Forget the dedicated key. Called when the association is released, so a key
338    /// cannot outlive the association that negotiated it.
339    pub fn clear_dedicated(&mut self) {
340        self.dedicated = None;
341    }
342}
343
344/// Build the twelve-byte GCM nonce: system title, then invocation counter.
345#[must_use]
346pub const fn nonce(system_title: &SystemTitle, invocation_counter: u32) -> [u8; 12] {
347    let t = system_title.0;
348    let c = invocation_counter.to_be_bytes();
349    [t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], c[0], c[1], c[2], c[3]]
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    /// `Key-Id` is an enumeration of two values. The authentication key is not one of
357    /// them — `identified-key` names the key that deciphers the content, and the
358    /// authentication key never does that — so answering `2` would put a number the
359    /// standard does not define into a `general-ciphering` header.
360    #[test]
361    fn only_the_two_ciphering_keys_have_a_key_id() {
362        assert_eq!(KeyUsage::GlobalUnicastEncryption.key_id(), Some(0));
363        assert_eq!(KeyUsage::GlobalBroadcastEncryption.key_id(), Some(1));
364        assert_eq!(KeyUsage::Authentication.key_id(), None);
365        assert_eq!(KeyUsage::KeyEncrypting.key_id(), None);
366        assert_eq!(KeyUsage::Dedicated.key_id(), None);
367    }
368
369    #[test]
370    fn a_nonce_is_the_title_then_the_counter() {
371        let st = SystemTitle::new([0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E]);
372        assert_eq!(
373            nonce(&st, 0x0000_0001),
374            [0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E, 0x00, 0x00, 0x00, 0x01]
375        );
376    }
377
378    #[test]
379    fn a_system_title_shows_its_manufacturer() {
380        let st = SystemTitle::new(*b"MMM\x00\x00\xbcaN");
381        assert_eq!(st.manufacturer(), Some("MMM"));
382    }
383
384    #[test]
385    fn a_secret_does_not_print_itself() {
386        #[cfg(feature = "std")]
387        {
388            use std::format;
389            let s = Key::new([0xAAu8; 16]);
390            assert_eq!(format!("{s:?}"), "[REDACTED]");
391            let ring = KeyRing::new([1; 16], [2; 16]);
392            let printed = format!("{ring:?}");
393            assert!(!printed.contains('1'), "no key bytes in a Debug rendering: {printed}");
394        }
395    }
396
397    /// Suite 2 is 256-bit AES-GCM, and the ring has to be able to hold the key or the
398    /// suite is unreachable however completely the provider implements it.
399    #[test]
400    fn a_ring_holds_keys_of_both_suite_widths() {
401        let ring = KeyRing::new_256([7; 32], [8; 32]);
402        assert_eq!(ring.get(KeyUsage::GlobalUnicastEncryption).map(<[u8]>::len), Some(32));
403        let ring = KeyRing::new([7; 16], [8; 16]);
404        assert_eq!(ring.get(KeyUsage::Authentication).map(<[u8]>::len), Some(16));
405        // And a length no suite defines is refused rather than padded.
406        assert!(Key::from_slice(&[0u8; 24]).is_err());
407        assert!(Key::from_slice(&[0u8; 32]).is_ok());
408    }
409
410    #[test]
411    fn a_dedicated_key_can_be_dropped_without_dropping_the_ring() {
412        let mut ring = KeyRing::new([1; 16], [2; 16]);
413        ring.set_dedicated(Key::new([3; 16]));
414        assert!(ring.get(KeyUsage::Dedicated).is_some());
415        ring.clear_dedicated();
416        assert!(ring.get(KeyUsage::Dedicated).is_none());
417        assert!(ring.get(KeyUsage::GlobalUnicastEncryption).is_some());
418    }
419}