Skip to main content

mbus_kit/
sim.rs

1//! Write OMS-secured wireless telegrams: for gateway simulators and tests (feature `oms`).
2//!
3//! [`Telegram`] is what a meter transmits: link layer, an optional ELL, the AFL for mode
4//! 7, a short transport header and the records, protected by mode 5, 7 or 10, with an
5//! optional plaintext tail after the protected part. A simulated gas meter with a rising
6//! counter:
7//!
8//! ```
9//! use mbus_kit::app::Authenticity;
10//! use mbus_kit::sim::{Security, Telegram};
11//! use mbus_kit::wireless::{self, Format};
12//! use mbus_kit::{Address, Manufacturer, Medium, oms::Key};
13//!
14//! let meter = Address {
15//!     manufacturer: Manufacturer::from_letters(*b"ELS").unwrap(),
16//!     id: [0x78, 0x56, 0x34, 0x12], // 12345678, least significant byte first
17//!     version: 0x33,
18//!     medium: Medium::GAS,
19//! };
20//! let key = Key::new([0x2B; 16]);
21//! for counter in 1..=3u32 {
22//!     // One record: DIF 04 (32-bit integer), VIF 13 (volume in litres).
23//!     let [a, b, c, d] = (1_250 * counter).to_le_bytes();
24//!     let records = [0x04, 0x13, a, b, c, d];
25//!     let telegram = Telegram {
26//!         access_number: counter as u8,
27//!         ..Telegram::new(meter, Security::Mode7 { counter, mac: true }, &records)
28//!     };
29//!     let mut radio = [0u8; 256];
30//!     let n = telegram.write(&key, Format::A, &mut radio)?;
31//!
32//!     let mut buf = [0u8; 512];
33//!     let (t, _) = wireless::open(&radio[..n], Format::A, &key, &mut buf)?.unwrap();
34//!     assert_eq!(t.app.authenticity, Authenticity::Authenticated { counter });
35//!     let volume = t.app.records().unwrap().next().unwrap()?;
36//!     assert_eq!(volume.quantity().unwrap().mantissa, i128::from(1_250 * counter));
37//! }
38//! # Ok::<(), mbus_kit::Error>(())
39//! ```
40//!
41//! Records are their wire bytes (DIF, VIF, data), as a meter's firmware holds them. A
42//! [`Telegram::tail`] travels after the protected part: in mode 5 and in mode 7 without
43//! MAC nothing protects it, and the decoder says so per record
44//! ([`Record::authenticity`](crate::Record::authenticity)); in mode 7 with MAC and in
45//! mode 10 the MAC or tag covers it.
46//!
47//! **A round trip through this writer and the crate's decoder proves that they agree,
48//! not that either is right.** The independent evidence is that the writer reproduces
49//! the published OMS Annex N frames N.2.1, N.2.3 and N.2.6 byte for byte
50//! (`tests/sim.rs`). Short transport headers only (CI `7A`), mode 7 with KDF-A and an
51//! 8-byte CMAC, mode 10 with an 8-byte tag; no fragments.
52
53use zeroize::Zeroize;
54
55use crate::app::{Address, Ell, ci};
56use crate::crc::crc16;
57use crate::oms::{self, Key};
58use crate::wireless::{self, Format, control};
59use crate::{Error, Result};
60
61/// How the records are protected.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub enum Security {
64    /// None: anyone in range could have sent it.
65    Plain,
66    /// Mode 5: AES-128-CBC with the meter's key, IV from the address and access number.
67    /// Confidential, not authenticated.
68    Mode5,
69    /// Mode 7: AES-128-CBC with a key derived from the meter's key and `counter` (KDF-A).
70    /// With `mac`, an AFL CMAC (8 bytes) over the transport layer authenticates it.
71    Mode7 {
72        /// The AFL message counter; a meter increments it per telegram.
73        counter: u32,
74        /// Whether the AFL carries a MAC. Without one the telegram is only encrypted.
75        mac: bool,
76    },
77    /// Mode 10: AES-128-CCM with a key derived from `counter`; the 8-byte tag
78    /// authenticates the header, the records and the tail.
79    Mode10 {
80        /// The TPL message counter; a meter increments it per telegram.
81        counter: u32,
82    },
83}
84
85/// A telegram as a meter transmits it. Build it with [`Telegram::new`] and change
86/// fields with struct update syntax.
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct Telegram<'a> {
89    /// The link layer's C field: [`control::SND_NR`] for a meter's periodic telegram.
90    pub c: u8,
91    /// The meter (link layer address; it forms the IV, the nonce and the derived keys).
92    pub address: Address,
93    /// An extended link layer: `8C` (CC and access number), `8E` with a receiver, `8D`
94    /// / `8F` with a session number and payload CRC, encrypted with AES-128-CTR when
95    /// the session number announces it ([`Ell::encrypted`]).
96    pub ell: Option<Ell>,
97    /// The transport layer's access number; a meter increments it per telegram.
98    pub access_number: u8,
99    /// The transport layer's status byte (battery low, errors, …).
100    pub status: u8,
101    /// The configuration field's S bit: the meter transmits on a fixed schedule.
102    pub synchronous: bool,
103    /// How the records are protected.
104    pub security: Security,
105    /// The records as transmitted, without the `2F 2F` marker (it is added for modes 5
106    /// and 7).
107    pub records: &'a [u8],
108    /// Records after the protected part, in plaintext.
109    pub tail: &'a [u8],
110}
111
112impl<'a> Telegram<'a> {
113    /// A periodic telegram (`SND_NR`) from `address` with `records`: no ELL, access
114    /// number and status 0, no tail.
115    pub const fn new(address: Address, security: Security, records: &'a [u8]) -> Self {
116        Self {
117            c: control::SND_NR,
118            address,
119            ell: None,
120            access_number: 0,
121            status: 0,
122            synchronous: false,
123            security,
124            records,
125            tail: &[],
126        }
127    }
128
129    /// Write the telegram into `out` in `format`, protected with the meter's `key`
130    /// (unused for [`Security::Plain`] without an encrypted ELL). Returns the number of
131    /// bytes written.
132    ///
133    /// [`Error::InvalidLength`] when it does not fit in one frame (or mode 5/7 would need
134    /// more than 15 blocks, or 15 with a tail), [`Error::OutputTooSmall`] when `out`
135    /// cannot hold it. The plaintext and the derived keys are erased before returning.
136    pub fn write(&self, key: &Key, format: Format, out: &mut [u8]) -> Result<usize> {
137        let mut buf = [0u8; 256];
138        let result = self.application(key, &mut buf).and_then(|n| {
139            let (&first_ci, payload) =
140                buf.get(..n).and_then(<[u8]>::split_first).ok_or(Error::InvalidLength)?;
141            wireless::encode(format, self.c, &self.address, first_ci, payload, out)
142        });
143        buf.zeroize();
144        result
145    }
146
147    /// Everything after the link layer's address, from the first CI on, into `buf`.
148    fn application(&self, key: &Key, buf: &mut [u8]) -> Result<usize> {
149        let mut w = Writer { buf, n: 0 };
150        let ell_crc = match self.ell {
151            Some(ell) => ell_header(&ell, &mut w)?,
152            None => None,
153        };
154        let (counter, mac) = match self.security {
155            Security::Mode7 { counter, mac } => (counter, mac),
156            Security::Mode10 { counter } => (counter, false),
157            _ => (0, false),
158        };
159        let counter_le = counter.to_le_bytes();
160        // Mode 7: the AFL with message control, counter and, if asked for, the MAC.
161        let mut mac_at = None;
162        if let Security::Mode7 { .. } = self.security {
163            let (fcl, mcl, len): (u16, u8, u8) = if mac { (0x2C00, 0x25, 15) } else { (0x2800, 0x20, 7) };
164            w.put(&[ci::AFL, len])?;
165            w.put(&fcl.to_le_bytes())?;
166            w.put(&[mcl])?;
167            w.put(&counter_le)?;
168            if mac {
169                mac_at = Some(w.n);
170                w.put(&[0; 8])?;
171            }
172        }
173        // The transport header: CI, access number, status, configuration, its extension.
174        let s = if self.synchronous { 0x20 } else { 0 };
175        let tpl = w.n;
176        w.put(&[ci::RSP_SHORT, self.access_number, self.status])?;
177        match self.security {
178            Security::Plain => w.put(&[0x00, s])?,
179            Security::Mode5 | Security::Mode7 { .. } => {
180                let blocks = (self.records.len() + 2).div_ceil(16);
181                if blocks > 15 || (blocks == 15 && !self.tail.is_empty()) {
182                    return Err(Error::InvalidLength);
183                }
184                let mode = if self.security == Security::Mode5 { 5 } else { 7 };
185                // NNNN counts 16-byte blocks; the mode-7 CFE: KDF-A, key ID 0.
186                w.put(&[u8::try_from(blocks << 4).map_err(|_| Error::InvalidLength)?, mode | s])?;
187                if mode == 7 {
188                    w.put(&[0x10])?;
189                }
190            }
191            Security::Mode10 { .. } => {
192                // The low byte counts encrypted bytes (FF would mean "to the end"); CFE:
193                // KDF-A, 8-byte tag; then the message counter.
194                let n = u8::try_from(self.records.len())
195                    .ok()
196                    .filter(|&n| n != 0xFF)
197                    .ok_or(Error::InvalidLength)?;
198                w.put(&[n, 0x0A | s, 0x10, 0x01])?;
199                w.put(&counter_le)?;
200            }
201        }
202        let data = w.n;
203        match self.security {
204            Security::Plain | Security::Mode10 { .. } => w.put(self.records)?,
205            Security::Mode5 | Security::Mode7 { .. } => {
206                w.put(&[0x2F, 0x2F])?;
207                w.put(self.records)?;
208                while (w.n - data) % 16 != 0 {
209                    w.put(&[0x2F])?;
210                }
211                let plain = w.buf.get_mut(data..w.n).ok_or(Error::InvalidLength)?;
212                if self.security == Security::Mode5 {
213                    let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
214                    let x = self.access_number;
215                    oms::cbc_encrypt(key, &[a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x], plain)?;
216                } else {
217                    let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
218                    oms::cbc_encrypt(&kenc, &[0; 16], plain)?;
219                }
220            }
221        }
222        let encrypted_end = w.n;
223        w.put(self.tail)?;
224        if let Security::Mode10 { .. } = self.security {
225            // AAD: CI ‖ access, status, configuration, CFE ‖ tail (not the counter: it is
226            // in the nonce).
227            let mut aad = [0u8; 256];
228            let header = w.buf.get(tpl..tpl + 7).ok_or(Error::InvalidLength)?;
229            let tail_len = self.tail.len();
230            aad.get_mut(..7).ok_or(Error::InvalidLength)?.copy_from_slice(header);
231            aad.get_mut(7..7 + tail_len).ok_or(Error::InvalidLength)?.copy_from_slice(self.tail);
232            let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
233            let [m0, m1, i0, i1, i2, i3, v, t] = self.address.to_bytes();
234            let [c0, c1, c2, c3] = counter.to_be_bytes();
235            let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
236            let plain = w.buf.get_mut(data..encrypted_end).ok_or(Error::InvalidLength)?;
237            let tag = oms::ccm_encrypt(&kenc, &nonce, aad.get(..7 + tail_len).unwrap_or(&[]), plain)?;
238            w.put(&tag)?;
239        }
240        if let Some(at) = mac_at {
241            // OMS Vol. 2 §9.3.3: CMAC(Kmac, MCL ‖ MCR ‖ TPL CI … end), truncated to 8 bytes.
242            let kmac = oms::derive(key, 0x01, counter_le, self.address.id);
243            let tpl_bytes = w.buf.get(tpl..w.n).ok_or(Error::InvalidLength)?;
244            let tag = oms::cmac(&kmac, &[&[0x25], &counter_le, tpl_bytes]);
245            w.buf
246                .get_mut(at..at + 8)
247                .ok_or(Error::InvalidLength)?
248                .copy_from_slice(tag.get(..8).unwrap_or(&[]));
249        }
250        if let (Some(at), Some(ell)) = (ell_crc, self.ell) {
251            self.ell_seal(&ell, key, at, &mut w)?;
252        }
253        Ok(w.n)
254    }
255
256    /// The ELL payload CRC over everything after it, then AES-CTR from the CRC on when
257    /// the session number announces encryption.
258    fn ell_seal(&self, ell: &Ell, key: &Key, at: usize, w: &mut Writer<'_>) -> Result<()> {
259        let crc = crc16(w.buf.get(at + 2..w.n).ok_or(Error::InvalidLength)?).to_le_bytes();
260        w.buf.get_mut(at..at + 2).ok_or(Error::InvalidLength)?.copy_from_slice(&crc);
261        if ell.encrypted() {
262            let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
263            let [s0, s1, s2, s3] = ell.session.unwrap_or(0).to_le_bytes();
264            let iv = [a, b, c, d, e, f, g, h, ell.cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
265            oms::ctr_apply(key, &iv, w.buf.get_mut(at..w.n).ok_or(Error::InvalidLength)?);
266        }
267        Ok(())
268    }
269}
270
271/// Write the ELL header; returns where its payload CRC goes, if it has one.
272fn ell_header(ell: &Ell, w: &mut Writer<'_>) -> Result<Option<usize>> {
273    let first = match (ell.receiver, ell.session) {
274        (None, None) => ci::ELL_SHORT,
275        (Some(_), None) => ci::ELL_LONG,
276        (None, Some(_)) => ci::ELL_SHORT_SN,
277        (Some(_), Some(_)) => ci::ELL_LONG_SN,
278    };
279    w.put(&[first, ell.cc, ell.access_number])?;
280    if let Some(r) = ell.receiver {
281        w.put(&r.to_bytes())?;
282    }
283    let Some(sn) = ell.session else { return Ok(None) };
284    w.put(&sn.to_le_bytes())?;
285    let at = w.n;
286    w.put(&[0, 0])?;
287    Ok(Some(at))
288}
289
290/// Appends to a buffer; running out of room is [`Error::InvalidLength`] (no frame is
291/// that long).
292struct Writer<'b> {
293    buf: &'b mut [u8],
294    n: usize,
295}
296
297impl Writer<'_> {
298    fn put(&mut self, bytes: &[u8]) -> Result<()> {
299        let end = self.n.checked_add(bytes.len()).ok_or(Error::InvalidLength)?;
300        self.buf.get_mut(self.n..end).ok_or(Error::InvalidLength)?.copy_from_slice(bytes);
301        self.n = end;
302        Ok(())
303    }
304}