Skip to main content

matter_kit/group/
wire.rs

1//! Sending and receiving a group message (Core §4.16.2, §4.16.3, §4.18.4).
2//!
3//! Not part of [`Messaging`](crate::messaging::Messaging), and deliberately: §4.16 has no
4//! session, no exchange and no reply, so everything that layer does — routing to an exchange,
5//! arming MRP, acknowledging — is either absent or wrong here. What is left is the message
6//! layer's own work, done against a key found by trying candidates rather than by session id.
7
8use crate::error::{Error, ErrorCode, Result, bail};
9use crate::msg::{
10    Destination, MessageCounter, MessageHeader, NonceSource, ProtocolHeader, SessionId,
11    SessionKeys, SessionType, preview, protect, unprotect,
12};
13use crate::msg::{FabricIndex, GroupId, NodeId};
14use crate::platform::PeerAddr;
15
16use super::GroupContext;
17use super::keys::{GroupKeys, OperationalKey};
18use super::peers::{Admitted, PeerTable};
19
20/// The sending half: the two group counter spaces this node owns (§4.6.1).
21///
22/// A group message's counter is free-running and rolls over (§4.6.5.2.2) — unlike a session's,
23/// which must never repeat, because a group counter's nonce is diversified by the Source Node ID
24/// as well.
25#[derive(Debug)]
26pub struct Sender {
27    node: NodeId,
28    data: MessageCounter,
29    control: MessageCounter,
30}
31
32impl Sender {
33    /// A sender for `node`, with its two counters started where the caller says.
34    ///
35    /// §4.6.1.1 has a node choose its initial counters at random on boot, so these come from
36    /// [`Rng`](crate::platform::Rng) rather than from zero: starting at zero would make every
37    /// message this node has ever sent replayable against a peer that had not heard from it
38    /// since its last boot. Pass the random words as they come —
39    /// [`MessageCounter::new`](crate::msg::MessageCounter::new) narrows each to the range
40    /// §4.6.1.1 specifies.
41    ///
42    /// This is the **factory-reset** path. §4.6.1.3 randomises these two counters once, on a
43    /// factory reset, and requires them to be persisted and never to roll back after that — so
44    /// a node that has run before restores them with [`restore`](Self::restore) instead, and
45    /// calling this on every boot would rewind them and reuse a nonce.
46    #[must_use]
47    pub const fn new(node: NodeId, data: u32, control: u32) -> Self {
48        Self {
49            node,
50            data: MessageCounter::new(data),
51            control: MessageCounter::new(control),
52        }
53    }
54
55    /// A sender whose counters come from durable storage, at exactly the values given.
56    ///
57    /// §4.6.1.3: "Nodes are required to persist the Global Group Encrypted Message Counters in
58    /// durable storage. In particular, Nodes are required to ensure that the value of the
59    /// Global Group Encrypted Message Counters never rolls back". Unlike [`new`](Self::new)
60    /// these values are taken as they are: they are not a random seed, they are where this node
61    /// actually was, and narrowing them to §4.6.1.1's range would roll them back by up to 2³²
62    /// and reuse every nonce since.
63    ///
64    /// Persist *ahead* of where the counter stands, as §4.6.3 describes for the Check-In
65    /// counter: a node that stores every value writes flash on every message, and one that
66    /// stores the value it is at loses the writes it had not flushed when it lost power.
67    #[must_use]
68    pub const fn restore(node: NodeId, data: u32, control: u32) -> Self {
69        Self {
70            node,
71            data: MessageCounter::at(data),
72            control: MessageCounter::at(control),
73        }
74    }
75
76    /// The node these messages say they are from.
77    #[must_use]
78    pub const fn node(&self) -> NodeId {
79        self.node
80    }
81
82    /// Builds one group message (§4.16.2).
83    ///
84    /// `scratch` joins the protocol header and the payload for the AEAD, as on a unicast
85    /// session; `out` takes the finished message, which the caller sends to
86    /// [`multicast_address`](super::multicast_address) on
87    /// [`PORT`](crate::PORT).
88    ///
89    /// §4.16.2 step 2c: "The Security Flags SHALL have only the P Flag set" — a group message is
90    /// always privacy-obfuscated, because the whole point of the address is that anyone on the
91    /// link can see it.
92    #[expect(
93        clippy::too_many_arguments,
94        reason = "every one is a distinct fact about the message, the way `Messaging::send`'s \
95                  are; bundling them would move the same list one line up"
96    )]
97    pub fn send(
98        &mut self,
99        key: &OperationalKey,
100        group: GroupId,
101        protocol_header: &ProtocolHeader,
102        payload: &[u8],
103        control: bool,
104        scratch: &mut [u8],
105        out: &mut [u8],
106    ) -> Result<usize> {
107        let counter = if control {
108            self.control.take_with_rollover()
109        } else {
110            self.data.take_with_rollover()
111        };
112        let header = MessageHeader {
113            session_id: SessionId(key.session_id),
114            session_type: SessionType::Group,
115            message_counter: counter,
116            // §4.16.1: the Source Node ID is what identifies the sender to every receiver, and
117            // §4.8.1.1 folds it into the nonce — so unlike a unicast session it is never elided.
118            source: Some(self.node),
119            destination: Destination::Group(group),
120            privacy: true,
121            control,
122        };
123        let body = join(protocol_header, payload, scratch)?;
124        let keys = SessionKeys::from_encryption_key(key.key.clone())?;
125        protect(&header, NonceSource::Group, body, &keys, out)
126    }
127}
128
129/// A group message that authenticated and was fresh (§4.16.1, §4.18.4).
130#[derive(Debug)]
131pub struct Inbound<'a> {
132    /// §4.16.1's Groupcast Session Context.
133    pub context: GroupContext,
134    /// The protocol header it carried.
135    pub protocol: ProtocolHeader,
136    /// The payload, decrypted in place.
137    pub payload: &'a [u8],
138    /// The message counter it carried, which an [`mcsp`](super::mcsp) exchange would be about.
139    pub counter: u32,
140    /// Whether the **C** flag was set, so this is a control message (§4.18.1.1).
141    pub control: bool,
142}
143
144/// What [`receive`] concluded.
145#[derive(Debug)]
146pub enum Received<'a> {
147    /// Authenticated, fresh, and for the layer above.
148    Message(Inbound<'a>),
149    /// Authenticated but a duplicate or too old (§4.6.5). Dropped — a group message is never
150    /// reliable, so there is nothing to acknowledge.
151    Duplicate(GroupContext),
152    /// Authenticated, but the sender's counter is unknown under a cache-and-sync key.
153    ///
154    /// §4.18.4 step 3c: hold the message and run [`mcsp`](super::mcsp) first. The context says
155    /// who to ask and under which key.
156    NeedsSync(GroupContext),
157    /// Authenticated, but §4.16.1's peer table is full and "any message from a source that
158    /// cannot be tracked SHALL be dropped".
159    Untracked(GroupContext),
160}
161
162/// Processes one datagram that arrived on a group multicast address (§4.16.3, §4.18.4).
163///
164/// `buf` is decrypted in place, so everything returned borrows it. `compressed` maps a fabric
165/// index to its compressed identifier, which is the salt every operational group key is derived
166/// with — the fabric table owns that, not this module.
167///
168/// Every candidate key for the message's Group Session ID is tried, because §4.17.3.6 says the
169/// id "SHALL NOT be used as the sole means to locate the associated Operational Group Key, since
170/// it MAY collide within the fabric". A failed candidate leaves `buf` unusable for the next one,
171/// so each attempt works on a copy of the ciphertext in `scratch`.
172pub fn receive<'b, const K: usize, const M: usize, const D: usize, const C: usize>(
173    buf: &'b mut [u8],
174    from: PeerAddr,
175    keys: &GroupKeys<K, M>,
176    peers: &mut PeerTable<D, C>,
177    compressed: impl Fn(FabricIndex) -> Option<crate::fabric::CompressedFabricId>,
178    scratch: &mut [u8],
179) -> Result<Received<'b>> {
180    let head = preview(buf)?;
181    if !matches!(head.session_type, SessionType::Group) {
182        // A unicast message belongs to `Messaging::receive`; taking it here would skip the
183        // session lookup that is the only thing binding it to a peer.
184        bail!(InvalidArgument)
185    }
186    let original = scratch
187        .get_mut(..buf.len())
188        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
189    original.copy_from_slice(buf);
190
191    // §4.17.3.6: every installed key whose session id matches, in turn.
192    let candidates = keys.receiving_keys::<8>(compressed, head.session_id.0);
193    let mut authenticated = None;
194    for candidate in &candidates {
195        let Ok(session_keys) = SessionKeys::from_encryption_key(candidate.key.clone()) else {
196            continue;
197        };
198        // A failed AEAD leaves the buffer undefined (§3.6.2), so each attempt starts from the
199        // untouched ciphertext.
200        buf.copy_from_slice(original);
201        if let Ok((header, range)) = unprotect(buf, &session_keys, NonceSource::Group) {
202            authenticated = Some((candidate, header, range));
203            break;
204        }
205    }
206    let Some((key, header, range)) = authenticated else {
207        bail!(IntegrityCheckFailed)
208    };
209
210    // §4.4.1.5 and §4.8.1.1: a group message carries its Source Node ID, and the nonce is built
211    // from it — `unprotect` would have failed without one, but naming the requirement here is
212    // what stops a later change from quietly dropping it.
213    let source = header
214        .source
215        .ok_or(Error::new(ErrorCode::MessageReserved))?;
216    let Destination::Group(group) = header.destination else {
217        // The Session Type said group; the DSIZ must agree, or the two halves of the header
218        // describe different messages.
219        bail!(MessageReserved)
220    };
221    let context = GroupContext {
222        fabric_index: key.fabric_index,
223        group,
224        source,
225        from,
226        session_id: header.session_id.0,
227        key_set: key.key_set,
228    };
229
230    // Authenticated. Only now may any counter move (§4.7.2).
231    let admitted = peers.admit(
232        key.fabric_index,
233        source,
234        header.control,
235        header.message_counter,
236        key.policy,
237    );
238    match admitted {
239        Admitted::Duplicate => return Ok(Received::Duplicate(context)),
240        Admitted::NeedsSync => return Ok(Received::NeedsSync(context)),
241        Admitted::Untracked => return Ok(Received::Untracked(context)),
242        Admitted::Process => {}
243    }
244
245    let Some(payload) = buf.get(range) else {
246        bail!(MessageTruncated)
247    };
248    let (protocol, body) = ProtocolHeader::decode(payload)?;
249    Ok(Received::Message(Inbound {
250        context,
251        protocol,
252        payload: body,
253        counter: header.message_counter,
254        control: header.control,
255    }))
256}
257
258/// Joins the protocol header and the payload for the AEAD, as a unicast session does.
259fn join<'a>(
260    protocol_header: &ProtocolHeader,
261    payload: &[u8],
262    scratch: &'a mut [u8],
263) -> Result<&'a [u8]> {
264    let header_len = protocol_header.encode(scratch)?;
265    let end = header_len
266        .checked_add(payload.len())
267        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
268    let slot = scratch
269        .get_mut(header_len..end)
270        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
271    slot.copy_from_slice(payload);
272    scratch
273        .get(..end)
274        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
275}