matter_kit/sc/channel.rs
1//! The secure channel a node answers on: §5.5's rules, both handshakes, and the session they
2//! produce.
3//!
4//! [`PaseResponder`] and [`CaseResponder`] are state machines over their own messages, and it is
5//! right that they are: they take their inputs as parameters, so a test drives them with
6//! fixtures and no node. What neither of them is, is *the node's secure channel* — and the
7//! difference is a list of rules that belong to no handshake:
8//!
9//! * **§5.5's three admission rules.** One handshake at a time, sixty seconds to finish it,
10//! twenty failures and commissioning mode ends. None is a property of SPAKE2+; all three are
11//! properties of the channel it runs on, and a node that answers every `PBKDFParamRequest`
12//! unconditionally lets a second commissioner step into the first one's handshake and finish
13//! it in their place. A published analysis of Matter found exactly that missing from a
14//! *certified* implementation ([`commissioning::admission`](crate::commissioning::admission)).
15//! * **§11.19.8.1's ephemeral verifier.** While an Enhanced Commissioning window is open, PASE
16//! runs against the verifier the administrator supplied — not the factory passcode. A node
17//! that answers with its own is a node whose printed passcode still works after an
18//! administrator deliberately replaced it.
19//! * **§4.11.1.1's eviction.** The session a handshake produces has to go somewhere, and when
20//! there is no room the least recently used one is evicted and told so.
21//! * **§6.2.3's attestation challenge.** PASE produces it beside the session keys, it never
22//! crosses the wire, and `AttestationRequest` signs over it. A node that forgets to keep it
23//! cannot answer the command that proves it is a genuine device.
24//!
25//! Every one of those was, until this module existed, the application's to remember — which in
26//! this repository meant two hundred lines of `examples/light.rs`, where seven of the
27//! interoperability defects found so far have lived.
28//!
29//! # What it does not own
30//!
31//! The socket, the clock and the buffers. [`Channel::on_message`] is sans-I/O like everything
32//! else here: it is handed the opcode and the body, and it returns what to send. The caller
33//! still decides when to read and when to write, and still owns the interaction model above it.
34
35use core::cell::RefCell;
36
37use crate::commissioning::admission::{Admit, PaseAdmission};
38use crate::commissioning::window::CommissioningWindow;
39use crate::config::Config;
40use crate::crypto::{KeyStore, Spake2pVerifierData, SymmetricKey};
41use crate::error::Result;
42use crate::fabric::FabricTable;
43use crate::messaging::{Evicted, Messaging};
44use crate::msg::{FabricIndex, SessionId};
45use crate::platform::{Instant, Rng};
46use crate::sc::status::{SecureChannelCode, StatusReport};
47use crate::sc::{
48 CaseResponder, PaseResponder, PbkdfParameters, ResponderConfig, SessionParams, Sigma1, Sigma3,
49 opcode,
50};
51use crate::session::{Role, SecureSession, SessionKind};
52
53/// What the node brings to a handshake: its credentials, its randomness and its clock.
54///
55/// Borrowed rather than owned, and per call rather than per channel, because every one of these
56/// belongs to the node and outlives any one handshake — and because a `Channel` that owned them
57/// would need six type parameters to say so.
58pub struct ChannelContext<'a, C: Config, const N: usize, K: KeyStore, R: Rng> {
59 /// The fabrics `AddNOC` created, which is what CASE resolves a destination identifier
60 /// against.
61 pub fabrics: &'a RefCell<FabricTable<C, N>>,
62 /// Where private keys live: the key store is the platform's, never this crate's.
63 pub keys: &'a RefCell<K>,
64 /// The only source of randomness the handshakes have.
65 pub rng: &'a R,
66 /// The commissioning window, which decides whether PASE runs against the factory verifier
67 /// or an administrator's (§11.19.8.1), and which closes after twenty failures.
68 pub window: &'a RefCell<CommissioningWindow>,
69 /// The factory SPAKE2+ verifier, derived from the printed passcode at manufacture.
70 pub verifier: &'a Spake2pVerifierData,
71 /// The PBKDF parameters that verifier was derived with.
72 pub parameters: &'a PbkdfParameters,
73 /// Now. Nothing in this crate reads a clock for itself, so the caller says what time it is.
74 pub now: Instant,
75}
76
77/// The three buffers a handshake needs, named rather than positional.
78///
79/// All three are `&mut [u8]`, so passing them in the wrong order type-checks — and the failure
80/// would be a reply written into the buffer holding the eviction report, which is a message sent
81/// to the wrong peer rather than a compile error. They are named for the same reason
82/// [`Sigma2Randomness`](super::case::Sigma2Randomness) is.
83pub struct ChannelBuffers<'a> {
84 /// Where the answer to this message is written.
85 pub reply: &'a mut [u8],
86 /// Scratch for framing, when installing a session has to evict one.
87 pub frame: &'a mut [u8],
88 /// Where §4.11.1.1's `CloseSession` report to the evicted peer is left, ready to send.
89 pub evict: &'a mut [u8],
90}
91
92/// A session this channel established, and everything the node needs to know about it.
93#[derive(Debug, Clone)]
94#[non_exhaustive]
95pub struct Established {
96 /// The local session id it was installed under.
97 pub session: SessionId,
98 /// Which handshake produced it.
99 pub kind: SessionKind,
100 /// The fabric, for a CASE session; [`FabricIndex::NONE`] for PASE, which has none until
101 /// §11.18.6.8 step 10a binds one.
102 pub fabric: FabricIndex,
103 /// §6.2.3's attestation challenge, for a PASE session.
104 ///
105 /// It never crosses the wire and `AttestationRequest` signs over it, so a node that drops it
106 /// cannot answer the one command that proves it is a genuine device.
107 pub challenge: Option<SymmetricKey>,
108}
109
110/// What [`Channel::on_message`] produced.
111#[derive(Debug)]
112#[non_exhaustive]
113pub struct ChannelReply {
114 /// The opcode to send back, and how much of the reply buffer it occupies.
115 ///
116 /// `None` means say nothing: a message for a handshake that is not running is dropped
117 /// rather than answered, because answering it would tell a stranger what state the node is
118 /// in.
119 pub reply: Option<(u8, usize)>,
120 /// The session this message completed, if it completed one.
121 pub established: Option<Established>,
122 /// A session evicted to make room for it (§4.11.1.1), whose peer is owed the report already
123 /// framed in the eviction buffer.
124 pub evicted: Option<Evicted>,
125}
126
127impl ChannelReply {
128 const SILENT: Self = Self {
129 reply: None,
130 established: None,
131 evicted: None,
132 };
133
134 const fn answer(opcode: u8, len: usize) -> Self {
135 Self {
136 reply: Some((opcode, len)),
137 established: None,
138 evicted: None,
139 }
140 }
141}
142
143/// The secure channel of one node: §5.5's admission rules, PASE, CASE, and session installation.
144///
145/// One at a time by construction — §5.5's first rule is that a node runs one handshake at a
146/// time, so there is one slot for each kind and the type cannot represent two.
147#[derive(Debug)]
148pub struct Channel {
149 admission: PaseAdmission,
150 pase: Option<PaseResponder>,
151 pase_local: SessionId,
152 case: Option<CaseResponder>,
153 case_local: SessionId,
154 case_fabric: FabricIndex,
155 challenge: Option<SymmetricKey>,
156}
157
158impl Default for Channel {
159 fn default() -> Self {
160 Self::new()
161 }
162}
163
164impl Channel {
165 /// A channel with nothing in flight.
166 #[must_use]
167 pub const fn new() -> Self {
168 Self {
169 admission: PaseAdmission::new(),
170 pase: None,
171 pase_local: SessionId(0),
172 case: None,
173 case_local: SessionId(0),
174 case_fabric: FabricIndex::NONE,
175 challenge: None,
176 }
177 }
178
179 /// §6.2.3's attestation challenge from the PASE session in progress or just established.
180 #[must_use]
181 pub fn attestation_challenge(&self) -> Option<&SymmetricKey> {
182 self.challenge.as_ref()
183 }
184
185 /// Whether §5.5's channel is currently held by an established PASE session.
186 #[must_use]
187 pub const fn is_established(&self) -> bool {
188 self.admission.is_established()
189 }
190
191 /// Re-admits PASE, which is what *opening* a commissioning window means (§5.5).
192 ///
193 /// A node commissioned once is not admitting anybody: the channel stays shut from the moment
194 /// PASE succeeded until something says otherwise. Without this a node can never be
195 /// commissioned twice — `OpenCommissioningWindow` succeeds, the node advertises, and every
196 /// `PBKDFParamRequest` comes back `Busy`.
197 pub const fn reopen(&mut self) {
198 self.admission.reset();
199 }
200
201 /// Releases the channel when the PASE session on it closes (§5.5).
202 ///
203 /// "until session establishment fails or the successfully established PASE session is
204 /// terminated on the commissioning channel" — and a commissioner is under no obligation to
205 /// say so politely, which is why [`Received::SessionClosed`](crate::messaging::Received)
206 /// and a closed commissioning window both end up here.
207 pub fn closed(&mut self, session: SessionId) {
208 if session == self.pase_local {
209 self.admission.closed();
210 self.pase = None;
211 self.challenge = None;
212 }
213 }
214
215 /// Releases the channel without naming a session.
216 ///
217 /// §5.5 releases it when "the successfully established PASE session is terminated on the
218 /// commissioning channel" — and a commissioner is under no obligation to terminate it
219 /// politely. The CHIP controller calls `StopPairing`, evicts its own session, says nothing,
220 /// and opens a fresh PASE five seconds later; a node holding the channel answers `Busy` for
221 /// ever, which looks exactly like a device ignoring its own open commissioning window.
222 ///
223 /// So a device that can see commissioning has finished — an open window with a disarmed
224 /// fail-safe is the honest reading — says so here. [`Channel::closed`] is the tidier path
225 /// and applies when the session id is known.
226 pub fn release(&mut self) {
227 self.admission.closed();
228 self.pase = None;
229 }
230
231 /// When §5.5's sixty seconds runs out on the handshake in flight, if one is.
232 ///
233 /// A deadline like any other, so it goes where the loop's other deadlines go rather than
234 /// into a special case: `None` means nothing is waiting.
235 #[must_use]
236 pub const fn deadline(&self) -> Option<Instant> {
237 self.admission.deadline()
238 }
239
240 /// Drives the deadlines §5.5 puts on a handshake in flight.
241 ///
242 /// Call it from the run loop. A handshake that was abandoned holds the channel until it is
243 /// reaped, and one unanswered request would otherwise lock a device out of commissioning for
244 /// good.
245 pub fn poll(&mut self, now: Instant, window: &RefCell<CommissioningWindow>) {
246 if let Some(failure) = self.admission.poll(now) {
247 self.pase = None;
248 if failure.exit_commissioning_mode {
249 window.borrow_mut().close();
250 }
251 }
252 }
253
254 /// Answers one Secure Channel message (§4.11's opcodes).
255 ///
256 /// `reply` is where the answer is written. `frame` and `evict` are the two buffers
257 /// [`Messaging::install_session`] needs when a session has to be evicted to make room —
258 /// §4.11.1.1's report is framed under the evicted session's own keys, so it has to be built
259 /// before that session goes away, and the caller sends it afterwards.
260 ///
261 /// An opcode this channel does not serve comes back with no reply at all, rather than an
262 /// error: a message for a handshake that is not running tells a stranger nothing about the
263 /// node, and a node that answered would say which handshake it is in the middle of.
264 pub fn on_message<C, const S: usize, const X: usize, const N: usize, K, R>(
265 &mut self,
266 stack: &mut Messaging<C, S, X>,
267 opcode: u8,
268 body: &[u8],
269 ctx: &ChannelContext<'_, C, N, K, R>,
270 buffers: &mut ChannelBuffers<'_>,
271 ) -> Result<ChannelReply>
272 where
273 C: Config,
274 K: KeyStore,
275 R: Rng,
276 {
277 match opcode {
278 opcode::PBKDF_PARAM_REQUEST => self.pbkdf_param_request(body, ctx, buffers.reply),
279 opcode::PAKE1 => self.pake1(body, ctx, buffers.reply),
280 opcode::PAKE3 => self.pake3(stack, body, ctx, buffers),
281 opcode::SIGMA1 => self.sigma1(body, ctx, buffers.reply),
282 opcode::SIGMA3 => self.sigma3(stack, body, ctx, buffers),
283 _ => Ok(ChannelReply::SILENT),
284 }
285 }
286
287 /// §5.5's gate, then §4.14.1's first message.
288 fn pbkdf_param_request<C, const N: usize, K, R>(
289 &mut self,
290 body: &[u8],
291 ctx: &ChannelContext<'_, C, N, K, R>,
292 reply: &mut [u8],
293 ) -> Result<ChannelReply>
294 where
295 C: Config,
296 K: KeyStore,
297 R: Rng,
298 {
299 match self.admission.admit(true, ctx.now) {
300 Admit::Admitted => {}
301 refusal => {
302 // §4.11.1.3's codes: `Busy` says "not now", which is true while another
303 // commissioner holds the channel. The rest will not change until the device is
304 // put back into commissioning mode.
305 let code = if matches!(refusal, Admit::Busy) {
306 SecureChannelCode::Busy
307 } else {
308 SecureChannelCode::InvalidParameter
309 };
310 let len = StatusReport::secure_channel(code).encode(reply)?;
311 return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
312 }
313 }
314
315 // §11.19.8.1: an Enhanced window runs PASE against the verifier the *administrator*
316 // supplied, with that command's salt and iteration count. A Basic window carries no
317 // verifier and falls back to the factory one, which is what makes it Basic.
318 let ephemeral = ctx.window.borrow().ephemeral(ctx.now).and_then(|e| {
319 let verifier = Spake2pVerifierData::from_bytes(&e.verifier).ok()?;
320 let parameters = PbkdfParameters::new(e.iterations, &e.salt).ok()?;
321 Some((verifier, parameters))
322 });
323 let (verifier, parameters) = match ephemeral {
324 Some(pair) => pair,
325 None => (*ctx.verifier, ctx.parameters.clone()),
326 };
327
328 let mut responder = PaseResponder::new(
329 ResponderConfig {
330 verifier,
331 parameters,
332 session_params: Some(SessionParams::default()),
333 },
334 // A session id nothing else is using, with the low bit set so it is never zero —
335 // §4.13.2.4 reserves that for the unsecured session.
336 SessionId(ctx.rng.next_u32()? as u16 | 1),
337 );
338 let mut random = [0u8; 32];
339 ctx.rng.fill(&mut random)?;
340 match responder.on_pbkdf_param_request(body, &random, reply) {
341 Ok(len) => {
342 self.pase_local = responder.local_session_id();
343 self.pase = Some(responder);
344 Ok(ChannelReply::answer(opcode::PBKDF_PARAM_RESPONSE, len))
345 }
346 // A request this node could not parse is a failed attempt like any other: it frees
347 // the channel, and it counts towards the twenty.
348 Err(e) => {
349 self.fail(ctx.window);
350 Err(e)
351 }
352 }
353 }
354
355 fn pake1<C, const N: usize, K, R>(
356 &mut self,
357 body: &[u8],
358 ctx: &ChannelContext<'_, C, N, K, R>,
359 reply: &mut [u8],
360 ) -> Result<ChannelReply>
361 where
362 C: Config,
363 K: KeyStore,
364 R: Rng,
365 {
366 let Some(pase) = self.pase.as_mut() else {
367 return Ok(ChannelReply::SILENT);
368 };
369 let mut random = [0u8; 32];
370 ctx.rng.fill(&mut random)?;
371 match pase.on_pake1(body, &random, reply) {
372 Ok(len) => Ok(ChannelReply::answer(opcode::PAKE2, len)),
373 Err(e) => {
374 self.fail(ctx.window);
375 Err(e)
376 }
377 }
378 }
379
380 /// The last PASE message, and the session it produces.
381 fn pake3<C, const S: usize, const X: usize, const N: usize, K, R>(
382 &mut self,
383 stack: &mut Messaging<C, S, X>,
384 body: &[u8],
385 ctx: &ChannelContext<'_, C, N, K, R>,
386 buffers: &mut ChannelBuffers<'_>,
387 ) -> Result<ChannelReply>
388 where
389 C: Config,
390 K: KeyStore,
391 R: Rng,
392 {
393 let Some(pase) = self.pase.as_mut() else {
394 return Ok(ChannelReply::SILENT);
395 };
396 let (len, keys) = match pase.on_pake3(body, buffers.reply) {
397 Ok(pair) => pair,
398 Err(e) => {
399 self.fail(ctx.window);
400 return Err(e);
401 }
402 };
403 let challenge = keys.attestation_challenge.clone();
404 let session = SecureSession::new(
405 self.pase_local,
406 pase.peer_session_id(),
407 SessionKind::Pase,
408 Role::Responder,
409 keys,
410 ctx.rng.next_u32()?,
411 ctx.now,
412 );
413 let evicted = match stack.install_session(
414 session,
415 ctx.now,
416 ctx.rng.next_u32()?,
417 buffers.frame,
418 buffers.evict,
419 ) {
420 Ok(evicted) => evicted,
421 Err(e) => {
422 self.fail(ctx.window);
423 return Err(e);
424 }
425 };
426 self.challenge = Some(challenge.clone());
427 // §5.5 rule 1 holds "or has successfully established a session": the channel stays shut
428 // until that session is closed.
429 self.admission.established();
430 Ok(ChannelReply {
431 reply: Some((opcode::STATUS_REPORT, len)),
432 established: Some(Established {
433 session: self.pase_local,
434 kind: SessionKind::Pase,
435 fabric: FabricIndex::NONE,
436 challenge: Some(challenge),
437 }),
438 evicted,
439 })
440 }
441
442 /// §4.14.2.3's Sigma1, answered against the fabric its destination identifier names.
443 fn sigma1<C, const N: usize, K, R>(
444 &mut self,
445 body: &[u8],
446 ctx: &ChannelContext<'_, C, N, K, R>,
447 reply: &mut [u8],
448 ) -> Result<ChannelReply>
449 where
450 C: Config,
451 K: KeyStore,
452 R: Rng,
453 {
454 let local = SessionId(ctx.rng.next_u32()? as u16 | 1);
455 let mut responder_random = [0u8; 32];
456 let mut ephemeral = [0u8; 32];
457 let mut resumption = [0u8; 16];
458 ctx.rng.fill(&mut responder_random)?;
459 ctx.rng.fill(&mut ephemeral)?;
460 ctx.rng.fill(&mut resumption)?;
461
462 let accepted = Sigma1::decode(body).and_then(|sigma1| {
463 super::case::accept_sigma1(
464 &sigma1,
465 &ctx.fabrics.borrow(),
466 &mut *ctx.keys.borrow_mut(),
467 local,
468 Some(SessionParams::default()),
469 &super::case::Sigma2Randomness {
470 ephemeral: &ephemeral,
471 responder: &responder_random,
472 resumption: &resumption,
473 },
474 reply,
475 )
476 });
477 match accepted {
478 Ok((responder, fabric, len)) => {
479 self.case_local = local;
480 self.case_fabric = fabric;
481 self.case = Some(responder);
482 Ok(ChannelReply::answer(opcode::SIGMA2, len))
483 }
484 // §4.11.1.3: no fabric matched, which is the ordinary answer to a Sigma1 meant for
485 // another node on the link. The initiator is told so rather than left waiting.
486 Err(_) => {
487 self.case = None;
488 let len = StatusReport::secure_channel(SecureChannelCode::NoSharedTrustRoots)
489 .encode(reply)?;
490 Ok(ChannelReply::answer(opcode::STATUS_REPORT, len))
491 }
492 }
493 }
494
495 /// Sigma3, validated against the root of the fabric Sigma1 resolved.
496 fn sigma3<C, const S: usize, const X: usize, const N: usize, K, R>(
497 &mut self,
498 stack: &mut Messaging<C, S, X>,
499 body: &[u8],
500 ctx: &ChannelContext<'_, C, N, K, R>,
501 buffers: &mut ChannelBuffers<'_>,
502 ) -> Result<ChannelReply>
503 where
504 C: Config,
505 K: KeyStore,
506 R: Rng,
507 {
508 let Some(responder) = self.case.as_mut() else {
509 return Ok(ChannelReply::SILENT);
510 };
511 let accepted = Sigma3::decode(body).and_then(|sigma3| {
512 responder.accept_sigma3(
513 &sigma3,
514 &ctx.fabrics.borrow(),
515 self.case_fabric,
516 None,
517 buffers.reply,
518 )
519 });
520 let (outcome, len) = match accepted {
521 Ok(pair) => pair,
522 Err(e) => {
523 self.case = None;
524 return Err(e);
525 }
526 };
527
528 // Every identity the session needs comes from the outcome and the fabric, so it is built
529 // from both rather than field by field. `local_node_id` is the one that cannot be
530 // left out: §4.9.2's nonce carries the sender's operational node id, which is never in
531 // the header, so a session without it encrypts everything unreadably.
532 let fabric = ctx
533 .fabrics
534 .borrow()
535 .iter()
536 .find(|f| f.fabric_id == outcome.peer.fabric_id)
537 .cloned();
538 let Some(fabric) = fabric else {
539 self.case = None;
540 return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
541 };
542 let index = fabric.index;
543 let session = outcome.into_session(self.case_local, &fabric, ctx.rng.next_u32()?, ctx.now);
544 let evicted = stack.install_session(
545 session,
546 ctx.now,
547 ctx.rng.next_u32()?,
548 buffers.frame,
549 buffers.evict,
550 )?;
551 self.case = None;
552 Ok(ChannelReply {
553 reply: Some((opcode::STATUS_REPORT, len)),
554 established: Some(Established {
555 session: self.case_local,
556 kind: SessionKind::Case,
557 fabric: index,
558 challenge: None,
559 }),
560 evicted,
561 })
562 }
563
564 /// §5.5's failure path: the attempt frees the channel, counts towards the twenty, and closes
565 /// the window when it reaches them.
566 fn fail(&mut self, window: &RefCell<CommissioningWindow>) {
567 self.pase = None;
568 if self.admission.failed().exit_commissioning_mode {
569 window.borrow_mut().close();
570 }
571 }
572}