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