mbus-kit 0.4.0

M-Bus and wireless M-Bus (EN 13757-2/-3/-4) for Rust: heat, water and gas meter readout with a sans-I/O, no_std, allocation-free core
Documentation
//! Write OMS-secured wireless telegrams: for gateway simulators and tests (feature `oms`).
//!
//! [`Telegram`] is what a meter transmits: link layer, an optional ELL, the AFL for mode
//! 7, a short transport header and the records, protected by mode 5, 7 or 10, with an
//! optional plaintext tail after the protected part. A simulated gas meter with a rising
//! counter:
//!
//! ```
//! use mbus_kit::app::Authenticity;
//! use mbus_kit::sim::{Security, Telegram};
//! use mbus_kit::wireless::{self, Format};
//! use mbus_kit::{Address, Manufacturer, Medium, oms::Key};
//!
//! let meter = Address {
//!     manufacturer: Manufacturer::from_letters(*b"ELS").unwrap(),
//!     id: [0x78, 0x56, 0x34, 0x12], // 12345678, least significant byte first
//!     version: 0x33,
//!     medium: Medium::GAS,
//! };
//! let key = Key::new([0x2B; 16]);
//! for counter in 1..=3u32 {
//!     // One record: DIF 04 (32-bit integer), VIF 13 (volume in litres).
//!     let [a, b, c, d] = (1_250 * counter).to_le_bytes();
//!     let records = [0x04, 0x13, a, b, c, d];
//!     let telegram = Telegram {
//!         access_number: counter as u8,
//!         ..Telegram::new(meter, Security::Mode7 { counter, mac: true }, &records)
//!     };
//!     let mut radio = [0u8; 256];
//!     let n = telegram.write(&key, Format::A, &mut radio)?;
//!
//!     let mut buf = [0u8; 512];
//!     let (t, _) = wireless::open(&radio[..n], Format::A, &key, &mut buf)?.unwrap();
//!     assert_eq!(t.app.authenticity, Authenticity::Authenticated { counter });
//!     let volume = t.app.records().unwrap().next().unwrap()?;
//!     assert_eq!(volume.quantity().unwrap().mantissa, i128::from(1_250 * counter));
//! }
//! # Ok::<(), mbus_kit::Error>(())
//! ```
//!
//! Records are their wire bytes (DIF, VIF, data), as a meter's firmware holds them. A
//! [`Telegram::tail`] travels after the protected part: in mode 5 and in mode 7 without
//! MAC nothing protects it, and the decoder says so per record
//! ([`Record::authenticity`](crate::Record::authenticity)); in mode 7 with MAC and in
//! mode 10 the MAC or tag covers it.
//!
//! **A round trip through this writer and the crate's decoder proves that they agree,
//! not that either is right.** The independent evidence is that the writer reproduces
//! the published OMS Annex N frames N.2.1, N.2.3 and N.2.6 byte for byte
//! (`tests/sim.rs`). Short transport headers only (CI `7A`), mode 7 with KDF-A and an
//! 8-byte CMAC, mode 10 with an 8-byte tag; no fragments.

use zeroize::Zeroize;

use crate::app::{Address, Ell, ci};
use crate::crc::crc16;
use crate::oms::{self, Key};
use crate::wireless::{self, Format, control};
use crate::{Error, Result};

/// How the records are protected.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Security {
    /// None: anyone in range could have sent it.
    Plain,
    /// Mode 5: AES-128-CBC with the meter's key, IV from the address and access number.
    /// Confidential, not authenticated.
    Mode5,
    /// Mode 7: AES-128-CBC with a key derived from the meter's key and `counter` (KDF-A).
    /// With `mac`, an AFL CMAC (8 bytes) over the transport layer authenticates it.
    Mode7 {
        /// The AFL message counter; a meter increments it per telegram.
        counter: u32,
        /// Whether the AFL carries a MAC. Without one the telegram is only encrypted.
        mac: bool,
    },
    /// Mode 10: AES-128-CCM with a key derived from `counter`; the 8-byte tag
    /// authenticates the header, the records and the tail.
    Mode10 {
        /// The TPL message counter; a meter increments it per telegram.
        counter: u32,
    },
}

/// A telegram as a meter transmits it. Build it with [`Telegram::new`] and change
/// fields with struct update syntax.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Telegram<'a> {
    /// The link layer's C field: [`control::SND_NR`] for a meter's periodic telegram.
    pub c: u8,
    /// The meter (link layer address; it forms the IV, the nonce and the derived keys).
    pub address: Address,
    /// An extended link layer: `8C` (CC and access number), `8E` with a receiver, `8D`
    /// / `8F` with a session number and payload CRC, encrypted with AES-128-CTR when
    /// the session number announces it ([`Ell::encrypted`]).
    pub ell: Option<Ell>,
    /// The transport layer's access number; a meter increments it per telegram.
    pub access_number: u8,
    /// The transport layer's status byte (battery low, errors, …).
    pub status: u8,
    /// The configuration field's S bit: the meter transmits on a fixed schedule.
    pub synchronous: bool,
    /// How the records are protected.
    pub security: Security,
    /// The records as transmitted, without the `2F 2F` marker (it is added for modes 5
    /// and 7).
    pub records: &'a [u8],
    /// Records after the protected part, in plaintext.
    pub tail: &'a [u8],
}

