Skip to main content

spodes_rs/security/
agreement.rs

1//! Elliptic-curve key agreement for security suites 1 and 2 (IEC 62056-5-3,
2//! 5.3.4 / DLMS Green Book Annex C).
3//!
4//! Two parties derive a shared symmetric key from a static/ephemeral EC key pair
5//! each. The raw shared secret `Z` is the x-coordinate of the ECDH point
6//! (`FE2OS(x)`); it is then run through the NIST SP 800-56A single-step (concat)
7//! KDF to obtain the DLMS session key:
8//!
9//! ```text
10//! K = Hash( counter(0x00000001) ‖ Z ‖ AlgorithmID ‖ PartyUInfo ‖ PartyVInfo )
11//! ```
12//!
13//! where the hash is SHA-256 for suite 1 and SHA-384 for suite 2, PartyUInfo /
14//! PartyVInfo are the two system-titles, and the encryption key is the leftmost
15//! 16 (suite 1) or 32 (suite 2) octets of `K`. Validated against the One-Pass
16//! Diffie-Hellman test vector of DLMS Green Book Table C.2.
17
18use sha2::{Digest, Sha256, Sha384};
19
20use super::SecuritySuite;
21
22/// Errors from key agreement.
23#[derive(Debug, PartialEq, Eq)]
24pub enum AgreementError {
25    /// The suite has no elliptic-curve key agreement (suite 0).
26    UnsupportedSuite,
27    /// The private key was malformed for the curve.
28    InvalidPrivateKey,
29    /// The peer public key was malformed for the curve.
30    InvalidPublicKey,
31}
32
33impl std::fmt::Display for AgreementError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(f, "{self:?}")
36    }
37}
38
39impl std::error::Error for AgreementError {}
40
41/// Coordinate length (octets) of the suite's curve.
42fn coord_len(suite: SecuritySuite) -> Option<usize> {
43    match suite {
44        SecuritySuite::Suite1 => Some(32), // P-256
45        SecuritySuite::Suite2 => Some(48), // P-384
46        SecuritySuite::Suite0 => None,
47    }
48}
49
50/// Normalizes a public key to SEC1 uncompressed form (`0x04 ‖ x ‖ y`).
51fn to_sec1(point: &[u8], coord: usize) -> Vec<u8> {
52    if point.len() == 2 * coord {
53        let mut v = Vec::with_capacity(1 + point.len());
54        v.push(0x04);
55        v.extend_from_slice(point);
56        v
57    } else {
58        point.to_vec()
59    }
60}
61
62/// Computes the raw ECDH shared secret `Z = FE2OS(x)` between our `private_key`
63/// (raw scalar) and the peer's `public_key` (raw `x ‖ y` or SEC1) on the suite's
64/// curve.
65pub fn ecdh(suite: SecuritySuite, private_key: &[u8], public_key: &[u8]) -> Result<Vec<u8>, AgreementError> {
66    let coord = coord_len(suite).ok_or(AgreementError::UnsupportedSuite)?;
67    let sec1 = to_sec1(public_key, coord);
68    match suite {
69        SecuritySuite::Suite1 => {
70            let sk = p256::SecretKey::from_slice(private_key).map_err(|_| AgreementError::InvalidPrivateKey)?;
71            let pk = p256::PublicKey::from_sec1_bytes(&sec1).map_err(|_| AgreementError::InvalidPublicKey)?;
72            let shared = p256::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
73            Ok(shared.raw_secret_bytes().to_vec())
74        }
75        SecuritySuite::Suite2 => {
76            let sk = p384::SecretKey::from_slice(private_key).map_err(|_| AgreementError::InvalidPrivateKey)?;
77            let pk = p384::PublicKey::from_sec1_bytes(&sec1).map_err(|_| AgreementError::InvalidPublicKey)?;
78            let shared = p384::ecdh::diffie_hellman(sk.to_nonzero_scalar(), pk.as_affine());
79            Ok(shared.raw_secret_bytes().to_vec())
80        }
81        SecuritySuite::Suite0 => Err(AgreementError::UnsupportedSuite),
82    }
83}
84
85/// The NIST SP 800-56A single-step KDF over the suite's hash, producing
86/// `output_len` octets from the shared secret `z` and the other-info fields
87/// `algorithm_id ‖ party_u_info ‖ party_v_info`.
88pub fn kdf(
89    suite: SecuritySuite,
90    z: &[u8],
91    algorithm_id: &[u8],
92    party_u_info: &[u8],
93    party_v_info: &[u8],
94    output_len: usize,
95) -> Result<Vec<u8>, AgreementError> {
96    if suite == SecuritySuite::Suite0 {
97        return Err(AgreementError::UnsupportedSuite);
98    }
99    let mut out = Vec::with_capacity(output_len);
100    let mut counter: u32 = 1;
101    while out.len() < output_len {
102        let block = match suite {
103            SecuritySuite::Suite2 => {
104                let mut h = Sha384::new();
105                h.update(counter.to_be_bytes());
106                h.update(z);
107                h.update(algorithm_id);
108                h.update(party_u_info);
109                h.update(party_v_info);
110                h.finalize().to_vec()
111            }
112            _ => {
113                let mut h = Sha256::new();
114                h.update(counter.to_be_bytes());
115                h.update(z);
116                h.update(algorithm_id);
117                h.update(party_u_info);
118                h.update(party_v_info);
119                h.finalize().to_vec()
120            }
121        };
122        out.extend_from_slice(&block);
123        counter += 1;
124    }
125    out.truncate(output_len);
126    Ok(out)
127}
128
129/// Performs the full DLMS key agreement: ECDH followed by the KDF, returning the
130/// derived AES encryption key (16 octets for suite 1, 32 for suite 2).
131///
132/// `party_u_info` / `party_v_info` are the originator and recipient
133/// system-titles as used in the KDF (Green Book Table C.2).
134pub fn agree_key(
135    suite: SecuritySuite,
136    private_key: &[u8],
137    peer_public_key: &[u8],
138    algorithm_id: &[u8],
139    party_u_info: &[u8],
140    party_v_info: &[u8],
141) -> Result<Vec<u8>, AgreementError> {
142    let z = ecdh(suite, private_key, peer_public_key)?;
143    let key = kdf(suite, &z, algorithm_id, party_u_info, party_v_info, suite.aes_key_len())?;
144    Ok(key)
145}
146
147/// Derives the ephemeral public key (`FE2OS(x) ‖ FE2OS(y)`) from an ephemeral
148/// private key on the suite's curve, for embedding as key-ciphered-data.
149pub fn public_key(suite: SecuritySuite, private_key: &[u8]) -> Result<Vec<u8>, AgreementError> {
150    // The SEC1 uncompressed encoding is `0x04 ‖ x ‖ y`; DLMS wants `x ‖ y`.
151    match suite {
152        SecuritySuite::Suite1 => {
153            let sk = p256::SecretKey::from_slice(private_key).map_err(|_| AgreementError::InvalidPrivateKey)?;
154            Ok(sk.public_key().to_sec1_bytes()[1..].to_vec())
155        }
156        SecuritySuite::Suite2 => {
157            let sk = p384::SecretKey::from_slice(private_key).map_err(|_| AgreementError::InvalidPrivateKey)?;
158            Ok(sk.public_key().to_sec1_bytes()[1..].to_vec())
159        }
160        SecuritySuite::Suite0 => Err(AgreementError::UnsupportedSuite),
161    }
162}
163
164/// The originator side of a One-Pass Diffie-Hellman agreed-key exchange
165/// (C(1e, 1s), IEC 62056-5-3 Annex C.2).
166///
167/// The originator holds an ephemeral key pair and the recipient's static public
168/// key. It returns the derived AES session key and its ephemeral public key
169/// (`FE2OS(x) ‖ FE2OS(y)`), which the caller embeds as the `key-ciphered-data`
170/// of an agreed-key general-ciphering APDU so the recipient can derive the same
171/// key. `party_u_info` / `party_v_info` are the KDF system-titles and must match
172/// on both sides.
173pub fn originator_agree(
174    suite: SecuritySuite,
175    ephemeral_private: &[u8],
176    recipient_static_public: &[u8],
177    algorithm_id: &[u8],
178    party_u_info: &[u8],
179    party_v_info: &[u8],
180) -> Result<(Vec<u8>, Vec<u8>), AgreementError> {
181    let ephemeral_public = public_key(suite, ephemeral_private)?;
182    let key = agree_key(suite, ephemeral_private, recipient_static_public, algorithm_id, party_u_info, party_v_info)?;
183    Ok((key, ephemeral_public))
184}
185
186/// The recipient side of a One-Pass Diffie-Hellman agreed-key exchange.
187///
188/// The recipient holds a static private key and receives the originator's
189/// ephemeral public key (the `key-ciphered-data`). It derives the same session
190/// key. `party_u_info` / `party_v_info` must be identical to the originator's.
191pub fn recipient_agree(
192    suite: SecuritySuite,
193    recipient_static_private: &[u8],
194    ephemeral_public: &[u8],
195    algorithm_id: &[u8],
196    party_u_info: &[u8],
197    party_v_info: &[u8],
198) -> Result<Vec<u8>, AgreementError> {
199    agree_key(suite, recipient_static_private, ephemeral_public, algorithm_id, party_u_info, party_v_info)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    fn hb(s: &str) -> Vec<u8> {
207        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
208    }
209
210    #[test]
211    fn kdf_matches_green_book_c2_client_key() {
212        // DLMS Green Book Table C.2 (One-Pass Diffie-Hellman, suite 1):
213        // KDF(Z, AlgID, Sys-TC, Sys-TS) with the client shared secret.
214        let z = hb("0D4385BA0DD756CBCAB9887EB538396EE8F090A14C1079B4359F115B977F4615");
215        let alg_id = hb("60857405080300"); // AES-GCM-128
216        let sys_tc = hb("4D4D4D0000BC614E");
217        let sys_ts = hb("4D4D4D0000000001");
218        let k = kdf(SecuritySuite::Suite1, &z, &alg_id, &sys_tc, &sys_ts, 32).unwrap();
219        assert_eq!(k, hb("59A71FD81C929A86A99438DA17A66C058C6A93FD3065F5EE16A05D775927659B"));
220        // The AES-128 encryption key is the leftmost 16 octets.
221        let ek = kdf(SecuritySuite::Suite1, &z, &alg_id, &sys_tc, &sys_ts, 16).unwrap();
222        assert_eq!(ek, hb("59A71FD81C929A86A99438DA17A66C05"));
223    }
224
225    #[test]
226    fn kdf_matches_green_book_c2_server_key() {
227        // Server side: KDF(Z-GC-S, AlgID, Sys-TS, Sys-TC).
228        let z = hb("2B4302DC49790E2E78D990CFB52ED6E2F273DECE441A2D95E4301B93812A9FAC");
229        let alg_id = hb("60857405080300");
230        let sys_ts = hb("4D4D4D0000000001");
231        let sys_tc = hb("4D4D4D0000BC614E");
232        let ek = kdf(SecuritySuite::Suite1, &z, &alg_id, &sys_ts, &sys_tc, 16).unwrap();
233        assert_eq!(ek, hb("F0184BDA9466BFA4601A64A7EF46504A"));
234    }
235
236    #[test]
237    fn ecdh_round_trip_suite1() {
238        // Two P-256 key pairs derive the same shared secret Z.
239        let d_a = hb("418073C239FA6125011DE4D6CD2E645780289F761BB21BFB0835CB5585E8B373");
240        let d_b = hb("AE55414FFE079F9FC95649536BD1C2B5653D200813727E07D501A8B550C69207");
241        let pk_a = p256::SecretKey::from_slice(&d_a).unwrap().public_key();
242        let pk_b = p256::SecretKey::from_slice(&d_b).unwrap().public_key();
243        let pk_a_bytes = pk_a.to_sec1_bytes().to_vec();
244        let pk_b_bytes = pk_b.to_sec1_bytes().to_vec();
245        let z_ab = ecdh(SecuritySuite::Suite1, &d_a, &pk_b_bytes).unwrap();
246        let z_ba = ecdh(SecuritySuite::Suite1, &d_b, &pk_a_bytes).unwrap();
247        assert_eq!(z_ab, z_ba);
248        assert_eq!(z_ab.len(), 32);
249    }
250
251    #[test]
252    fn ecdh_round_trip_suite2() {
253        let d_a = [0x11u8; 48];
254        let d_b = [0x22u8; 48];
255        let pk_a = p384::SecretKey::from_slice(&d_a).unwrap().public_key().to_sec1_bytes().to_vec();
256        let pk_b = p384::SecretKey::from_slice(&d_b).unwrap().public_key().to_sec1_bytes().to_vec();
257        let z_ab = agree_key(SecuritySuite::Suite2, &d_a, &pk_b, b"\x60\x85\x74\x05\x08\x03\x02", b"U", b"V").unwrap();
258        let z_ba = agree_key(SecuritySuite::Suite2, &d_b, &pk_a, b"\x60\x85\x74\x05\x08\x03\x02", b"U", b"V").unwrap();
259        assert_eq!(z_ab, z_ba);
260        assert_eq!(z_ab.len(), 32); // AES-256 key
261    }
262
263    #[test]
264    fn suite0_has_no_agreement() {
265        assert_eq!(ecdh(SecuritySuite::Suite0, &[0u8; 32], &[0u8; 64]), Err(AgreementError::UnsupportedSuite));
266    }
267
268    #[test]
269    fn one_pass_agreement_derives_shared_key() {
270        // The client (originator) holds an ephemeral key pair; the server
271        // (recipient) holds a static key pair.
272        let ephemeral = hb("47DAB03842E5B6E74828EF4F449B378D7DD1A5DAE1FFCA5AE0B0BE0AD18EC57E");
273        let server_static = hb("AE55414FFE079F9FC95649536BD1C2B5653D200813727E07D501A8B550C69207");
274        let server_public = public_key(SecuritySuite::Suite1, &server_static).unwrap();
275        let alg_id = hb("60857405080300");
276        let sys_c = hb("4D4D4D0000BC614E");
277        let sys_s = hb("4D4D4D0000000001");
278
279        let (client_key, ephemeral_public) =
280            originator_agree(SecuritySuite::Suite1, &ephemeral, &server_public, &alg_id, &sys_c, &sys_s).unwrap();
281        let server_key =
282            recipient_agree(SecuritySuite::Suite1, &server_static, &ephemeral_public, &alg_id, &sys_c, &sys_s).unwrap();
283
284        // Both sides derive the same AES-128 session key.
285        assert_eq!(client_key, server_key);
286        assert_eq!(client_key.len(), 16);
287    }
288
289    #[test]
290    fn agreed_key_is_usable_for_apdu_ciphering() {
291        use crate::security::SecurityPolicy;
292        use crate::service::ciphering::{self, glo, SecurityContext};
293        use crate::service::general_ciphering::{GeneralCiphering, KeyInfo};
294
295        let ephemeral = hb("47DAB03842E5B6E74828EF4F449B378D7DD1A5DAE1FFCA5AE0B0BE0AD18EC57E");
296        let server_static = hb("AE55414FFE079F9FC95649536BD1C2B5653D200813727E07D501A8B550C69207");
297        let server_public = public_key(SecuritySuite::Suite1, &server_static).unwrap();
298        let alg_id = hb("60857405080300");
299        let sys_c = vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E];
300        let sys_s = vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01];
301
302        // Client derives the session key and advertises its ephemeral key in an
303        // agreed-key general-ciphering APDU.
304        let (client_key, ephemeral_public) =
305            originator_agree(SecuritySuite::Suite1, &ephemeral, &server_public, &alg_id, &sys_c, &sys_s).unwrap();
306        let carrier = GeneralCiphering {
307            transaction_id: vec![0x01; 8],
308            originator_system_title: sys_c.clone(),
309            recipient_system_title: sys_s.clone(),
310            date_time: Vec::new(),
311            other_information: Vec::new(),
312            key_info: KeyInfo::AgreedKey { key_parameters: vec![0x01], key_ciphered_data: ephemeral_public },
313            ciphered_content: Vec::new(),
314        };
315
316        // Server parses the APDU, extracts the ephemeral key and derives the
317        // same session key.
318        let parsed = GeneralCiphering::decode(&carrier.encode()).unwrap();
319        let KeyInfo::AgreedKey { key_ciphered_data, .. } = &parsed.key_info else {
320            panic!("expected agreed-key");
321        };
322        let server_key =
323            recipient_agree(SecuritySuite::Suite1, &server_static, key_ciphered_data, &alg_id, &sys_c, &sys_s).unwrap();
324        assert_eq!(client_key, server_key);
325
326        // The agreed key protects and unprotects an APDU end to end (client
327        // system-title in the IV on both directions of this exchange).
328        let client_ctx = SecurityContext::for_suite(
329            SecurityPolicy::AuthenticationEncryption,
330            SecuritySuite::Suite1,
331            client_key,
332            vec![0x11; 16],
333            sys_c.clone(),
334            1,
335        )
336        .unwrap();
337        let plaintext = vec![0xC4, 0x01, 0xC1, 0x00, 0x12, 0x12, 0x34];
338        let protected = ciphering::protect(&client_ctx, glo::GET_RESPONSE, &plaintext).unwrap();
339        let mut server_ctx = SecurityContext::for_suite(
340            SecurityPolicy::AuthenticationEncryption,
341            SecuritySuite::Suite1,
342            server_key,
343            vec![0x11; 16],
344            sys_c,
345            0,
346        )
347        .unwrap();
348        let (_, recovered) = ciphering::unprotect(&mut server_ctx, &protected).unwrap();
349        assert_eq!(recovered, plaintext);
350    }
351}