matter_kit/group/mod.rs
1//! Group communication: one message, many nodes (Core §4.16, §4.17, §4.18).
2//!
3//! Needs the `rustcrypto` feature: every operational group key is derived with
4//! [`crypto`](crate::crypto)'s KDF from [`fabric`](crate::fabric)'s compressed identifier.
5//!
6//! A wall switch that controls twenty lights cannot send twenty messages. §4.16 is the
7//! alternative: one IPv6 multicast datagram addressed by a 16-bit **Group ID**, encrypted under
8//! a symmetric key every member of the group holds.
9//!
10//! That one sentence is also the whole of the difficulty. A group message has no session, no
11//! exchange, no acknowledgement and no reply — so everything a unicast session gives for free
12//! has to be rebuilt:
13//!
14//! * **Which key?** §4.17.3.6's [`Group Session ID`](session_id) narrows the candidates, and
15//! narrowing is all it does: "It SHALL NOT be used as the sole means to locate the associated
16//! Operational Group Key, since it MAY collide within the fabric." Every candidate is tried
17//! until the MIC passes.
18//! * **Is it fresh?** There is no handshake to agree a starting counter, so §4.18's
19//! [`PeerTable`] tracks one per sender, and the [`GroupKeySecurityPolicy`] on the key chooses
20//! between trusting the first counter seen and synchronising over [`mcsp`].
21//! * **Who sent it?** §4.16.1's [`GroupContext`] — fabric, group, source node — is what the
22//! layer above is given in place of a session.
23//!
24//! # Keys are derived, not distributed
25//!
26//! §4.17.2: an **epoch key** is what an administrator installs, and the key a message is
27//! actually encrypted under is
28//! [`operational_group_key`](crate::fabric::operational_group_key) — the epoch key salted with
29//! the fabric's compressed identifier. So the same epoch key gives different operational keys on
30//! different fabrics, and a node that is removed from a group simply stops being sent new epoch
31//! keys: §4.17.3, "denying access to updated versions of these keys serves as a means to eject
32//! group members".
33//!
34//! A **key set** holds up to three epoch keys with start times, which is what makes rotation
35//! possible without a flag day: a sender uses the newest key whose start time has passed, and a
36//! receiver accepts "any key derived from one of the currently installed epoch keys", future
37//! start times included.
38//!
39//! ```
40//! use matter_kit::fabric::CompressedFabricId;
41//! use matter_kit::group;
42//!
43//! // §4.17.2's worked example, and §4.17.3.6's, which continues it.
44//! let epoch = [
45//! 0x23, 0x5b, 0xf7, 0xe6, 0x28, 0x23, 0xd3, 0x58,
46//! 0xdc, 0xa4, 0xba, 0x50, 0xb1, 0x53, 0x5f, 0x4b,
47//! ];
48//! let compressed = CompressedFabricId(0x87E1_B004_E235_A130);
49//! let operational = matter_kit::fabric::operational_group_key(
50//! &matter_kit::crypto::SymmetricKey::new(epoch),
51//! compressed,
52//! )?;
53//! assert_eq!(operational.as_bytes()[..2], [0xa6, 0xf5]);
54//! assert_eq!(group::session_id(&operational)?, 0xB9F7);
55//! # Ok::<(), matter_kit::Error>(())
56//! ```
57
58pub mod keys;
59pub mod mcsp;
60pub mod peers;
61pub mod wire;
62
63pub use keys::{
64 EpochKey, GroupKeySecurityPolicy, GroupKeySet, GroupKeys, IPK_KEY_SET, KeySetId,
65 MAX_EPOCH_KEYS, OperationalKey,
66};
67pub use mcsp::{CHALLENGE_LEN, SyncRequest, SyncResponse};
68pub use peers::{Admitted, PeerState, PeerTable};
69pub use wire::{Inbound, Received, Sender};
70
71use crate::crypto::{SymmetricKey, kdf};
72use crate::error::Result;
73use crate::msg::{FabricId, GroupId, NodeId};
74use crate::platform::PeerAddr;
75
76/// §4.17.3.6's `Info`: the ASCII of `"GroupKeyHash"`.
77pub const GROUP_KEY_HASH_INFO: &[u8] = b"GroupKeyHash";
78
79/// The IANA-assigned site-scoped multicast address for Matter, `FF05::FA` (§2.5.6.2).
80///
81/// Required of "any device supporting the Groupcast cluster, whether as a Listener or Sender",
82/// and the one address that does not depend on the fabric.
83pub const IANA_MULTICAST: PeerAddr =
84 PeerAddr::new([0xFF, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFA]);
85
86/// §4.17.3.6's Group Session ID: which operational keys *might* have encrypted a message.
87///
88/// > The Group Session ID MAY help receiving nodes efficiently locate the Operational Group Key
89/// > used to encrypt an incoming groupcast message. It SHALL NOT be used as the sole means to
90/// > locate the associated Operational Group Key, since it MAY collide within the fabric.
91///
92/// Sixteen bits derived from the key, read big-endian — "GroupSessionId is computed by
93/// considering the GroupKeyHash as a Big-Endian value" — which is the opposite of every other
94/// scalar in the message header and the one thing to get wrong here.
95pub fn session_id(operational: &SymmetricKey) -> Result<u16> {
96 let mut hash = [0u8; 2];
97 kdf(operational.as_bytes(), &[], GROUP_KEY_HASH_INFO, &mut hash)?;
98 Ok(u16::from_be_bytes(hash))
99}
100
101/// §2.5.6.2's per-group IPv6 multicast address, `FF35:0040:FD<Fabric ID>00:<Group ID>`.
102///
103/// A unicast-prefix-based multicast address (RFC 3306) with site-local scope, so that "a low
104/// probability of a node receiving a multicast message it is not interested in" comes from the
105/// address rather than from decrypting everything. A collision needs two identical 64-bit
106/// fabric ids *and* two identical group ids, and even then the MIC disambiguates.
107#[must_use]
108pub fn multicast_address(fabric: FabricId, group: GroupId) -> PeerAddr {
109 let fabric = fabric.0.to_be_bytes();
110 let group = group.0.to_be_bytes();
111 PeerAddr::new([
112 // 0xFF3 | scop 5: site-local, which "spans all networks in the Fabric".
113 0xFF, 0x35, // Reserved, then plen 0x40: a 64-bit network prefix.
114 0x00, 0x40,
115 // The prefix: 0xFD for a locally assigned ULA, then the upper 56 bits of the fabric id.
116 0xFD, fabric[0], fabric[1], fabric[2], fabric[3], fabric[4], fabric[5], fabric[6],
117 // The 32-bit group identifier: the low 8 bits of the fabric id, a zero, then the group.
118 fabric[7], 0x00, group[0], group[1],
119 ])
120}
121
122/// §4.16.1's Groupcast Session Context: what a group message carries in place of a session.
123///
124/// > Together, Fabric Index, Group ID and Source Node ID comprise a unique identifier that
125/// > upper layers may use to understand the source and destination of groupcast messages.
126///
127/// Built fresh on every message — "on ingress of each groupcast message, the following ephemeral
128/// context SHALL be constructed" — because a group session is not a thing that is established,
129/// only a membership that happens to still hold.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct GroupContext {
132 /// "the local Fabric Index for the Fabric to which an incoming message's group is scoped".
133 pub fabric_index: crate::msg::FabricIndex,
134 /// "the Group ID to which a groupcast message was sent".
135 pub group: GroupId,
136 /// "The Source Node ID enclosed by the sender of a groupcast message."
137 pub source: NodeId,
138 /// The unicast address the datagram came from, which is where an [`mcsp`] request goes —
139 /// "as are required for the Message Counter Synchronization Protocol".
140 pub from: PeerAddr,
141 /// §4.17.3.6's Group Session ID the message named.
142 pub session_id: u16,
143 /// Which key set the key that authenticated it belongs to.
144 pub key_set: KeySetId,
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn the_group_session_id_is_read_big_endian() {
153 // §4.17.3.6's worked example: an operational group key of a6:f5:…:60 gives a
154 // GroupKeyHash of b9:f7 and a Group Session ID of 0xB9F7. Reading the two octets the
155 // other way round would give 0xF7B9, which is what every other scalar in the message
156 // header would have been.
157 let operational = SymmetricKey::new([
158 0xa6, 0xf5, 0x30, 0x6b, 0xaf, 0x6d, 0x05, 0x0a, 0xf2, 0x3b, 0xa4, 0xbd, 0x6b, 0x9d,
159 0xd9, 0x60,
160 ]);
161 assert_eq!(session_id(&operational).expect("kdf"), 0xB9F7);
162 }
163
164 #[test]
165 fn the_multicast_address_is_the_specs_worked_form() {
166 // §2.5.6.2: `FF35:0040:FD<Fabric ID>00:<Group ID>`, with the fabric id big-endian and
167 // split across the prefix and the group identifier, and the group id big-endian.
168 let addr = multicast_address(FabricId(0x0102_0304_0506_0708), GroupId(0xABCD));
169 assert_eq!(
170 addr.addr,
171 [
172 0xFF, 0x35, 0x00, 0x40, 0xFD, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00,
173 0xAB, 0xCD,
174 ]
175 );
176 assert!(addr.is_multicast());
177 }
178
179 #[test]
180 fn the_iana_address_is_ff05_fa() {
181 assert_eq!(IANA_MULTICAST.addr[0..2], [0xFF, 0x05]);
182 assert_eq!(IANA_MULTICAST.addr[15], 0xFA);
183 assert!(IANA_MULTICAST.is_multicast());
184 }
185}