Skip to main content

mbus_kit/
app.rs

1//! The layers above the link layer: ELL, AFL and TPL (EN 13757-3, EN 13757-7,
2//! OMS Vol. 2), and the data records they carry.
3//!
4//! ```text
5//! [ELL 8C–8F]  [AFL 90]  TPL (CI + header)  records
6//! ```
7//!
8//! | CI | Layer | Header |
9//! |---|---|---|
10//! | `8C`, `8E` | extended link layer: CC, access number (`8E`: + receiver address) | |
11//! | `8D`, `8F` | the same + session number and payload CRC; **AES-CTR** encrypted | |
12//! | `90` | authentication and fragmentation layer: message counter, **CMAC** | |
13//! | `72`, `5B`, `6F`, `75`, `8B`, `80` | transport layer | long (12 bytes) |
14//! | `7A`, `5A`, `6E`, `74`, `8A` | transport layer | short (4 bytes) |
15//! | `78`, `51`, `70`, `71` | transport layer | none |
16//!
17//! [`Application::parse`] reads every layer without a key and stops at the first
18//! encrypted one: [`Body::Encrypted`] then says how it is encrypted, and (feature `oms`)
19//! [`Encrypted::decrypt`] opens it. [`Application::authenticity`] says what, if
20//! anything, was cryptographically verified: radio data is not evidence until it is
21//! (constitution V).
22
23use core::fmt;
24
25use crate::crc::crc16;
26use crate::record::Records;
27use crate::{Check, Error, Result};
28
29/// CI values.
30pub mod ci {
31    /// Response with variable data structure, long header.
32    pub const RSP_LONG: u8 = 0x72;
33    /// Response with variable data structure, short header.
34    pub const RSP_SHORT: u8 = 0x7A;
35    /// Response with variable data structure, no header.
36    pub const RSP_NONE: u8 = 0x78;
37    /// Data send (master to slave), no header.
38    pub const SND_UD: u8 = 0x51;
39    /// Command to a device, short header (OMS).
40    pub const CMD_SHORT: u8 = 0x5A;
41    /// Command to a device, long header (OMS).
42    pub const CMD_LONG: u8 = 0x5B;
43    /// Application error, short header.
44    pub const ERROR_SHORT: u8 = 0x6E;
45    /// Application error, long header.
46    pub const ERROR_LONG: u8 = 0x6F;
47    /// Application error, no header.
48    pub const ERROR_NONE: u8 = 0x70;
49    /// Alarm, no header.
50    pub const ALARM_NONE: u8 = 0x71;
51    /// Alarm, short header.
52    pub const ALARM_SHORT: u8 = 0x74;
53    /// Alarm, long header.
54    pub const ALARM_LONG: u8 = 0x75;
55    /// Transport layer to a device, long header, no application data.
56    pub const TPL_TO_DEVICE: u8 = 0x80;
57    /// Transport layer from a device, short header, no application data.
58    pub const TPL_SHORT: u8 = 0x8A;
59    /// Transport layer from a device, long header, no application data.
60    pub const TPL_LONG: u8 = 0x8B;
61    /// Extended link layer: CC, access number.
62    pub const ELL_SHORT: u8 = 0x8C;
63    /// Extended link layer with session number and payload CRC (AES-CTR).
64    pub const ELL_SHORT_SN: u8 = 0x8D;
65    /// Extended link layer with receiver address.
66    pub const ELL_LONG: u8 = 0x8E;
67    /// Extended link layer with receiver address, session number and payload CRC.
68    pub const ELL_LONG_SN: u8 = 0x8F;
69    /// Authentication and fragmentation layer.
70    pub const AFL: u8 = 0x90;
71    /// Format frame (the record layout of compact frames), no header.
72    pub const FORMAT_NONE: u8 = 0x69;
73    /// Format frame, short header.
74    pub const FORMAT_SHORT: u8 = 0x6A;
75    /// Format frame, long header.
76    pub const FORMAT_LONG: u8 = 0x6B;
77    /// Compact frame, no header.
78    pub const COMPACT_NONE: u8 = 0x79;
79    /// Compact frame, short header.
80    pub const COMPACT_SHORT: u8 = 0x7B;
81    /// Compact frame, long header.
82    pub const COMPACT_LONG: u8 = 0x73;
83}
84
85/// A manufacturer code: three letters packed into 15 bits (the FLAG association ID).
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
87pub struct Manufacturer(pub u16);
88
89impl Manufacturer {
90    /// The code for three upper-case letters, e.g. `b"KAM"`.
91    pub const fn from_letters(l: [u8; 3]) -> Option<Self> {
92        let [a, b, c] = l;
93        if !a.is_ascii_uppercase() || !b.is_ascii_uppercase() || !c.is_ascii_uppercase() {
94            return None;
95        }
96        Some(Self((((a - 64) as u16) << 10) | (((b - 64) as u16) << 5) | ((c - 64) as u16)))
97    }
98
99    /// The three letters.
100    pub const fn letters(self) -> [u8; 3] {
101        let v = self.0;
102        [(((v >> 10) & 0x1F) as u8) + 64, (((v >> 5) & 0x1F) as u8) + 64, ((v & 0x1F) as u8) + 64]
103    }
104}
105
106impl fmt::Display for Manufacturer {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        for b in self.letters() {
109            write!(f, "{}", char::from(b))?;
110        }
111        Ok(())
112    }
113}
114
115/// The medium (device type) a meter measures.
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub struct Medium(pub u8);
118
119impl Medium {
120    /// Electricity.
121    pub const ELECTRICITY: Self = Self(0x02);
122    /// Gas.
123    pub const GAS: Self = Self(0x03);
124    /// Heat, measured at the outlet.
125    pub const HEAT: Self = Self(0x04);
126    /// Warm water (30–90 °C).
127    pub const WARM_WATER: Self = Self(0x06);
128    /// Water.
129    pub const WATER: Self = Self(0x07);
130    /// Heat cost allocator.
131    pub const HEAT_COST_ALLOCATOR: Self = Self(0x08);
132    /// Cooling load, measured at the outlet.
133    pub const COOLING: Self = Self(0x0A);
134    /// Heat, measured at the inlet.
135    pub const HEAT_INLET: Self = Self(0x0C);
136    /// Combined heat and cooling.
137    pub const HEAT_COOLING: Self = Self(0x0D);
138    /// Hot water (≥ 90 °C).
139    pub const HOT_WATER: Self = Self(0x15);
140    /// Cold water.
141    pub const COLD_WATER: Self = Self(0x16);
142
143    /// A short English name, if this crate knows the code.
144    pub const fn name(self) -> Option<&'static str> {
145        Some(match self.0 {
146            0x00 => "other",
147            0x01 => "oil",
148            0x02 => "electricity",
149            0x03 => "gas",
150            0x04 => "heat (outlet)",
151            0x05 => "steam",
152            0x06 => "warm water",
153            0x07 => "water",
154            0x08 => "heat cost allocator",
155            0x09 => "compressed air",
156            0x0A => "cooling (outlet)",
157            0x0B => "cooling (inlet)",
158            0x0C => "heat (inlet)",
159            0x0D => "heat / cooling",
160            0x0E => "bus / system",
161            0x0F => "unknown",
162            0x15 => "hot water",
163            0x16 => "cold water",
164            0x17 => "dual water",
165            0x18 => "pressure",
166            0x19 => "A/D converter",
167            0x1A => "smoke detector",
168            0x1B => "room sensor",
169            0x1C => "gas detector",
170            0x20 => "breaker (electricity)",
171            0x21 => "valve (gas or water)",
172            0x25 => "customer unit (display)",
173            0x28 => "waste water",
174            0x29 => "garbage",
175            0x31 => "communication controller",
176            0x32 => "unidirectional repeater",
177            0x33 => "bidirectional repeater",
178            0x36 => "radio converter (system side)",
179            0x37 => "radio converter (meter side)",
180            0x38 => "wired adapter",
181            _ => return None,
182        })
183    }
184}
185
186impl fmt::Display for Medium {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        match self.name() {
189            Some(n) => f.write_str(n),
190            None => write!(f, "medium 0x{:02x}", self.0),
191        }
192    }
193}
194
195/// A meter's address: manufacturer, identification number, version and device type.
196///
197/// The same eight bytes appear in the wireless link layer and in a long header (where
198/// they name the meter behind a repeater or a gateway). They select the key and form
199/// part of the OMS initialisation vector.
200#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
201pub struct Address {
202    /// Manufacturer (FLAG association code).
203    pub manufacturer: Manufacturer,
204    /// Identification number, 8 BCD digits, as transmitted (LSB first).
205    pub id: [u8; 4],
206    /// Version / generation.
207    pub version: u8,
208    /// Device type (medium).
209    pub medium: Medium,
210}
211
212impl Address {
213    /// The identification number as printed on the meter, if it is valid BCD.
214    pub fn id_number(&self) -> Option<u32> {
215        crate::value::bcd_u32(self.id)
216    }
217
218    /// The address in link-layer order: manufacturer (LE), ID, version, medium.
219    pub const fn to_bytes(self) -> [u8; 8] {
220        let [m0, m1] = self.manufacturer.0.to_le_bytes();
221        let [i0, i1, i2, i3] = self.id;
222        [m0, m1, i0, i1, i2, i3, self.version, self.medium.0]
223    }
224
225    /// Parse link-layer order (manufacturer first).
226    pub const fn from_link_bytes(b: [u8; 8]) -> Self {
227        let [m0, m1, i0, i1, i2, i3, version, medium] = b;
228        Self {
229            manufacturer: Manufacturer(u16::from_le_bytes([m0, m1])),
230            id: [i0, i1, i2, i3],
231            version,
232            medium: Medium(medium),
233        }
234    }
235}
236
237impl fmt::Display for Address {
238    /// `KAM 12345678 water v27`; the raw ID in hex if it is not valid BCD.
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        if let Some(n) = self.id_number() {
241            write!(f, "{} {n:08} {} v{}", self.manufacturer, self.medium, self.version)
242        } else {
243            let [a, b, c, d] = self.id;
244            write!(f, "{} {d:02X}{c:02X}{b:02X}{a:02X} {} v{}", self.manufacturer, self.medium, self.version)
245        }
246    }
247}
248
249/// The security mode from a transport header's configuration field (OMS Vol. 2
250/// §7.2.4, Tables 19 and 20).
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct SecurityMode {
253    /// The mode: 0 = none, 5 = AES-128-CBC with a static key, 7 = AES-128-CBC with a
254    /// derived key and CMAC, others as defined in EN 13757-7.
255    pub mode: u8,
256    /// The number of encrypted 16-byte blocks; 0 = none, 15 = everything to the end.
257    pub encrypted_blocks: u8,
258}
259
260impl SecurityMode {
261    /// Read the mode from the 2-byte configuration field (as transmitted, LSB first).
262    pub const fn from_config(config: [u8; 2]) -> Self {
263        let [low, high] = config;
264        Self { mode: high & 0x1F, encrypted_blocks: low >> 4 }
265    }
266}
267
268/// The short header: access number, status and configuration.
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
270pub struct ShortHeader {
271    /// Access number, incremented by the meter per telegram.
272    pub access_number: u8,
273    /// Status byte (application errors, battery low, …).
274    pub status: u8,
275    /// Configuration field, as transmitted.
276    pub config: [u8; 2],
277    /// The configuration field extension: mode 7 one byte (KDF, key id), mode 10 two
278    /// bytes (content index, tag size, KDF, key id), as a little-endian value.
279    pub config_ext: Option<u16>,
280    /// Mode 10: the message counter in the transport layer. Strictly increasing per meter.
281    pub counter: Option<u32>,
282}
283
284impl ShortHeader {
285    /// The security mode the configuration field announces.
286    pub const fn security(&self) -> SecurityMode {
287        SecurityMode::from_config(self.config)
288    }
289}
290
291/// The long header: the meter's address plus the short header.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct LongHeader {
294    /// The meter (ID first on the wire here, unlike the link layer).
295    pub address: Address,
296    /// Access number, status and configuration.
297    pub short: ShortHeader,
298}
299
300/// The transport-layer header.
301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub enum Header {
303    /// No header.
304    None,
305    /// Short header.
306    Short(ShortHeader),
307    /// Long header.
308    Long(LongHeader),
309}
310
311impl Header {
312    /// The security mode, or mode 0 when there is no header.
313    pub const fn security(&self) -> SecurityMode {
314        match self {
315            Self::None => SecurityMode { mode: 0, encrypted_blocks: 0 },
316            Self::Short(s) => s.security(),
317            Self::Long(l) => l.short.security(),
318        }
319    }
320
321    /// The short part (access number, status, configuration), if there is a header.
322    pub const fn short(&self) -> Option<&ShortHeader> {
323        match self {
324            Self::None => None,
325            Self::Short(s) | Self::Long(LongHeader { short: s, .. }) => Some(s),
326        }
327    }
328}
329
330/// The extended link layer (CI `8C`–`8F`).
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub struct Ell {
333    /// Communication control (bidirectional, response delay, synchronous, hop, …).
334    pub cc: u8,
335    /// The link layer's access number (the TPL's is used for the mode-5 IV).
336    pub access_number: u8,
337    /// `8E`/`8F`: the receiver's address.
338    pub receiver: Option<Address>,
339    /// `8D`/`8F`: the session number (encryption in bits 31–29, time, session counter).
340    pub session: Option<u32>,
341}
342
343impl Ell {
344    /// Whether the session number announces AES-128-CTR encryption (ENC = 1).
345    pub const fn encrypted(&self) -> bool {
346        matches!(self.session, Some(sn) if sn >> 29 == 1)
347    }
348}
349
350/// The authentication and fragmentation layer (CI `90`, OMS Vol. 2 §6, EN 13757-7).
351///
352/// Its MAC is verified only for security mode 7 (by [`Encrypted::decrypt`]); an AFL MAC in
353/// front of a plaintext or mode-5 transport layer is parsed, not checked. A fragment
354/// (fragment ID not 0) has [`Body::Fragment`]; join the fragments with
355/// [`Reassembly`](crate::fragment::Reassembly).
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Afl {
358    /// Fragmentation control: bit 14 more fragments, 13–9 which fields are present,
359    /// 7–0 fragment ID.
360    pub fcl: u16,
361    /// Message control: authentication type in bits 3–0.
362    pub mcl: Option<u8>,
363    /// Key information.
364    pub key_info: Option<u16>,
365    /// Message counter: strictly increasing per meter; compare it to detect replays.
366    pub counter: Option<u32>,
367    /// Message length: the bytes of the whole message from the TPL CI on (first fragment
368    /// of a fragmented message only).
369    pub length: Option<u16>,
370    mac: [u8; 16],
371    mac_len: u8,
372}
373
374impl Afl {
375    /// More fragments follow this one.
376    pub const fn more_fragments(&self) -> bool {
377        self.fcl & 0x4000 != 0
378    }
379
380    /// The fragment ID: 0 for an unfragmented message, 1, 2, … for the fragments of one.
381    pub const fn fragment_id(&self) -> u8 {
382        self.fcl.to_le_bytes()[0]
383    }
384
385    /// The AFL of a reassembled message: message control, key information, counter and
386    /// length from the first fragment, the MAC from the last (OMS Vol. 2 §6.2).
387    pub(crate) const fn joined(first: &Self, last: &Self) -> Self {
388        Self {
389            fcl: (first.fcl & 0x3A00) | (last.fcl & 0x04FF),
390            mcl: first.mcl,
391            key_info: first.key_info,
392            counter: first.counter,
393            length: first.length,
394            mac: last.mac,
395            mac_len: last.mac_len,
396        }
397    }
398
399    /// The message authentication code, as received (empty if absent).
400    pub fn mac(&self) -> &[u8] {
401        self.mac.get(..usize::from(self.mac_len)).unwrap_or(&[])
402    }
403}
404
405/// What was cryptographically verified about a telegram. Only
406/// [`Authenticity::Authenticated`] makes a radio reading evidence.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum Authenticity {
409    /// Nothing: plaintext, or still encrypted. Anyone in radio range can send this.
410    None,
411    /// Decrypted with the meter's key (mode 5, ELL, or mode 7 without a MAC):
412    /// **confidential, but not integrity-protected.** These modes are malleable: without
413    /// the key, an attacker can change bits of the plaintext through the IV inputs in the
414    /// header (mode 5) or the CTR ciphertext with a fixed-up CRC (ELL), and `2F 2F` and the
415    /// payload CRC still pass. And anyone holding the key, often shared by a fleet, can
416    /// send anything. Not evidence of a reading.
417    Encrypted,
418    /// The AFL CMAC was verified with the key derived for this message (mode 7).
419    Authenticated {
420        /// The message counter the MAC covers. Reject a counter not greater than the
421        /// last one accepted from this meter: the library keeps no state.
422        counter: u32,
423    },
424}
425
426/// How an encrypted layer is protected.
427#[derive(Clone, Copy, Debug, PartialEq, Eq)]
428#[non_exhaustive]
429pub enum Security {
430    /// TPL mode 5: AES-128-CBC with a static key and an IV from address and access
431    /// number.
432    Mode5,
433    /// TPL mode 7: AES-128-CBC with a per-message key derived from the AFL counter.
434    Mode7,
435    /// TPL mode 10: AES-128-CCM with a per-message key; the tag authenticates.
436    Mode10,
437    /// ELL: AES-128-CTR (CI `8D`/`8F`).
438    EllCtr,
439    /// Any other TPL security mode (not decrypted by this crate).
440    Other(u8),
441}
442
443/// An encrypted layer and everything needed to open it.
444#[derive(Clone, Copy, Debug)]
445pub struct Encrypted<'a> {
446    /// How it is protected.
447    pub security: Security,
448    /// The encrypted bytes, and any plain bytes after them.
449    pub data: &'a [u8],
450    /// How many leading bytes of `data` are encrypted.
451    pub encrypted_len: usize,
452    /// The meter whose key opens it, if known.
453    pub meter: Option<Address>,
454    #[cfg_attr(not(feature = "oms"), allow(dead_code))]
455    pub(crate) ctx: Context,
456}
457
458/// What decryption needs from the layers around the ciphertext.
459#[derive(Clone, Copy, Debug, Default)]
460#[cfg_attr(not(feature = "oms"), allow(dead_code))]
461pub(crate) struct Context {
462    /// IV for mode 5 and the ELL; zero for mode 7.
463    pub(crate) iv: [u8; 16],
464    /// The TPL CI (part of the MAC input).
465    pub(crate) ci: u8,
466    /// The TPL header bytes after the CI (MAC input, CCM associated data): at most 12 +
467    /// CFE (2) + key version (1).
468    pub(crate) header: [u8; 16],
469    pub(crate) header_len: u8,
470    /// The layers parsed so far, copied into the decrypted result.
471    pub(crate) ell: Option<Ell>,
472    pub(crate) afl: Option<Afl>,
473    pub(crate) tpl: Option<(u8, Header)>,
474    pub(crate) link: Option<Address>,
475    /// Parsing the plaintext of a decrypted ELL.
476    pub(crate) inside_ell: bool,
477    /// Mode 10: TPL message counter and tag.
478    pub(crate) counter: Option<u32>,
479    pub(crate) tag: [u8; 16],
480    pub(crate) tag_len: u8,
481}
482
483/// The payload after the transport header.
484#[derive(Clone, Debug)]
485pub enum Body<'a> {
486    /// Data records.
487    Records(Records<'a>),
488    /// An encrypted layer; open it with [`Encrypted::decrypt`] (feature `oms`).
489    Encrypted(Encrypted<'a>),
490    /// An application error (CI `6E`–`70`): the error code bytes (OMS Vol. 2 Table 40:
491    /// `01` CI error, `03` too many records, `08` busy, …).
492    ApplicationError(&'a [u8]),
493    /// An alarm (CI `71`, `74`, `75`): the alarm status bytes.
494    Alarm(&'a [u8]),
495    /// A transport layer without application data (CI `80`, `8A`, `8B`): an ACK, an
496    /// access demand or a request.
497    Empty,
498    /// A compact frame (CI `79`, `7B`, `73`): values only; expand it with the layout of
499    /// an earlier full frame ([`Compact::expand`](crate::compact::Compact::expand)).
500    Compact(crate::compact::Compact<'a>),
501    /// A format frame (CI `69`, `6A`, `6B`): a record layout for compact frames.
502    Format(crate::compact::Format<'a>),
503    /// One fragment of a longer message (AFL fragment ID not 0): the bytes after the AFL,
504    /// a piece of the transport layer. Join them with
505    /// [`Reassembly`](crate::fragment::Reassembly).
506    Fragment(&'a [u8]),
507}
508
509/// A parsed telegram above the link layer.
510#[derive(Clone, Debug)]
511pub struct Application<'a> {
512    /// The extended link layer, if present.
513    pub ell: Option<Ell>,
514    /// The authentication and fragmentation layer, if present.
515    pub afl: Option<Afl>,
516    /// The transport layer's CI, or the ELL's while the ELL is still encrypted.
517    pub ci: u8,
518    /// The transport header.
519    pub header: Header,
520    /// What was cryptographically verified.
521    pub authenticity: Authenticity,
522    /// The payload.
523    pub body: Body<'a>,
524    meter: Option<Address>,
525}
526
527impl<'a> Application<'a> {
528    /// Parse the bytes after a CI field: a wired telegram, or a wireless one when the
529    /// link-layer address does not matter (it is needed for a mode-5 short header and
530    /// the ELL: use [`Application::parse_with_link`]).
531    pub fn parse(ci: u8, data: &'a [u8]) -> Result<Self> {
532        Self::parse_with_link(ci, data, None)
533    }
534
535    /// Parse the bytes after a CI field of a wireless telegram from `link`.
536    pub fn parse_with_link(ci: u8, data: &'a [u8], link: Option<Address>) -> Result<Self> {
537        let ctx = Context { link, ..Context::default() };
538        parse_layers(ci, data, ctx, Stage::Ell)
539    }
540
541    /// Parse a message reassembled from fragments: `data` from the TPL CI on, with the
542    /// AFL joined from the first and last fragment.
543    pub(crate) fn reassembled(
544        data: &'a [u8],
545        afl: Afl,
546        ell: Option<Ell>,
547        link: Option<Address>,
548        decrypted: bool,
549    ) -> Result<Self> {
550        let (&ci, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
551        let ctx = Context { link, ell, afl: Some(afl), inside_ell: decrypted, ..Context::default() };
552        let mut app = parse_layers(ci, rest, ctx, Stage::Tpl)?;
553        if decrypted && !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
554            app.authenticity = Authenticity::Encrypted;
555        }
556        Ok(app)
557    }
558
559    /// The meter: the long header's address if there is one (a meter behind a radio
560    /// adapter or gateway), the link layer's otherwise.
561    pub const fn meter(&self) -> Option<Address> {
562        self.meter
563    }
564
565    /// A compact frame expanded with a layout from `formats` into `out`, as an
566    /// application with the same meter, header and authenticity and the full records
567    /// ([`Compact::expand`](crate::compact::Compact::expand)); any other body is
568    /// [`Error::UnsupportedCi`].
569    pub fn expand<'o, F: crate::compact::Formats + ?Sized>(
570        &self,
571        formats: &F,
572        out: &'o mut [u8],
573    ) -> Result<Application<'o>> {
574        let Body::Compact(c) = &self.body else { return Err(Error::UnsupportedCi(self.ci)) };
575        let records = c.expand(formats, out)?;
576        Ok(Application {
577            ell: self.ell,
578            afl: self.afl,
579            ci: self.ci,
580            header: self.header,
581            authenticity: self.authenticity,
582            body: Body::Records(records),
583            meter: self.meter,
584        })
585    }
586
587    /// The records, if the body is plain records.
588    pub fn records(&self) -> Option<Records<'a>> {
589        match &self.body {
590            Body::Records(r) => Some(r.clone()),
591            _ => None,
592        }
593    }
594}
595
596#[cfg(feature = "oms")]
597impl Encrypted<'_> {
598    /// Decrypt (and, for mode 7 with an AFL MAC, authenticate) this layer into `out`,
599    /// and parse what is inside.
600    ///
601    /// | Security | Key | Verified by | Authenticity |
602    /// |---|---|---|---|
603    /// | mode 5 | the meter's | `2F 2F` | [`Authenticity::Encrypted`] |
604    /// | mode 7 | derived from the meter's and the AFL counter | AFL CMAC, then `2F 2F` | [`Authenticity::Authenticated`] (without a MAC: `Encrypted`) |
605    /// | ELL | the meter's | payload CRC | `Encrypted`; the inner layers may add more |
606    ///
607    /// `out` needs `self.data.len()` bytes. On any failed check the result is an error
608    /// naming the check ([`Check`]), never partial records and never key material. An
609    /// ELL may contain a TPL that is itself encrypted: the result's body is then
610    /// [`Body::Encrypted`] again.
611    pub fn decrypt<'o, K: crate::oms::Keys + ?Sized>(
612        &self,
613        keys: &K,
614        out: &'o mut [u8],
615    ) -> Result<Application<'o>> {
616        use crate::oms;
617        let meter = self.meter.ok_or(Error::NoKey)?;
618        let key = keys.key(&meter).ok_or(Error::NoKey)?;
619        let buf = out.get_mut(..self.data.len()).ok_or(Error::OutputTooSmall)?;
620        buf.copy_from_slice(self.data);
621        let ctx = &self.ctx;
622        let authenticity = match self.security {
623            Security::EllCtr => {
624                oms::ctr_apply(key, &ctx.iv, buf);
625                let plain: &'o [u8] = buf;
626                let (crc, rest) = plain.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
627                if crc16(rest) != u16::from_le_bytes(*crc) {
628                    return Err(Error::Verification(Check::PayloadCrc));
629                }
630                let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
631                let inner = Context { link: ctx.link, ell: ctx.ell, inside_ell: true, ..Context::default() };
632                let mut app = parse_layers(next, rest, inner, Stage::Afl)?;
633                if !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
634                    app.authenticity = Authenticity::Encrypted;
635                }
636                return Ok(app);
637            }
638            Security::Mode5 => {
639                let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
640                oms::cbc_decrypt(key, &ctx.iv, enc)?;
641                Authenticity::Encrypted
642            }
643            Security::Mode7 => {
644                let afl = ctx.afl.ok_or(Error::Verification(Check::MissingCounter))?;
645                let counter = afl.counter.ok_or(Error::Verification(Check::MissingCounter))?;
646                let c = counter.to_le_bytes();
647                let mut authenticity = Authenticity::Encrypted;
648                // The message control announces a MAC (AT 5–7) that is not there: stripped.
649                if afl.mac().is_empty() && afl.mcl.and_then(mac_len).is_some() {
650                    return Err(Error::Verification(Check::Mac));
651                }
652                if !afl.mac().is_empty() {
653                    // OMS Vol. 2 §9.3.3: CMAC(Kmac, MCL ‖ MCR ‖ [ML] ‖ TPL CI … end), verified
654                    // over the ciphertext before decrypting.
655                    let kmac = oms::derive(key, 0x01, c, meter.id);
656                    let ml = afl.length.map(u16::to_le_bytes);
657                    let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
658                    let tag = oms::cmac(
659                        &kmac,
660                        &[
661                            &[afl.mcl.unwrap_or(0)],
662                            &c,
663                            ml.as_ref().map_or(&[][..], |m| &m[..]),
664                            &[ctx.ci],
665                            header,
666                            self.data,
667                        ],
668                    );
669                    let mac = afl.mac();
670                    if !oms::mac_matches(tag.get(..mac.len()).unwrap_or(&[]), mac) {
671                        return Err(Error::Verification(Check::Mac));
672                    }
673                    authenticity = Authenticity::Authenticated { counter };
674                }
675                let kenc = oms::derive(key, 0x00, c, meter.id);
676                let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
677                oms::cbc_decrypt(&kenc, &[0; 16], enc)?;
678                authenticity
679            }
680            Security::Mode10 => return self.open_ccm(key, meter, buf),
681            Security::Other(mode) => return Err(Error::UnsupportedSecurity(mode)),
682        };
683        let plain: &'o [u8] = buf;
684        if matches!(ctx.ci, ci::COMPACT_SHORT | ci::COMPACT_LONG) {
685            // No public vector settles whether 2F 2F is inside the full-frame CRC; refuse
686            // rather than guess. (ELL-encrypted compact frames, the common case, work.)
687            return Err(Error::UnsupportedCi(ctx.ci));
688        }
689        if !plain.starts_with(&[0x2F, 0x2F]) {
690            return Err(Error::Verification(Check::Marker));
691        }
692        let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
693        Ok(Application {
694            ell: ctx.ell,
695            afl: ctx.afl,
696            ci,
697            header,
698            authenticity,
699            body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
700            meter: self.meter,
701        })
702    }
703
704    /// Mode 10: verify the CCM tag and decrypt (OMS Vol. 2 §9.3.7).
705    fn open_ccm<'o>(
706        &self,
707        key: &crate::oms::Key,
708        meter: Address,
709        buf: &'o mut [u8],
710    ) -> Result<Application<'o>> {
711        use crate::oms;
712        let ctx = &self.ctx;
713        // OMS Vol. 2 §9.3.7: Kenc from the TPL counter; nonce M ‖ A ‖ 00 ‖ counter
714        // (big-endian); associated data CI ‖ TPL header ‖ CFE ‖ [key version] ‖ the
715        // unencrypted tail, if any.
716        let counter = ctx.counter.ok_or(Error::Verification(Check::MissingCounter))?;
717        let kenc = oms::derive(key, 0x00, counter.to_le_bytes(), meter.id);
718        let [m0, m1, i0, i1, i2, i3, v, t] = meter.to_bytes();
719        let [c0, c1, c2, c3] = counter.to_be_bytes();
720        let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
721        let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
722        // Bytes after the encrypted part are authenticated as associated data, or the
723        // telegram is refused: a tail outside the tag would let anyone append records to
724        // an "authenticated" message (EN 13757-7 itself is not public).
725        let tail = self.data.get(self.encrypted_len..).unwrap_or(&[]);
726        let mut aad = [0u8; 1 + 16 + 256];
727        let aad_len = 1 + header.len() + tail.len();
728        if let Some((first, rest)) = aad.split_first_mut() {
729            *first = ctx.ci;
730            rest.get_mut(..header.len()).ok_or(Error::InvalidLength)?.copy_from_slice(header);
731            rest.get_mut(header.len()..header.len() + tail.len())
732                .ok_or(Error::InvalidLength)?
733                .copy_from_slice(tail);
734        }
735        let tag = ctx.tag.get(..usize::from(ctx.tag_len)).unwrap_or(&[]);
736        let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
737        oms::ccm_decrypt(&kenc, &nonce, aad.get(..aad_len).unwrap_or(&[]), enc, tag)?;
738        let plain: &'o [u8] = buf;
739        let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
740        Ok(Application {
741            ell: ctx.ell,
742            afl: ctx.afl,
743            ci,
744            header,
745            authenticity: Authenticity::Authenticated { counter },
746            body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
747            meter: self.meter,
748        })
749    }
750}
751
752/// Which layers may still come: each at most once, in this order.
753#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
754enum Stage {
755    Ell,
756    Afl,
757    Tpl,
758}
759
760fn address_id_first(b: [u8; 8]) -> Address {
761    let [i0, i1, i2, i3, m0, m1, version, medium] = b;
762    Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium])
763}
764
765#[allow(clippy::too_many_lines)]
766fn parse_layers(ci: u8, data: &[u8], mut ctx: Context, stage: Stage) -> Result<Application<'_>> {
767    match ci {
768        ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN => {
769            if stage > Stage::Ell {
770                return Err(Error::UnexpectedLayer(ci));
771            }
772            let (&[cc, access], mut rest) = data.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
773            let mut ell = Ell { cc, access_number: access, receiver: None, session: None };
774            if matches!(ci, ci::ELL_LONG | ci::ELL_LONG_SN) {
775                let (a, r) = rest.split_first_chunk::<8>().ok_or(Error::UnexpectedEnd)?;
776                ell.receiver = Some(Address::from_link_bytes(*a));
777                rest = r;
778            }
779            if matches!(ci, ci::ELL_SHORT_SN | ci::ELL_LONG_SN) {
780                let (sn, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
781                let session = u32::from_le_bytes(*sn);
782                ell.session = Some(session);
783                ctx.ell = Some(ell);
784                if ell.encrypted() {
785                    // IV: M ‖ A of the transmitter ‖ CC without H and R ‖ SN ‖ FN 0 ‖ BC 0.
786                    let mut iv = [0u8; 16];
787                    if let Some(link) = ctx.link {
788                        let [a, b, c, d, e, f, g, h] = link.to_bytes();
789                        let [s0, s1, s2, s3] = *sn;
790                        iv = [a, b, c, d, e, f, g, h, cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
791                    }
792                    ctx.iv = iv;
793                    return Ok(Application {
794                        ell: Some(ell),
795                        afl: None,
796                        ci,
797                        header: Header::None,
798                        authenticity: Authenticity::None,
799                        meter: ctx.link,
800                        body: Body::Encrypted(Encrypted {
801                            security: Security::EllCtr,
802                            data: r,
803                            encrypted_len: r.len(),
804                            meter: ctx.link,
805                            ctx,
806                        }),
807                    });
808                }
809                // Not encrypted: the payload CRC is plain and covers the rest.
810                let (crc, r) = r.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
811                if crc16(r) != u16::from_le_bytes(*crc) {
812                    return Err(Error::Verification(Check::PayloadCrc));
813                }
814                rest = r;
815            }
816            ctx.ell = Some(ell);
817            let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
818            parse_layers(next, rest, ctx, Stage::Afl)
819        }
820        ci::AFL => {
821            if stage > Stage::Afl {
822                return Err(Error::UnexpectedLayer(ci));
823            }
824            let (&len, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
825            let afl_bytes = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
826            let rest = rest.get(usize::from(len)..).ok_or(Error::UnexpectedEnd)?;
827            let afl = parse_afl(afl_bytes)?;
828            ctx.afl = Some(afl);
829            if afl.fragment_id() != 0 {
830                // OMS Vol. 2 §7.3: only the first fragment carries the TPL, cut anywhere.
831                return Ok(Application {
832                    ell: ctx.ell,
833                    afl: Some(afl),
834                    ci,
835                    header: Header::None,
836                    authenticity: Authenticity::None,
837                    body: Body::Fragment(rest),
838                    meter: ctx.link,
839                });
840            }
841            let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
842            parse_layers(next, rest, ctx, Stage::Tpl)
843        }
844        _ => parse_tpl(ci, data, ctx),
845    }
846}
847
848/// AT 5, 6, 7: AES-CMAC truncated to 8, 12, 16 bytes (OMS Vol. 2 §6.2.1).
849pub(crate) const fn mac_len(mcl: u8) -> Option<usize> {
850    match mcl & 0x0F {
851        5 => Some(8),
852        6 => Some(12),
853        7 => Some(16),
854        _ => None,
855    }
856}
857
858fn parse_afl(b: &[u8]) -> Result<Afl> {
859    let (fcl, mut rest) = b.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
860    let fcl = u16::from_le_bytes(*fcl);
861    let mut afl =
862        Afl { fcl, mcl: None, key_info: None, counter: None, length: None, mac: [0; 16], mac_len: 0 };
863    if fcl & 0x2000 != 0 {
864        let (&mcl, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
865        afl.mcl = Some(mcl);
866        rest = r;
867    }
868    if fcl & 0x0200 != 0 {
869        let (ki, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
870        afl.key_info = Some(u16::from_le_bytes(*ki));
871        rest = r;
872    }
873    if fcl & 0x0800 != 0 {
874        let (c, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
875        afl.counter = Some(u32::from_le_bytes(*c));
876        rest = r;
877    }
878    if fcl & 0x0400 != 0 {
879        // With MCL: its authentication type sets the length. Without (the last fragment of
880        // a message, OMS Vol. 2 §6.2.4): the MAC fills the AFL up to the ML field.
881        let n = match afl.mcl {
882            Some(mcl) => mac_len(mcl).ok_or(Error::InvalidLength)?,
883            None => rest.len().saturating_sub(if fcl & 0x1000 != 0 { 2 } else { 0 }),
884        };
885        if !matches!(n, 8 | 12 | 16) {
886            return Err(Error::InvalidLength);
887        }
888        let mac = rest.get(..n).ok_or(Error::UnexpectedEnd)?;
889        afl.mac.get_mut(..n).ok_or(Error::InvalidLength)?.copy_from_slice(mac);
890        afl.mac_len = u8::try_from(n).map_err(|_| Error::InvalidLength)?;
891        rest = rest.get(n..).unwrap_or(&[]);
892    }
893    if fcl & 0x1000 != 0 {
894        let (l, _) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
895        afl.length = Some(u16::from_le_bytes(*l));
896    }
897    Ok(afl)
898}
899
900#[derive(Clone, Copy)]
901enum Kind {
902    Records,
903    Error,
904    Alarm,
905    Empty,
906    Compact,
907    Format,
908}
909
910#[allow(clippy::too_many_lines)] // one table-driven pass over the transport header
911fn parse_tpl(ci: u8, data: &[u8], mut ctx: Context) -> Result<Application<'_>> {
912    // (header length, what follows)
913    let (len, kind) = match ci {
914        ci::RSP_LONG | ci::CMD_LONG => (12, Kind::Records),
915        ci::RSP_SHORT | ci::CMD_SHORT => (4, Kind::Records),
916        ci::RSP_NONE | ci::SND_UD => (0, Kind::Records),
917        ci::ERROR_LONG => (12, Kind::Error),
918        ci::ERROR_SHORT => (4, Kind::Error),
919        ci::ERROR_NONE => (0, Kind::Error),
920        ci::ALARM_LONG => (12, Kind::Alarm),
921        ci::ALARM_SHORT => (4, Kind::Alarm),
922        ci::ALARM_NONE => (0, Kind::Alarm),
923        ci::TPL_TO_DEVICE | ci::TPL_LONG => (12, Kind::Empty),
924        ci::TPL_SHORT => (4, Kind::Empty),
925        ci::COMPACT_NONE => (0, Kind::Compact),
926        ci::COMPACT_SHORT => (4, Kind::Compact),
927        ci::COMPACT_LONG => (12, Kind::Compact),
928        ci::FORMAT_NONE => (0, Kind::Format),
929        ci::FORMAT_SHORT => (4, Kind::Format),
930        ci::FORMAT_LONG => (12, Kind::Format),
931        ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN | ci::AFL => {
932            return Err(Error::UnexpectedLayer(ci));
933        }
934        other => return Err(Error::UnsupportedCi(other)),
935    };
936    let head = data.get(..len).ok_or(Error::UnexpectedEnd)?;
937    let mut rest = data.get(len..).ok_or(Error::UnexpectedEnd)?;
938    let header = match *head {
939        [i0, i1, i2, i3, m0, m1, version, medium, access, status, c0, c1] => Header::Long(LongHeader {
940            address: address_id_first([i0, i1, i2, i3, m0, m1, version, medium]),
941            short: ShortHeader {
942                access_number: access,
943                status,
944                config: [c0, c1],
945                config_ext: None,
946                counter: None,
947            },
948        }),
949        [access, status, c0, c1] => Header::Short(ShortHeader {
950            access_number: access,
951            status,
952            config: [c0, c1],
953            config_ext: None,
954            counter: None,
955        }),
956        _ => Header::None,
957    };
958    let security = header.security();
959    let mut header = header;
960    let mut header_len = len;
961    // Bytes after the fixed header that belong to it: the CFE, a key version.
962    let mut ext = [0u8; 3];
963    let mut ext_len = 0usize;
964    if security.mode == 7 {
965        // Mode 7 has a configuration field extension byte (OMS Vol. 2 Table 21).
966        let (&cfe, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
967        rest = r;
968        ext[0] = cfe;
969        ext_len = 1;
970        if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
971            s.config_ext = Some(u16::from(cfe));
972        }
973    }
974    if security.mode == 10 {
975        // Mode 10: CFE (2 bytes), key version if CFE bit 6, message counter (4) (OMS Vol. 2
976        // §7.2.4.5); the tag is the end of the message.
977        let (cfe, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
978        let [e0, e1] = *cfe;
979        rest = r;
980        ext = [e0, e1, 0];
981        ext_len = 2;
982        let cfe = u16::from_le_bytes([e0, e1]);
983        if cfe & 0x0040 != 0 {
984            let (&kv, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
985            rest = r;
986            ext[2] = kv;
987            ext_len = 3;
988        }
989        let (mc, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
990        rest = r;
991        let counter = u32::from_le_bytes(*mc);
992        ctx.counter = Some(counter);
993        let tag_len = 4 + 4 * usize::from((cfe >> 8) & 0x03);
994        let split = rest.len().checked_sub(tag_len).ok_or(Error::UnexpectedEnd)?;
995        let (data, tag) = rest.split_at(split);
996        ctx.tag.get_mut(..tag_len).ok_or(Error::InvalidLength)?.copy_from_slice(tag);
997        ctx.tag_len = u8::try_from(tag_len).map_err(|_| Error::InvalidLength)?;
998        rest = data;
999        if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1000            s.config_ext = Some(cfe);
1001            s.counter = Some(counter);
1002        }
1003    }
1004    header_len += ext_len;
1005    let meter = match header {
1006        Header::Long(l) => Some(l.address),
1007        _ => ctx.link,
1008    };
1009    let app = |body| Application {
1010        ell: ctx.ell,
1011        afl: ctx.afl,
1012        ci,
1013        header,
1014        authenticity: Authenticity::None,
1015        body,
1016        meter,
1017    };
1018    // Mode 10 is always opened: with nothing encrypted the tag still authenticates.
1019    // Only modes 5 and 7 count 16-byte blocks in NNNN (0 = plaintext). Mode 10 is always
1020    // opened (with nothing encrypted the tag still authenticates); any other mode (13: TLS)
1021    // has its own layout and stays encrypted.
1022    if security.mode == 0 || (security.encrypted_blocks == 0 && matches!(security.mode, 5 | 7)) {
1023        let body = match kind {
1024            // Behind a decrypted ELL every byte came out of the ciphertext.
1025            Kind::Records if ctx.inside_ell => Body::Records(Records::decrypted(rest, rest.len())),
1026            Kind::Records => Body::Records(Records::new(rest)),
1027            Kind::Error => Body::ApplicationError(rest),
1028            Kind::Alarm => Body::Alarm(rest),
1029            Kind::Empty => Body::Empty,
1030            Kind::Compact => Body::Compact(crate::compact::Compact::parse(rest, ctx.inside_ell)?),
1031            Kind::Format => {
1032                let (&len, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1033                let body = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
1034                let (sig, headers) = body.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1035                let format = crate::compact::Format::received(u16::from_le_bytes(*sig), headers)
1036                    .ok_or(Error::Verification(Check::FullFrameCrc))?;
1037                Body::Format(format)
1038            }
1039        };
1040        return Ok(app(body));
1041    }
1042    let encrypted_len = if security.mode == 10 {
1043        // Mode 10 counts encrypted bytes in the whole low byte; FF means everything.
1044        match header.short().map_or(0, |s| s.config[0]) {
1045            0xFF => rest.len(),
1046            n => usize::from(n),
1047        }
1048    } else if security.encrypted_blocks == 0x0F || !matches!(security.mode, 5 | 7) {
1049        // 15 blocks means "to the end"; other modes: the whole rest is opaque.
1050        rest.len()
1051    } else {
1052        usize::from(security.encrypted_blocks) * 16
1053    };
1054    if encrypted_len > rest.len() || (matches!(security.mode, 5 | 7) && encrypted_len % 16 != 0) {
1055        return Err(Error::Verification(Check::Length));
1056    }
1057    let security = match security.mode {
1058        5 => Security::Mode5,
1059        7 => Security::Mode7,
1060        10 => Security::Mode10,
1061        other => Security::Other(other),
1062    };
1063    if let (Security::Mode5, Some(m), Some(s)) = (security, meter, header.short()) {
1064        let [a, b, c, d, e, f, g, h] = m.to_bytes();
1065        let x = s.access_number;
1066        ctx.iv = [a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x];
1067    }
1068    ctx.ci = ci;
1069    ctx.header.get_mut(..len).ok_or(Error::InvalidLength)?.copy_from_slice(head);
1070    ctx.header
1071        .get_mut(len..len + ext_len)
1072        .ok_or(Error::InvalidLength)?
1073        .copy_from_slice(ext.get(..ext_len).unwrap_or(&[]));
1074    ctx.header_len = u8::try_from(header_len).map_err(|_| Error::InvalidLength)?;
1075    ctx.tpl = Some((ci, header));
1076    Ok(app(Body::Encrypted(Encrypted { security, data: rest, encrypted_len, meter, ctx })))
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081    extern crate std;
1082    use super::*;
1083    use std::string::ToString;
1084
1085    #[test]
1086    fn manufacturer_codes() {
1087        assert_eq!(Manufacturer(0x4024).to_string(), "PAD");
1088        let kam = Manufacturer::from_letters(*b"KAM").unwrap();
1089        assert_eq!(kam.0, 0x2C2D);
1090        assert_eq!(kam.to_string(), "KAM");
1091        assert_eq!(Manufacturer::from_letters(*b"k1m"), None);
1092    }
1093
1094    #[test]
1095    fn security_mode_from_config() {
1096        // OMS mode 5 with 1 encrypted block: configuration 0x0510, sent as 10 05.
1097        let s = SecurityMode::from_config([0x10, 0x05]);
1098        assert_eq!(s, SecurityMode { mode: 5, encrypted_blocks: 1 });
1099        let mut data = [0u8; 4 + 18];
1100        data[..4].copy_from_slice(&[0x01, 0x00, 0x10, 0x05]);
1101        let app = Application::parse(ci::RSP_SHORT, &data).unwrap();
1102        let Body::Encrypted(e) = app.body else { panic!() };
1103        assert_eq!((e.security, e.encrypted_len, e.data.len()), (Security::Mode5, 16, 18));
1104        // More blocks announced than present.
1105        assert_eq!(
1106            Application::parse(ci::RSP_SHORT, &data[..10]).unwrap_err(),
1107            Error::Verification(Check::Length)
1108        );
1109    }
1110
1111    // 002-oms-security/SR-004: each layer once, in order.
1112    #[test]
1113    fn layer_order_is_enforced() {
1114        assert_eq!(Application::parse(0x7A, &[0, 0, 0, 0]).unwrap().authenticity, Authenticity::None);
1115        // AFL after the TPL is not a TPL.
1116        assert_eq!(
1117            Application::parse(0x90, &[0x02, 0x00, 0x00, 0x8C, 0, 0, 0x78]).unwrap_err(),
1118            Error::UnexpectedLayer(0x8C)
1119        );
1120        assert_eq!(
1121            Application::parse(0x8C, &[0x20, 0x01, 0x8C, 0, 0, 0x78]).unwrap_err(),
1122            Error::UnexpectedLayer(0x8C)
1123        );
1124        assert_eq!(Application::parse(0x42, &[]).unwrap_err(), Error::UnsupportedCi(0x42));
1125    }
1126}