1use 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
58pub trait GroupTable {
64 fn memberships(&self, each: &mut dyn FnMut(FabricIndex, GroupId, EndpointId));
69
70 fn name(&self, fabric: FabricIndex, group: GroupId) -> Option<&str> {
72 let _ = (fabric, group);
73 None
74 }
75}
76
77impl GroupTable for () {
79 fn memberships(&self, _each: &mut dyn FnMut(FabricIndex, GroupId, EndpointId)) {}
80}
81
82#[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 #[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 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 #[must_use]
117 pub const fn keys(&self) -> &'a RefCell<GroupKeys<C, K, M>> {
118 self.keys
119 }
120}
121
122fn 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 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 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 !previous_present {
158 return Err(Status::InvalidCommand);
159 }
160 if key.len() != SYMMETRIC_KEY_LENGTH_BYTES {
161 return Err(Status::ConstraintError);
162 }
163 if start <= previous_start {
166 return Err(Status::InvalidCommand);
167 }
168 previous_start = start;
169 }
170 _ => return Err(Status::InvalidCommand),
174 }
175 }
176 Ok(())
177}
178
179fn 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 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 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 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 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 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 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 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
433fn 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
446fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
448 !ctx.fabric_filtered || ctx.fabric_index == Some(index)
449}
450
451impl<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}