Skip to main content

spodes_rs/spodus/
access_policy.rs

1//! Meter access policies (СТО 34.01-5.1-013-2023, §10.6, `0.0.94.7.132.255`).
2//!
3//! The credentials the ИВКЭ uses to open an association with each meter are held
4//! as a `Data` (IC 1) object whose value is an `array meters_passwords`, per
5//! §10.6:
6//!
7//! ```text
8//! meters_passwords ::= structure {
9//!     meter_id: octet-string,
10//!     police_id: byte,          // security policy
11//!     suit_id: byte,            // cryptographic suite
12//!     array security_list { type: byte, key: octet-string }
13//! }
14//! ```
15
16use crate::classes::data::Data;
17use crate::types::CosemDataType;
18
19use super::obis;
20
21/// `type` values of a `security_list` item (§10.6).
22pub mod security_item_type {
23    /// Low-security password.
24    pub const LLS_PASSWORD: u8 = 0;
25    /// Low-security authentication key.
26    pub const LLS_AUTHENTICATION_KEY: u8 = 1;
27    /// Low-security encryption key.
28    pub const LLS_ENCRYPTION_KEY: u8 = 2;
29    /// High-security authentication key.
30    pub const HLS_AUTHENTICATION_KEY: u8 = 3;
31    /// High-security encryption key.
32    pub const HLS_ENCRYPTION_KEY: u8 = 4;
33    /// Key-encryption key (KEK).
34    pub const KEK: u8 = 5;
35}
36
37/// One `security_list` entry: a typed key or password.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct SecurityItem {
40    /// Item type (see [`security_item_type`]).
41    pub item_type: u8,
42    /// Key or password value.
43    pub key: Vec<u8>,
44}
45
46/// The access policy for a single meter (`meters_passwords`).
47#[derive(Clone, Debug, Default, PartialEq, Eq)]
48pub struct AccessPolicy {
49    /// Meter identifier the policy applies to.
50    pub meter_id: Vec<u8>,
51    /// Security policy id (`police_id`).
52    pub policy_id: u8,
53    /// Cryptographic suite id (`suit_id`).
54    pub suite_id: u8,
55    /// Keys and passwords for this meter.
56    pub security_list: Vec<SecurityItem>,
57}
58
59impl AccessPolicy {
60    /// The COSEM `meters_passwords` structure for this policy.
61    fn to_structure(&self) -> CosemDataType {
62        let security_list = self
63            .security_list
64            .iter()
65            .map(|item| {
66                CosemDataType::Structure(vec![
67                    CosemDataType::Unsigned(item.item_type),
68                    CosemDataType::OctetString(item.key.clone()),
69                ])
70            })
71            .collect();
72        CosemDataType::Structure(vec![
73            CosemDataType::OctetString(self.meter_id.clone()),
74            CosemDataType::Unsigned(self.policy_id),
75            CosemDataType::Unsigned(self.suite_id),
76            CosemDataType::Array(security_list),
77        ])
78    }
79}
80
81/// The access-policy list (§10.6, `0.0.94.7.132.255`).
82#[derive(Clone, Debug, Default)]
83pub struct AccessPolicies {
84    policies: Vec<AccessPolicy>,
85}
86
87impl AccessPolicies {
88    /// Creates an empty policy list.
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// Adds a meter access policy.
94    pub fn add(&mut self, policy: AccessPolicy) {
95        self.policies.push(policy);
96    }
97
98    /// Finds the policy for a given meter id.
99    pub fn find(&self, meter_id: &[u8]) -> Option<&AccessPolicy> {
100        self.policies.iter().find(|p| p.meter_id == meter_id)
101    }
102
103    /// Builds the COSEM `Data` (IC 1) object holding the policy array.
104    pub fn build(&self) -> Data {
105        let array = self.policies.iter().map(AccessPolicy::to_structure).collect();
106        Data::new(obis::access_policies(), CosemDataType::Array(array))
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::interface::InterfaceClass;
114
115    #[test]
116    fn access_policies_build_data_object() {
117        let mut policies = AccessPolicies::new();
118        policies.add(AccessPolicy {
119            meter_id: b"SIT12260004".to_vec(),
120            policy_id: 3,
121            suite_id: 0,
122            security_list: vec![
123                SecurityItem { item_type: security_item_type::LLS_PASSWORD, key: b"12345678".to_vec() },
124                SecurityItem { item_type: security_item_type::HLS_ENCRYPTION_KEY, key: vec![0xAB; 16] },
125            ],
126        });
127
128        assert_eq!(policies.find(b"SIT12260004").unwrap().policy_id, 3);
129        assert!(policies.find(b"unknown").is_none());
130
131        let object = policies.build();
132        assert_eq!(object.class_id(), 1);
133        assert_eq!(object.logical_name(), &obis::access_policies());
134
135        // Attribute 2: array of one meters_passwords structure.
136        let CosemDataType::Array(rows) = &object.attributes()[1].1 else { panic!("array") };
137        assert_eq!(rows.len(), 1);
138        let CosemDataType::Structure(fields) = &rows[0] else { panic!("structure") };
139        assert_eq!(fields[0], CosemDataType::OctetString(b"SIT12260004".to_vec()));
140        assert_eq!(fields[1], CosemDataType::Unsigned(3));
141        assert_eq!(fields[2], CosemDataType::Unsigned(0));
142        let CosemDataType::Array(items) = &fields[3] else { panic!("security_list array") };
143        assert_eq!(items.len(), 2);
144    }
145}