Skip to main content

spodes_rs/security/
mod.rs

1//! DLMS/COSEM security model.
2//!
3//! This module gathers the three orthogonal security concepts:
4//!
5//! * [`crate::security::SecuritySuite`] — the cryptographic suite (0, 1 or 2) selecting the
6//!   authenticated-encryption, signature, key-agreement and hash algorithms
7//!   (IEC 62056-5-3, 5.3.7 / DLMS Green Book Table 19).
8//! * [`crate::security::SecurityPolicy`] — the protection level applied to APDUs (none,
9//!   authentication, encryption or authenticated encryption).
10//! * [`crate::security::AuthMechanism`] — the authentication mechanism negotiated when opening an
11//!   application association (mechanism_id 0..10), including the Russian GOST
12//!   profile of Р 1323565.1, §7.5.
13//!
14//! The four-pass HLS handshake computations live in [`crate::security::hls`].
15
16pub mod access_rights;
17pub mod agreement;
18pub mod gost3410;
19pub mod hls;
20pub mod signature;
21
22/// A DLMS/COSEM security suite (IEC 62056-5-3, 5.3.7).
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum SecuritySuite {
25    /// Suite 0 — AES-GCM-128, AES-128 key wrap. No PKI.
26    Suite0,
27    /// Suite 1 — ECDH-ECDSA-AES-GCM-128-SHA-256 (curve P-256).
28    Suite1,
29    /// Suite 2 — ECDH-ECDSA-AES-GCM-256-SHA-384 (curve P-384).
30    Suite2,
31}
32
33impl SecuritySuite {
34    /// The 4-bit suite id carried in the security control byte.
35    pub fn id(&self) -> u8 {
36        match self {
37            SecuritySuite::Suite0 => 0,
38            SecuritySuite::Suite1 => 1,
39            SecuritySuite::Suite2 => 2,
40        }
41    }
42
43    /// Parses a suite from its id.
44    pub fn from_id(id: u8) -> Option<SecuritySuite> {
45        match id {
46            0 => Some(SecuritySuite::Suite0),
47            1 => Some(SecuritySuite::Suite1),
48            2 => Some(SecuritySuite::Suite2),
49            _ => None,
50        }
51    }
52
53    /// The standard suite name.
54    pub fn name(&self) -> &'static str {
55        match self {
56            SecuritySuite::Suite0 => "AES-GCM-128",
57            SecuritySuite::Suite1 => "ECDH-ECDSA-AES-GCM-128-SHA-256",
58            SecuritySuite::Suite2 => "ECDH-ECDSA-AES-GCM-256-SHA-384",
59        }
60    }
61
62    /// The AES key length in octets for authenticated encryption (16 or 32).
63    pub fn aes_key_len(&self) -> usize {
64        match self {
65            SecuritySuite::Suite0 | SecuritySuite::Suite1 => 16,
66            SecuritySuite::Suite2 => 32,
67        }
68    }
69
70    /// Whether the suite provides digital signatures and key agreement (PKI).
71    pub fn has_public_key(&self) -> bool {
72        !matches!(self, SecuritySuite::Suite0)
73    }
74}
75
76/// The protection level applied to an APDU. Together with the security suite it
77/// determines the security control byte (SC) of a ciphered APDU.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum SecurityPolicy {
80    /// No protection.
81    None,
82    /// Authentication only (GMAC / AES-GCM tag over the plaintext).
83    Authentication,
84    /// Encryption only.
85    Encryption,
86    /// Authenticated encryption (both).
87    AuthenticationEncryption,
88}
89
90impl SecurityPolicy {
91    /// The authentication/encryption bits of the security control byte
92    /// (bit 4 = authentication, bit 5 = encryption).
93    pub fn security_control_bits(&self) -> u8 {
94        match self {
95            SecurityPolicy::None => 0x00,
96            SecurityPolicy::Authentication => 0x10,
97            SecurityPolicy::Encryption => 0x20,
98            SecurityPolicy::AuthenticationEncryption => 0x30,
99        }
100    }
101
102    /// Derives the policy from a security control byte.
103    pub fn from_security_control(sc: u8) -> SecurityPolicy {
104        match (sc & 0x10 != 0, sc & 0x20 != 0) {
105            (false, false) => SecurityPolicy::None,
106            (true, false) => SecurityPolicy::Authentication,
107            (false, true) => SecurityPolicy::Encryption,
108            (true, true) => SecurityPolicy::AuthenticationEncryption,
109        }
110    }
111
112    /// Builds the full security control byte for this policy and suite.
113    pub fn security_control_byte(&self, suite: SecuritySuite) -> u8 {
114        self.security_control_bits() | (suite.id() & 0x0F)
115    }
116}
117
118/// An HLS/LLS authentication mechanism (mechanism_id 0..10).
119///
120/// Mechanisms 0..7 are defined by IEC 62056-5-3 / the DLMS Green Book;
121/// mechanisms 8..10 are the Russian GOST profile of Р 1323565.1, §7.5.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
123pub enum AuthMechanism {
124    /// (0) No authentication (lowest level security).
125    None,
126    /// (1) Low Level Security — password.
127    Lls,
128    /// (2) HLS, manufacturer-specific.
129    HlsManufacturer,
130    /// (3) HLS with MD5 (not recommended).
131    HlsMd5,
132    /// (4) HLS with SHA-1 (not recommended).
133    HlsSha1,
134    /// (5) HLS with GMAC.
135    HlsGmac,
136    /// (6) HLS with SHA-256.
137    HlsSha256,
138    /// (7) HLS with ECDSA.
139    HlsEcdsa,
140    /// (8) HLS CMAC — Kuznyechik CMAC (GOST, Р 1323565.1).
141    HlsGostCmac,
142    /// (9) HLS GOST34112018-256 — Streebog-256 hash (GOST, Р 1323565.1).
143    HlsGostStreebog,
144    /// (10) HLS GOST34102018-256 — GOST 34.10 signature (GOST, Р 1323565.1).
145    HlsGostSignature,
146}
147
148impl AuthMechanism {
149    /// The mechanism id (last arc of the mechanism-name OID).
150    pub fn id(&self) -> u8 {
151        match self {
152            AuthMechanism::None => 0,
153            AuthMechanism::Lls => 1,
154            AuthMechanism::HlsManufacturer => 2,
155            AuthMechanism::HlsMd5 => 3,
156            AuthMechanism::HlsSha1 => 4,
157            AuthMechanism::HlsGmac => 5,
158            AuthMechanism::HlsSha256 => 6,
159            AuthMechanism::HlsEcdsa => 7,
160            AuthMechanism::HlsGostCmac => 8,
161            AuthMechanism::HlsGostStreebog => 9,
162            AuthMechanism::HlsGostSignature => 10,
163        }
164    }
165
166    /// Parses a mechanism from its id.
167    pub fn from_id(id: u8) -> Option<AuthMechanism> {
168        Some(match id {
169            0 => AuthMechanism::None,
170            1 => AuthMechanism::Lls,
171            2 => AuthMechanism::HlsManufacturer,
172            3 => AuthMechanism::HlsMd5,
173            4 => AuthMechanism::HlsSha1,
174            5 => AuthMechanism::HlsGmac,
175            6 => AuthMechanism::HlsSha256,
176            7 => AuthMechanism::HlsEcdsa,
177            8 => AuthMechanism::HlsGostCmac,
178            9 => AuthMechanism::HlsGostStreebog,
179            10 => AuthMechanism::HlsGostSignature,
180            _ => return None,
181        })
182    }
183
184    /// The COSEM authentication-mechanism-name OID `2.16.756.5.8.2.<id>`,
185    /// encoded as the 7 raw octets of the OBJECT IDENTIFIER value.
186    pub fn oid(&self) -> [u8; 7] {
187        [0x60, 0x85, 0x74, 0x05, 0x08, 0x02, self.id()]
188    }
189
190    /// Whether the mechanism is a High Level Security mechanism (uses the
191    /// four-pass challenge/response handshake).
192    pub fn is_hls(&self) -> bool {
193        self.id() >= 2
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn security_suite_ids_and_key_lengths() {
203        assert_eq!(SecuritySuite::Suite0.id(), 0);
204        assert_eq!(SecuritySuite::Suite2.id(), 2);
205        assert_eq!(SecuritySuite::from_id(1), Some(SecuritySuite::Suite1));
206        assert_eq!(SecuritySuite::from_id(3), None);
207        assert_eq!(SecuritySuite::Suite1.aes_key_len(), 16);
208        assert_eq!(SecuritySuite::Suite2.aes_key_len(), 32);
209        assert!(!SecuritySuite::Suite0.has_public_key());
210        assert!(SecuritySuite::Suite2.has_public_key());
211    }
212
213    #[test]
214    fn security_policy_maps_to_control_byte() {
215        assert_eq!(SecurityPolicy::None.security_control_bits(), 0x00);
216        assert_eq!(SecurityPolicy::Authentication.security_control_bits(), 0x10);
217        assert_eq!(SecurityPolicy::Encryption.security_control_bits(), 0x20);
218        assert_eq!(SecurityPolicy::AuthenticationEncryption.security_control_bits(), 0x30);
219        // Suite id occupies the low nibble.
220        assert_eq!(SecurityPolicy::AuthenticationEncryption.security_control_byte(SecuritySuite::Suite2), 0x32);
221        assert_eq!(SecurityPolicy::from_security_control(0x30), SecurityPolicy::AuthenticationEncryption);
222        assert_eq!(SecurityPolicy::from_security_control(0x10), SecurityPolicy::Authentication);
223    }
224
225    #[test]
226    fn all_mechanisms_round_trip_and_have_oids() {
227        for id in 0..=10u8 {
228            let m = AuthMechanism::from_id(id).unwrap();
229            assert_eq!(m.id(), id);
230            let oid = m.oid();
231            assert_eq!(&oid[..6], &[0x60, 0x85, 0x74, 0x05, 0x08, 0x02]);
232            assert_eq!(oid[6], id);
233        }
234        assert_eq!(AuthMechanism::from_id(11), None);
235        // GOST mechanisms are HLS.
236        assert!(AuthMechanism::HlsGostStreebog.is_hls());
237        assert!(!AuthMechanism::Lls.is_hls());
238    }
239}