Skip to main content

spodes_rs/service/
general_ciphering.rs

1//! General ciphering APDUs (IEC 62056-5-3, 5.7.2): the address-carrying wrappers
2//! that transport a protected xDLMS APDU independently of the service.
3//!
4//! * general-glo-ciphering (`[219]`, 0xDB) and general-ded-ciphering (`[220]`, 0xDC)
5//!   prepend the originator system-title to a ciphered-service octet-string
6//!   (`SC ‖ IC ‖ ciphertext ‖ tag`, produced by [`super::ciphering`]).
7//! * general-ciphering (`[221]`, 0xDD) additionally carries the transaction-id,
8//!   both system-titles, date-time and other-information.
9//!
10//! This module only frames the APDU; the authenticated encryption itself is done
11//! by [`super::ciphering`]. The general-ciphering `key-info` field (agreed-key /
12//! PKI key transport) is not modelled — general-ciphering here assumes a
13//! pre-shared symmetric key (key-info absent).
14
15use super::{push_length, read_length, ServiceError};
16
17/// general-glo-ciphering APDU tag (`[219]`).
18pub const GENERAL_GLO_CIPHERING_TAG: u8 = 0xDB;
19/// general-ded-ciphering APDU tag (`[220]`).
20pub const GENERAL_DED_CIPHERING_TAG: u8 = 0xDC;
21/// general-ciphering APDU tag (`[221]`).
22pub const GENERAL_CIPHERING_TAG: u8 = 0xDD;
23/// general-signing APDU tag (`[223]`).
24pub const GENERAL_SIGNING_TAG: u8 = 0xDF;
25
26/// The `key-info` field of a general-ciphering APDU (IEC 62056-5-3, 5.7.2.4).
27///
28/// It is a CHOICE; only the two variants used by DLMS symmetric-key transport
29/// are modelled: absent (a pre-shared key is used) and `agreed-key` (an EC key
30/// agreement supplies the session key).
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum KeyInfo {
33    /// No key-info: the recipient already holds the symmetric key.
34    None,
35    /// Agreed-key (`[2]`): an EC key-agreement scheme derives the session key.
36    AgreedKey {
37        /// Key-parameters: the one-octet key-agreement scheme id (01 = ephemeral
38        /// unified, 02 = static unified, …).
39        key_parameters: Vec<u8>,
40        /// Key-ciphered-data: the ephemeral public key(s) and signature needed by
41        /// the recipient to complete the agreement (empty for the static model).
42        key_ciphered_data: Vec<u8>,
43    },
44}
45
46/// A general-glo-ciphering or general-ded-ciphering APDU.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct GeneralGloDedCiphering {
49    /// `true` for general-ded-ciphering (`[220]`), `false` for the glo variant.
50    pub dedicated: bool,
51    /// System-title of the originator (usually 8 octets).
52    pub system_title: Vec<u8>,
53    /// Ciphered service: `SC ‖ IC ‖ ciphertext ‖ tag`.
54    pub ciphered_service: Vec<u8>,
55}
56
57impl GeneralGloDedCiphering {
58    /// Encodes the APDU.
59    pub fn encode(&self) -> Vec<u8> {
60        let tag = if self.dedicated { GENERAL_DED_CIPHERING_TAG } else { GENERAL_GLO_CIPHERING_TAG };
61        let mut buf = vec![tag];
62        push_octet_string(&self.system_title, &mut buf);
63        push_octet_string(&self.ciphered_service, &mut buf);
64        buf
65    }
66
67    /// Decodes the APDU.
68    pub fn decode(bytes: &[u8]) -> Result<GeneralGloDedCiphering, ServiceError> {
69        let dedicated = match bytes.first() {
70            Some(&GENERAL_GLO_CIPHERING_TAG) => false,
71            Some(&GENERAL_DED_CIPHERING_TAG) => true,
72            Some(&other) => return Err(ServiceError::UnexpectedTag(other)),
73            None => return Err(ServiceError::Truncated),
74        };
75        let (system_title, n) = take_octet_string(&bytes[1..])?;
76        let (ciphered_service, _) = take_octet_string(&bytes[1 + n..])?;
77        Ok(GeneralGloDedCiphering { dedicated, system_title, ciphered_service })
78    }
79}
80
81/// A general-ciphering APDU (`[221]`).
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct GeneralCiphering {
84    /// Transaction-id identifying the exchange between the two parties.
85    pub transaction_id: Vec<u8>,
86    /// System-title of the originator.
87    pub originator_system_title: Vec<u8>,
88    /// System-title of the recipient (empty for broadcast).
89    pub recipient_system_title: Vec<u8>,
90    /// Optional date-time (empty octet-string when unused).
91    pub date_time: Vec<u8>,
92    /// Optional other-information (empty octet-string when unused).
93    pub other_information: Vec<u8>,
94    /// Key-info: absent (pre-shared key) or an agreed-key CHOICE.
95    pub key_info: KeyInfo,
96    /// Ciphered content: `SC ‖ IC ‖ ciphertext ‖ tag`.
97    pub ciphered_content: Vec<u8>,
98}
99
100impl GeneralCiphering {
101    /// Encodes the APDU.
102    pub fn encode(&self) -> Vec<u8> {
103        let mut buf = vec![GENERAL_CIPHERING_TAG];
104        push_octet_string(&self.transaction_id, &mut buf);
105        push_octet_string(&self.originator_system_title, &mut buf);
106        push_octet_string(&self.recipient_system_title, &mut buf);
107        push_octet_string(&self.date_time, &mut buf);
108        push_octet_string(&self.other_information, &mut buf);
109        match &self.key_info {
110            KeyInfo::None => buf.push(0x00),
111            KeyInfo::AgreedKey { key_parameters, key_ciphered_data } => {
112                buf.push(0x01); // key-info present
113                buf.push(0x02); // agreed-key CHOICE
114                push_octet_string(key_parameters, &mut buf);
115                push_octet_string(key_ciphered_data, &mut buf);
116            }
117        }
118        push_octet_string(&self.ciphered_content, &mut buf);
119        buf
120    }
121
122    /// Decodes the APDU. The `key-info` CHOICE is supported for absent and
123    /// agreed-key; other CHOICE variants yield [`ServiceError::InvalidData`].
124    pub fn decode(bytes: &[u8]) -> Result<GeneralCiphering, ServiceError> {
125        if bytes.first() != Some(&GENERAL_CIPHERING_TAG) {
126            return Err(ServiceError::UnexpectedTag(*bytes.first().unwrap_or(&0)));
127        }
128        let mut pos = 1;
129        let (transaction_id, n) = take_octet_string(&bytes[pos..])?;
130        pos += n;
131        let (originator_system_title, n) = take_octet_string(&bytes[pos..])?;
132        pos += n;
133        let (recipient_system_title, n) = take_octet_string(&bytes[pos..])?;
134        pos += n;
135        let (date_time, n) = take_octet_string(&bytes[pos..])?;
136        pos += n;
137        let (other_information, n) = take_octet_string(&bytes[pos..])?;
138        pos += n;
139        let key_info = match bytes.get(pos) {
140            Some(0x00) => {
141                pos += 1;
142                KeyInfo::None
143            }
144            Some(0x01) => {
145                // key-info present; the CHOICE tag follows.
146                match bytes.get(pos + 1) {
147                    Some(0x02) => {
148                        pos += 2;
149                        let (key_parameters, n) = take_octet_string(&bytes[pos..])?;
150                        pos += n;
151                        let (key_ciphered_data, n) = take_octet_string(&bytes[pos..])?;
152                        pos += n;
153                        KeyInfo::AgreedKey { key_parameters, key_ciphered_data }
154                    }
155                    Some(_) => return Err(ServiceError::InvalidData), // other CHOICE variants
156                    None => return Err(ServiceError::Truncated),
157                }
158            }
159            Some(&other) => return Err(ServiceError::UnexpectedType(other)),
160            None => return Err(ServiceError::Truncated),
161        };
162        let (ciphered_content, _) = take_octet_string(&bytes[pos..])?;
163        Ok(GeneralCiphering {
164            transaction_id,
165            originator_system_title,
166            recipient_system_title,
167            date_time,
168            other_information,
169            key_info,
170            ciphered_content,
171        })
172    }
173}
174
175/// A general-signing APDU (`[223]`): the address-carrying fields of a
176/// general-ciphering APDU followed by the (optionally protected) content and its
177/// digital signature (IEC 62056-5-3, 5.7.2.5 / DLMS Green Book 9.2.7.2.5).
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct GeneralSigning {
180    /// Transaction-id identifying the exchange between the two parties.
181    pub transaction_id: Vec<u8>,
182    /// System-title of the originator.
183    pub originator_system_title: Vec<u8>,
184    /// System-title of the recipient (empty for broadcast).
185    pub recipient_system_title: Vec<u8>,
186    /// Optional date-time (empty octet-string when unused).
187    pub date_time: Vec<u8>,
188    /// Optional other-information (empty octet-string when unused).
189    pub other_information: Vec<u8>,
190    /// The signed content: a plain or ciphered xDLMS APDU.
191    pub content: Vec<u8>,
192    /// The digital signature over the content (ECDSA `r ‖ s` or GOST 34.10).
193    pub signature: Vec<u8>,
194}
195
196impl GeneralSigning {
197    /// Encodes the APDU.
198    pub fn encode(&self) -> Vec<u8> {
199        let mut buf = vec![GENERAL_SIGNING_TAG];
200        push_octet_string(&self.transaction_id, &mut buf);
201        push_octet_string(&self.originator_system_title, &mut buf);
202        push_octet_string(&self.recipient_system_title, &mut buf);
203        push_octet_string(&self.date_time, &mut buf);
204        push_octet_string(&self.other_information, &mut buf);
205        push_octet_string(&self.content, &mut buf);
206        push_octet_string(&self.signature, &mut buf);
207        buf
208    }
209
210    /// Decodes the APDU.
211    pub fn decode(bytes: &[u8]) -> Result<GeneralSigning, ServiceError> {
212        if bytes.first() != Some(&GENERAL_SIGNING_TAG) {
213            return Err(ServiceError::UnexpectedTag(*bytes.first().unwrap_or(&0)));
214        }
215        let mut pos = 1;
216        let (transaction_id, n) = take_octet_string(&bytes[pos..])?;
217        pos += n;
218        let (originator_system_title, n) = take_octet_string(&bytes[pos..])?;
219        pos += n;
220        let (recipient_system_title, n) = take_octet_string(&bytes[pos..])?;
221        pos += n;
222        let (date_time, n) = take_octet_string(&bytes[pos..])?;
223        pos += n;
224        let (other_information, n) = take_octet_string(&bytes[pos..])?;
225        pos += n;
226        let (content, n) = take_octet_string(&bytes[pos..])?;
227        pos += n;
228        let (signature, _) = take_octet_string(&bytes[pos..])?;
229        Ok(GeneralSigning {
230            transaction_id,
231            originator_system_title,
232            recipient_system_title,
233            date_time,
234            other_information,
235            content,
236            signature,
237        })
238    }
239}
240
241/// Writes an A-XDR octet-string: `<length> <bytes>`.
242fn push_octet_string(bytes: &[u8], buf: &mut Vec<u8>) {
243    push_length(bytes.len(), buf);
244    buf.extend_from_slice(bytes);
245}
246
247/// Reads an A-XDR octet-string, returning its bytes and the octets consumed.
248fn take_octet_string(bytes: &[u8]) -> Result<(Vec<u8>, usize), ServiceError> {
249    let (len, header) = read_length(bytes)?;
250    let slice = bytes.get(header..header + len).ok_or(ServiceError::Truncated)?;
251    Ok((slice.to_vec(), header + len))
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn general_glo_ciphering_round_trips() {
260        let apdu = GeneralGloDedCiphering {
261            dedicated: false,
262            system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01],
263            ciphered_service: vec![0x30, 0x00, 0x00, 0x00, 0x01, 0xAA, 0xBB],
264        };
265        let bytes = apdu.encode();
266        // DB 08 <sys-title> 07 <ciphered-service>.
267        assert_eq!(bytes[..2], [0xDB, 0x08]);
268        assert_eq!(bytes[10], 0x07);
269        assert_eq!(GeneralGloDedCiphering::decode(&bytes).unwrap(), apdu);
270    }
271
272    #[test]
273    fn general_ded_ciphering_tag() {
274        let apdu = GeneralGloDedCiphering {
275            dedicated: true,
276            system_title: vec![0x01; 8],
277            ciphered_service: vec![0x30, 0x00, 0x00, 0x00, 0x01],
278        };
279        assert_eq!(apdu.encode()[0], GENERAL_DED_CIPHERING_TAG);
280        assert_eq!(GeneralGloDedCiphering::decode(&apdu.encode()).unwrap(), apdu);
281    }
282
283    #[test]
284    fn general_ciphering_round_trips() {
285        let apdu = GeneralCiphering {
286            transaction_id: vec![0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45],
287            originator_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01],
288            recipient_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E],
289            date_time: Vec::new(),
290            other_information: Vec::new(),
291            key_info: KeyInfo::None,
292            ciphered_content: vec![0x30, 0x00, 0x00, 0x00, 0x01, 0xCA, 0xFE],
293        };
294        let bytes = apdu.encode();
295        // DD 08 <tx-id> 08 <orig> 08 <recip> 00 00 00 07 <content>.
296        assert_eq!(bytes[0], 0xDD);
297        assert_eq!(GeneralCiphering::decode(&bytes).unwrap(), apdu);
298    }
299
300    #[test]
301    fn general_ciphering_with_agreed_key_round_trips() {
302        // Shape from DLMS Green Book Table C.1 (ephemeral unified, scheme 01):
303        // ... 01 02 0101 <key-ciphered-data> ...
304        let apdu = GeneralCiphering {
305            transaction_id: vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08],
306            originator_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E],
307            recipient_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01],
308            date_time: Vec::new(),
309            other_information: Vec::new(),
310            key_info: KeyInfo::AgreedKey {
311                key_parameters: vec![0x01],         // ephemeral unified model
312                key_ciphered_data: vec![0xAA; 128], // ephemeral pubkey ‖ signature
313            },
314            ciphered_content: vec![0x30, 0x00, 0x00, 0x00, 0x01, 0xCA, 0xFE],
315        };
316        let bytes = apdu.encode();
317        // key-info: 01 (present) 02 (agreed-key) 01 01 (params) 81 80 <128 octets>.
318        // It follows tag + 3 octet-strings (1+9 each) + two empty (00) fields.
319        let ki = &bytes[30..];
320        assert_eq!(ki[..6], [0x01, 0x02, 0x01, 0x01, 0x81, 0x80]);
321        assert_eq!(GeneralCiphering::decode(&bytes).unwrap(), apdu);
322    }
323
324    #[test]
325    fn general_signing_round_trips() {
326        let apdu = GeneralSigning {
327            transaction_id: vec![0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45],
328            originator_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01],
329            recipient_system_title: vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E],
330            date_time: Vec::new(),
331            other_information: Vec::new(),
332            content: vec![0xC4, 0x01, 0xC1, 0x00, 0x12, 0x12, 0x34],
333            signature: vec![0xAB; 64],
334        };
335        let bytes = apdu.encode();
336        // DF <tx> <orig> <recip> 00 00 <content> 40 <64-octet signature>.
337        assert_eq!(bytes[0], 0xDF);
338        assert_eq!(GeneralSigning::decode(&bytes).unwrap(), apdu);
339    }
340
341    #[test]
342    fn general_ciphering_rejects_key_info() {
343        let mut bytes = GeneralCiphering {
344            transaction_id: vec![0; 8],
345            originator_system_title: vec![0; 8],
346            recipient_system_title: Vec::new(),
347            date_time: Vec::new(),
348            other_information: Vec::new(),
349            key_info: KeyInfo::None,
350            ciphered_content: vec![0x30],
351        }
352        .encode();
353        // Turn the key-info-absent flag into "present" with an unsupported
354        // CHOICE tag (0x01 = wrapped-key, not modelled).
355        let flag = bytes.len() - 3;
356        bytes[flag] = 0x01; // present
357        bytes.insert(flag + 1, 0x01); // wrapped-key CHOICE
358        assert_eq!(GeneralCiphering::decode(&bytes), Err(ServiceError::InvalidData));
359    }
360}