Skip to main content

matter_kit/clusters/
group_key_management.rs

1//! Group Key Management, cluster `0x003F` (Core §11.2).
2//!
3//! Where an administrator installs the keys that make groupcast possible, and the map from a
4//! Group ID to the key set that secures it. §4.17.4: "the key material of a Node is exposed via
5//! Attributes with ACL entries that only allow access by the key distribution Administrator."
6//!
7//! # Keys go in and never come back out
8//!
9//! §11.2.7.2 is the rule that matters most here, and it is one line:
10//!
11//! > the contents of that Group Key Set SHALL be sent in a KeySetReadResponse command, but with
12//! > the EpochKey0, EpochKey1 and EpochKey2 fields replaced by null.
13//!
14//! An administrator can write a key, learn *that* a key exists, and learn its policy and start
15//! times. It cannot read the key back. A device that echoed the epoch keys would let anyone with
16//! Administer privilege on any fabric — including one being removed — walk away with the key to
17//! every group message on the node.
18//!
19//! # Key set 0 is not a key set
20//!
21//! §11.2.7.4: `KeySetRemove` of key set `0` is `INVALID_COMMAND`. Zero is the Identity
22//! Protection Key's, synthesised by `AddNOC` (§11.18.6.8.1), and "the only method to remove the
23//! IPK is usage of the RemoveFabric command". Removing it any other way would leave the fabric
24//! with a CASE handshake it could no longer complete.
25//!
26//! # A write is a replacement, on purpose
27//!
28//! §4.17.3.2: "Any update of the key set, including a partial update, SHALL remove all previous
29//! keys in the set, however many were defined." That is what makes `KeySetWrite` idempotent and
30//! keeps "the Administrator … always the source of truth" — a merge would leave a node holding
31//! a key the administrator believed it had withdrawn.
32
33use core::cell::RefCell;
34
35use crate::clusters::generated::group_key_management as spec_gkm;
36use crate::config::Config;
37use crate::crypto::{SYMMETRIC_KEY_LENGTH_BYTES, SymmetricKey};
38use crate::dm::spec::{Conforming, Optional};
39use crate::dm::{Resolved, ResolvedCommand};
40use crate::group::keys::{EpochKey, GroupKeySecurityPolicy, GroupKeySet, GroupKeys, KeySetId};
41use crate::im::{
42    ClusterHandler, ClusterId, CommandId, EndpointId, InteractionContext, Status, StatusIb, WriteOp,
43};
44use crate::msg::{FabricIndex, GroupId};
45use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, ToTlv, Value};
46
47use super::Cluster;
48
49pub use spec_gkm::attribute::{
50    GROUP_KEY_MAP, GROUP_TABLE, MAX_GROUP_KEYS_PER_FABRIC, MAX_GROUPS_PER_FABRIC,
51};
52pub use spec_gkm::command::{
53    KEY_SET_READ, KEY_SET_READ_ALL_INDICES, KEY_SET_READ_ALL_INDICES_RESPONSE,
54    KEY_SET_READ_RESPONSE, KEY_SET_REMOVE, KEY_SET_WRITE,
55};
56pub use spec_gkm::{ID, PICS, REVISION};
57
58/// What a device knows about which endpoints are in which group.
59///
60/// §11.2.6.2: `GroupTable` "reflects data managed via the Groups cluster", so this cluster does
61/// not own it — it reads it. The one rule it must not break is stated there too: "The GroupTable
62/// SHALL NOT contain any entry whose GroupInfoMapStruct has an empty Endpoints list."
63pub trait GroupTable {
64    /// Every `(fabric, group, endpoint)` membership the node holds, in any order.
65    ///
66    /// The cluster groups them by `(fabric, group)` itself, so an implementation can simply walk
67    /// its Groups cluster instances.
68    fn memberships(&self, each: &mut dyn FnMut(FabricIndex, GroupId, EndpointId));
69
70    /// A group's name, if the Groups cluster kept one (§1.3.6.1's `GroupNames` feature).
71    fn name(&self, fabric: FabricIndex, group: GroupId) -> Option<&str> {
72        let _ = (fabric, group);
73        None
74    }
75}
76
77/// A node with no Groups cluster, whose `GroupTable` is therefore empty.
78impl GroupTable for () {
79    fn memberships(&self, _each: &mut dyn FnMut(FabricIndex, GroupId, EndpointId)) {}
80}
81
82/// The Group Key Management cluster (§11.2).
83///
84/// `K` and `M` size [`GroupKeys`]; `T` is whatever can answer "which endpoints are in this
85/// group", which is the Groups cluster on a device that has one.
86#[derive(Debug)]
87pub struct GroupKeyManagement<
88    'a,
89    C: Config,
90    T: GroupTable,
91    const K: usize = 15,
92    const M: usize = 20,
93> {
94    keys: &'a RefCell<GroupKeys<C, K, M>>,
95    table: &'a T,
96}
97
98impl<'a, C: Config, T: GroupTable, const K: usize, const M: usize>
99    GroupKeyManagement<'a, C, T, K, M>
100{
101    /// A cluster over the node's group keys and its group membership.
102    #[must_use]
103    pub const fn new(keys: &'a RefCell<GroupKeys<C, K, M>>, table: &'a T) -> Self {
104        Self { keys, table }
105    }
106
107    /// The descriptor for an instance, derived from the specification's tables.
108    pub fn conforming(
109        feature_map: u32,
110        optional: &Optional<'_>,
111    ) -> crate::error::Result<Conforming<5, 4, 2, 0>> {
112        Conforming::new(&spec_gkm::CLUSTER, feature_map, optional)
113    }
114
115    /// The key table this cluster manages, for the message layer to send and receive with.
116    #[must_use]
117    pub const fn keys(&self) -> &'a RefCell<GroupKeys<C, K, M>> {
118        self.keys
119    }
120}
121
122/// §11.2.7.1's validation of a `GroupKeySetStruct`, in the order the specification lists it.
123///
124/// The order is the answer: a null `EpochKey0` is `INVALID_COMMAND` and a sixteen-octet check
125/// failure is `CONSTRAINT_ERROR`, so a client that sent neither can tell which it got wrong.
126fn validate(set: &spec_gkm::GroupKeySetStruct<'_>) -> core::result::Result<(), Status> {
127    let epochs = [
128        (set.epoch_key0.0, set.epoch_start_time0.0),
129        (set.epoch_key1.0, set.epoch_start_time1.0),
130        (set.epoch_key2.0, set.epoch_start_time2.0),
131    ];
132    // "If the EpochKey0 field is null or its associated EpochStartTime0 field is null, then this
133    // command SHALL fail with an INVALID_COMMAND status code."
134    let (Some(key0), Some(start0)) = epochs[0] else {
135        return Err(Status::InvalidCommand);
136    };
137    if key0.len() != SYMMETRIC_KEY_LENGTH_BYTES {
138        return Err(Status::ConstraintError);
139    }
140    // "If the EpochStartTime0 is set to 0, then this command SHALL fail with an INVALID_COMMAND
141    // status code." Zero is legal *internally* — `AddNOC` synthesises the IPK's set with it —
142    // but never from a client.
143    if start0 == 0 {
144        return Err(Status::InvalidCommand);
145    }
146
147    let mut previous_start = start0;
148    let mut previous_present = true;
149    for (key, start) in epochs.into_iter().skip(1) {
150        match (key, start) {
151            (None, None) => {
152                previous_present = false;
153            }
154            (Some(key), Some(start)) => {
155                // "If the EpochKey2 field is not null, then the EpochKey1 and EpochKey0 fields
156                // SHALL NOT be null" — a chain with a hole in it is not a rotation.
157                if !previous_present {
158                    return Err(Status::InvalidCommand);
159                }
160                if key.len() != SYMMETRIC_KEY_LENGTH_BYTES {
161                    return Err(Status::ConstraintError);
162                }
163                // "SHALL contain a later epoch start time than the epoch start time found in
164                // the EpochStartTime0 field" — the order is what "current" is read from.
165                if start <= previous_start {
166                    return Err(Status::InvalidCommand);
167                }
168                previous_start = start;
169            }
170            // "If exactly one of the EpochKey1 or EpochStartTime1 is null, rather than both
171            // being null, or neither being null" — a key with no start time is unusable, and a
172            // start time with no key names nothing.
173            _ => return Err(Status::InvalidCommand),
174        }
175    }
176    Ok(())
177}
178
179/// Turns a validated `GroupKeySetStruct` into the stored form.
180fn to_key_set(
181    set: &spec_gkm::GroupKeySetStruct<'_>,
182    fabric: FabricIndex,
183) -> core::result::Result<GroupKeySet, Status> {
184    let mut epoch_keys = heapless::Vec::new();
185    for (key, start) in [
186        (set.epoch_key0.0, set.epoch_start_time0.0),
187        (set.epoch_key1.0, set.epoch_start_time1.0),
188        (set.epoch_key2.0, set.epoch_start_time2.0),
189    ] {
190        let (Some(key), Some(start_time_us)) = (key, start) else {
191            continue;
192        };
193        let bytes = <[u8; SYMMETRIC_KEY_LENGTH_BYTES]>::try_from(key)
194            .map_err(|_| Status::ConstraintError)?;
195        epoch_keys
196            .push(EpochKey {
197                key: SymmetricKey::new(bytes),
198                start_time_us,
199            })
200            .map_err(|_| Status::ResourceExhausted)?;
201    }
202    Ok(GroupKeySet {
203        fabric_index: fabric,
204        id: set.group_key_set_id,
205        policy: GroupKeySecurityPolicy::from_value(set.group_key_security_policy.value())
206            .map_err(|_| Status::ConstraintError)?,
207        epoch_keys,
208    })
209}
210
211impl<C: Config, T: GroupTable, const K: usize, const M: usize> ClusterHandler
212    for GroupKeyManagement<'_, C, T, K, M>
213{
214    /// §11.2.7.4: a fabric's group keys go with the fabric. Leaving them behind leaves key
215    /// material for a fabric this node is no longer on — the IPK included.
216    fn on_lifecycle(&self, event: crate::im::Lifecycle) {
217        if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
218            self.keys.borrow_mut().remove_fabric(fabric);
219        }
220    }
221    fn read(
222        &self,
223        resolved: &Resolved<'_>,
224        ctx: &InteractionContext<'_>,
225        w: &mut TlvWriter<'_>,
226        tag: Tag,
227    ) -> core::result::Result<(), Status> {
228        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
229        let keys = self.keys.borrow();
230        match resolved.attribute {
231            MAX_GROUPS_PER_FABRIC => full(w.unsigned(tag, keys.max_groups_per_fabric() as u64)),
232            MAX_GROUP_KEYS_PER_FABRIC => {
233                full(w.unsigned(tag, keys.max_key_sets_per_fabric() as u64))
234            }
235            GROUP_KEY_MAP => {
236                full(w.start_array(tag))?;
237                for (fabric, group, key_set) in keys.map() {
238                    if !visible(ctx, *fabric) {
239                        continue;
240                    }
241                    full(
242                        spec_gkm::GroupKeyMapStruct {
243                            group_id: *group,
244                            group_key_set_id: *key_set,
245                            fabric_index: *fabric,
246                        }
247                        .to_tlv(w, Tag::Anonymous),
248                    )?;
249                }
250                full(w.end_container())
251            }
252            GROUP_TABLE => self.read_group_table(ctx, w, tag),
253            _ => Err(Status::UnsupportedAttribute),
254        }
255    }
256
257    fn write(
258        &self,
259        resolved: &Resolved<'_>,
260        data: &[u8],
261        op: WriteOp,
262        ctx: &InteractionContext<'_>,
263    ) -> core::result::Result<(), Status> {
264        if resolved.attribute != GROUP_KEY_MAP {
265            // `GroupTable` is `R F`: it is the Groups cluster's data, and writing it here would
266            // let an administrator claim a membership no endpoint has.
267            return Err(Status::UnsupportedWrite);
268        }
269        let Some(fabric) = ctx.fabric_index.filter(|f| f.0 != 0) else {
270            return Err(Status::UnsupportedAccess);
271        };
272
273        let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
274        let element = reader
275            .next_element()
276            .map_err(|_| Status::InvalidAction)?
277            .ok_or(Status::InvalidAction)?;
278        let mut keys = self.keys.borrow_mut();
279        match op {
280            WriteOp::Replace => {
281                if element.value.container() != Some(ContainerKind::Array) {
282                    return Err(Status::InvalidAction);
283                }
284                let mut entries: heapless::Vec<(GroupId, KeySetId), M> = heapless::Vec::new();
285                loop {
286                    let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
287                    else {
288                        return Err(Status::InvalidAction);
289                    };
290                    if item.value == Value::EndOfContainer {
291                        break;
292                    }
293                    let entry = decode_map_entry(&mut reader, &item)?;
294                    entries.push(entry).map_err(|_| Status::ResourceExhausted)?;
295                }
296                keys.replace_map(fabric, &entries)
297            }
298            WriteOp::Append => {
299                let (group, key_set) = decode_map_entry(&mut reader, &element)?;
300                keys.map_group(fabric, group, key_set)
301            }
302        }
303    }
304
305    fn invoke(
306        &self,
307        resolved: &ResolvedCommand<'_>,
308        fields: Option<&[u8]>,
309        ctx: &InteractionContext<'_>,
310        w: &mut TlvWriter<'_>,
311        tag: Tag,
312    ) -> core::result::Result<Option<CommandId>, StatusIb> {
313        // §11.2.7: "All commands in this cluster SHALL be scoped to the accessing fabric."
314        let fabric = ctx
315            .fabric_index
316            .filter(|f| f.0 != 0)
317            .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
318        let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
319        match resolved.command.id {
320            KEY_SET_WRITE => {
321                let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
322                let decoded: spec_gkm::KeySetWriteFields<'_> = super::decode_fields(payload)?;
323                validate(&decoded.group_key_set)?;
324                let set = to_key_set(&decoded.group_key_set, fabric)?;
325                self.keys.borrow_mut().write_key_set(set)?;
326                Ok(None)
327            }
328            KEY_SET_READ => {
329                let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
330                let decoded: spec_gkm::KeySetReadFields = super::decode_fields(payload)?;
331                let keys = self.keys.borrow();
332                let set = keys
333                    .key_set(fabric, decoded.group_key_set_id)
334                    .ok_or(StatusIb::from(Status::NotFound))?;
335                full(Self::read_response(set).to_tlv(w, tag))?;
336                Ok(Some(KEY_SET_READ_RESPONSE))
337            }
338            KEY_SET_REMOVE => {
339                let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
340                let decoded: spec_gkm::KeySetRemoveFields = super::decode_fields(payload)?;
341                self.keys
342                    .borrow_mut()
343                    .remove_key_set(fabric, decoded.group_key_set_id)?;
344                Ok(None)
345            }
346            KEY_SET_READ_ALL_INDICES => {
347                let keys = self.keys.borrow();
348                full(w.start_structure(tag))?;
349                full(w.start_array(Tag::Context(0)))?;
350                for set in keys.key_sets().iter().filter(|s| s.fabric_index == fabric) {
351                    full(w.unsigned(Tag::Anonymous, u64::from(set.id)))?;
352                }
353                full(w.end_container())?;
354                full(w.end_container())?;
355                Ok(Some(KEY_SET_READ_ALL_INDICES_RESPONSE))
356            }
357            _ => Err(Status::UnsupportedCommand.into()),
358        }
359    }
360}
361
362impl<C: Config, T: GroupTable, const K: usize, const M: usize> GroupKeyManagement<'_, C, T, K, M> {
363    /// §11.2.7.3's response: everything about the key set except the keys.
364    fn read_response(set: &GroupKeySet) -> spec_gkm::KeySetReadResponseFields<'static> {
365        let start = |index: usize| {
366            set.epoch_keys
367                .get(index)
368                .map(|k| k.start_time_us)
369                .map_or(crate::tlv::Nullable::null(), crate::tlv::Nullable::some)
370        };
371        spec_gkm::KeySetReadResponseFields {
372            group_key_set: spec_gkm::GroupKeySetStruct {
373                group_key_set_id: set.id,
374                group_key_security_policy: spec_gkm::GroupKeySecurityPolicyEnum::from_value(
375                    set.policy.value(),
376                )
377                .unwrap_or(spec_gkm::GroupKeySecurityPolicyEnum::TrustFirst),
378                // §11.2.7.2: "with the EpochKey0, EpochKey1 and EpochKey2 fields replaced by
379                // null". The start times are not secret and are what an administrator needs in
380                // order to schedule the next rotation; the keys never leave the node.
381                epoch_key0: crate::tlv::Nullable::null(),
382                epoch_start_time0: start(0),
383                epoch_key1: crate::tlv::Nullable::null(),
384                epoch_start_time1: start(1),
385                epoch_key2: crate::tlv::Nullable::null(),
386                epoch_start_time2: start(2),
387                group_key_multicast_policy: None,
388                fabric_index: set.fabric_index,
389            },
390        }
391    }
392
393    /// §11.2.6.2's `GroupTable`, grouped by `(fabric, group)`.
394    fn read_group_table(
395        &self,
396        ctx: &InteractionContext<'_>,
397        w: &mut TlvWriter<'_>,
398        tag: Tag,
399    ) -> core::result::Result<(), Status> {
400        let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
401        // Collect the distinct (fabric, group) pairs first: the trait yields memberships in any
402        // order, and one group's endpoints have to be written as one list.
403        let mut groups: heapless::Vec<(FabricIndex, GroupId), M> = heapless::Vec::new();
404        self.table.memberships(&mut |fabric, group, _| {
405            if visible(ctx, fabric) && !groups.contains(&(fabric, group)) {
406                let _ = groups.push((fabric, group));
407            }
408        });
409
410        full(w.start_array(tag))?;
411        for (fabric, group) in &groups {
412            full(w.start_structure(Tag::Anonymous))?;
413            full(w.unsigned(Tag::Context(1), u64::from(group.0)))?;
414            full(w.start_array(Tag::Context(2)))?;
415            let mut result = Ok(());
416            self.table.memberships(&mut |f, g, endpoint| {
417                if f == *fabric && g == *group && result.is_ok() {
418                    result = w.unsigned(Tag::Anonymous, u64::from(endpoint));
419                }
420            });
421            full(result)?;
422            full(w.end_container())?;
423            if let Some(name) = self.table.name(*fabric, *group) {
424                full(w.utf8(Tag::Context(3), name))?;
425            }
426            full(w.unsigned(Tag::Context(254), u64::from(fabric.0)))?;
427            full(w.end_container())?;
428        }
429        full(w.end_container())
430    }
431}
432
433/// Reads one `GroupKeyMapStruct`. §7.19.1.8.1: the client's `FabricIndex` is ignored.
434fn decode_map_entry<'a>(
435    reader: &mut TlvReader<'a>,
436    element: &crate::tlv::Element<'a>,
437) -> core::result::Result<(GroupId, KeySetId), Status> {
438    if element.value.container() != Some(ContainerKind::Structure) {
439        return Err(Status::InvalidAction);
440    }
441    let entry = <spec_gkm::GroupKeyMapStruct as crate::tlv::FromTlv<'a>>::from_tlv(reader, element)
442        .map_err(|_| Status::InvalidAction)?;
443    Ok((entry.group_id, entry.group_key_set_id))
444}
445
446/// Whether a fabric's entries belong in this read (§7.19.1.8.2).
447fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
448    !ctx.fabric_filtered || ctx.fabric_index == Some(index)
449}
450
451/// So a tuple of clusters can dispatch to it by id.
452impl<C: Config, T: GroupTable, const K: usize, const M: usize> Cluster
453    for GroupKeyManagement<'_, C, T, K, M>
454{
455    const ID: ClusterId = ID;
456}