Skip to main content

spodes_rs/security/
hls.rs

1//! Four-pass HLS handshake computations for every supported mechanism.
2//!
3//! During High Level Security the client processes the server challenge `StoC`
4//! and the server processes the client challenge `CtoS`; each side verifies the
5//! peer's processed value before the association is established
6//! (IEC 62056-5-3 Table 32; Р 1323565.1 §7.5).
7//!
8//! Each function computes `f(challenge)` for one mechanism. The GMAC mechanism
9//! (5) lives in the Association LN class; the signature mechanisms (7 ECDSA and
10//! 10 GOST 34.10) require a private key and are not computed here.
11
12use cmac::{Cmac, KeyInit, Mac};
13use kuznyechik::Kuznyechik;
14use sha2::Digest;
15
16use md5::Md5;
17use sha1::Sha1;
18use sha2::Sha256;
19use streebog::Streebog256;
20
21use super::AuthMechanism;
22
23/// Hashes the concatenation of `parts` with digest `D`.
24fn digest_concat<D: Digest>(parts: &[&[u8]]) -> Vec<u8> {
25    let mut d = D::new();
26    for part in parts {
27        d.update(part);
28    }
29    d.finalize().to_vec()
30}
31
32/// Mechanisms 3 (MD5) and 4 (SHA-1): `f(challenge) = HASH(challenge ‖ secret)`.
33///
34/// Returns `None` for other mechanisms.
35pub fn hash_legacy(mechanism: AuthMechanism, challenge: &[u8], secret: &[u8]) -> Option<Vec<u8>> {
36    match mechanism {
37        AuthMechanism::HlsMd5 => Some(digest_concat::<Md5>(&[challenge, secret])),
38        AuthMechanism::HlsSha1 => Some(digest_concat::<Sha1>(&[challenge, secret])),
39        _ => None,
40    }
41}
42
43/// Mechanisms 6 (SHA-256) and 9 (Streebog-256):
44/// `f = HASH(secret ‖ st_a ‖ st_b ‖ challenge_a ‖ challenge_b)`.
45///
46/// For `f(StoC)` use `st_a = system-title-C`, `st_b = system-title-S`,
47/// `challenge_a = StoC`, `challenge_b = CtoS`; for `f(CtoS)` swap both pairs
48/// (IEC 62056-5-3 Table 32 mechanism 6; Р 1323565.1 §7.5.2 mechanism 9).
49///
50/// Returns `None` for other mechanisms.
51pub fn hash_with_titles(
52    mechanism: AuthMechanism,
53    secret: &[u8],
54    st_a: &[u8],
55    st_b: &[u8],
56    challenge_a: &[u8],
57    challenge_b: &[u8],
58) -> Option<Vec<u8>> {
59    let parts = [secret, st_a, st_b, challenge_a, challenge_b];
60    match mechanism {
61        AuthMechanism::HlsSha256 => Some(digest_concat::<Sha256>(&parts)),
62        AuthMechanism::HlsGostStreebog => Some(digest_concat::<Streebog256>(&parts)),
63        _ => None,
64    }
65}
66
67/// Mechanism 8 (HLS CMAC, GOST): `KUZN_CMAC(LSB256(K_EM), iv ‖ SC ‖ challenge_a ‖ challenge_b)`.
68///
69/// `K_EM` is the 512-bit global encryption/authentication key; its least
70/// significant 256 bits (the last 32 octets) form the Kuznyechik CMAC key. The
71/// resulting 16-octet MAC becomes the tail of `f = SC ‖ IC ‖ MAC`
72/// (Р 1323565.1 §7.5.1). `iv` is `system-title ‖ IC`.
73pub fn gost_cmac(
74    k_em: &[u8],
75    iv: &[u8],
76    security_control: u8,
77    challenge_a: &[u8],
78    challenge_b: &[u8],
79) -> Result<Vec<u8>, &'static str> {
80    if k_em.len() != 64 {
81        return Err("K_EM must be 64 octets (512 bits)");
82    }
83    let key = &k_em[32..]; // LSB256(K_EM)
84    let mut mac = Cmac::<Kuznyechik>::new_from_slice(key).map_err(|_| "invalid CMAC key length")?;
85    mac.update(iv);
86    mac.update(&[security_control]);
87    mac.update(challenge_a);
88    mac.update(challenge_b);
89    Ok(mac.finalize().into_bytes().to_vec())
90}
91
92/// The AES S-box.
93#[rustfmt::skip]
94const S_BOX: [u8; 256] = [
95    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
96    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
97    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
98    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
99    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
100    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
101    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
102    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
103    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
104    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
105    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
106    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
107    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
108    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
109    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
110    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
111];
112
113/// The AES round constants.
114#[rustfmt::skip]
115const R_CON: [u8; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
116
117/// GF(2^8) `xtime` multiply-by-2 with the AES reduction polynomial.
118fn xtime(v: u8) -> u8 {
119    if v & 0x80 != 0 {
120        (v << 1) ^ 0x1b
121    } else {
122        v << 1
123    }
124}
125
126/// AES-128 single-block encryption with on-the-fly key expansion. `key` is
127/// mutated in place to the final round key, matching the reference `Aes1Encrypt`.
128fn aes128_block(block: &mut [u8; 16], key: &mut [u8; 16]) {
129    for &rcon in R_CON.iter() {
130        // AddRoundKey combined with SubBytes.
131        for i in 0..16 {
132            block[i] = S_BOX[(block[i] ^ key[i]) as usize];
133        }
134        // ShiftRows.
135        let t = block[1];
136        block[1] = block[5];
137        block[5] = block[9];
138        block[9] = block[13];
139        block[13] = t;
140        block.swap(2, 10);
141        block.swap(6, 14);
142        let t = block[15];
143        block[15] = block[11];
144        block[11] = block[7];
145        block[7] = block[3];
146        block[3] = t;
147        // MixColumns (all rounds except the last).
148        if rcon != 0x36 {
149            for c in 0..4 {
150                let b = c << 2;
151                let all = block[b] ^ block[b + 1] ^ block[b + 2] ^ block[b + 3];
152                let first = block[b];
153                block[b] ^= xtime(block[b] ^ block[b + 1]) ^ all;
154                block[b + 1] ^= xtime(block[b + 1] ^ block[b + 2]) ^ all;
155                block[b + 2] ^= xtime(block[b + 2] ^ block[b + 3]) ^ all;
156                block[b + 3] ^= xtime(block[b + 3] ^ first) ^ all;
157            }
158        }
159        // Expand the round key in place.
160        key[0] ^= S_BOX[key[13] as usize] ^ rcon;
161        key[1] ^= S_BOX[key[14] as usize];
162        key[2] ^= S_BOX[key[15] as usize];
163        key[3] ^= S_BOX[key[12] as usize];
164        for i in 4..16 {
165            key[i] ^= key[i - 4];
166        }
167    }
168    // Final AddRoundKey.
169    for i in 0..16 {
170        block[i] ^= key[i];
171    }
172}
173
174/// HLS mechanism 2 (manufacturer-specific "high" authentication).
175///
176/// DLMS/COSEM does not specify mechanism 2, so implementations follow the widely
177/// deployed Texas-Instruments scheme: AES-128 over the zero-padded
178/// `challenge`, keyed by the zero-padded `secret`. The challenge and secret are
179/// padded to a common length that is a multiple of 16 (the larger of the two,
180/// rounded up); each 16-octet block of the padded challenge is then encrypted.
181/// As in the reference, the key is carried mutated from one block to the next,
182/// so multi-block challenges are not plain ECB.
183pub fn manufacturer_aes(secret: &[u8], challenge: &[u8]) -> Vec<u8> {
184    let mut len = challenge.len().div_ceil(16) * 16;
185    if secret.len() > challenge.len() {
186        len = secret.len().div_ceil(16) * 16;
187    }
188    let mut key = [0u8; 16];
189    let n = secret.len().min(16);
190    key[..n].copy_from_slice(&secret[..n]);
191    let mut out = vec![0u8; len];
192    out[..challenge.len()].copy_from_slice(challenge);
193    for chunk in out.chunks_mut(16) {
194        let mut block = [0u8; 16];
195        block.copy_from_slice(chunk);
196        aes128_block(&mut block, &mut key);
197        chunk.copy_from_slice(&block);
198    }
199    out
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    fn hex(s: &[u8]) -> Vec<u8> {
207        fn nib(c: u8) -> u8 {
208            match c {
209                b'0'..=b'9' => c - b'0',
210                b'a'..=b'f' => c - b'a' + 10,
211                b'A'..=b'F' => c - b'A' + 10,
212                _ => panic!("bad hex"),
213            }
214        }
215        s.chunks(2).map(|p| (nib(p[0]) << 4) | nib(p[1])).collect()
216    }
217
218    #[test]
219    fn manufacturer_aes_matches_reference_vectors() {
220        // Reference vectors for the Aes1Encrypt / Secure routine
221        // (the algorithm this meter family uses for mechanism 2).
222        // Single block: secret "12345678", challenge 00112233 44556677.
223        let out = manufacturer_aes(b"12345678", &hex(b"0011223344556677"));
224        assert_eq!(out, hex(b"3ce1760a845b8570bb2a2afe44392d0e"));
225
226        // Multi-block: 16-octet secret 00..0f, 32-octet challenge 80..9f. The
227        // second block is keyed by the mutated key, not plain ECB.
228        let secret: Vec<u8> = (0u8..16).collect();
229        let challenge: Vec<u8> = (0u8..32).map(|i| 0x80 + i).collect();
230        let out = manufacturer_aes(&secret, &challenge);
231        assert_eq!(out, hex(b"ac26591c0f8bd80ee7c7e3a2d14e2b2292dcb47a3f51368a5c18314b86eb4ae0"));
232    }
233
234    #[test]
235    fn sha1_legacy_matches() {
236        // f(challenge) = SHA-1(challenge ‖ secret).
237        let out = hash_legacy(AuthMechanism::HlsSha1, &[0xAA, 0xBB], b"secret").unwrap();
238        let mut h = Sha1::new();
239        h.update([0xAA, 0xBB]);
240        h.update(b"secret");
241        assert_eq!(out, h.finalize().to_vec());
242    }
243
244    #[test]
245    fn streebog_matches_r1323565_a5_2_vector() {
246        // Р 1323565.1, Annex A.5.2 (mechanism 9, HLS GOST34112018-256).
247        let secret = hex(b"78797a7b7c7d7e7f707172737475767788898a8b8c8d8e8f8081828384858687");
248        let st_c = hex(b"ff00ee11dd22cc33");
249        let st_s = hex(b"bb44aa5599668877");
250        let stoc = hex(b"8899aabbccddeeff");
251        let ctos = hex(b"0011223344556677");
252        let answer_c = hash_with_titles(AuthMechanism::HlsGostStreebog, &secret, &st_c, &st_s, &stoc, &ctos).unwrap();
253        assert_eq!(answer_c, hex(b"4c375b843898b6f0a0744051f74e42f2a944581d46c495e743e97abdcd9d7c58"));
254        // f(CtoS) swaps both pairs.
255        let answer_s = hash_with_titles(AuthMechanism::HlsGostStreebog, &secret, &st_s, &st_c, &ctos, &stoc).unwrap();
256        assert_eq!(answer_s, hex(b"55dcd7e597cc90ec215c2faae8f86c0a1d707ddeac1adf5cbd17dfaa5378c500"));
257    }
258
259    #[test]
260    fn sha256_hash_with_titles_is_deterministic() {
261        let a =
262            hash_with_titles(AuthMechanism::HlsSha256, b"secret", b"CCCCCCCC", b"SSSSSSSS", &[1, 2], &[3, 4]).unwrap();
263        assert_eq!(a.len(), 32);
264        let b =
265            hash_with_titles(AuthMechanism::HlsSha256, b"secret", b"CCCCCCCC", b"SSSSSSSS", &[1, 2], &[3, 4]).unwrap();
266        assert_eq!(a, b);
267    }
268
269    #[test]
270    fn gost_cmac_produces_16_octet_mac_and_verifies() {
271        let k_em = hex(b"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f");
272        let iv = hex(b"4d4d4d0000bc614e01234567"); // system-title ‖ IC
273        let stoc = hex(b"8899aabbccddeeff");
274        let ctos = hex(b"0011223344556677");
275        let mac = gost_cmac(&k_em, &iv, 0x30, &stoc, &ctos).unwrap();
276        assert_eq!(mac.len(), 16);
277        // Recomputing over the same data verifies.
278        let again = gost_cmac(&k_em, &iv, 0x30, &stoc, &ctos).unwrap();
279        assert_eq!(mac, again);
280        // K_EM must be 512 bits.
281        assert!(gost_cmac(&[0u8; 32], &iv, 0x30, &stoc, &ctos).is_err());
282    }
283}