Skip to main content

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    #[expect(
289        clippy::cast_possible_truncation,
290        reason = "§4.13.2.4 wants an unpredictable 16-bit local session id; any 16 bits of the draw serve"
291    )]
292    fn pbkdf_param_request<C, const N: usize, K, R>(
293        &mut self,
294        body: &[u8],
295        ctx: &ChannelContext<'_, C, N, K, R>,
296        reply: &mut [u8],
297    ) -> Result<ChannelReply>
298    where
299        C: Config,
300        K: KeyStore,
301        R: Rng,
302    {
303        match self.admission.admit(true, ctx.now) {
304            Admit::Admitted => {}
305            refusal => {
306                // §4.11.1.3's codes: `Busy` says "not now", which is true while another
307                // commissioner holds the channel. The rest will not change until the device is
308                // put back into commissioning mode.
309                let code = if matches!(refusal, Admit::Busy) {
310                    SecureChannelCode::Busy
311                } else {
312                    SecureChannelCode::InvalidParameter
313                };
314                let len = StatusReport::secure_channel(code).encode(reply)?;
315                return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
316            }
317        }
318
319        // §11.19.8.1: an Enhanced window runs PASE against the verifier the *administrator*
320        // supplied, with that command's salt and iteration count. A Basic window carries no
321        // verifier and falls back to the factory one, which is what makes it Basic.
322        let ephemeral = ctx.window.borrow().ephemeral(ctx.now).and_then(|e| {
323            let verifier = Spake2pVerifierData::from_bytes(&e.verifier).ok()?;
324            let parameters = PbkdfParameters::new(e.iterations, &e.salt).ok()?;
325            Some((verifier, parameters))
326        });
327        let (verifier, parameters) = match ephemeral {
328            Some(pair) => pair,
329            None => (*ctx.verifier, ctx.parameters.clone()),
330        };
331
332        let mut responder = PaseResponder::new(
333            ResponderConfig {
334                verifier,
335                parameters,
336                session_params: Some(SessionParams::default()),
337            },
338            // A session id nothing else is using, with the low bit set so it is never zero —
339            // §4.13.2.4 reserves that for the unsecured session.
340            SessionId(ctx.rng.next_u32()? as u16 | 1),
341        );
342        let mut random = [0u8; 32];
343        ctx.rng.fill(&mut random)?;
344        match responder.on_pbkdf_param_request(body, &random, reply) {
345            Ok(len) => {
346                self.pase_local = responder.local_session_id();
347                self.pase = Some(responder);
348                Ok(ChannelReply::answer(opcode::PBKDF_PARAM_RESPONSE, len))
349            }
350            // A request this node could not parse is a failed attempt like any other: it frees
351            // the channel, and it counts towards the twenty.
352            Err(e) => {
353                self.fail(ctx.window);
354                Err(e)
355            }
356        }
357    }
358
359    fn pake1<C, const N: usize, K, R>(
360        &mut self,
361        body: &[u8],
362        ctx: &ChannelContext<'_, C, N, K, R>,
363        reply: &mut [u8],
364    ) -> Result<ChannelReply>
365    where
366        C: Config,
367        K: KeyStore,
368        R: Rng,
369    {
370        let Some(pase) = self.pase.as_mut() else {
371            return Ok(ChannelReply::SILENT);
372        };
373        let mut random = [0u8; 32];
374        ctx.rng.fill(&mut random)?;
375        match pase.on_pake1(body, &random, reply) {
376            Ok(len) => Ok(ChannelReply::answer(opcode::PAKE2, len)),
377            Err(e) => {
378                self.fail(ctx.window);
379                Err(e)
380            }
381        }
382    }
383
384    /// The last PASE message, and the session it produces.
385    fn pake3<C, const S: usize, const X: usize, const N: usize, K, R>(
386        &mut self,
387        stack: &mut Messaging<C, S, X>,
388        body: &[u8],
389        ctx: &ChannelContext<'_, C, N, K, R>,
390        buffers: &mut ChannelBuffers<'_>,
391    ) -> Result<ChannelReply>
392    where
393        C: Config,
394        K: KeyStore,
395        R: Rng,
396    {
397        let Some(pase) = self.pase.as_mut() else {
398            return Ok(ChannelReply::SILENT);
399        };
400        let (len, keys) = match pase.on_pake3(body, buffers.reply) {
401            Ok(pair) => pair,
402            Err(e) => {
403                self.fail(ctx.window);
404                return Err(e);
405            }
406        };
407        let challenge = keys.attestation_challenge.clone();
408        let session = SecureSession::new(
409            self.pase_local,
410            pase.peer_session_id(),
411            SessionKind::Pase,
412            Role::Responder,
413            keys,
414            ctx.rng.next_u32()?,
415            ctx.now,
416        );
417        let evicted = match stack.install_session(
418            session,
419            ctx.now,
420            ctx.rng.next_u32()?,
421            buffers.frame,
422            buffers.evict,
423        ) {
424            Ok(evicted) => evicted,
425            Err(e) => {
426                self.fail(ctx.window);
427                return Err(e);
428            }
429        };
430        self.challenge = Some(challenge.clone());
431        // §5.5 rule 1 holds "or has successfully established a session": the channel stays shut
432        // until that session is closed.
433        self.admission.established();
434        Ok(ChannelReply {
435            reply: Some((opcode::STATUS_REPORT, len)),
436            established: Some(Established {
437                session: self.pase_local,
438                kind: SessionKind::Pase,
439                fabric: FabricIndex::NONE,
440                challenge: Some(challenge),
441            }),
442            evicted,
443        })
444    }
445
446    /// §4.14.2.3's Sigma1, answered against the fabric its destination identifier names.
447    #[expect(
448        clippy::cast_possible_truncation,
449        reason = "§4.13.2.4 wants an unpredictable 16-bit local session id; any 16 bits of the draw serve"
450    )]
451    fn sigma1<C, const N: usize, K, R>(
452        &mut self,
453        body: &[u8],
454        ctx: &ChannelContext<'_, C, N, K, R>,
455        reply: &mut [u8],
456    ) -> Result<ChannelReply>
457    where
458        C: Config,
459        K: KeyStore,
460        R: Rng,
461    {
462        let local = SessionId(ctx.rng.next_u32()? as u16 | 1);
463        let mut responder_random = [0u8; 32];
464        let mut ephemeral = [0u8; 32];
465        let mut resumption = [0u8; 16];
466        ctx.rng.fill(&mut responder_random)?;
467        ctx.rng.fill(&mut ephemeral)?;
468        ctx.rng.fill(&mut resumption)?;
469
470        let accepted = Sigma1::decode(body).and_then(|sigma1| {
471            super::case::accept_sigma1(
472                &sigma1,
473                &ctx.fabrics.borrow(),
474                &mut *ctx.keys.borrow_mut(),
475                local,
476                Some(SessionParams::default()),
477                &super::case::Sigma2Randomness {
478                    ephemeral: &ephemeral,
479                    responder: &responder_random,
480                    resumption: &resumption,
481                },
482                reply,
483            )
484        });
485        match accepted {
486            Ok((responder, fabric, len)) => {
487                self.case_local = local;
488                self.case_fabric = fabric;
489                self.case = Some(responder);
490                Ok(ChannelReply::answer(opcode::SIGMA2, len))
491            }
492            // §4.11.1.3: no fabric matched, which is the ordinary answer to a Sigma1 meant for
493            // another node on the link. The initiator is told so rather than left waiting.
494            Err(_) => {
495                self.case = None;
496                let len = StatusReport::secure_channel(SecureChannelCode::NoSharedTrustRoots)
497                    .encode(reply)?;
498                Ok(ChannelReply::answer(opcode::STATUS_REPORT, len))
499            }
500        }
501    }
502
503    /// Sigma3, validated against the root of the fabric Sigma1 resolved.
504    fn sigma3<C, const S: usize, const X: usize, const N: usize, K, R>(
505        &mut self,
506        stack: &mut Messaging<C, S, X>,
507        body: &[u8],
508        ctx: &ChannelContext<'_, C, N, K, R>,
509        buffers: &mut ChannelBuffers<'_>,
510    ) -> Result<ChannelReply>
511    where
512        C: Config,
513        K: KeyStore,
514        R: Rng,
515    {
516        let Some(responder) = self.case.as_mut() else {
517            return Ok(ChannelReply::SILENT);
518        };
519        let accepted = Sigma3::decode(body).and_then(|sigma3| {
520            responder.accept_sigma3(
521                &sigma3,
522                &ctx.fabrics.borrow(),
523                self.case_fabric,
524                None,
525                buffers.reply,
526            )
527        });
528        let (outcome, len) = match accepted {
529            Ok(pair) => pair,
530            Err(e) => {
531                self.case = None;
532                return Err(e);
533            }
534        };
535
536        // Every identity the session needs comes from the outcome and the fabric, so it is built
537        // from both rather than field by field. `local_node_id` is the one that cannot be
538        // left out: §4.9.2's nonce carries the sender's operational node id, which is never in
539        // the header, so a session without it encrypts everything unreadably.
540        let fabric = ctx
541            .fabrics
542            .borrow()
543            .iter()
544            .find(|f| f.fabric_id == outcome.peer.fabric_id)
545            .cloned();
546        let Some(fabric) = fabric else {
547            self.case = None;
548            return Ok(ChannelReply::answer(opcode::STATUS_REPORT, len));
549        };
550        let index = fabric.index;
551        let session = outcome.into_session(self.case_local, &fabric, ctx.rng.next_u32()?, ctx.now);
552        let evicted = stack.install_session(
553            session,
554            ctx.now,
555            ctx.rng.next_u32()?,
556            buffers.frame,
557            buffers.evict,
558        )?;
559        self.case = None;
560        Ok(ChannelReply {
561            reply: Some((opcode::STATUS_REPORT, len)),
562            established: Some(Established {
563                session: self.case_local,
564                kind: SessionKind::Case,
565                fabric: index,
566                challenge: None,
567            }),
568            evicted,
569        })
570    }
571
572    /// §5.5's failure path: the attempt frees the channel, counts towards the twenty, and closes
573    /// the window when it reaches them.
574    fn fail(&mut self, window: &RefCell<CommissioningWindow>) {
575        self.pase = None;
576        if self.admission.failed().exit_commissioning_mode {
577            window.borrow_mut().close();
578        }
579    }
580}