Skip to main content

matter_kit/sc/
mod.rs

1//! The Secure Channel protocol: session establishment and status (Core §4.11, §4.14).
2//!
3//! Everything that happens before a node can say anything useful. PASE turns a printed
4//! passcode into the first session; CASE turns operational certificates into every session
5//! after that; [`StatusReport`] is how both of them, and every other
6//! protocol, report how it went.
7//!
8//! ```
9//! # #[cfg(feature = "rustcrypto")]
10//! # fn demo() -> Result<(), matter_kit::Error> {
11//! use matter_kit::sc::{PaseInitiator, PaseResponder, ResponderConfig, PbkdfParameters};
12//! use matter_kit::crypto::Spake2pVerifierData;
13//! use matter_kit::msg::SessionId;
14//!
15//! // What a factory burns into the device: the verifier for its printed passcode.
16//! let parameters = PbkdfParameters::new(1_000, b"SPAKE2P Key Salt")?;
17//! let verifier =
18//!     Spake2pVerifierData::from_passcode(20_202_021, &parameters.salt, parameters.iterations)?;
19//!
20//! let mut device = PaseResponder::new(
21//!     ResponderConfig { verifier, parameters: parameters.clone(), session_params: None },
22//!     SessionId(1),
23//! );
24//! let mut commissioner = PaseInitiator::new(20_202_021, SessionId(2), Some(parameters), None);
25//! # Ok(())
26//! # }
27//! ```
28//!
29//! `tests/pase_over_sim.rs` runs the whole exchange over the simulated network.
30
31/// PASE and CASE are cryptography; [`status`] is not, and every protocol needs it — so a
32/// node built without a [`crypto`](crate::crypto) backend still has
33/// [`StatusReport`](status::StatusReport).
34#[cfg(feature = "rustcrypto")]
35#[cfg_attr(docsrs, doc(cfg(feature = "rustcrypto")))]
36pub mod case;
37#[cfg(feature = "rustcrypto")]
38mod pase;
39pub mod status;
40
41#[cfg(feature = "rustcrypto")]
42pub use case::{
43    CaseInitiator, CaseOutcome, CaseResponder, MAX_ENCRYPTED2, MAX_ENCRYPTED3, MAX_SESSION_PARAMS,
44    MAX_SIGMA1, MAX_SIGMA2, MAX_SIGMA3, MAX_TBSDATA, ResumptionState, Sigma1, Sigma2, Sigma2Resume,
45    Sigma3, TbeData, Transcript,
46};
47#[cfg(feature = "rustcrypto")]
48pub(crate) use pase::Fields;
49#[cfg(feature = "rustcrypto")]
50pub use pase::{
51    PASSCODE_ID_COMMISSIONING, Pake1, Pake2, Pake3, PaseInitiator, PaseResponder,
52    PbkdfParamRequest, PbkdfParamResponse, PbkdfParameters, RANDOM_LEN, ResponderConfig,
53};
54pub use status::{GeneralCode, SecureChannelCode, StatusReport};
55
56#[cfg(feature = "rustcrypto")]
57use crate::error::{Error, ErrorCode, Result};
58use crate::exchange::MrpParams;
59use crate::platform::Duration;
60#[cfg(feature = "rustcrypto")]
61use crate::tlv::{Tag, TlvWriter};
62use crate::transport::TransportModes;
63
64/// The Secure Channel protocol opcodes of Core Table 18.
65///
66/// Every message on [`ProtocolId::SECURE_CHANNEL`](crate::msg::ProtocolId::SECURE_CHANNEL)
67/// carries one of these, and a receiver dispatches on it before it knows anything else about
68/// the payload.
69pub mod opcode {
70    /// `0x00` — Message Counter Synchronization Request.
71    pub const MSG_COUNTER_SYNC_REQ: u8 = 0x00;
72    /// `0x01` — Message Counter Synchronization Response.
73    pub const MSG_COUNTER_SYNC_RSP: u8 = 0x01;
74    /// `0x10` — MRP Standalone Acknowledgement (§4.12.7.1).
75    ///
76    /// "This message is dedicated for the purpose of sending a stand-alone acknowledgement
77    /// when there is no other data message available to piggyback an acknowledgement on top
78    /// of." Its payload is empty and it is never itself reliable — acknowledging an
79    /// acknowledgement would not terminate.
80    pub const MRP_STANDALONE_ACK: u8 = 0x10;
81    /// `0x20` — `PBKDFParamRequest`, the first message of PASE.
82    pub const PBKDF_PARAM_REQUEST: u8 = 0x20;
83    /// `0x21` — `PBKDFParamResponse`.
84    pub const PBKDF_PARAM_RESPONSE: u8 = 0x21;
85    /// `0x22` — PASE `Pake1`, "the first PAKE message of the PASE protocol".
86    pub const PAKE1: u8 = 0x22;
87    /// `0x23` — PASE `Pake2`.
88    pub const PAKE2: u8 = 0x23;
89    /// `0x24` — PASE `Pake3`.
90    pub const PAKE3: u8 = 0x24;
91    /// `0x30` — CASE `Sigma1`.
92    pub const SIGMA1: u8 = 0x30;
93    /// `0x31` — CASE `Sigma2`.
94    pub const SIGMA2: u8 = 0x31;
95    /// `0x32` — CASE `Sigma3`.
96    pub const SIGMA3: u8 = 0x32;
97    /// `0x33` — CASE `Sigma2_Resume`.
98    pub const SIGMA2_RESUME: u8 = 0x33;
99    /// `0x40` — `StatusReport` (Appendix D).
100    pub const STATUS_REPORT: u8 = 0x40;
101    /// `0x50` — the ICD Check-In message (§4.22).
102    pub const ICD_CHECK_IN: u8 = 0x50;
103}
104
105/// `session-parameter-struct` — what each side announces about itself during session
106/// establishment (Core §4.13.1, Table 23).
107///
108/// It rides in five messages: CASE `Sigma1`, `Sigma2` and `Sigma2_Resume`, and PASE
109/// `PBKDFParamRequest` and `PBKDFParamResponse`. Nine fields, and the shape of the struct is
110/// **not** the shape of the schema, deliberately:
111///
112/// | Tag | Field | §4.13.1 | Here |
113/// |---|---|---|---|
114/// | 1 | `SESSION_IDLE_INTERVAL` | optional | always sent |
115/// | 2 | `SESSION_ACTIVE_INTERVAL` | optional | always sent — see below |
116/// | 3 | `SESSION_ACTIVE_THRESHOLD` | optional | always sent |
117/// | 4 | `DATA_MODEL_REVISION` | mandatory | [`Self::data_model_revision`] |
118/// | 5 | `INTERACTION_MODEL_REVISION` | mandatory | [`Self::interaction_model_revision`] |
119/// | 6 | `SPECIFICATION_VERSION` | mandatory | [`Self::specification_version`] |
120/// | 7 | `MAX_PATHS_PER_INVOKE` | mandatory | [`Self::max_paths_per_invoke`] |
121/// | 8 | `SUPPORTED_TRANSPORTS` | mandatory | [`Self::supported_transports`] |
122/// | 9 | `MAX_TCP_MESSAGE_SIZE` | optional | [`Self::max_tcp_message_size`] |
123///
124/// **Why no field is an `Option` except the last.** Tags 4–8 have been mandatory since
125/// Matter 1.3, so a struct that can omit them is a struct that can represent a message the
126/// specification forbids. Tags 1–3 stay optional in the schema, but §4.13.1 adds "if any tag
127/// after tag 2 (SESSION_ACTIVE_INTERVAL) is present, then the SESSION_ACTIVE_INTERVAL SHALL
128/// also be present" — and tags 4–8 are always present — so tag 2 is mandatory in practice,
129/// and sending 1 and 3 alongside it costs eight octets and removes two more `Option`s. What
130/// is left optional is the one field that genuinely is: `MAX_TCP_MESSAGE_SIZE`, which is
131/// meaningless on a node that does not speak TCP.
132///
133/// The consequence that matters is that **this struct cannot encode to an empty structure**.
134/// The previous shape — three `Option`s and a derived `Default` — could, and did: every
135/// released CHIP SDK refuses an empty `session-parameter-struct`, because
136/// `PairingSession::DecodeSessionParametersIfPresent` calls `Next()` once without guarding
137/// it against `CHIP_END_OF_TLV` where every later call in the same function is guarded. A
138/// conformant struct is never empty, so conformance and interoperability close the same hole
139/// (D77).
140///
141/// **Receiving is the asymmetric half.** A peer older than 1.3 sends only tags 1–3, so
142/// `SessionParams::decode` — crate-private, because a peer's parameters reach this crate only
143/// inside a message it parses — starts from [`SessionParams::legacy_peer`], Table 23's default
144/// for every parameter, and overwrites what the peer actually sent. Table 23 requires
145/// exactly that: "A Node SHALL use the provided default value for each parameter unless the
146/// message recipient Node advertises an alternate value".
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct SessionParams {
149    /// `SESSION_IDLE_INTERVAL [1]`, in milliseconds — "minimum amount of time between sender
150    /// retries when the destination node is Idle". Table 23's default is 500 ms.
151    pub idle_interval_ms: u32,
152    /// `SESSION_ACTIVE_INTERVAL [2]`, in milliseconds — the same when the destination is
153    /// Active. Table 23's default is 300 ms.
154    pub active_interval_ms: u32,
155    /// `SESSION_ACTIVE_THRESHOLD [3]`, in milliseconds — "minimum amount of time the node
156    /// SHOULD stay active after network activity". Table 23's default is 4000 ms.
157    pub active_threshold_ms: u16,
158    /// `DATA_MODEL_REVISION [4]` — §7.1.1's revision. [`crate::DATA_MODEL_REVISION`] here.
159    pub data_model_revision: u16,
160    /// `INTERACTION_MODEL_REVISION [5]` — §8.1.1's revision.
161    /// [`crate::im::INTERACTION_MODEL_REVISION`] here.
162    pub interaction_model_revision: u16,
163    /// `SPECIFICATION_VERSION [6]` — §11.1.5.22's four component bytes.
164    /// [`crate::SPECIFICATION_VERSION`] here.
165    pub specification_version: u32,
166    /// `MAX_PATHS_PER_INVOKE [7]` — "the maximum number of elements in the InvokeRequests
167    /// list that the Node is able to process". §11.1.5.23: "If the MaxPathsPerInvoke
168    /// attribute is absent or zero … clients SHALL assume a value of 1", so 1 is the floor
169    /// and never 0.
170    pub max_paths_per_invoke: u16,
171    /// `SUPPORTED_TRANSPORTS [8]` — Table 7's bitmap, "in addition to MRP". Empty means MRP
172    /// only, which is every node that does not speak TCP.
173    pub supported_transports: TransportModes,
174    /// `MAX_TCP_MESSAGE_SIZE [9]`, in octets — "maximum size of the message carried over
175    /// TCP, excluding the framing message length field, that the node is capable of
176    /// receiving". `None` on a node with no TCP; Table 23's default is 64000.
177    pub max_tcp_message_size: Option<u32>,
178}
179
180impl SessionParams {
181    /// Table 23's default `MAX_TCP_MESSAGE_SIZE`.
182    ///
183    /// The three MRP timings have defaults too, and they are not repeated here: Table 22 and
184    /// Table 23 are the same three numbers, and [`MrpParams::default`] already carries them.
185    /// Two copies of a specification default are two things to forget at an uplift.
186    pub const DEFAULT_MAX_TCP_MESSAGE_SIZE: u32 = 64_000;
187
188    /// What a peer is assumed to be when it sends no `session-parameter-struct` at all, or
189    /// one from before Matter 1.3 — every parameter at Table 23's default.
190    ///
191    /// The revisions are the **floors**, not this crate's values, and that is the whole
192    /// point: §4.13.1 says "if the DATA_MODEL_REVISION field is missing, it implies a
193    /// DataModelRevision value of either 16 or 17", so a peer that omitted it is a 1.0-era
194    /// peer and must be treated as one. Assuming this node's own revisions for a silent peer
195    /// would be assuming the peer understands everything this node does.
196    #[must_use]
197    pub fn legacy_peer() -> Self {
198        // Table 22's MRP defaults and Table 23's session defaults are the same three numbers,
199        // so they come from the one place that already holds them. The revisions are 1.0's:
200        // §7.1.1's 16, §8.1.1's 10, and specification 1.0.0.0.
201        Self::announce_with_revisions(&MrpParams::default(), 16, 10, 0x0100_0000)
202    }
203
204    /// The shared body of [`Self::announce`] and [`Self::legacy_peer`]: the same nine fields,
205    /// differing only in whose revisions they carry.
206    fn announce_with_revisions(
207        mrp: &MrpParams,
208        data_model_revision: u16,
209        interaction_model_revision: u16,
210        specification_version: u32,
211    ) -> Self {
212        Self {
213            idle_interval_ms: clamp_ms_u32(mrp.idle_interval),
214            active_interval_ms: clamp_ms_u32(mrp.active_interval),
215            active_threshold_ms: clamp_ms_u16(mrp.active_threshold),
216            data_model_revision,
217            interaction_model_revision,
218            specification_version,
219            // §11.1.5.23: "absent or zero … clients SHALL assume a value of 1".
220            max_paths_per_invoke: 1,
221            // Table 7's bitmap is "in addition to MRP", so empty is MRP only.
222            supported_transports: TransportModes::empty(),
223            max_tcp_message_size: None,
224        }
225    }
226
227    /// What this node announces: its own MRP timings, and this crate's revisions.
228    ///
229    /// `MAX_PATHS_PER_INVOKE` starts at 1 — §11.1.5.23's floor, and the value a node that
230    /// has not thought about batched Invoke must report — and `SUPPORTED_TRANSPORTS` starts
231    /// empty. Both are raised with the builders below, and both must match what the node
232    /// actually does: a peer is entitled to send `MAX_PATHS_PER_INVOKE` commands in one
233    /// Invoke and to open a TCP connection if this says it may.
234    #[must_use]
235    pub fn announce(mrp: &MrpParams) -> Self {
236        Self::announce_with_revisions(
237            mrp,
238            crate::DATA_MODEL_REVISION,
239            crate::im::INTERACTION_MODEL_REVISION,
240            crate::SPECIFICATION_VERSION,
241        )
242    }
243
244    /// Announces a `MAX_PATHS_PER_INVOKE` above the floor.
245    ///
246    /// Clamped to at least 1, because §11.1.5.23 makes zero mean one and a zero on the wire
247    /// would be read as "absent" by a peer that follows it.
248    #[must_use]
249    pub const fn with_max_paths_per_invoke(mut self, max: u16) -> Self {
250        self.max_paths_per_invoke = if max == 0 { 1 } else { max };
251        self
252    }
253
254    /// Announces the transports this node supports in addition to MRP, and the largest TCP
255    /// message it can receive.
256    ///
257    /// The two travel together because one without the other is a contradiction: a size for
258    /// a transport that was not announced tells a peer nothing, and announcing
259    /// [`TransportModes::TCP_SERVER`] without a size leaves the peer on Table 23's 64000.
260    #[must_use]
261    pub const fn with_transports(mut self, modes: TransportModes, max_tcp_message: u32) -> Self {
262        self.supported_transports = modes;
263        self.max_tcp_message_size = if modes.is_empty() {
264            None
265        } else {
266            Some(max_tcp_message)
267        };
268        self
269    }
270
271    /// Turns an announcement into MRP parameters, clamping what the peer sent.
272    ///
273    /// The clamping is not optional politeness: these values decide how long this node
274    /// waits before retransmitting, and they came from a stranger.
275    #[must_use]
276    pub fn to_mrp(self) -> MrpParams {
277        MrpParams {
278            idle_interval: Duration::from_millis(u64::from(self.idle_interval_ms)),
279            active_interval: Duration::from_millis(u64::from(self.active_interval_ms)),
280            active_threshold: Duration::from_millis(u64::from(self.active_threshold_ms)),
281        }
282        .clamped()
283    }
284
285    /// Whether the peer said it will accept a TCP connection (Table 7, bit 2).
286    #[must_use]
287    pub const fn accepts_tcp(&self) -> bool {
288        self.supported_transports
289            .contains(TransportModes::TCP_SERVER)
290    }
291
292    /// The largest TCP message the peer said it can receive, or Table 23's default.
293    #[must_use]
294    pub const fn max_tcp_message_size_or_default(&self) -> u32 {
295        match self.max_tcp_message_size {
296            Some(n) => n,
297            None => Self::DEFAULT_MAX_TCP_MESSAGE_SIZE,
298        }
299    }
300
301    #[cfg(feature = "rustcrypto")]
302    pub(crate) fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
303        w.start_structure(tag)?;
304        // Tags 1-3 are optional in the schema and unconditional here: §4.13.1 requires tag 2
305        // whenever anything after it is present, and tags 4-8 always are.
306        w.unsigned(Tag::Context(1), u64::from(self.idle_interval_ms))?;
307        w.unsigned(Tag::Context(2), u64::from(self.active_interval_ms))?;
308        w.unsigned(Tag::Context(3), u64::from(self.active_threshold_ms))?;
309        w.unsigned(Tag::Context(4), u64::from(self.data_model_revision))?;
310        w.unsigned(Tag::Context(5), u64::from(self.interaction_model_revision))?;
311        w.unsigned(Tag::Context(6), u64::from(self.specification_version))?;
312        w.unsigned(Tag::Context(7), u64::from(self.max_paths_per_invoke))?;
313        w.unsigned(Tag::Context(8), u64::from(self.supported_transports.bits()))?;
314        if let Some(size) = self.max_tcp_message_size {
315            w.unsigned(Tag::Context(9), u64::from(size))?;
316        }
317        w.end_container()
318    }
319
320    /// Reads a `session-parameter-struct` whose opening element the caller has just taken.
321    ///
322    /// Absent fields keep [`SessionParams::legacy_peer`]'s value rather than becoming `None`,
323    /// which is what Table 23 asks for: "A Node SHALL use the provided default value for each
324    /// parameter unless the message recipient Node advertises an alternate value".
325    ///
326    /// This is a *nested* structure, so it reads through [`Fields::nested`]: without that the
327    /// loop runs past its own end-of-container and swallows whatever follows it in the
328    /// enclosing message. In a Sigma1 that is the resumption id and MIC, so an initiator that
329    /// announced its MRP parameters would have its resumption request silently dropped and
330    /// fall back to a full handshake — a failure with no error anywhere.
331    #[cfg(feature = "rustcrypto")]
332    pub(crate) fn decode(fields: &mut pase::Fields<'_>) -> Result<Self> {
333        fields.nested(|fields| {
334            let mut out = Self::legacy_peer();
335            let mut seen = 0u32;
336            while let Some((tag, element)) = fields.next()? {
337                // Core §A.5.1: members of a structure have unique tags.
338                if tag < 32 {
339                    let bit = 1u32 << tag;
340                    if seen & bit != 0 {
341                        return Err(Error::new(ErrorCode::TlvDuplicateTag));
342                    }
343                    seen |= bit;
344                }
345                match tag {
346                    1 => out.idle_interval_ms = saturating_u32(element.unsigned()?),
347                    2 => out.active_interval_ms = saturating_u32(element.unsigned()?),
348                    3 => out.active_threshold_ms = saturating_u16(element.unsigned()?),
349                    4 => out.data_model_revision = saturating_u16(element.unsigned()?),
350                    5 => out.interaction_model_revision = saturating_u16(element.unsigned()?),
351                    6 => out.specification_version = saturating_u32(element.unsigned()?),
352                    // §11.1.5.23: zero means one.
353                    7 => out.max_paths_per_invoke = saturating_u16(element.unsigned()?).max(1),
354                    // Bit 0 is reserved and "clients SHALL silently ignore this bit", which
355                    // `from_bits_truncate` does along with every other unknown bit.
356                    8 => {
357                        out.supported_transports =
358                            TransportModes::from_bits_truncate(saturating_u32(element.unsigned()?));
359                    }
360                    9 => out.max_tcp_message_size = Some(saturating_u32(element.unsigned()?)),
361                    // A later revision adds fields here; an older node skips what it does not
362                    // know rather than refusing the session.
363                    _ => fields.skip(&element)?,
364                }
365            }
366            Ok(out)
367        })
368    }
369}
370
371impl Default for SessionParams {
372    /// This node's announcement with Table 22's MRP timings — the same thing
373    /// [`SessionParams::announce`] builds from [`MrpParams::default`].
374    ///
375    /// A `Default` here was once the defect rather than the convenience: when every field was
376    /// an `Option`, the derived `Default` was three `None`s and encoded to an empty structure
377    /// that every released CHIP SDK refuses (D77). It is safe now for a structural reason
378    /// rather than a careful one — §4.13.1's tags 4-8 are mandatory, so they are plain fields,
379    /// and there is no combination of this type that encodes to an empty container.
380    fn default() -> Self {
381        Self::announce(&MrpParams::default())
382    }
383}
384
385/// An MRP interval in milliseconds, saturating.
386///
387/// `MrpParams` is already clamped to §4.13.1's ceilings by [`MrpParams::clamped`], so this
388/// only has to be total, not lossy in practice.
389fn clamp_ms_u32(d: Duration) -> u32 {
390    u32::try_from(d.as_millis()).unwrap_or(u32::MAX)
391}
392
393fn clamp_ms_u16(d: Duration) -> u16 {
394    u16::try_from(d.as_millis()).unwrap_or(u16::MAX)
395}
396
397/// Narrows a TLV unsigned to `u32`, saturating rather than failing.
398///
399/// Every one of these fields is schema-constrained to 16 or 32 bits, so a wider value is a
400/// peer that is wrong. Refusing the session over it would be a denial of service with extra
401/// steps; saturating keeps the clamp in [`SessionParams::to_mrp`] in charge of the only
402/// values that can hurt this node.
403#[cfg(feature = "rustcrypto")]
404const fn saturating_u32(v: u64) -> u32 {
405    if v > u32::MAX as u64 {
406        u32::MAX
407    } else {
408        v as u32
409    }
410}
411
412#[cfg(feature = "rustcrypto")]
413const fn saturating_u16(v: u64) -> u16 {
414    if v > u16::MAX as u64 {
415        u16::MAX
416    } else {
417        v as u16
418    }
419}