Skip to main content

dlms_cosem_kit/xdlms/
protection.rs

1//! The protection wrappers: ciphered services, general ciphering and general signing.
2//!
3//! These types carry protected APDUs on the wire. They do no cryptography — see
4//! [`crate::security`] for that — so a translator, a fuzzer and a server can all handle
5//! a protected APDU without a key.
6
7use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
8
9/// The security control byte that introduces every protected APDU.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub struct SecurityControl(pub u8);
12
13impl SecurityControl {
14    /// A control byte for a suite, with the chosen protection, on the unicast key set.
15    #[must_use]
16    pub const fn new(suite: u8, authenticated: bool, encrypted: bool) -> Self {
17        let mut v = suite & 0x0F;
18        if authenticated {
19            v |= 0x10;
20        }
21        if encrypted {
22            v |= 0x20;
23        }
24        Self(v)
25    }
26
27    /// The same control byte with the broadcast-key bit set or cleared.
28    ///
29    /// The bit selects which key set opens the frame, so it is part of what a receiver
30    /// *demands* rather than something it reads off the wire — see
31    /// [`crate::security::SecurityPolicy::broadcast`].
32    #[must_use]
33    pub const fn with_broadcast(self, broadcast: bool) -> Self {
34        Self(if broadcast { self.0 | 0x40 } else { self.0 & !0x40 })
35    }
36
37    /// The security suite id, 0–2.
38    #[must_use]
39    pub const fn suite(self) -> u8 {
40        self.0 & 0x0F
41    }
42
43    /// True when an authentication tag is appended.
44    #[must_use]
45    pub const fn authenticated(self) -> bool {
46        self.0 & 0x10 != 0
47    }
48
49    /// True when the payload is encrypted.
50    #[must_use]
51    pub const fn encrypted(self) -> bool {
52        self.0 & 0x20 != 0
53    }
54
55    /// True when the broadcast key set is used instead of the unicast one.
56    #[must_use]
57    pub const fn broadcast_key(self) -> bool {
58        self.0 & 0x40 != 0
59    }
60
61    /// True when the payload is compressed.
62    ///
63    /// This crate reports compression and never performs it: a frame that needs it
64    /// fails by name rather than being decoded into nonsense.
65    #[must_use]
66    pub const fn compressed(self) -> bool {
67        self.0 & 0x80 != 0
68    }
69
70    /// True when no protection at all is applied.
71    #[must_use]
72    pub const fn is_plain(self) -> bool {
73        !self.authenticated() && !self.encrypted()
74    }
75}
76
77/// A protected service APDU: the body of a `glo-` or `ded-` tagged APDU.
78///
79/// The `payload` is what the cipher produced: for authenticated-and-encrypted it is the
80/// ciphertext followed by the twelve-byte tag; for authenticated-only it is the
81/// plaintext followed by the tag; for neither it is the plaintext.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct CipheredService<'a> {
84    /// What protection was applied.
85    pub security_control: SecurityControl,
86    /// The sender's frame counter, which forms the second half of the nonce.
87    pub invocation_counter: u32,
88    /// The protected bytes.
89    pub payload: &'a [u8],
90}
91
92impl Encode for CipheredService<'_> {
93    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
94        w.write_length(5 + self.payload.len())?;
95        w.write_u8(self.security_control.0)?;
96        w.write_u32(self.invocation_counter)?;
97        w.write_bytes(self.payload)
98    }
99}
100
101impl<'a> Decode<'a> for CipheredService<'a> {
102    fn decode(r: &mut Reader<'a>) -> Result<Self> {
103        let body = r.length_prefixed()?;
104        let mut br = Reader::with_base(body, r.offset() - body.len());
105        Ok(Self {
106            security_control: SecurityControl(br.u8()?),
107            invocation_counter: br.u32()?,
108            payload: br.take_rest(),
109        })
110    }
111}
112
113/// A protected APDU that names the system title it came from.
114///
115/// `general-glo-ciphering` and `general-ded-ciphering` differ only in which key the
116/// receiver looks up, which is why they share this type and are told apart by the tag.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct GeneralGloCiphering<'a> {
119    /// The originator's system title — how a listener finds the key.
120    pub system_title: &'a [u8],
121    /// The protected service.
122    pub ciphered: CipheredService<'a>,
123}
124
125impl Encode for GeneralGloCiphering<'_> {
126    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
127        w.write_length_prefixed(self.system_title)?;
128        self.ciphered.encode(w)
129    }
130}
131
132impl<'a> Decode<'a> for GeneralGloCiphering<'a> {
133    fn decode(r: &mut Reader<'a>) -> Result<Self> {
134        Ok(Self { system_title: r.length_prefixed()?, ciphered: CipheredService::decode(r)? })
135    }
136}
137
138/// Which key protected a `general-ciphering` APDU.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum KeyInfo<'a> {
141    /// A key both sides already hold, named by id.
142    Identified {
143        /// 0 for the global unicast key, 1 for the global broadcast key.
144        key_id: u8,
145    },
146    /// A key delivered with the message, wrapped under a key-encrypting key.
147    Wrapped {
148        /// Which key-encrypting key unwraps it. `0` is the master key, and is the only
149        /// value the standard defines — this is a *kek* id, not the id of the key being
150        /// delivered, which the ASN.1 makes plain and which is easy to read the other
151        /// way round.
152        kek_id: u8,
153        /// The wrapped key.
154        ciphered_key: &'a [u8],
155    },
156    /// A key derived by agreement, with the parameters that derived it.
157    Agreed {
158        /// The key agreement parameters.
159        parameters: &'a [u8],
160        /// The data the agreement produced.
161        ciphered_key: &'a [u8],
162    },
163}
164
165impl Encode for KeyInfo<'_> {
166    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
167        match self {
168            Self::Identified { key_id } => w.write_bytes(&[0, *key_id]),
169            Self::Wrapped { kek_id, ciphered_key } => {
170                w.write_bytes(&[1, *kek_id])?;
171                w.write_length_prefixed(ciphered_key)
172            }
173            Self::Agreed { parameters, ciphered_key } => {
174                w.write_u8(2)?;
175                w.write_length_prefixed(parameters)?;
176                w.write_length_prefixed(ciphered_key)
177            }
178        }
179    }
180}
181
182impl<'a> Decode<'a> for KeyInfo<'a> {
183    fn decode(r: &mut Reader<'a>) -> Result<Self> {
184        Ok(match r.u8()? {
185            0 => Self::Identified { key_id: r.u8()? },
186            1 => Self::Wrapped { kek_id: r.u8()?, ciphered_key: r.length_prefixed()? },
187            2 => Self::Agreed { parameters: r.length_prefixed()?, ciphered_key: r.length_prefixed()? },
188            other => return Err(r.err_back(ErrorKind::InvalidTag(other), 1)),
189        })
190    }
191}
192
193/// A protected APDU that carries everything a third party needs to check it.
194///
195/// Unlike `glo-`/`ded-` ciphering, `general-ciphering` names both ends, may carry the
196/// key, and may travel end to end across intermediaries that cannot read it.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct GeneralCiphering<'a> {
199    /// Correlates a request with its response across a third party.
200    pub transaction_id: &'a [u8],
201    /// Who protected it.
202    pub originator_system_title: &'a [u8],
203    /// Who may unprotect it.
204    pub recipient_system_title: &'a [u8],
205    /// When, as raw octets — empty when absent.
206    pub date_time: &'a [u8],
207    /// Anything else the profile puts here.
208    pub other_information: &'a [u8],
209    /// Which key, when the message says.
210    pub key_info: Option<KeyInfo<'a>>,
211    /// The protected service.
212    pub ciphered: CipheredService<'a>,
213}
214
215impl Encode for GeneralCiphering<'_> {
216    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
217        w.write_length_prefixed(self.transaction_id)?;
218        w.write_length_prefixed(self.originator_system_title)?;
219        w.write_length_prefixed(self.recipient_system_title)?;
220        w.write_length_prefixed(self.date_time)?;
221        w.write_length_prefixed(self.other_information)?;
222        match &self.key_info {
223            None => w.write_u8(0)?,
224            Some(k) => {
225                w.write_u8(1)?;
226                k.encode(w)?;
227            }
228        }
229        self.ciphered.encode(w)
230    }
231}
232
233impl<'a> Decode<'a> for GeneralCiphering<'a> {
234    fn decode(r: &mut Reader<'a>) -> Result<Self> {
235        Ok(Self {
236            transaction_id: r.length_prefixed()?,
237            originator_system_title: r.length_prefixed()?,
238            recipient_system_title: r.length_prefixed()?,
239            date_time: r.length_prefixed()?,
240            other_information: r.length_prefixed()?,
241            key_info: if r.u8()? == 0 { None } else { Some(KeyInfo::decode(r)?) },
242            ciphered: CipheredService::decode(r)?,
243        })
244    }
245}
246
247/// A signed APDU: proof of origin that survives an intermediary.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub struct GeneralSigning<'a> {
250    /// Correlates a request with its response.
251    pub transaction_id: &'a [u8],
252    /// Who signed.
253    pub originator_system_title: &'a [u8],
254    /// Who it is for.
255    pub recipient_system_title: &'a [u8],
256    /// When, as raw octets — empty when absent.
257    pub date_time: &'a [u8],
258    /// Anything else the profile puts here.
259    pub other_information: &'a [u8],
260    /// The signed APDU, itself possibly ciphered.
261    pub content: &'a [u8],
262    /// The signature over everything before it.
263    pub signature: &'a [u8],
264}
265
266impl Encode for GeneralSigning<'_> {
267    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
268        w.write_length_prefixed(self.transaction_id)?;
269        w.write_length_prefixed(self.originator_system_title)?;
270        w.write_length_prefixed(self.recipient_system_title)?;
271        w.write_length_prefixed(self.date_time)?;
272        w.write_length_prefixed(self.other_information)?;
273        w.write_length_prefixed(self.content)?;
274        w.write_length_prefixed(self.signature)
275    }
276}
277
278impl<'a> Decode<'a> for GeneralSigning<'a> {
279    fn decode(r: &mut Reader<'a>) -> Result<Self> {
280        Ok(Self {
281            transaction_id: r.length_prefixed()?,
282            originator_system_title: r.length_prefixed()?,
283            recipient_system_title: r.length_prefixed()?,
284            date_time: r.length_prefixed()?,
285            other_information: r.length_prefixed()?,
286            content: r.length_prefixed()?,
287            signature: r.length_prefixed()?,
288        })
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use crate::codec::SliceWriter;
296
297    #[test]
298    fn security_control_bits() {
299        let sc = SecurityControl::new(1, true, true);
300        assert_eq!(sc.suite(), 1);
301        assert!(sc.authenticated() && sc.encrypted());
302        assert!(!sc.broadcast_key() && !sc.compressed());
303        assert_eq!(sc.0, 0x31);
304        assert!(SecurityControl(0x00).is_plain());
305        assert!(SecurityControl(0x80).compressed());
306        assert!(SecurityControl(0x40).broadcast_key());
307    }
308
309    #[test]
310    fn a_ciphered_service_round_trips() {
311        let c = CipheredService {
312            security_control: SecurityControl::new(0, true, true),
313            invocation_counter: 0x0000_0001,
314            payload: &[0xAA, 0xBB, 0xCC],
315        };
316        let mut buf = [0u8; 32];
317        let mut w = SliceWriter::new(&mut buf);
318        c.encode(&mut w).unwrap();
319        assert_eq!(w.as_slice(), [0x08, 0x30, 0, 0, 0, 1, 0xAA, 0xBB, 0xCC]);
320        assert_eq!(CipheredService::from_bytes(w.as_slice()).unwrap(), c);
321    }
322
323    #[test]
324    fn general_glo_ciphering_names_the_originator() {
325        let g = GeneralGloCiphering {
326            system_title: b"MMM\x00\x00\xbcaN",
327            ciphered: CipheredService {
328                security_control: SecurityControl::new(0, true, true),
329                invocation_counter: 5,
330                payload: &[0x01],
331            },
332        };
333        let mut buf = [0u8; 64];
334        let mut w = SliceWriter::new(&mut buf);
335        g.encode(&mut w).unwrap();
336        assert_eq!(w.as_slice()[0], 8, "system title is length-prefixed");
337        assert_eq!(GeneralGloCiphering::from_bytes(w.as_slice()).unwrap(), g);
338    }
339
340    #[test]
341    fn key_info_variants_round_trip() {
342        for k in [
343            KeyInfo::Identified { key_id: 0 },
344            KeyInfo::Wrapped { kek_id: 0, ciphered_key: &[1, 2, 3] },
345            KeyInfo::Agreed { parameters: &[9], ciphered_key: &[8, 7] },
346        ] {
347            let mut buf = [0u8; 32];
348            let mut w = SliceWriter::new(&mut buf);
349            k.encode(&mut w).unwrap();
350            assert_eq!(KeyInfo::from_bytes(w.as_slice()).unwrap(), k);
351        }
352    }
353}