Skip to main content

matter_kit/group/
mcsp.rs

1//! The Message Counter Synchronization Protocol (Core §4.18.3).
2//!
3//! Two messages, of eight and twelve octets, and neither is TLV. They exist because a group
4//! message has no handshake: a receiver that has never heard from a sender has no counter to
5//! compare against, and §4.18 is how it gets one without simply trusting whatever arrives.
6//!
7//! Both ride on the Secure Channel protocol with the **C** flag set, "secured with the group key
8//! for which counter synchronization is requested", and both go by *unicast* — the request to
9//! the address the multicast came from, the response back.
10
11use crate::error::{Error, ErrorCode, Result};
12
13/// §4.18.3.1: the Challenge is "a 64-bit random number generated using the DRBG".
14pub const CHALLENGE_LEN: usize = 8;
15
16/// §4.18.5: "the Node SHALL first wait for a uniformly random amount of time between 0 and
17/// MSG_COUNTER_SYNC_REQ_JITTER", so that a multicast heard by fifty nodes does not produce
18/// fifty simultaneous unicast requests back at the sender.
19pub const SYNC_REQ_JITTER_MS: u32 = 500;
20
21/// §4.18.5: how long a synchronisation exchange may stay open. On expiry "any message waiting
22/// on synchronization associated with the exchange SHALL be discarded".
23pub const SYNC_TIMEOUT_MS: u32 = 2000;
24
25/// `MsgCounterSyncReq` (§4.18.3.1).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct SyncRequest {
28    /// The 64-bit random value that "uniquely identifies the synchronization request
29    /// cryptographically", and which the response has to echo.
30    pub challenge: [u8; CHALLENGE_LEN],
31}
32
33impl SyncRequest {
34    /// Writes the payload.
35    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8]> {
36        let slot = buf
37            .get_mut(..CHALLENGE_LEN)
38            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
39        slot.copy_from_slice(&self.challenge);
40        Ok(slot)
41    }
42
43    /// Reads the payload.
44    ///
45    /// Trailing octets are refused: the message is exactly eight, and anything more means the
46    /// sender and this reader disagree about what they are speaking.
47    pub fn decode(payload: &[u8]) -> Result<Self> {
48        let challenge = <[u8; CHALLENGE_LEN]>::try_from(payload)
49            .map_err(|_| Error::new(ErrorCode::MessageTruncated))?;
50        Ok(Self { challenge })
51    }
52}
53
54/// `MsgCounterSyncRsp` (§4.18.3.2).
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct SyncResponse {
57    /// "The current data message counter for the node sending the MsgCounterSyncRsp message."
58    pub counter: u32,
59    /// "The Response SHALL be the same as the 64-bit value sent in the Challenge field of the
60    /// corresponding MsgCounterSyncReq."
61    pub response: [u8; CHALLENGE_LEN],
62}
63
64impl SyncResponse {
65    /// The encoded length: a 32-bit counter and the echoed challenge.
66    pub const LEN: usize = 4 + CHALLENGE_LEN;
67
68    /// Writes the payload.
69    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8]> {
70        let slot = buf
71            .get_mut(..Self::LEN)
72            .ok_or(Error::new(ErrorCode::BufferTooSmall))?;
73        let (counter, response) = slot.split_at_mut(4);
74        counter.copy_from_slice(&self.counter.to_le_bytes());
75        response.copy_from_slice(&self.response);
76        Ok(slot)
77    }
78
79    /// Reads the payload.
80    pub fn decode(payload: &[u8]) -> Result<Self> {
81        let bytes = <[u8; Self::LEN]>::try_from(payload)
82            .map_err(|_| Error::new(ErrorCode::MessageTruncated))?;
83        let (counter, response) = bytes.split_at(4);
84        let counter =
85            <[u8; 4]>::try_from(counter).map_err(|_| Error::new(ErrorCode::MessageTruncated))?;
86        let response = <[u8; CHALLENGE_LEN]>::try_from(response)
87            .map_err(|_| Error::new(ErrorCode::MessageTruncated))?;
88        Ok(Self {
89            counter: u32::from_le_bytes(counter),
90            response,
91        })
92    }
93
94    /// Whether this response answers `request` (§4.18.5).
95    ///
96    /// > The Response field corresponds to the Challenge field of the MsgCounterSyncReq message.
97    ///
98    /// Compared in constant time: the challenge is what stops an off-path attacker from
99    /// answering a synchronisation request with a counter of its choosing, and a comparison that
100    /// returned early would leak it one octet at a time.
101    #[must_use]
102    pub fn answers(&self, request: &SyncRequest) -> bool {
103        crate::crypto::ct_eq(&self.response, &request.challenge)
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn a_request_is_eight_octets_of_challenge() {
113        let request = SyncRequest {
114            challenge: [1, 2, 3, 4, 5, 6, 7, 8],
115        };
116        let mut buf = [0u8; 16];
117        assert_eq!(request.encode(&mut buf).unwrap(), &[1, 2, 3, 4, 5, 6, 7, 8]);
118        assert_eq!(
119            SyncRequest::decode(&[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(),
120            request
121        );
122        // Table 26 gives the field one size, so neither short nor long is the message.
123        assert!(SyncRequest::decode(&[1, 2, 3]).is_err());
124        assert!(SyncRequest::decode(&[0u8; 9]).is_err());
125    }
126
127    #[test]
128    fn a_response_is_a_counter_then_the_echoed_challenge() {
129        let response = SyncResponse {
130            counter: 0x0102_0304,
131            response: [9, 8, 7, 6, 5, 4, 3, 2],
132        };
133        let mut buf = [0u8; 16];
134        assert_eq!(
135            response.encode(&mut buf).unwrap(),
136            &[0x04, 0x03, 0x02, 0x01, 9, 8, 7, 6, 5, 4, 3, 2]
137        );
138        assert_eq!(
139            SyncResponse::decode(&[0x04, 0x03, 0x02, 0x01, 9, 8, 7, 6, 5, 4, 3, 2]).unwrap(),
140            response
141        );
142    }
143
144    #[test]
145    fn a_response_answers_only_its_own_challenge() {
146        let request = SyncRequest {
147            challenge: [1, 2, 3, 4, 5, 6, 7, 8],
148        };
149        let good = SyncResponse {
150            counter: 7,
151            response: request.challenge,
152        };
153        assert!(good.answers(&request));
154        let mut wrong = good;
155        wrong.response[7] ^= 1;
156        assert!(!wrong.answers(&request));
157    }
158}