1use core::fmt;
24
25use crate::crc::crc16;
26use crate::record::Records;
27use crate::{Check, Error, Result};
28
29pub mod ci {
31 pub const RSP_LONG: u8 = 0x72;
33 pub const RSP_SHORT: u8 = 0x7A;
35 pub const RSP_NONE: u8 = 0x78;
37 pub const SND_UD: u8 = 0x51;
39 pub const CMD_SHORT: u8 = 0x5A;
41 pub const CMD_LONG: u8 = 0x5B;
43 pub const ERROR_SHORT: u8 = 0x6E;
45 pub const ERROR_LONG: u8 = 0x6F;
47 pub const ERROR_NONE: u8 = 0x70;
49 pub const ALARM_NONE: u8 = 0x71;
51 pub const ALARM_SHORT: u8 = 0x74;
53 pub const ALARM_LONG: u8 = 0x75;
55 pub const TPL_TO_DEVICE: u8 = 0x80;
57 pub const TPL_SHORT: u8 = 0x8A;
59 pub const TPL_LONG: u8 = 0x8B;
61 pub const ELL_SHORT: u8 = 0x8C;
63 pub const ELL_SHORT_SN: u8 = 0x8D;
65 pub const ELL_LONG: u8 = 0x8E;
67 pub const ELL_LONG_SN: u8 = 0x8F;
69 pub const AFL: u8 = 0x90;
71 pub const FORMAT_NONE: u8 = 0x69;
73 pub const FORMAT_SHORT: u8 = 0x6A;
75 pub const FORMAT_LONG: u8 = 0x6B;
77 pub const COMPACT_NONE: u8 = 0x79;
79 pub const COMPACT_SHORT: u8 = 0x7B;
81 pub const COMPACT_LONG: u8 = 0x73;
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
87pub struct Manufacturer(pub u16);
88
89impl Manufacturer {
90 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub struct Medium(pub u8);
118
119impl Medium {
120 pub const ELECTRICITY: Self = Self(0x02);
122 pub const GAS: Self = Self(0x03);
124 pub const HEAT: Self = Self(0x04);
126 pub const WARM_WATER: Self = Self(0x06);
128 pub const WATER: Self = Self(0x07);
130 pub const HEAT_COST_ALLOCATOR: Self = Self(0x08);
132 pub const COOLING: Self = Self(0x0A);
134 pub const HEAT_INLET: Self = Self(0x0C);
136 pub const HEAT_COOLING: Self = Self(0x0D);
138 pub const HOT_WATER: Self = Self(0x15);
140 pub const COLD_WATER: Self = Self(0x16);
142
143 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
201pub struct Address {
202 pub manufacturer: Manufacturer,
204 pub id: [u8; 4],
206 pub version: u8,
208 pub medium: Medium,
210}
211
212impl Address {
213 pub fn id_number(&self) -> Option<u32> {
215 crate::value::bcd_u32(self.id)
216 }
217
218 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct SecurityMode {
253 pub mode: u8,
256 pub encrypted_blocks: u8,
258}
259
260impl SecurityMode {
261 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
270pub struct ShortHeader {
271 pub access_number: u8,
273 pub status: u8,
275 pub config: [u8; 2],
277 pub config_ext: Option<u16>,
280 pub counter: Option<u32>,
282}
283
284impl ShortHeader {
285 pub const fn security(&self) -> SecurityMode {
287 SecurityMode::from_config(self.config)
288 }
289}
290
291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct LongHeader {
294 pub address: Address,
296 pub short: ShortHeader,
298}
299
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub enum Header {
303 None,
305 Short(ShortHeader),
307 Long(LongHeader),
309}
310
311impl Header {
312 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub struct Ell {
333 pub cc: u8,
335 pub access_number: u8,
337 pub receiver: Option<Address>,
339 pub session: Option<u32>,
341}
342
343impl Ell {
344 pub const fn encrypted(&self) -> bool {
346 matches!(self.session, Some(sn) if sn >> 29 == 1)
347 }
348}
349
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Afl {
358 pub fcl: u16,
361 pub mcl: Option<u8>,
363 pub key_info: Option<u16>,
365 pub counter: Option<u32>,
367 pub length: Option<u16>,
370 mac: [u8; 16],
371 mac_len: u8,
372}
373
374impl Afl {
375 pub const fn more_fragments(&self) -> bool {
377 self.fcl & 0x4000 != 0
378 }
379
380 pub const fn fragment_id(&self) -> u8 {
382 self.fcl.to_le_bytes()[0]
383 }
384
385 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 pub fn mac(&self) -> &[u8] {
401 self.mac.get(..usize::from(self.mac_len)).unwrap_or(&[])
402 }
403}
404
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum Authenticity {
409 None,
411 Encrypted,
418 Authenticated {
426 counter: u32,
429 },
430}
431
432#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum Security {
436 Mode5,
439 Mode7,
441 Mode10,
443 EllCtr,
445 Other(u8),
447}
448
449#[derive(Clone, Copy, Debug)]
451pub struct Encrypted<'a> {
452 pub security: Security,
454 pub data: &'a [u8],
456 pub encrypted_len: usize,
458 pub meter: Option<Address>,
460 #[cfg_attr(not(feature = "oms"), allow(dead_code))]
461 pub(crate) ctx: Context,
462}
463
464#[derive(Clone, Copy, Debug, Default)]
466#[cfg_attr(not(feature = "oms"), allow(dead_code))]
467pub(crate) struct Context {
468 pub(crate) iv: [u8; 16],
470 pub(crate) ci: u8,
472 pub(crate) header: [u8; 16],
475 pub(crate) header_len: u8,
476 pub(crate) ell: Option<Ell>,
478 pub(crate) afl: Option<Afl>,
479 pub(crate) tpl: Option<(u8, Header)>,
480 pub(crate) link: Option<Address>,
481 pub(crate) inside_ell: bool,
483 pub(crate) counter: Option<u32>,
485 pub(crate) tag: [u8; 16],
486 pub(crate) tag_len: u8,
487}
488
489#[derive(Clone, Debug)]
491pub enum Body<'a> {
492 Records(Records<'a>),
494 Encrypted(Encrypted<'a>),
496 ApplicationError(&'a [u8]),
499 Alarm(&'a [u8]),
501 Empty,
504 Compact(crate::compact::Compact<'a>),
507 Format(crate::compact::Format<'a>),
509 Fragment(&'a [u8]),
513}
514
515#[derive(Clone, Debug)]
517pub struct Application<'a> {
518 pub ell: Option<Ell>,
520 pub afl: Option<Afl>,
522 pub ci: u8,
524 pub header: Header,
526 pub authenticity: Authenticity,
528 pub body: Body<'a>,
530 meter: Option<Address>,
531}
532
533impl<'a> Application<'a> {
534 pub fn parse(ci: u8, data: &'a [u8]) -> Result<Self> {
538 Self::parse_with_link(ci, data, None)
539 }
540
541 pub fn parse_with_link(ci: u8, data: &'a [u8], link: Option<Address>) -> Result<Self> {
543 let ctx = Context { link, ..Context::default() };
544 parse_layers(ci, data, ctx, Stage::Ell)
545 }
546
547 pub(crate) fn reassembled(
550 data: &'a [u8],
551 afl: Afl,
552 ell: Option<Ell>,
553 link: Option<Address>,
554 decrypted: bool,
555 ) -> Result<Self> {
556 let (&ci, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
557 let ctx = Context { link, ell, afl: Some(afl), inside_ell: decrypted, ..Context::default() };
558 let mut app = parse_layers(ci, rest, ctx, Stage::Tpl)?;
559 if decrypted && !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
560 app.authenticity = Authenticity::Encrypted;
561 }
562 Ok(app)
563 }
564
565 pub const fn meter(&self) -> Option<Address> {
569 self.meter
570 }
571
572 pub fn expand<'o, F: crate::compact::Formats + ?Sized>(
577 &self,
578 formats: &F,
579 out: &'o mut [u8],
580 ) -> Result<Application<'o>> {
581 let Body::Compact(c) = &self.body else { return Err(Error::UnsupportedCi(self.ci)) };
582 let records = c.expand(formats, out)?;
583 Ok(Application {
584 ell: self.ell,
585 afl: self.afl,
586 ci: self.ci,
587 header: self.header,
588 authenticity: self.authenticity,
589 body: Body::Records(records),
590 meter: self.meter,
591 })
592 }
593
594 pub fn records(&self) -> Option<Records<'a>> {
596 match &self.body {
597 Body::Records(r) => Some(r.clone()),
598 _ => None,
599 }
600 }
601}
602
603#[cfg(feature = "oms")]
604impl Encrypted<'_> {
605 pub fn decrypt<'o, K: crate::oms::Keys + ?Sized>(
622 &self,
623 keys: &K,
624 out: &'o mut [u8],
625 ) -> Result<Application<'o>> {
626 use crate::oms;
627 if self.security != Security::EllCtr && !matches!(tpl_layout(self.ctx.ci), Ok((_, Kind::Records))) {
632 return Err(Error::UnsupportedCi(self.ctx.ci));
633 }
634 let meter = self.meter.ok_or(Error::NoKey)?;
635 let key = keys.key(&meter).ok_or(Error::NoKey)?;
636 let buf = out.get_mut(..self.data.len()).ok_or(Error::OutputTooSmall)?;
637 buf.copy_from_slice(self.data);
638 let ctx = &self.ctx;
639 let authenticity = match self.security {
640 Security::EllCtr => {
641 oms::ctr_apply(key, &ctx.iv, buf);
642 let plain: &'o [u8] = buf;
643 let (crc, rest) = plain.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
644 if crc16(rest) != u16::from_le_bytes(*crc) {
645 return Err(Error::Verification(Check::PayloadCrc));
646 }
647 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
648 let inner = Context { link: ctx.link, ell: ctx.ell, inside_ell: true, ..Context::default() };
649 let mut app = parse_layers(next, rest, inner, Stage::Afl)?;
650 if !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
651 app.authenticity = Authenticity::Encrypted;
652 }
653 return Ok(app);
654 }
655 Security::Mode5 => {
656 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
657 oms::cbc_decrypt(key, &ctx.iv, enc)?;
658 Authenticity::Encrypted
659 }
660 Security::Mode7 => {
661 let afl = ctx.afl.ok_or(Error::Verification(Check::MissingCounter))?;
662 let counter = afl.counter.ok_or(Error::Verification(Check::MissingCounter))?;
663 let c = counter.to_le_bytes();
664 let mut authenticity = Authenticity::Encrypted;
665 if afl.mac().is_empty() && afl.mcl.and_then(mac_len).is_some() {
667 return Err(Error::Verification(Check::Mac));
668 }
669 if !afl.mac().is_empty() {
670 if afl.mcl.map(|m| m & 0x40 != 0) != Some(afl.length.is_some()) {
673 return Err(Error::Verification(Check::Mac));
674 }
675 let kmac = oms::derive(key, 0x01, c, meter.id);
678 let ml = afl.length.map(u16::to_le_bytes);
679 let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
680 let tag = oms::cmac(
681 &kmac,
682 &[
683 &[afl.mcl.unwrap_or(0)],
684 &c,
685 ml.as_ref().map_or(&[][..], |m| &m[..]),
686 &[ctx.ci],
687 header,
688 self.data,
689 ],
690 );
691 let mac = afl.mac();
692 if !oms::mac_matches(tag.get(..mac.len()).unwrap_or(&[]), mac) {
693 return Err(Error::Verification(Check::Mac));
694 }
695 authenticity = Authenticity::Authenticated { counter };
696 }
697 let kenc = oms::derive(key, 0x00, c, meter.id);
698 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
699 oms::cbc_decrypt(&kenc, &[0; 16], enc)?;
700 authenticity
701 }
702 Security::Mode10 => return self.open_ccm(key, meter, buf),
703 Security::Other(mode) => return Err(Error::UnsupportedSecurity(mode)),
704 };
705 let plain: &'o [u8] = buf;
706 let tail = match authenticity {
709 Authenticity::Authenticated { .. } => authenticity,
710 _ if ctx.inside_ell => Authenticity::Encrypted,
711 _ => Authenticity::None,
712 };
713 if !plain.starts_with(&[0x2F, 0x2F]) {
714 return Err(Error::Verification(Check::Marker));
715 }
716 let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
717 Ok(Application {
718 ell: ctx.ell,
719 afl: ctx.afl,
720 ci,
721 header,
722 authenticity,
723 body: Body::Records(Records::protected(plain, self.encrypted_len, authenticity, tail)),
724 meter: self.meter,
725 })
726 }
727
728 fn open_ccm<'o>(
730 &self,
731 key: &crate::oms::Key,
732 meter: Address,
733 buf: &'o mut [u8],
734 ) -> Result<Application<'o>> {
735 use crate::oms;
736 let ctx = &self.ctx;
737 let counter = ctx.counter.ok_or(Error::Verification(Check::MissingCounter))?;
741 let kenc = oms::derive(key, 0x00, counter.to_le_bytes(), meter.id);
742 let [m0, m1, i0, i1, i2, i3, v, t] = meter.to_bytes();
743 let [c0, c1, c2, c3] = counter.to_be_bytes();
744 let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
745 let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
746 let tail = self.data.get(self.encrypted_len..).unwrap_or(&[]);
750 let mut aad = [0u8; 1 + 16 + 256];
751 let aad_len = 1 + header.len() + tail.len();
752 if let Some((first, rest)) = aad.split_first_mut() {
753 *first = ctx.ci;
754 rest.get_mut(..header.len()).ok_or(Error::InvalidLength)?.copy_from_slice(header);
755 rest.get_mut(header.len()..header.len() + tail.len())
756 .ok_or(Error::InvalidLength)?
757 .copy_from_slice(tail);
758 }
759 let tag = ctx.tag.get(..usize::from(ctx.tag_len)).unwrap_or(&[]);
760 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
761 oms::ccm_decrypt(&kenc, &nonce, aad.get(..aad_len).unwrap_or(&[]), enc, tag)?;
762 let plain: &'o [u8] = buf;
763 let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
764 Ok(Application {
765 ell: ctx.ell,
766 afl: ctx.afl,
767 ci,
768 header,
769 authenticity: Authenticity::Authenticated { counter },
770 body: Body::Records(Records::protected(
771 plain,
772 self.encrypted_len,
773 Authenticity::Authenticated { counter },
774 Authenticity::Authenticated { counter },
775 )),
776 meter: self.meter,
777 })
778 }
779}
780
781#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
783enum Stage {
784 Ell,
785 Afl,
786 Tpl,
787}
788
789fn address_id_first(b: [u8; 8]) -> Address {
790 let [i0, i1, i2, i3, m0, m1, version, medium] = b;
791 Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium])
792}
793
794#[allow(clippy::too_many_lines)]
795fn parse_layers(ci: u8, data: &[u8], mut ctx: Context, stage: Stage) -> Result<Application<'_>> {
796 match ci {
797 ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN => {
798 if stage > Stage::Ell {
799 return Err(Error::UnexpectedLayer(ci));
800 }
801 let (&[cc, access], mut rest) = data.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
802 let mut ell = Ell { cc, access_number: access, receiver: None, session: None };
803 if matches!(ci, ci::ELL_LONG | ci::ELL_LONG_SN) {
804 let (a, r) = rest.split_first_chunk::<8>().ok_or(Error::UnexpectedEnd)?;
805 ell.receiver = Some(Address::from_link_bytes(*a));
806 rest = r;
807 }
808 if matches!(ci, ci::ELL_SHORT_SN | ci::ELL_LONG_SN) {
809 let (sn, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
810 let session = u32::from_le_bytes(*sn);
811 ell.session = Some(session);
812 ctx.ell = Some(ell);
813 if ell.encrypted() {
814 let mut iv = [0u8; 16];
816 if let Some(link) = ctx.link {
817 let [a, b, c, d, e, f, g, h] = link.to_bytes();
818 let [s0, s1, s2, s3] = *sn;
819 iv = [a, b, c, d, e, f, g, h, cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
820 }
821 ctx.iv = iv;
822 return Ok(Application {
823 ell: Some(ell),
824 afl: None,
825 ci,
826 header: Header::None,
827 authenticity: Authenticity::None,
828 meter: ctx.link,
829 body: Body::Encrypted(Encrypted {
830 security: Security::EllCtr,
831 data: r,
832 encrypted_len: r.len(),
833 meter: ctx.link,
834 ctx,
835 }),
836 });
837 }
838 let (crc, r) = r.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
840 if crc16(r) != u16::from_le_bytes(*crc) {
841 return Err(Error::Verification(Check::PayloadCrc));
842 }
843 rest = r;
844 }
845 ctx.ell = Some(ell);
846 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
847 parse_layers(next, rest, ctx, Stage::Afl)
848 }
849 ci::AFL => {
850 if stage > Stage::Afl {
851 return Err(Error::UnexpectedLayer(ci));
852 }
853 let (&len, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
854 let afl_bytes = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
855 let rest = rest.get(usize::from(len)..).ok_or(Error::UnexpectedEnd)?;
856 let afl = parse_afl(afl_bytes)?;
857 ctx.afl = Some(afl);
858 if afl.fragment_id() != 0 {
859 return Ok(Application {
861 ell: ctx.ell,
862 afl: Some(afl),
863 ci,
864 header: Header::None,
865 authenticity: Authenticity::None,
866 body: Body::Fragment(rest),
867 meter: ctx.link,
868 });
869 }
870 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
871 parse_layers(next, rest, ctx, Stage::Tpl)
872 }
873 _ => parse_tpl(ci, data, ctx),
874 }
875}
876
877pub(crate) const fn mac_len(mcl: u8) -> Option<usize> {
879 match mcl & 0x0F {
880 5 => Some(8),
881 6 => Some(12),
882 7 => Some(16),
883 _ => None,
884 }
885}
886
887fn parse_afl(b: &[u8]) -> Result<Afl> {
888 let (fcl, mut rest) = b.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
889 let fcl = u16::from_le_bytes(*fcl);
890 let mut afl =
891 Afl { fcl, mcl: None, key_info: None, counter: None, length: None, mac: [0; 16], mac_len: 0 };
892 if fcl & 0x2000 != 0 {
893 let (&mcl, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
894 afl.mcl = Some(mcl);
895 rest = r;
896 }
897 if fcl & 0x0200 != 0 {
898 let (ki, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
899 afl.key_info = Some(u16::from_le_bytes(*ki));
900 rest = r;
901 }
902 if fcl & 0x0800 != 0 {
903 let (c, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
904 afl.counter = Some(u32::from_le_bytes(*c));
905 rest = r;
906 }
907 if fcl & 0x0400 != 0 {
908 let n = match afl.mcl {
911 Some(mcl) => mac_len(mcl).ok_or(Error::InvalidLength)?,
912 None => rest.len().saturating_sub(if fcl & 0x1000 != 0 { 2 } else { 0 }),
913 };
914 if !matches!(n, 8 | 12 | 16) {
915 return Err(Error::InvalidLength);
916 }
917 let mac = rest.get(..n).ok_or(Error::UnexpectedEnd)?;
918 afl.mac.get_mut(..n).ok_or(Error::InvalidLength)?.copy_from_slice(mac);
919 afl.mac_len = u8::try_from(n).map_err(|_| Error::InvalidLength)?;
920 rest = rest.get(n..).unwrap_or(&[]);
921 }
922 if fcl & 0x1000 != 0 {
923 let (l, _) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
924 afl.length = Some(u16::from_le_bytes(*l));
925 }
926 Ok(afl)
927}
928
929#[derive(Clone, Copy)]
930enum Kind {
931 Records,
932 Error,
933 Alarm,
934 Empty,
935 Compact,
936 Format,
937}
938
939fn tpl_layout(ci: u8) -> Result<(usize, Kind)> {
941 Ok(match ci {
942 ci::RSP_LONG | ci::CMD_LONG => (12, Kind::Records),
943 ci::RSP_SHORT | ci::CMD_SHORT => (4, Kind::Records),
944 ci::RSP_NONE | ci::SND_UD => (0, Kind::Records),
945 ci::ERROR_LONG => (12, Kind::Error),
946 ci::ERROR_SHORT => (4, Kind::Error),
947 ci::ERROR_NONE => (0, Kind::Error),
948 ci::ALARM_LONG => (12, Kind::Alarm),
949 ci::ALARM_SHORT => (4, Kind::Alarm),
950 ci::ALARM_NONE => (0, Kind::Alarm),
951 ci::TPL_TO_DEVICE | ci::TPL_LONG => (12, Kind::Empty),
952 ci::TPL_SHORT => (4, Kind::Empty),
953 ci::COMPACT_NONE => (0, Kind::Compact),
954 ci::COMPACT_SHORT => (4, Kind::Compact),
955 ci::COMPACT_LONG => (12, Kind::Compact),
956 ci::FORMAT_NONE => (0, Kind::Format),
957 ci::FORMAT_SHORT => (4, Kind::Format),
958 ci::FORMAT_LONG => (12, Kind::Format),
959 ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN | ci::AFL => {
960 return Err(Error::UnexpectedLayer(ci));
961 }
962 other => return Err(Error::UnsupportedCi(other)),
963 })
964}
965
966#[allow(clippy::too_many_lines)] fn parse_tpl(ci: u8, data: &[u8], mut ctx: Context) -> Result<Application<'_>> {
968 let (len, kind) = tpl_layout(ci)?;
969 let head = data.get(..len).ok_or(Error::UnexpectedEnd)?;
970 let mut rest = data.get(len..).ok_or(Error::UnexpectedEnd)?;
971 let header = match *head {
972 [i0, i1, i2, i3, m0, m1, version, medium, access, status, c0, c1] => Header::Long(LongHeader {
973 address: address_id_first([i0, i1, i2, i3, m0, m1, version, medium]),
974 short: ShortHeader {
975 access_number: access,
976 status,
977 config: [c0, c1],
978 config_ext: None,
979 counter: None,
980 },
981 }),
982 [access, status, c0, c1] => Header::Short(ShortHeader {
983 access_number: access,
984 status,
985 config: [c0, c1],
986 config_ext: None,
987 counter: None,
988 }),
989 _ => Header::None,
990 };
991 let security = header.security();
992 let mut header = header;
993 let mut header_len = len;
994 let mut ext = [0u8; 3];
996 let mut ext_len = 0usize;
997 if security.mode == 7 {
998 let (&cfe, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1000 rest = r;
1001 ext[0] = cfe;
1002 ext_len = 1;
1003 if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1004 s.config_ext = Some(u16::from(cfe));
1005 }
1006 }
1007 if security.mode == 10 {
1008 let (cfe, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1011 let [e0, e1] = *cfe;
1012 rest = r;
1013 ext = [e0, e1, 0];
1014 ext_len = 2;
1015 let cfe = u16::from_le_bytes([e0, e1]);
1016 if cfe & 0x0040 != 0 {
1017 let (&kv, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1018 rest = r;
1019 ext[2] = kv;
1020 ext_len = 3;
1021 }
1022 let (mc, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
1023 rest = r;
1024 let counter = u32::from_le_bytes(*mc);
1025 ctx.counter = Some(counter);
1026 let tag_len = 4 + 4 * usize::from((cfe >> 8) & 0x03);
1027 let split = rest.len().checked_sub(tag_len).ok_or(Error::UnexpectedEnd)?;
1028 let (data, tag) = rest.split_at(split);
1029 ctx.tag.get_mut(..tag_len).ok_or(Error::InvalidLength)?.copy_from_slice(tag);
1030 ctx.tag_len = u8::try_from(tag_len).map_err(|_| Error::InvalidLength)?;
1031 rest = data;
1032 if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1033 s.config_ext = Some(cfe);
1034 s.counter = Some(counter);
1035 }
1036 }
1037 header_len += ext_len;
1038 let meter = match header {
1039 Header::Long(l) => Some(l.address),
1040 _ => ctx.link,
1041 };
1042 let app = |body| Application {
1043 ell: ctx.ell,
1044 afl: ctx.afl,
1045 ci,
1046 header,
1047 authenticity: Authenticity::None,
1048 body,
1049 meter,
1050 };
1051 if security.mode == 0 || (security.encrypted_blocks == 0 && matches!(security.mode, 5 | 7)) {
1056 let body = match kind {
1057 Kind::Records if ctx.inside_ell => Body::Records(Records::protected(
1059 rest,
1060 rest.len(),
1061 Authenticity::Encrypted,
1062 Authenticity::Encrypted,
1063 )),
1064 Kind::Records => Body::Records(Records::new(rest)),
1065 Kind::Error => Body::ApplicationError(rest),
1066 Kind::Alarm => Body::Alarm(rest),
1067 Kind::Empty => Body::Empty,
1068 Kind::Compact => Body::Compact(crate::compact::Compact::parse(rest, ctx.inside_ell)?),
1069 Kind::Format => {
1070 let (&len, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1071 let body = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
1072 let (sig, headers) = body.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1073 let format = crate::compact::Format::received(u16::from_le_bytes(*sig), headers)
1074 .ok_or(Error::Verification(Check::FullFrameCrc))?;
1075 Body::Format(format)
1076 }
1077 };
1078 return Ok(app(body));
1079 }
1080 let encrypted_len = if security.mode == 10 {
1081 match header.short().map_or(0, |s| s.config[0]) {
1083 0xFF => rest.len(),
1084 n => usize::from(n),
1085 }
1086 } else if security.encrypted_blocks == 0x0F || !matches!(security.mode, 5 | 7) {
1087 rest.len()
1089 } else {
1090 usize::from(security.encrypted_blocks) * 16
1091 };
1092 if encrypted_len > rest.len() || (matches!(security.mode, 5 | 7) && encrypted_len % 16 != 0) {
1093 return Err(Error::Verification(Check::Length));
1094 }
1095 let security = match security.mode {
1096 5 => Security::Mode5,
1097 7 => Security::Mode7,
1098 10 => Security::Mode10,
1099 other => Security::Other(other),
1100 };
1101 if let (Security::Mode5, Some(m), Some(s)) = (security, meter, header.short()) {
1102 let [a, b, c, d, e, f, g, h] = m.to_bytes();
1103 let x = s.access_number;
1104 ctx.iv = [a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x];
1105 }
1106 ctx.ci = ci;
1107 ctx.header.get_mut(..len).ok_or(Error::InvalidLength)?.copy_from_slice(head);
1108 ctx.header
1109 .get_mut(len..len + ext_len)
1110 .ok_or(Error::InvalidLength)?
1111 .copy_from_slice(ext.get(..ext_len).unwrap_or(&[]));
1112 ctx.header_len = u8::try_from(header_len).map_err(|_| Error::InvalidLength)?;
1113 ctx.tpl = Some((ci, header));
1114 Ok(app(Body::Encrypted(Encrypted { security, data: rest, encrypted_len, meter, ctx })))
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 extern crate std;
1120 use super::*;
1121 use std::string::ToString;
1122
1123 #[test]
1124 fn manufacturer_codes() {
1125 assert_eq!(Manufacturer(0x4024).to_string(), "PAD");
1126 let kam = Manufacturer::from_letters(*b"KAM").unwrap();
1127 assert_eq!(kam.0, 0x2C2D);
1128 assert_eq!(kam.to_string(), "KAM");
1129 assert_eq!(Manufacturer::from_letters(*b"k1m"), None);
1130 }
1131
1132 #[test]
1133 fn security_mode_from_config() {
1134 let s = SecurityMode::from_config([0x10, 0x05]);
1136 assert_eq!(s, SecurityMode { mode: 5, encrypted_blocks: 1 });
1137 let mut data = [0u8; 4 + 18];
1138 data[..4].copy_from_slice(&[0x01, 0x00, 0x10, 0x05]);
1139 let app = Application::parse(ci::RSP_SHORT, &data).unwrap();
1140 let Body::Encrypted(e) = app.body else { panic!() };
1141 assert_eq!((e.security, e.encrypted_len, e.data.len()), (Security::Mode5, 16, 18));
1142 assert_eq!(
1144 Application::parse(ci::RSP_SHORT, &data[..10]).unwrap_err(),
1145 Error::Verification(Check::Length)
1146 );
1147 }
1148
1149 #[test]
1151 fn layer_order_is_enforced() {
1152 assert_eq!(Application::parse(0x7A, &[0, 0, 0, 0]).unwrap().authenticity, Authenticity::None);
1153 assert_eq!(
1155 Application::parse(0x90, &[0x02, 0x00, 0x00, 0x8C, 0, 0, 0x78]).unwrap_err(),
1156 Error::UnexpectedLayer(0x8C)
1157 );
1158 assert_eq!(
1159 Application::parse(0x8C, &[0x20, 0x01, 0x8C, 0, 0, 0x78]).unwrap_err(),
1160 Error::UnexpectedLayer(0x8C)
1161 );
1162 assert_eq!(Application::parse(0x42, &[]).unwrap_err(), Error::UnsupportedCi(0x42));
1163 }
1164
1165 #[cfg(feature = "oms")]
1166 fn meter() -> Address {
1167 Address {
1168 manufacturer: Manufacturer(0x1593),
1169 id: [0x78, 0x56, 0x34, 0x12],
1170 version: 0x33,
1171 medium: Medium::GAS,
1172 }
1173 }
1174
1175 #[cfg(feature = "oms")]
1178 fn mode_7_with_ml(mcl: u8, key: &crate::oms::Key) -> std::vec::Vec<u8> {
1179 use crate::oms;
1180 let counter = 7u32.to_le_bytes();
1181 let ml = 22u16.to_le_bytes(); let mut plain = [0x2F; 16];
1183 plain[2..5].copy_from_slice(&[0x01, 0x13, 0x05]);
1184 oms::cbc_encrypt(&oms::derive(key, 0, counter, meter().id), &[0; 16], &mut plain).unwrap();
1185 let tpl = [&[ci::RSP_SHORT, 1, 0, 0x10, 0x07, 0x10][..], &plain].concat();
1186 let tag = oms::cmac(&oms::derive(key, 1, counter, meter().id), &[&[mcl], &counter, &ml, &tpl]);
1187 [&[17, 0x00, 0x3C, mcl][..], &counter, &tag[..8], &ml, &tpl].concat()
1188 }
1189
1190 #[cfg(feature = "oms")]
1191 #[test]
1192 fn ml_in_the_mac_input_needs_the_mcl_to_say_so() {
1193 let key = crate::oms::Key::new([0x42; 16]);
1196 let mut out = [0u8; 64];
1197 for (mcl, ok) in [(0x65, true), (0x25, false)] {
1198 let data = mode_7_with_ml(mcl, &key);
1199 let app = Application::parse_with_link(ci::AFL, &data, Some(meter())).unwrap();
1200 let Body::Encrypted(e) = &app.body else { panic!() };
1201 let r = e.decrypt(&key, &mut out);
1202 if ok {
1203 assert_eq!(r.unwrap().authenticity, Authenticity::Authenticated { counter: 7 });
1204 } else {
1205 assert_eq!(r.unwrap_err(), Error::Verification(Check::Mac));
1206 }
1207 }
1208 }
1209
1210 #[cfg(feature = "oms")]
1211 #[test]
1212 fn decryption_yields_records_only_for_a_records_ci() {
1213 use crate::oms;
1216 let key = oms::Key::new([0x42; 16]);
1217 let mut plain = [0x2F; 16];
1218 plain[2..5].copy_from_slice(&[0x01, 0x13, 0x05]);
1219 let [a, b, c, d, e, f, g, h] = meter().to_bytes();
1220 oms::cbc_encrypt(&key, &[a, b, c, d, e, f, g, h, 1, 1, 1, 1, 1, 1, 1, 1], &mut plain).unwrap();
1221 let mut out = [0u8; 64];
1222 for (ci, ok) in [
1223 (ci::RSP_SHORT, true),
1224 (ci::ALARM_SHORT, false),
1225 (ci::ERROR_SHORT, false),
1226 (ci::TPL_SHORT, false),
1227 ] {
1228 let data = [&[1, 0, 0x10, 0x05][..], &plain].concat();
1229 let app = Application::parse_with_link(ci, &data, Some(meter())).unwrap();
1230 let Body::Encrypted(enc) = &app.body else { panic!("{ci:02X}") };
1231 match enc.decrypt(&key, &mut out) {
1232 Ok(inner) => assert!(ok && inner.records().is_some(), "{ci:02X}"),
1233 Err(err) => assert!(!ok && err == Error::UnsupportedCi(ci), "{ci:02X}: {err:?}"),
1234 }
1235 }
1236 }
1237}