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