impl<'a> Telegram<'a> {
    /// A periodic telegram (`SND_NR`) from `address` with `records`: no ELL, access
    /// number and status 0, no tail.
    pub const fn new(address: Address, security: Security, records: &'a [u8]) -> Self {
        Self {
            c: control::SND_NR,
            address,
            ell: None,
            access_number: 0,
            status: 0,
            synchronous: false,
            security,
            records,
            tail: &[],
        }
    }

    /// Write the telegram into `out` in `format`, protected with the meter's `key`
    /// (unused for [`Security::Plain`] without an encrypted ELL). Returns the number of
    /// bytes written.
    ///
    /// [`Error::InvalidLength`] when it does not fit in one frame (or mode 5/7 would need
    /// more than 15 blocks, or 15 with a tail), [`Error::OutputTooSmall`] when `out`
    /// cannot hold it. The plaintext and the derived keys are erased before returning.
    pub fn write(&self, key: &Key, format: Format, out: &mut [u8]) -> Result<usize> {
        let mut buf = [0u8; 256];
        let result = self.application(key, &mut buf).and_then(|n| {
            let (&first_ci, payload) =
                buf.get(..n).and_then(<[u8]>::split_first).ok_or(Error::InvalidLength)?;
            wireless::encode(format, self.c, &self.address, first_ci, payload, out)
        });
        buf.zeroize();
        result
    }

    /// Everything after the link layer's address, from the first CI on, into `buf`.
    fn application(&self, key: &Key, buf: &mut [u8]) -> Result<usize> {
        let mut w = Writer { buf, n: 0 };
        let ell_crc = match self.ell {
            Some(ell) => ell_header(&ell, &mut w)?,
            None => None,
        };
        let (counter, mac) = match self.security {
            Security::Mode7 { counter, mac } => (counter, mac),
            Security::Mode10 { counter } => (counter, false),
            _ => (0, false),
        };
        let counter_le = counter.to_le_bytes();
        // Mode 7: the AFL with message control, counter and, if asked for, the MAC.
        let mut mac_at = None;
        if let Security::Mode7 { .. } = self.security {
            let (fcl, mcl, len): (u16, u8, u8) = if mac { (0x2C00, 0x25, 15) } else { (0x2800, 0x20, 7) };
            w.put(&[ci::AFL, len])?;
            w.put(&fcl.to_le_bytes())?;
            w.put(&[mcl])?;
            w.put(&counter_le)?;
            if mac {
                mac_at = Some(w.n);
                w.put(&[0; 8])?;
            }
        }
        // The transport header: CI, access number, status, configuration, its extension.
        let s = if self.synchronous { 0x20 } else { 0 };
        let tpl = w.n;
        w.put(&[ci::RSP_SHORT, self.access_number, self.status])?;
        match self.security {
            Security::Plain => w.put(&[0x00, s])?,
            Security::Mode5 | Security::Mode7 { .. } => {
                let blocks = (self.records.len() + 2).div_ceil(16);
                if blocks > 15 || (blocks == 15 && !self.tail.is_empty()) {
                    return Err(Error::InvalidLength);
                }
                let mode = if self.security == Security::Mode5 { 5 } else { 7 };
                // NNNN counts 16-byte blocks; the mode-7 CFE: KDF-A, key ID 0.
                w.put(&[u8::try_from(blocks << 4).map_err(|_| Error::InvalidLength)?, mode | s])?;
                if mode == 7 {
                    w.put(&[0x10])?;
                }
            }
            Security::Mode10 { .. } => {
                // The low byte counts encrypted bytes (FF would mean "to the end"); CFE:
                // KDF-A, 8-byte tag; then the message counter.
                let n = u8::try_from(self.records.len())
                    .ok()
                    .filter(|&n| n != 0xFF)
                    .ok_or(Error::InvalidLength)?;
                w.put(&[n, 0x0A | s, 0x10, 0x01])?;
                w.put(&counter_le)?;
            }
        }
        let data = w.n;
        match self.security {
            Security::Plain | Security::Mode10 { .. } => w.put(self.records)?,
            Security::Mode5 | Security::Mode7 { .. } => {
                w.put(&[0x2F, 0x2F])?;
                w.put(self.records)?;
                while (w.n - data) % 16 != 0 {
                    w.put(&[0x2F])?;
                }
                let plain = w.buf.get_mut(data..w.n).ok_or(Error::InvalidLength)?;
                if self.security == Security::Mode5 {
                    let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
                    let x = self.access_number;
                    oms::cbc_encrypt(key, &[a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x], plain)?;
                } else {
                    let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
                    oms::cbc_encrypt(&kenc, &[0; 16], plain)?;
                }
            }
        }
        let encrypted_end = w.n;
        w.put(self.tail)?;
        if let Security::Mode10 { .. } = self.security {
            // AAD: CI ‖ access, status, configuration, CFE ‖ tail (not the counter: it is
            // in the nonce).
            let mut aad = [0u8; 256];
            let header = w.buf.get(tpl..tpl + 7).ok_or(Error::InvalidLength)?;
            let tail_len = self.tail.len();
            aad.get_mut(..7).ok_or(Error::InvalidLength)?.copy_from_slice(header);
            aad.get_mut(7..7 + tail_len).ok_or(Error::InvalidLength)?.copy_from_slice(self.tail);
            let kenc = oms::derive(key, 0x00, counter_le, self.address.id);
            let [m0, m1, i0, i1, i2, i3, v, t] = self.address.to_bytes();
            let [c0, c1, c2, c3] = counter.to_be_bytes();
            let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
            let plain = w.buf.get_mut(data..encrypted_end).ok_or(Error::InvalidLength)?;
            let tag = oms::ccm_encrypt(&kenc, &nonce, aad.get(..7 + tail_len).unwrap_or(&[]), plain)?;
            w.put(&tag)?;
        }
        if let Some(at) = mac_at {
            // OMS Vol. 2 §9.3.3: CMAC(Kmac, MCL ‖ MCR ‖ TPL CI … end), truncated to 8 bytes.
            let kmac = oms::derive(key, 0x01, counter_le, self.address.id);
            let tpl_bytes = w.buf.get(tpl..w.n).ok_or(Error::InvalidLength)?;
            let tag = oms::cmac(&kmac, &[&[0x25], &counter_le, tpl_bytes]);
            w.buf
                .get_mut(at..at + 8)
                .ok_or(Error::InvalidLength)?
                .copy_from_slice(tag.get(..8).unwrap_or(&[]));
        }
        if let (Some(at), Some(ell)) = (ell_crc, self.ell) {
            self.ell_seal(&ell, key, at, &mut w)?;
        }
        Ok(w.n)
    }

