Skip to main content

mbus_kit/
oms.rs

1//! OMS security (feature `oms`): keys and the AES primitives of security modes 5 and 7
2//! and the ELL (OMS Vol. 2, EN 13757-7).
3//!
4//! | Layer | Cipher | Verified by |
5//! |---|---|---|
6//! | TPL, mode 5 | AES-128-CBC, IV = M ‖ A ‖ 8 × access number | `2F 2F` after decryption |
7//! | TPL, mode 7 | AES-128-CBC, IV = 0, key derived per message (CMAC KDF) | AFL CMAC (and `2F 2F`) |
8//! | TPL, mode 10 | AES-128-CCM, nonce = M ‖ A ‖ 00 ‖ counter, key derived per message | CCM tag (authenticates) |
9//! | ELL (CI `8D`/`8F`) | AES-128-CTR, IV = M ‖ A ‖ CC ‖ SN ‖ FN ‖ BC | payload CRC |
10//!
11//! Keys are the caller's: [`Key`] holds one, erases it on drop and never shows it in
12//! `Debug`. [`Keys`] is how the library asks for the key of a meter; implement it for a
13//! key store, or use a single [`Key`] or a slice of `(Address, Key)` pairs.
14//!
15//! Only mode 7 with a verified CMAC and mode 10 authenticate a telegram. Mode 5 and the ELL give
16//! confidentiality only: `2F 2F` and the payload CRC detect a wrong key, not tampering.
17//! Both are malleable without the key (CBC through the IV inputs in the header, CTR with
18//! a recomputed CRC), and a fleet-wide key lets its holders send anything
19//! ([`Authenticity`](crate::app::Authenticity)).
20
21use core::fmt;
22
23use aes::Aes128;
24use aes::cipher::generic_array::GenericArray;
25use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyInit, KeyIvInit, StreamCipher};
26use cmac::{Cmac, Mac};
27use zeroize::Zeroize;
28
29use crate::app::Address;
30use crate::{Check, Error, Result};
31
32/// A 128-bit AES key. Erased from memory when dropped; never printed.
33#[derive(Clone)]
34pub struct Key([u8; 16]);
35
36impl Drop for Key {
37    fn drop(&mut self) {
38        self.0.zeroize();
39    }
40}
41
42impl Key {
43    /// A key from its 16 bytes.
44    pub const fn new(bytes: [u8; 16]) -> Self {
45        Self(bytes)
46    }
47
48    /// A key from 32 hex digits (whitespace allowed), as meter key sheets print them.
49    /// `None` if the text is not exactly 16 bytes of hex. The intermediate buffer is
50    /// erased.
51    pub fn from_hex(text: &str) -> Option<Self> {
52        let mut key = Self([0; 16]);
53        let mut n = 0usize;
54        let mut high: Option<u8> = None;
55        for c in text.bytes().filter(|c| !c.is_ascii_whitespace()) {
56            let v = match c {
57                b'0'..=b'9' => c - b'0',
58                b'a'..=b'f' => c - b'a' + 10,
59                b'A'..=b'F' => c - b'A' + 10,
60                _ => return None,
61            };
62            match high.take() {
63                None => high = Some(v),
64                Some(h) => {
65                    *key.0.get_mut(n)? = (h << 4) | v;
66                    n += 1;
67                }
68            }
69        }
70        (n == 16 && high.is_none()).then_some(key)
71    }
72
73    pub(crate) const fn bytes(&self) -> &[u8; 16] {
74        &self.0
75    }
76}
77
78impl fmt::Debug for Key {
79    /// `Key(..)`: the bytes never appear (constitution IV).
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.write_str("Key(..)")
82    }
83}
84
85impl From<[u8; 16]> for Key {
86    fn from(bytes: [u8; 16]) -> Self {
87        Self(bytes)
88    }
89}
90
91/// Where the library gets the key for a meter.
92pub trait Keys {
93    /// The key for `meter`, or `None`.
94    fn key(&self, meter: &Address) -> Option<&Key>;
95}
96
97/// One key for every meter: for a single meter, or a test.
98impl Keys for Key {
99    fn key(&self, _: &Address) -> Option<&Key> {
100        Some(self)
101    }
102}
103
104/// A key per meter, matched on manufacturer and identification number (version and
105/// device type are not part of a key sheet, and a gateway's long header may differ).
106impl Keys for [(Address, Key)] {
107    fn key(&self, meter: &Address) -> Option<&Key> {
108        self.iter().find(|(a, _)| a.manufacturer == meter.manufacturer && a.id == meter.id).map(|(_, k)| k)
109    }
110}
111
112impl<const N: usize> Keys for [(Address, Key); N] {
113    fn key(&self, meter: &Address) -> Option<&Key> {
114        self.as_slice().key(meter)
115    }
116}
117
118impl<K: Keys + ?Sized> Keys for &K {
119    fn key(&self, meter: &Address) -> Option<&Key> {
120        (**self).key(meter)
121    }
122}
123
124/// AES-128-CBC decryption of whole blocks, in place.
125pub(crate) fn cbc_decrypt(key: &Key, iv: &[u8; 16], data: &mut [u8]) -> Result<()> {
126    if data.len() % 16 != 0 {
127        return Err(Error::Verification(Check::Length));
128    }
129    let mut cipher = cbc::Decryptor::<Aes128>::new(key.bytes().into(), iv.into());
130    for block in data.chunks_exact_mut(16) {
131        cipher.decrypt_block_mut(GenericArray::from_mut_slice(block));
132    }
133    Ok(())
134}
135
136/// AES-128-CBC encryption of whole blocks, in place (the simulator).
137pub(crate) fn cbc_encrypt(key: &Key, iv: &[u8; 16], data: &mut [u8]) -> Result<()> {
138    if data.len() % 16 != 0 {
139        return Err(Error::InvalidLength);
140    }
141    let mut cipher = cbc::Encryptor::<Aes128>::new(key.bytes().into(), iv.into());
142    for block in data.chunks_exact_mut(16) {
143        cipher.encrypt_block_mut(GenericArray::from_mut_slice(block));
144    }
145    Ok(())
146}
147
148/// AES-128-CCM encryption in place with an 8-byte tag (the simulator).
149pub(crate) fn ccm_encrypt(key: &Key, nonce: &[u8; 13], aad: &[u8], data: &mut [u8]) -> Result<[u8; 8]> {
150    use ccm::aead::AeadInPlace;
151    use ccm::consts::{U8, U13};
152    let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
153    let tag = cipher.encrypt_in_place_detached(nonce.into(), aad, data).map_err(|_| Error::InvalidLength)?;
154    Ok(tag.into())
155}
156
157/// AES-128-CCM decryption in place with tag verification (8-byte tags, as OMS requires).
158/// The plaintext is only left in `data` when the tag verifies; otherwise it is erased.
159pub(crate) fn ccm_decrypt(
160    key: &Key,
161    nonce: &[u8; 13],
162    aad: &[u8],
163    data: &mut [u8],
164    tag: &[u8],
165) -> Result<()> {
166    use ccm::aead::AeadInPlace;
167    use ccm::consts::{U8, U13};
168    let tag: &[u8; 8] = tag.try_into().map_err(|_| Error::UnsupportedSecurity(10))?;
169    let cipher = ccm::Ccm::<Aes128, U8, U13>::new(key.bytes().into());
170    cipher.decrypt_in_place_detached(nonce.into(), aad, data, tag.into()).map_err(|_| {
171        data.zeroize();
172        Error::Verification(Check::Tag)
173    })
174}
175
176/// AES-128-CTR (big-endian 128-bit counter), in place.
177pub(crate) fn ctr_apply(key: &Key, iv: &[u8; 16], data: &mut [u8]) {
178    ctr::Ctr128BE::<Aes128>::new(key.bytes().into(), iv.into()).apply_keystream(data);
179}
180
181/// AES-CMAC over the concatenation of `parts`.
182pub(crate) fn cmac(key: &Key, parts: &[&[u8]]) -> [u8; 16] {
183    let mut mac = <Cmac<Aes128> as KeyInit>::new(key.bytes().into());
184    for p in parts {
185        mac.update(p);
186    }
187    mac.finalize().into_bytes().into()
188}
189
190/// Constant-time comparison of a received MAC against the computed one.
191pub(crate) fn mac_matches(computed: &[u8], received: &[u8]) -> bool {
192    computed.len() == received.len()
193        && computed.iter().zip(received).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
194}
195
196/// The OMS key derivation (OMS Vol. 2 §9.5, KDF-A): `CMAC(K, D ‖ C ‖ ID ‖ 07…07)`, with
197/// `D = 00` for the encryption key from the meter, `01` for its MAC key, the message
198/// counter `C` and the meter's identification number, both as transmitted.
199pub(crate) fn derive(key: &Key, d: u8, counter: [u8; 4], id: [u8; 4]) -> Key {
200    let [c0, c1, c2, c3] = counter;
201    let [i0, i1, i2, i3] = id;
202    let input = [d, c0, c1, c2, c3, i0, i1, i2, i3, 7, 7, 7, 7, 7, 7, 7];
203    let mut derived = cmac(key, &[&input]);
204    let k = Key(derived);
205    derived.zeroize();
206    k
207}
208
209#[cfg(test)]
210mod tests {
211    extern crate std;
212    use super::*;
213    use std::format;
214
215    #[test]
216    fn keys_never_print() {
217        let k = Key::from_hex("01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 11").unwrap();
218        assert_eq!(format!("{k:?}"), "Key(..)");
219        assert_eq!(k.bytes()[15], 0x11);
220        assert!(Key::from_hex("0102").is_none());
221        assert!(Key::from_hex("zz02030405060708090A0B0C0D0E0F11").is_none());
222        assert!(Key::from_hex("0102030405060708090A0B0C0D0E0F1122").is_none());
223    }
224
225    #[test]
226    fn cmac_matches_rfc_4493() {
227        // RFC 4493, example 2: K = 2b7e1516…, M = 6bc1bee2 2e409f96 e93d7e11 7393172a.
228        let k = Key::from_hex("2b7e151628aed2a6abf7158809cf4f3c").unwrap();
229        let m =
230            [0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a];
231        let t = cmac(&k, &[&m[..8], &m[8..]]);
232        assert_eq!(
233            t,
234            [0x07, 0x0a, 0x16, 0xb4, 0x6b, 0x4d, 0x41, 0x44, 0xf7, 0x9b, 0xdd, 0x9d, 0xd0, 0x4a, 0x28, 0x7c]
235        );
236    }
237}