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<
173    'b,
174    Cfg: crate::config::Config,
175    const K: usize,
176    const M: usize,
177    const D: usize,
178    const C: usize,
179>(
180    buf: &'b mut [u8],
181    from: PeerAddr,
182    keys: &GroupKeys<Cfg, K, M>,
183    peers: &mut PeerTable<D, C>,
184    compressed: impl Fn(FabricIndex) -> Option<crate::fabric::CompressedFabricId>,
185    scratch: &mut [u8],
186) -> Result<Received<'b>> {
187    let head = preview(buf)?;
188    if !matches!(head.session_type, SessionType::Group) {
189        // A unicast message belongs to `Messaging::receive`; taking it here would skip the
190        // session lookup that is the only thing binding it to a peer.
191        bail!(InvalidArgument)
192    }
193    let original = scratch
194        .get_mut(..buf.len())
195        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
196    original.copy_from_slice(buf);
197
198    // §4.17.3.6: every installed key whose session id matches, in turn.
199    let candidates = keys.receiving_keys::<8>(compressed, head.session_id.0);
200    let mut authenticated = None;
201    for candidate in &candidates {
202        let Ok(session_keys) = SessionKeys::from_encryption_key(candidate.key.clone()) else {
203            continue;
204        };
205        // A failed AEAD leaves the buffer undefined (§3.6.2), so each attempt starts from the
206        // untouched ciphertext.
207        buf.copy_from_slice(original);
208        if let Ok((header, range)) = unprotect(buf, &session_keys, NonceSource::Group) {
209            authenticated = Some((candidate, header, range));
210            break;
211        }
212    }
213    let Some((key, header, range)) = authenticated else {
214        bail!(IntegrityCheckFailed)
215    };
216
217    // §4.4.1.5 and §4.8.1.1: a group message carries its Source Node ID, and the nonce is built
218    // from it — `unprotect` would have failed without one, but naming the requirement here is
219    // what stops a later change from quietly dropping it.
220    let source = header
221        .source
222        .ok_or(Error::new(ErrorCode::MessageReserved))?;
223    let Destination::Group(group) = header.destination else {
224        // The Session Type said group; the DSIZ must agree, or the two halves of the header
225        // describe different messages.
226        bail!(MessageReserved)
227    };
228    let context = GroupContext {
229        fabric_index: key.fabric_index,
230        group,
231        source,
232        from,
233        session_id: header.session_id.0,
234        key_set: key.key_set,
235    };
236
237    // Authenticated. Only now may any counter move (§4.7.2).
238    let admitted = peers.admit(
239        key.fabric_index,
240        source,
241        header.control,
242        header.message_counter,
243        key.policy,
244    );
245    match admitted {
246        Admitted::Duplicate => return Ok(Received::Duplicate(context)),
247        Admitted::NeedsSync => return Ok(Received::NeedsSync(context)),
248        Admitted::Untracked => return Ok(Received::Untracked(context)),
249        Admitted::Process => {}
250    }
251
252    let Some(payload) = buf.get(range) else {
253        bail!(MessageTruncated)
254    };
255    let (protocol, body) = ProtocolHeader::decode(payload)?;
256    Ok(Received::Message(Inbound {
257        context,
258        protocol,
259        payload: body,
260        counter: header.message_counter,
261        control: header.control,
262    }))
263}
264
265/// Joins the protocol header and the payload for the AEAD, as a unicast session does.
266fn join<'a>(
267    protocol_header: &ProtocolHeader,
268    payload: &[u8],
269    scratch: &'a mut [u8],
270) -> Result<&'a [u8]> {
271    let header_len = protocol_header.encode(scratch)?;
272    let end = header_len
273        .checked_add(payload.len())
274        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
275    let slot = scratch
276        .get_mut(header_len..end)
277        .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
278    slot.copy_from_slice(payload);
279    scratch
280        .get(..end)
281        .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))
282}