    /// The ELL payload CRC over everything after it, then AES-CTR from the CRC on when
    /// the session number announces encryption.
    fn ell_seal(&self, ell: &Ell, key: &Key, at: usize, w: &mut Writer<'_>) -> Result<()> {
        let crc = crc16(w.buf.get(at + 2..w.n).ok_or(Error::InvalidLength)?).to_le_bytes();
        w.buf.get_mut(at..at + 2).ok_or(Error::InvalidLength)?.copy_from_slice(&crc);
        if ell.encrypted() {
            let [a, b, c, d, e, f, g, h] = self.address.to_bytes();
            let [s0, s1, s2, s3] = ell.session.unwrap_or(0).to_le_bytes();
            let iv = [a, b, c, d, e, f, g, h, ell.cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
            oms::ctr_apply(key, &iv, w.buf.get_mut(at..w.n).ok_or(Error::InvalidLength)?);
        }
        Ok(())
    }
}

/// Write the ELL header; returns where its payload CRC goes, if it has one.
fn ell_header(ell: &Ell, w: &mut Writer<'_>) -> Result<Option<usize>> {
    let first = match (ell.receiver, ell.session) {
        (None, None) => ci::ELL_SHORT,
        (Some(_), None) => ci::ELL_LONG,
        (None, Some(_)) => ci::ELL_SHORT_SN,
        (Some(_), Some(_)) => ci::ELL_LONG_SN,
    };
    w.put(&[first, ell.cc, ell.access_number])?;
    if let Some(r) = ell.receiver {
        w.put(&r.to_bytes())?;
    }
    let Some(sn) = ell.session else { return Ok(None) };
    w.put(&sn.to_le_bytes())?;
    let at = w.n;
    w.put(&[0, 0])?;
    Ok(Some(at))
}

/// Appends to a buffer; running out of room is [`Error::InvalidLength`] (no frame is
/// that long).
struct Writer<'b> {
    buf: &'b mut [u8],
    n: usize,
}

impl Writer<'_> {
    fn put(&mut self, bytes: &[u8]) -> Result<()> {
        let end = self.n.checked_add(bytes.len()).ok_or(Error::InvalidLength)?;
        self.buf.get_mut(self.n..end).ok_or(Error::InvalidLength)?.copy_from_slice(bytes);
        self.n = end;
        Ok(())
    }
}