Skip to main content

matter_kit/group/
keys.rs

1//! Group key sets and the map from a group to one (Core §4.17, §11.2).
2//!
3//! The table an administrator writes through the Group Key Management cluster, and the lookup a
4//! message goes through in both directions: a sender asks "which key encrypts for this group",
5//! a receiver asks "which keys could have encrypted this".
6
7use heapless::Vec;
8
9use crate::config::Config;
10use crate::crypto::SymmetricKey;
11use crate::error::{Error, ErrorCode, Result};
12use crate::fabric::{CompressedFabricId, operational_group_key};
13use crate::im::Status;
14use crate::msg::{FabricIndex, GroupId};
15use crate::platform::Instant;
16
17/// A Group Key Set ID (§11.2.5.4). `0` is the IPK's, which §11.2.7.1 forbids writing.
18pub type KeySetId = u16;
19
20/// §11.2.7.1: "if the GroupKeySetID is 0 … the server SHALL respond with INVALID_COMMAND" —
21/// key set 0 is the Identity Protection Key's, installed by `AddNOC` and owned by the fabric.
22pub const IPK_KEY_SET: KeySetId = 0;
23
24/// §4.17.3.2: "there SHALL be at least 1 and at most 3 epoch keys in rotation".
25pub const MAX_EPOCH_KEYS: usize = 3;
26
27/// §11.2.5.4's `GroupKeySecurityPolicyEnum`, which chooses how a receiver decides a message is
28/// fresh (§4.18.1).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30#[repr(u8)]
31pub enum GroupKeySecurityPolicy {
32    /// §4.18.1.1: "The first authenticated message counter from an unsynchronized peer is
33    /// trusted." Lower latency, and — the specification's own warning — "susceptible to
34    /// accepting a replayed message after a Node has been rebooted".
35    TrustFirst = 0,
36    /// §4.18.1.2: hold the message, synchronise over [`mcsp`](super::mcsp), then process it.
37    /// Replay protection across a reboot, at the cost of a round trip. Provisional: support is
38    /// declared through the cluster's `CacheAndSync` feature.
39    CacheAndSync = 1,
40}
41
42impl GroupKeySecurityPolicy {
43    /// The wire value.
44    #[must_use]
45    pub const fn value(self) -> u8 {
46        self as u8
47    }
48
49    /// Reads the wire value.
50    pub const fn from_value(value: u8) -> Result<Self> {
51        Ok(match value {
52            0 => Self::TrustFirst,
53            1 => Self::CacheAndSync,
54            // §7.19.2: a value this revision does not define is not one to guess at, and
55            // guessing wrong here would pick the *weaker* replay policy.
56            _ => return Err(Error::new(ErrorCode::TlvOutOfRange)),
57        })
58    }
59}
60
61/// One epoch key and the moment it becomes the one a sender uses (§4.17.3).
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct EpochKey {
64    /// The key an administrator generated with `Crypto_DRBG`.
65    pub key: SymmetricKey,
66    /// "absolute UTC time in microseconds encoded using the epoch-us representation".
67    ///
68    /// §4.17.3.1: "An epoch key marked with the maximum start time SHALL be disabled" — which
69    /// is [`DISABLED`](Self::DISABLED).
70    pub start_time_us: u64,
71}
72
73impl EpochKey {
74    /// §4.17.3.1's disabled marker: "An epoch key marked with the maximum start time SHALL be
75    /// disabled and render the corresponding epoch key slot unused."
76    pub const DISABLED: u64 = u64::MAX;
77
78    /// Whether this slot is in use.
79    #[must_use]
80    pub const fn is_enabled(&self) -> bool {
81        self.start_time_us != Self::DISABLED
82    }
83}
84
85/// A group key set: up to three epoch keys in rotation, and the policy that governs them
86/// (§4.17.2.2, §11.2.5.4).
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct GroupKeySet {
89    /// Which fabric it belongs to. Key material is per fabric: §4.17.2.1, "with the exception of
90    /// the group security info, all input key material SHALL be maintained on a per-Fabric
91    /// basis".
92    pub fabric_index: FabricIndex,
93    /// Its id, unique within the fabric.
94    pub id: KeySetId,
95    /// How a receiver decides a message under this key is fresh.
96    pub policy: GroupKeySecurityPolicy,
97    /// The epoch keys, oldest first — §4.17.3.2: "An epoch key update SHALL order the keys from
98    /// oldest to newest."
99    pub epoch_keys: Vec<EpochKey, MAX_EPOCH_KEYS>,
100}
101
102impl GroupKeySet {
103    /// A key set holding one epoch key, which is what §11.27.7.1's `JoinGroup` and
104    /// §11.18.6.8's `AddNOC` both synthesise.
105    ///
106    /// Rotation needs two or three; a group that has just been created has one, and building it
107    /// is otherwise four lines of `heapless::Vec` at every call site.
108    #[must_use]
109    pub fn single(
110        fabric_index: FabricIndex,
111        id: KeySetId,
112        policy: GroupKeySecurityPolicy,
113        key: SymmetricKey,
114        start_time_us: u64,
115    ) -> Self {
116        let mut epoch_keys = Vec::new();
117        let _ = epoch_keys.push(EpochKey { key, start_time_us });
118        Self {
119            fabric_index,
120            id,
121            policy,
122            epoch_keys,
123        }
124    }
125
126    /// The epoch key a *sender* uses: §4.17.3.1's "the epoch key with the latest start time that
127    /// is not in the future".
128    ///
129    /// `now` is UTC microseconds, or [`None`] on a node without a synchronised clock — which
130    /// §4.17.3.4 provides for: "such a Node can note which of the keys is the current epoch key
131    /// by comparing their relative start times and using the current epoch key which has the
132    /// second newest time." With fewer than two enabled keys that degrades to the newest, which
133    /// is the only one it could mean.
134    #[must_use]
135    pub fn current(&self, now: Option<u64>) -> Option<&EpochKey> {
136        let mut enabled: Vec<&EpochKey, MAX_EPOCH_KEYS> =
137            self.epoch_keys.iter().filter(|k| k.is_enabled()).collect();
138        // Oldest first is how they arrive, but an administrator is not the only source of this
139        // table — a persisted set read back is not ordered by anything.
140        enabled.sort_unstable_by_key(|k| k.start_time_us);
141        match now {
142            Some(now) => enabled
143                .iter()
144                .rev()
145                .find(|k| k.start_time_us <= now)
146                .copied()
147                // Every start time is in the future: the node's clock is behind the
148                // administrator's, and the oldest key is the closest thing to current.
149                .or_else(|| enabled.first().copied()),
150            None => {
151                let len = enabled.len();
152                enabled
153                    .get(len.saturating_sub(2))
154                    .or_else(|| enabled.first())
155                    .copied()
156            }
157        }
158    }
159}
160
161/// The per-fabric group state of §11.2: the key sets, and which key set each group uses.
162///
163/// `K` bounds the key sets across every fabric and `M` the group-to-key-set map. The per-fabric
164/// quotas §11.2.6.3's `MaxGroupKeysPerFabric` and §11.2.6.2's `MaxGroupsPerFabric` report come
165/// from [`Config`], and [`GroupKeys::CHECK`] refuses at compile time a `K` or `M` too small to
166/// give every fabric its share — which is the only way those two attributes can be the promise
167/// the specification says they are rather than a pair of numbers typed beside the table.
168#[derive(Debug)]
169pub struct GroupKeys<C: Config, const K: usize = 15, const M: usize = 20> {
170    sets: Vec<GroupKeySet, K>,
171    map: Vec<(FabricIndex, GroupId, KeySetId), M>,
172    _config: core::marker::PhantomData<C>,
173}
174
175/// An operational key a message can be sent or received under.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct OperationalKey {
178    /// The key itself, derived from an epoch key and the fabric's compressed identifier.
179    pub key: SymmetricKey,
180    /// Which key set it came from, so the policy that governs it can be found again.
181    pub key_set: KeySetId,
182    /// The fabric it belongs to.
183    pub fabric_index: FabricIndex,
184    /// The policy of the key set (§4.18.1).
185    pub policy: GroupKeySecurityPolicy,
186    /// §4.17.3.6's Group Session ID, which goes in the message header.
187    pub session_id: u16,
188}
189
190impl<C: Config, const K: usize, const M: usize> crate::config::Capacity for GroupKeys<C, K, M> {
191    const TOTAL: usize = K;
192    /// §11.2.6.3's `MaxGroupKeysPerFabric`.
193    const PER_FABRIC: usize = C::GROUP_KEYS_PER_FABRIC;
194}
195
196impl<C: Config, const K: usize, const M: usize> Default for GroupKeys<C, K, M> {
197    fn default() -> Self {
198        Self::new()
199    }
200}
201
202impl<C: Config, const K: usize, const M: usize> GroupKeys<C, K, M> {
203    /// Compile-time proof that both tables can keep §2.11.1.2's promises.
204    ///
205    /// > at least four groups per fabric … at least three group keys per fabric
206    ///
207    /// The quotas are what stop the first fabric to provision from filling the table; this is
208    /// what stops the quotas from promising room that is not there.
209    pub const CHECK: () = {
210        let () = crate::config::AssertValid::<C>::CHECK;
211        assert!(
212            K >= C::GROUP_KEYS_PER_FABRIC * C::FABRICS,
213            "GroupKeys: Core §2.11.1.2 promises GROUP_KEYS_PER_FABRIC to every fabric, so K \
214             must be FABRICS × that many"
215        );
216        assert!(
217            M >= C::GROUPS_PER_FABRIC * C::FABRICS,
218            "GroupKeys: Core §2.11.1.2 promises GROUPS_PER_FABRIC to every fabric, so M must \
219             be FABRICS × that many"
220        );
221    };
222
223    /// An empty table.
224    #[must_use]
225    pub fn new() -> Self {
226        let () = Self::CHECK;
227        Self {
228            sets: Vec::new(),
229            map: Vec::new(),
230            _config: core::marker::PhantomData,
231        }
232    }
233
234    /// `MaxGroupsPerFabric` (§11.2.6.2).
235    #[must_use]
236    pub const fn max_groups_per_fabric(&self) -> usize {
237        C::GROUPS_PER_FABRIC
238    }
239
240    /// `MaxGroupKeysPerFabric` (§11.2.6.3).
241    #[must_use]
242    pub const fn max_key_sets_per_fabric(&self) -> usize {
243        C::GROUP_KEYS_PER_FABRIC
244    }
245
246    /// Every key set, for a device about to persist them.
247    #[must_use]
248    pub fn key_sets(&self) -> &[GroupKeySet] {
249        &self.sets
250    }
251
252    /// The `GroupKeyMap` entries (§11.2.6.1).
253    #[must_use]
254    pub fn map(&self) -> &[(FabricIndex, GroupId, KeySetId)] {
255        &self.map
256    }
257
258    /// Installs or replaces a key set — §11.2.7.1's `KeySetWrite`.
259    ///
260    /// > Any update of the key set, including a partial update, SHALL remove all previous keys
261    /// > in the set, however many were defined.
262    ///
263    /// So this replaces rather than merges, which is what makes the command idempotent and the
264    /// administrator "always the source of truth".
265    pub fn write_key_set(&mut self, set: GroupKeySet) -> core::result::Result<(), Status> {
266        if set.epoch_keys.is_empty() {
267            // §11.2.7.1: EpochKey0 is mandatory, so a set with nothing in it is not one.
268            return Err(Status::InvalidCommand);
269        }
270        if let Some(existing) = self
271            .sets
272            .iter_mut()
273            .find(|s| s.id == set.id && s.fabric_index == set.fabric_index)
274        {
275            *existing = set;
276            return Ok(());
277        }
278        if self.count_sets(set.fabric_index) >= C::GROUP_KEYS_PER_FABRIC {
279            return Err(Status::ResourceExhausted);
280        }
281        self.sets.push(set).map_err(|_| Status::ResourceExhausted)
282    }
283
284    /// One key set, if this fabric has it.
285    #[must_use]
286    pub fn key_set(&self, fabric: FabricIndex, id: KeySetId) -> Option<&GroupKeySet> {
287        self.sets
288            .iter()
289            .find(|s| s.id == id && s.fabric_index == fabric)
290    }
291
292    /// Removes a key set — §11.2.7.4's `KeySetRemove`.
293    ///
294    /// > This command SHALL fail with an INVALID_COMMAND status code back to the initiator if
295    /// > the GroupKeySetID being removed is 0, which is the key set associated with the Identity
296    /// > Protection Key (IPK).
297    pub fn remove_key_set(
298        &mut self,
299        fabric: FabricIndex,
300        id: KeySetId,
301    ) -> core::result::Result<(), Status> {
302        if id == IPK_KEY_SET {
303            return Err(Status::InvalidCommand);
304        }
305        if self.key_set(fabric, id).is_none() {
306            return Err(Status::NotFound);
307        }
308        self.sets
309            .retain(|s| !(s.id == id && s.fabric_index == fabric));
310        // §11.2.7.4: "This command SHALL also remove all entries in the GroupKeyMap whose
311        // GroupKeySetID matches" — a group mapped to a key set that no longer exists could
312        // neither send nor receive, and would keep its multicast subscription alive for nothing.
313        self.map.retain(|(f, _, set)| !(*set == id && *f == fabric));
314        Ok(())
315    }
316
317    /// Maps a group to a key set — one entry of §11.2.6.1's `GroupKeyMap`.
318    pub fn map_group(
319        &mut self,
320        fabric: FabricIndex,
321        group: GroupId,
322        key_set: KeySetId,
323    ) -> core::result::Result<(), Status> {
324        // §11.2.6.1: "an entry in this list SHALL only be added if the GroupKeySetID exists",
325        // and a map to nothing is a group that can neither send nor receive.
326        if self.key_set(fabric, key_set).is_none() {
327            return Err(Status::NotFound);
328        }
329        if let Some(entry) = self
330            .map
331            .iter_mut()
332            .find(|(f, g, _)| *f == fabric && *g == group)
333        {
334            entry.2 = key_set;
335            return Ok(());
336        }
337        if self.count_groups(fabric) >= C::GROUPS_PER_FABRIC {
338            return Err(Status::ResourceExhausted);
339        }
340        self.map
341            .push((fabric, group, key_set))
342            .map_err(|_| Status::ResourceExhausted)
343    }
344
345    /// Replaces one fabric's whole `GroupKeyMap`, which is what a list write does.
346    pub fn replace_map(
347        &mut self,
348        fabric: FabricIndex,
349        entries: &[(GroupId, KeySetId)],
350    ) -> core::result::Result<(), Status> {
351        if entries.len() > C::GROUPS_PER_FABRIC {
352            return Err(Status::ResourceExhausted);
353        }
354        for (_, key_set) in entries {
355            if self.key_set(fabric, *key_set).is_none() {
356                return Err(Status::NotFound);
357            }
358        }
359        self.map.retain(|(f, _, _)| *f != fabric);
360        for (group, key_set) in entries {
361            self.map
362                .push((fabric, *group, *key_set))
363                .map_err(|_| Status::ResourceExhausted)?;
364        }
365        Ok(())
366    }
367
368    /// Forgets everything one fabric installed — what `RemoveFabric` must do.
369    pub fn remove_fabric(&mut self, fabric: FabricIndex) {
370        self.sets.retain(|s| s.fabric_index != fabric);
371        self.map.retain(|(f, _, _)| *f != fabric);
372    }
373
374    /// The key a *sender* encrypts a message to `group` with (§4.16.2 step 1).
375    ///
376    /// > Obtain, for the given GroupKeySetID, the current Operational Group Key as the
377    /// > Encryption Key, and the associated Group Session ID. If no key is found for the given
378    /// > GroupKeySetID, security processing SHALL fail and no further security processing SHALL
379    /// > be done on this message.
380    pub fn sending_key(
381        &self,
382        fabric: FabricIndex,
383        compressed: CompressedFabricId,
384        group: GroupId,
385        now: Option<Instant>,
386    ) -> Result<OperationalKey> {
387        let key_set = self
388            .map
389            .iter()
390            .find(|(f, g, _)| *f == fabric && *g == group)
391            .map(|(_, _, set)| *set)
392            .ok_or(Error::new(ErrorCode::NoSession))?;
393        let set = self
394            .key_set(fabric, key_set)
395            .ok_or(Error::new(ErrorCode::NoSession))?;
396        let epoch = set
397            .current(now.map(Instant::as_micros))
398            .ok_or(Error::new(ErrorCode::NoSession))?;
399        Self::operational(set, epoch, compressed)
400    }
401
402    /// Every key a *receiver* should try for a message that named `session_id` (§4.17.3.6).
403    ///
404    /// > On receipt of a message of Group Session Type, all valid, installed, operational group
405    /// > key candidates referenced by the given Group Session ID SHALL be attempted until
406    /// > authentication is passed or there are no more operational group keys to try.
407    ///
408    /// Every *installed* epoch key, not just the current one: §4.17.3.1 has a receiver "accept
409    /// the use of any key derived from one of the currently installed epoch keys … regardless of
410    /// whether the start time for the key is in the future or the past", because the sender's
411    /// clock is not this node's.
412    pub fn receiving_keys<const N: usize>(
413        &self,
414        compressed: impl Fn(FabricIndex) -> Option<CompressedFabricId>,
415        session_id: u16,
416    ) -> Vec<OperationalKey, N> {
417        let mut out = Vec::new();
418        for set in &self.sets {
419            let Some(compressed) = compressed(set.fabric_index) else {
420                continue;
421            };
422            for epoch in set.epoch_keys.iter().filter(|k| k.is_enabled()) {
423                let Ok(candidate) = Self::operational(set, epoch, compressed) else {
424                    continue;
425                };
426                if candidate.session_id == session_id && out.push(candidate).is_err() {
427                    return out;
428                }
429            }
430        }
431        out
432    }
433
434    /// §4.17.2's derivation, plus §4.17.3.6's session id, which always travel together.
435    fn operational(
436        set: &GroupKeySet,
437        epoch: &EpochKey,
438        compressed: CompressedFabricId,
439    ) -> Result<OperationalKey> {
440        let key = operational_group_key(&epoch.key, compressed)?;
441        let session_id = super::session_id(&key)?;
442        Ok(OperationalKey {
443            key,
444            key_set: set.id,
445            fabric_index: set.fabric_index,
446            policy: set.policy,
447            session_id,
448        })
449    }
450
451    fn count_sets(&self, fabric: FabricIndex) -> usize {
452        self.sets
453            .iter()
454            .filter(|s| s.fabric_index == fabric)
455            .count()
456    }
457
458    fn count_groups(&self, fabric: FabricIndex) -> usize {
459        self.map.iter().filter(|(f, _, _)| *f == fabric).count()
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    const F1: FabricIndex = FabricIndex(1);
468
469    fn key(byte: u8) -> SymmetricKey {
470        SymmetricKey::new([byte; 16])
471    }
472
473    fn set_with(times: &[u64]) -> GroupKeySet {
474        let mut epoch_keys = Vec::new();
475        for (i, start) in times.iter().enumerate() {
476            let _ = epoch_keys.push(EpochKey {
477                key: key(i as u8),
478                start_time_us: *start,
479            });
480        }
481        GroupKeySet {
482            fabric_index: F1,
483            id: 1,
484            policy: GroupKeySecurityPolicy::TrustFirst,
485            epoch_keys,
486        }
487    }
488
489    #[test]
490    fn the_current_key_is_the_newest_that_has_started() {
491        // §4.17.3.1: "the epoch key with the latest start time that is not in the future".
492        let set = set_with(&[100, 200, 300]);
493        assert_eq!(set.current(Some(250)).unwrap().start_time_us, 200);
494        assert_eq!(set.current(Some(300)).unwrap().start_time_us, 300);
495        assert_eq!(set.current(Some(99)).unwrap().start_time_us, 100);
496    }
497
498    #[test]
499    fn a_node_without_a_clock_uses_the_second_newest() {
500        // §4.17.3.4: "such a Node can note which of the keys is the current epoch key by
501        // comparing their relative start times and using the current epoch key which has the
502        // second newest time."
503        let set = set_with(&[100, 200, 300]);
504        assert_eq!(set.current(None).unwrap().start_time_us, 200);
505        // With two keys the second newest is the older of them; with one there is no choice.
506        assert_eq!(
507            set_with(&[100, 200]).current(None).unwrap().start_time_us,
508            100
509        );
510        assert_eq!(set_with(&[100]).current(None).unwrap().start_time_us, 100);
511    }
512
513    #[test]
514    fn a_disabled_slot_is_not_a_key() {
515        // §4.17.3.1: "An epoch key marked with the maximum start time SHALL be disabled and
516        // render the corresponding epoch key slot unused."
517        let set = set_with(&[100, EpochKey::DISABLED]);
518        assert_eq!(set.current(Some(u64::MAX)).unwrap().start_time_us, 100);
519        assert_eq!(set.current(None).unwrap().start_time_us, 100);
520    }
521
522    #[test]
523    fn keys_out_of_order_still_resolve() {
524        // §4.17.3.2 asks an administrator to order them oldest to newest, but a set read back
525        // from persistence is ordered by nothing at all.
526        let set = set_with(&[300, 100, 200]);
527        assert_eq!(set.current(Some(250)).unwrap().start_time_us, 200);
528        assert_eq!(set.current(None).unwrap().start_time_us, 200);
529    }
530}