Skip to main content

matter_kit/sc/
pase.rs

1//! Passcode-Authenticated Session Establishment (Core §4.14.1).
2//!
3//! How a commissioner that knows a device's printed passcode gets its first encrypted
4//! session with it. Five messages, all on the **unsecured** session — there is no key yet —
5//! and all inside one exchange:
6//!
7//! ```text
8//!  commissioner (initiator)                        commissionee (responder)
9//!    PBKDFParamRequest   ──────────────────────▶   picks a salt and iteration count
10//!                        ◀──────────────────────   PBKDFParamResponse
11//!    w0,w1 = PBKDF(passcode)
12//!    Pake1 (pA)          ──────────────────────▶
13//!                        ◀──────────────────────   Pake2 (pB, cB)
14//!    check cB
15//!    Pake3 (cA)          ──────────────────────▶   check cA
16//!                        ◀──────────────────────   PakeFinished (StatusReport)
17//!    I2RKey ‖ R2IKey ‖ AttestationChallenge = KDF(Ke)
18//! ```
19//!
20//! # Sans-I/O
21//!
22//! Neither state machine touches a socket, a clock or a random generator. Randomness is a
23//! parameter — 32 octets for the SPAKE2+ ephemeral, 32 for the protocol random — so a test
24//! can replay a failure exactly, and the caller's one [`Rng`](crate::platform::Rng) is the
25//! only source of entropy in the process.
26//!
27//! # What has actually been proved when it finishes
28//!
29//! That the peer knew the passcode. Nothing else. A PASE session has no fabric, no
30//! operational identity, and no access beyond what commissioning needs — which is why
31//! [`SessionKind::Pase`](crate::session::SessionKind::Pase) is a distinct variant rather
32//! than a flag on a CASE session.
33
34use crate::crypto::{
35    Confirmation, HASH_LEN_BYTES, PUBLIC_KEY_SIZE_BYTES, Spake2pProver, Spake2pVerifier,
36    Spake2pVerifierData, context as spake_context, ct_eq,
37};
38use crate::error::{Error, ErrorCode, Result, bail};
39use crate::msg::SessionId;
40use crate::session::EstablishedKeys;
41use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value, set_once};
42
43use super::SessionParams;
44use super::status::{SecureChannelCode, StatusReport};
45
46/// The length of the protocol randoms (§4.14.1.2).
47pub const RANDOM_LEN: usize = 32;
48
49/// "A value of 0 for the passcodeID SHALL correspond to the PAKE passcode verifier for the
50/// currently-open commissioning window … Non-zero values are reserved for future use."
51pub const PASSCODE_ID_COMMISSIONING: u16 = 0;
52
53/// The PBKDF salt and iteration count (`Crypto_PBKDFParameterSet`, §3.9).
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct PbkdfParameters {
56    /// `CRYPTO_PBKDF_ITERATIONS_MIN <= iterations <= CRYPTO_PBKDF_ITERATIONS_MAX`.
57    pub iterations: u32,
58    /// "A random value per device of at least 16 bytes and at most 32 bytes".
59    pub salt: heapless::Vec<u8, { crate::crypto::PBKDF_SALT_MAX_BYTES }>,
60}
61
62impl PbkdfParameters {
63    /// Builds a parameter set, checking both constraints of §3.9.
64    ///
65    /// These arrive from a peer and go straight into a PBKDF2 that the device then spends
66    /// real time on, so the bounds are enforced here rather than left to the primitive.
67    pub fn new(iterations: u32, salt: &[u8]) -> Result<Self> {
68        if !(crate::crypto::PBKDF_ITERATIONS_MIN..=crate::crypto::PBKDF_ITERATIONS_MAX)
69            .contains(&iterations)
70        {
71            bail!(InvalidArgument)
72        }
73        let Ok(salt) = heapless::Vec::from_slice(salt) else {
74            bail!(InvalidArgument)
75        };
76        if salt.len() < crate::crypto::PBKDF_SALT_MIN_BYTES {
77            bail!(InvalidArgument)
78        }
79        Ok(Self { iterations, salt })
80    }
81}
82
83/// `pbkdfparamreq-struct` (§4.14.1.2).
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct PbkdfParamRequest {
86    /// `InitiatorRandom` — 32 octets from a DRBG.
87    pub initiator_random: [u8; RANDOM_LEN],
88    /// The session id the initiator will listen on.
89    pub initiator_session_id: SessionId,
90    /// Which verifier to use; always [`PASSCODE_ID_COMMISSIONING`] today.
91    pub passcode_id: u16,
92    /// Whether the initiator already knows the salt and iteration count — from a QR code,
93    /// typically. When true, "the responder SHALL NOT return the PBKDF parameters".
94    pub has_pbkdf_parameters: bool,
95    /// The initiator's MRP parameters, if it sent them.
96    pub session_params: Option<SessionParams>,
97}
98
99impl PbkdfParamRequest {
100    /// Writes the TLV encoding, "with an anonymous tag for the outermost struct".
101    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
102        let mut w = TlvWriter::new(out);
103        w.start_structure(Tag::Anonymous)?;
104        w.octets(Tag::Context(1), &self.initiator_random)?;
105        w.unsigned(Tag::Context(2), u64::from(self.initiator_session_id.0))?;
106        w.unsigned(Tag::Context(3), u64::from(self.passcode_id))?;
107        w.bool(Tag::Context(4), self.has_pbkdf_parameters)?;
108        if let Some(params) = &self.session_params {
109            params.encode(&mut w, Tag::Context(5))?;
110        }
111        w.end_container()?;
112        Ok(w.finish()?.len())
113    }
114
115    /// Reads the TLV encoding.
116    pub fn decode(buf: &[u8]) -> Result<Self> {
117        let mut fields = Fields::new(buf)?;
118        let mut out = Self {
119            initiator_random: [0; RANDOM_LEN],
120            initiator_session_id: SessionId(0),
121            passcode_id: PASSCODE_ID_COMMISSIONING,
122            has_pbkdf_parameters: false,
123            session_params: None,
124        };
125        let mut seen_random = false;
126        while let Some((tag, element)) = fields.next()? {
127            match tag {
128                1 => {
129                    let bytes = element.octets()?;
130                    let Ok(arr) = <[u8; RANDOM_LEN]>::try_from(bytes) else {
131                        bail!(InvalidArgument)
132                    };
133                    out.initiator_random = arr;
134                    seen_random = true;
135                }
136                2 => out.initiator_session_id = SessionId(u16_of(element.unsigned()?)?),
137                3 => out.passcode_id = u16_of(element.unsigned()?)?,
138                4 => out.has_pbkdf_parameters = element.bool()?,
139                5 => out.session_params = Some(SessionParams::decode(&mut fields)?),
140                // "any context-specific tags not listed in the associated TLV schemas
141                // SHALL be reserved for future use, and SHALL be silently ignored".
142                _ => fields.skip(&element)?,
143            }
144        }
145        if !seen_random {
146            bail!(TlvNotFound)
147        }
148        Ok(out)
149    }
150}
151
152/// `pbkdfparamresp-struct` (§4.14.1.2).
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct PbkdfParamResponse {
155    /// Echoed from the request, which is what binds the two messages together.
156    pub initiator_random: [u8; RANDOM_LEN],
157    /// `ResponderRandom` — 32 octets from a DRBG.
158    pub responder_random: [u8; RANDOM_LEN],
159    /// The session id the responder will listen on.
160    pub responder_session_id: SessionId,
161    /// Absent when the request said the initiator already had them.
162    pub pbkdf_parameters: Option<PbkdfParameters>,
163    /// The responder's MRP parameters, if it sent them.
164    pub session_params: Option<SessionParams>,
165}
166
167impl PbkdfParamResponse {
168    /// Writes the TLV encoding.
169    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
170        let mut w = TlvWriter::new(out);
171        w.start_structure(Tag::Anonymous)?;
172        w.octets(Tag::Context(1), &self.initiator_random)?;
173        w.octets(Tag::Context(2), &self.responder_random)?;
174        w.unsigned(Tag::Context(3), u64::from(self.responder_session_id.0))?;
175        // The parameter set is always present; it is *empty* when the initiator already
176        // knows the values, which is what "SHALL NOT include the PBKDF parameters" means.
177        w.start_structure(Tag::Context(4))?;
178        if let Some(params) = &self.pbkdf_parameters {
179            w.unsigned(Tag::Context(1), u64::from(params.iterations))?;
180            w.octets(Tag::Context(2), &params.salt)?;
181        }
182        w.end_container()?;
183        if let Some(params) = &self.session_params {
184            params.encode(&mut w, Tag::Context(5))?;
185        }
186        w.end_container()?;
187        Ok(w.finish()?.len())
188    }
189
190    /// Reads the TLV encoding.
191    pub fn decode(buf: &[u8]) -> Result<Self> {
192        let mut fields = Fields::new(buf)?;
193        let mut out = Self {
194            initiator_random: [0; RANDOM_LEN],
195            responder_random: [0; RANDOM_LEN],
196            responder_session_id: SessionId(0),
197            pbkdf_parameters: None,
198            session_params: None,
199        };
200        while let Some((tag, element)) = fields.next()? {
201            match tag {
202                1 => out.initiator_random = random_of(&element)?,
203                2 => out.responder_random = random_of(&element)?,
204                3 => out.responder_session_id = SessionId(u16_of(element.unsigned()?)?),
205                4 => out.pbkdf_parameters = decode_pbkdf_parameters(&mut fields, &element)?,
206                5 => out.session_params = Some(SessionParams::decode(&mut fields)?),
207                _ => fields.skip(&element)?,
208            }
209        }
210        Ok(out)
211    }
212}
213
214fn decode_pbkdf_parameters(
215    fields: &mut Fields<'_>,
216    element: &crate::tlv::Element<'_>,
217) -> Result<Option<PbkdfParameters>> {
218    if element.value.container() != Some(ContainerKind::Structure) {
219        bail!(TlvWrongType)
220    }
221    // `Crypto_PBKDFParameterSet` is tag 4 of a `pbkdfparamresp-struct` and
222    // `responderSessionParams` is tag 5, so this nested decode must stop at its own
223    // end-of-container: without `nested`, it would consume the session parameters that
224    // follow it and the responder's MRP announcement would vanish.
225    let (iterations, salt) = fields.nested(|fields| {
226        let mut iterations = None;
227        let mut salt: Option<heapless::Vec<u8, { crate::crypto::PBKDF_SALT_MAX_BYTES }>> = None;
228        while let Some((tag, inner)) = fields.next()? {
229            match tag {
230                1 => set_once(&mut iterations, u32_of(inner.unsigned()?)?)?,
231                2 => {
232                    let Ok(v) = heapless::Vec::from_slice(inner.octets()?) else {
233                        bail!(InvalidArgument)
234                    };
235                    set_once(&mut salt, v)?;
236                }
237                _ => fields.skip(&inner)?,
238            }
239        }
240        Ok((iterations, salt))
241    })?;
242    match (iterations, salt) {
243        // Both present: a real parameter set, checked against §3.9's bounds.
244        (Some(iterations), Some(salt)) => Ok(Some(PbkdfParameters::new(iterations, &salt)?)),
245        // Neither: the empty set the responder sends when the initiator already knows them.
246        (None, None) => Ok(None),
247        // One without the other is malformed; guessing the missing half would mean
248        // running a PBKDF with a value nobody agreed on.
249        _ => Err(Error::new(ErrorCode::InvalidArgument)),
250    }
251}
252
253/// `pake-1-struct` — the initiator's SPAKE2+ share.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub struct Pake1 {
256    /// `pA`.
257    pub pa: [u8; PUBLIC_KEY_SIZE_BYTES],
258}
259
260/// `pake-2-struct` — the responder's share and its confirmation.
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub struct Pake2 {
263    /// `pB`.
264    pub pb: [u8; PUBLIC_KEY_SIZE_BYTES],
265    /// `cB`.
266    pub cb: Confirmation,
267}
268
269/// `pake-3-struct` — the initiator's confirmation.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct Pake3 {
272    /// `cA`.
273    pub ca: Confirmation,
274}
275
276impl Pake1 {
277    /// Writes the TLV encoding.
278    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
279        let mut w = TlvWriter::new(out);
280        w.start_structure(Tag::Anonymous)?;
281        w.octets(Tag::Context(1), &self.pa)?;
282        w.end_container()?;
283        Ok(w.finish()?.len())
284    }
285
286    /// Reads the TLV encoding.
287    pub fn decode(buf: &[u8]) -> Result<Self> {
288        let mut fields = Fields::new(buf)?;
289        let mut pa = None;
290        while let Some((tag, element)) = fields.next()? {
291            match tag {
292                1 => pa = Some(point_of(&element)?),
293                _ => fields.skip(&element)?,
294            }
295        }
296        Ok(Self {
297            pa: pa.ok_or(Error::new(ErrorCode::TlvNotFound))?,
298        })
299    }
300}
301
302impl Pake2 {
303    /// Writes the TLV encoding.
304    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
305        let mut w = TlvWriter::new(out);
306        w.start_structure(Tag::Anonymous)?;
307        w.octets(Tag::Context(1), &self.pb)?;
308        w.octets(Tag::Context(2), &self.cb)?;
309        w.end_container()?;
310        Ok(w.finish()?.len())
311    }
312
313    /// Reads the TLV encoding.
314    pub fn decode(buf: &[u8]) -> Result<Self> {
315        let mut fields = Fields::new(buf)?;
316        let (mut pb, mut cb) = (None, None);
317        while let Some((tag, element)) = fields.next()? {
318            match tag {
319                1 => pb = Some(point_of(&element)?),
320                2 => cb = Some(confirmation_of(&element)?),
321                _ => fields.skip(&element)?,
322            }
323        }
324        Ok(Self {
325            pb: pb.ok_or(Error::new(ErrorCode::TlvNotFound))?,
326            cb: cb.ok_or(Error::new(ErrorCode::TlvNotFound))?,
327        })
328    }
329}
330
331impl Pake3 {
332    /// Writes the TLV encoding.
333    pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
334        let mut w = TlvWriter::new(out);
335        w.start_structure(Tag::Anonymous)?;
336        w.octets(Tag::Context(1), &self.ca)?;
337        w.end_container()?;
338        Ok(w.finish()?.len())
339    }
340
341    /// Reads the TLV encoding.
342    pub fn decode(buf: &[u8]) -> Result<Self> {
343        let mut fields = Fields::new(buf)?;
344        let mut ca = None;
345        while let Some((tag, element)) = fields.next()? {
346            match tag {
347                1 => ca = Some(confirmation_of(&element)?),
348                _ => fields.skip(&element)?,
349            }
350        }
351        Ok(Self {
352            ca: ca.ok_or(Error::new(ErrorCode::TlvNotFound))?,
353        })
354    }
355}
356
357// --- The state machines -------------------------------------------------------------
358
359/// What the commissionee needs before it can answer at all.
360#[derive(Debug, Clone)]
361pub struct ResponderConfig {
362    /// The stored `(w0, L)` for the open commissioning window.
363    pub verifier: Spake2pVerifierData,
364    /// The salt and iteration count that verifier was computed with.
365    pub parameters: PbkdfParameters,
366    /// This node's MRP parameters, to advertise.
367    pub session_params: Option<SessionParams>,
368}
369
370/// The commissionee's side of PASE.
371#[derive(Debug)]
372pub struct PaseResponder {
373    config: ResponderConfig,
374    local_session_id: SessionId,
375    peer_session_id: SessionId,
376    /// The exact octets of the two parameter messages, which the transcript hashes.
377    request_bytes: heapless::Vec<u8, 256>,
378    response_bytes: heapless::Vec<u8, 256>,
379    verifier: Option<Spake2pVerifier>,
380    expected_ca: Option<Confirmation>,
381    keys: Option<EstablishedKeys>,
382    state: State,
383}
384
385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
386enum State {
387    AwaitingRequest,
388    AwaitingPake1,
389    AwaitingPake3,
390    Established,
391    Failed,
392}
393
394impl PaseResponder {
395    /// A commissionee ready to receive a `PBKDFParamRequest`.
396    ///
397    /// `local_session_id` must not collide with any live session
398    /// ([`SessionTable::allocate_id`](crate::session::SessionTable::allocate_id)).
399    #[must_use]
400    pub fn new(config: ResponderConfig, local_session_id: SessionId) -> Self {
401        Self {
402            config,
403            local_session_id,
404            peer_session_id: SessionId(0),
405            request_bytes: heapless::Vec::new(),
406            response_bytes: heapless::Vec::new(),
407            verifier: None,
408            expected_ca: None,
409            keys: None,
410            state: State::AwaitingRequest,
411        }
412    }
413
414    /// The session id this node will listen on.
415    #[must_use]
416    pub const fn local_session_id(&self) -> SessionId {
417        self.local_session_id
418    }
419
420    /// The session id the peer will listen on, once it has said.
421    #[must_use]
422    pub const fn peer_session_id(&self) -> SessionId {
423        self.peer_session_id
424    }
425
426    /// Handles `PBKDFParamRequest`, writing `PBKDFParamResponse` into `out`.
427    ///
428    /// `responder_random` must be 32 octets from a cryptographically secure generator.
429    pub fn on_pbkdf_param_request(
430        &mut self,
431        payload: &[u8],
432        responder_random: &[u8; RANDOM_LEN],
433        out: &mut [u8],
434    ) -> Result<usize> {
435        if self.state != State::AwaitingRequest {
436            self.state = State::Failed;
437            bail!(InvalidState)
438        }
439        let request = PbkdfParamRequest::decode(payload)?;
440
441        // §4.14.1.2: "Verify passcodeID is set to 0."
442        if request.passcode_id != PASSCODE_ID_COMMISSIONING {
443            self.state = State::Failed;
444            bail!(InvalidArgument)
445        }
446        self.peer_session_id = request.initiator_session_id;
447
448        let response = PbkdfParamResponse {
449            initiator_random: request.initiator_random,
450            responder_random: *responder_random,
451            responder_session_id: self.local_session_id,
452            // "If hasPBKDFParameters is True the responder SHALL NOT include the PBKDF
453            // parameters" — the initiator read them off the QR code.
454            pbkdf_parameters: if request.has_pbkdf_parameters {
455                None
456            } else {
457                Some(self.config.parameters.clone())
458            },
459            session_params: self.config.session_params,
460        };
461        let n = response.encode(out)?;
462
463        // The transcript hashes these two messages verbatim, so they are kept as octets
464        // rather than re-encoded later — a re-encoding that differed by one byte would
465        // produce a context the peer does not share, and the failure would look like a
466        // wrong passcode.
467        self.request_bytes = copy_of(payload)?;
468        self.response_bytes = copy_of(out.get(..n).unwrap_or(&[]))?;
469        self.state = State::AwaitingPake1;
470        Ok(n)
471    }
472
473    /// Handles `Pake1`, writing `Pake2` into `out`.
474    ///
475    /// `responder_ephemeral` must be 32 octets from a cryptographically secure generator —
476    /// the SPAKE2+ scalar `y`.
477    pub fn on_pake1(
478        &mut self,
479        payload: &[u8],
480        responder_ephemeral: &[u8; 32],
481        out: &mut [u8],
482    ) -> Result<usize> {
483        if self.state != State::AwaitingPake1 {
484            self.state = State::Failed;
485            bail!(InvalidState)
486        }
487        let pake1 = Pake1::decode(payload)?;
488        let verifier = Spake2pVerifier::new(&self.config.verifier, responder_ephemeral)?;
489
490        let context = spake_context(&self.request_bytes, &self.response_bytes);
491        let (ca, cb, ke) = verifier.finish(&pake1.pa, &context)?;
492
493        let n = Pake2 {
494            pb: *verifier.pb(),
495            cb,
496        }
497        .encode(out)?;
498
499        // The keys exist now, but nothing may use them until cA is checked: an attacker
500        // who guessed wrong would otherwise get a session.
501        self.keys = Some(EstablishedKeys::derive(ke.as_bytes(), &[])?);
502        self.expected_ca = Some(ca);
503        self.verifier = Some(verifier);
504        self.state = State::AwaitingPake3;
505        Ok(n)
506    }
507
508    /// Handles `Pake3`, writing `PakeFinished` into `out` and returning the session keys.
509    ///
510    /// A `cA` that does not match is [`ErrorCode::IntegrityCheckFailed`] and leaves the
511    /// responder permanently failed — §4.14.1.2 says to "perform no further processing",
512    /// and letting the peer try again on the same exchange would turn one guess into many.
513    pub fn on_pake3(&mut self, payload: &[u8], out: &mut [u8]) -> Result<(usize, EstablishedKeys)> {
514        if self.state != State::AwaitingPake3 {
515            self.state = State::Failed;
516            bail!(InvalidState)
517        }
518        let pake3 = Pake3::decode(payload)?;
519        let Some(expected) = self.expected_ca else {
520            self.state = State::Failed;
521            bail!(InvalidState)
522        };
523        if !ct_eq(&pake3.ca, &expected) {
524            self.state = State::Failed;
525            bail!(IntegrityCheckFailed)
526        }
527        let Some(keys) = self.keys.clone() else {
528            self.state = State::Failed;
529            bail!(InvalidState)
530        };
531        let n = StatusReport::secure_channel(SecureChannelCode::SessionEstablishmentSuccess)
532            .encode(out)?;
533        self.state = State::Established;
534        Ok((n, keys))
535    }
536
537    /// Whether the exchange completed successfully.
538    #[must_use]
539    pub const fn is_established(&self) -> bool {
540        matches!(self.state, State::Established)
541    }
542
543    /// Whether the exchange failed and must be abandoned.
544    #[must_use]
545    pub const fn is_failed(&self) -> bool {
546        matches!(self.state, State::Failed)
547    }
548}
549
550/// The commissioner's side of PASE.
551#[derive(Debug)]
552pub struct PaseInitiator {
553    passcode: u32,
554    local_session_id: SessionId,
555    peer_session_id: SessionId,
556    /// Parameters known up front, from a QR code.
557    known_parameters: Option<PbkdfParameters>,
558    session_params: Option<SessionParams>,
559    /// Kept so the response's echo can be checked against it. Recovering it by re-parsing
560    /// the request would work, but tying the check to a byte offset in an encoding is the
561    /// sort of thing that survives until the encoding changes.
562    initiator_random: [u8; RANDOM_LEN],
563    request_bytes: heapless::Vec<u8, 256>,
564    response_bytes: heapless::Vec<u8, 256>,
565    prover: Option<Spake2pProver>,
566    expected_cb: Option<Confirmation>,
567    ca: Option<Confirmation>,
568    keys: Option<EstablishedKeys>,
569    state: State,
570}
571
572impl PaseInitiator {
573    /// A commissioner that knows `passcode`.
574    ///
575    /// `known_parameters` is `Some` when the salt and iteration count came from the
576    /// onboarding payload, which saves a round trip's worth of information but not a round
577    /// trip: the request is sent either way.
578    #[must_use]
579    pub fn new(
580        passcode: u32,
581        local_session_id: SessionId,
582        known_parameters: Option<PbkdfParameters>,
583        session_params: Option<SessionParams>,
584    ) -> Self {
585        Self {
586            passcode,
587            local_session_id,
588            peer_session_id: SessionId(0),
589            known_parameters,
590            session_params,
591            initiator_random: [0; RANDOM_LEN],
592            request_bytes: heapless::Vec::new(),
593            response_bytes: heapless::Vec::new(),
594            prover: None,
595            expected_cb: None,
596            ca: None,
597            keys: None,
598            state: State::AwaitingRequest,
599        }
600    }
601
602    /// The session id this node will listen on.
603    #[must_use]
604    pub const fn local_session_id(&self) -> SessionId {
605        self.local_session_id
606    }
607
608    /// The session id the peer will listen on, once it has said.
609    #[must_use]
610    pub const fn peer_session_id(&self) -> SessionId {
611        self.peer_session_id
612    }
613
614    /// Writes the opening `PBKDFParamRequest`.
615    ///
616    /// `initiator_random` must be 32 octets from a cryptographically secure generator.
617    pub fn start(&mut self, initiator_random: &[u8; RANDOM_LEN], out: &mut [u8]) -> Result<usize> {
618        if self.state != State::AwaitingRequest {
619            bail!(InvalidState)
620        }
621        let request = PbkdfParamRequest {
622            initiator_random: *initiator_random,
623            initiator_session_id: self.local_session_id,
624            passcode_id: PASSCODE_ID_COMMISSIONING,
625            has_pbkdf_parameters: self.known_parameters.is_some(),
626            session_params: self.session_params,
627        };
628        let n = request.encode(out)?;
629        self.initiator_random = *initiator_random;
630        self.request_bytes = copy_of(out.get(..n).unwrap_or(&[]))?;
631        self.state = State::AwaitingPake1;
632        Ok(n)
633    }
634
635    /// Handles `PBKDFParamResponse`, writing `Pake1` into `out`.
636    ///
637    /// `initiator_ephemeral` must be 32 octets from a cryptographically secure generator —
638    /// the SPAKE2+ scalar `x`. This is the call that runs PBKDF2, which on a constrained
639    /// commissioner is the most expensive thing in the exchange.
640    pub fn on_pbkdf_param_response(
641        &mut self,
642        payload: &[u8],
643        initiator_ephemeral: &[u8; 32],
644        out: &mut [u8],
645    ) -> Result<usize> {
646        if self.state != State::AwaitingPake1 {
647            self.state = State::Failed;
648            bail!(InvalidState)
649        }
650        let response = PbkdfParamResponse::decode(payload)?;
651
652        // The echoed random binds this response to this request. Without the check, an
653        // off-path attacker's response would be accepted into the transcript.
654        if !ct_eq(&response.initiator_random, &self.initiator_random) {
655            self.state = State::Failed;
656            bail!(InvalidArgument)
657        }
658        self.peer_session_id = response.responder_session_id;
659
660        // Whichever side supplied them, exactly one set must be available.
661        let parameters = match (&self.known_parameters, &response.pbkdf_parameters) {
662            (Some(known), None) => known.clone(),
663            (None, Some(sent)) => sent.clone(),
664            (Some(known), Some(_)) => {
665                // The responder sent parameters that were not asked for. Using the known
666                // ones keeps the exchange going and keeps this node's own QR code
667                // authoritative.
668                known.clone()
669            }
670            (None, None) => {
671                self.state = State::Failed;
672                bail!(InvalidArgument)
673            }
674        };
675
676        let prover = Spake2pProver::new(
677            self.passcode,
678            &parameters.salt,
679            parameters.iterations,
680            initiator_ephemeral,
681        )?;
682        let n = Pake1 { pa: *prover.pa() }.encode(out)?;
683
684        self.response_bytes = copy_of(payload)?;
685        self.prover = Some(prover);
686        self.state = State::AwaitingPake3;
687        Ok(n)
688    }
689
690    /// Handles `Pake2`, checking `cB` and writing `Pake3` into `out`.
691    ///
692    /// A `cB` that does not match means the responder did not know the passcode — or is
693    /// not the device the passcode belongs to. §4.14.1.2 says to stop, and this does.
694    pub fn on_pake2(&mut self, payload: &[u8], out: &mut [u8]) -> Result<usize> {
695        if self.state != State::AwaitingPake3 {
696            self.state = State::Failed;
697            bail!(InvalidState)
698        }
699        let pake2 = Pake2::decode(payload)?;
700        let Some(prover) = &self.prover else {
701            self.state = State::Failed;
702            bail!(InvalidState)
703        };
704
705        let context = spake_context(&self.request_bytes, &self.response_bytes);
706        let (ca, cb, ke) = prover.finish(&pake2.pb, &context)?;
707
708        if !ct_eq(&pake2.cb, &cb) {
709            self.state = State::Failed;
710            bail!(IntegrityCheckFailed)
711        }
712
713        let n = Pake3 { ca }.encode(out)?;
714        self.keys = Some(EstablishedKeys::derive(ke.as_bytes(), &[])?);
715        self.expected_cb = Some(cb);
716        self.ca = Some(ca);
717        self.state = State::Established;
718        Ok(n)
719    }
720
721    /// Handles `PakeFinished`, returning the session keys.
722    ///
723    /// §4.14.1.2: "The initiator SHALL NOT send any encrypted application data until it
724    /// receives PakeFinished from the responder" — which is why the keys are handed over
725    /// here and not at [`PaseInitiator::on_pake2`].
726    pub fn on_pake_finished(&mut self, payload: &[u8]) -> Result<EstablishedKeys> {
727        if self.state != State::Established {
728            bail!(InvalidState)
729        }
730        let report = StatusReport::decode(payload)?;
731        if !report.is_success()
732            || report.secure_channel_code() != Some(SecureChannelCode::SessionEstablishmentSuccess)
733        {
734            self.state = State::Failed;
735            bail!(InvalidState)
736        }
737        self.keys.clone().ok_or(Error::new(ErrorCode::InvalidState))
738    }
739
740    /// Whether `Pake2` has been accepted.
741    #[must_use]
742    pub const fn is_established(&self) -> bool {
743        matches!(self.state, State::Established)
744    }
745
746    /// Whether the exchange failed.
747    #[must_use]
748    pub const fn is_failed(&self) -> bool {
749        matches!(self.state, State::Failed)
750    }
751}
752
753// --- TLV helpers ----------------------------------------------------------------------
754
755/// A cursor over the members of an anonymous outer structure.
756///
757/// Every PASE message is "the TLV-encoded … struct with an anonymous tag for the outermost
758/// struct", so all five decoders want the same thing: iterate the context-tagged members,
759/// skip the ones this revision does not know.
760pub(crate) struct Fields<'a> {
761    reader: TlvReader<'a>,
762    depth: usize,
763}
764
765impl<'a> Fields<'a> {
766    pub(crate) fn new(buf: &'a [u8]) -> Result<Self> {
767        let mut reader = TlvReader::new(buf);
768        let Some(first) = reader.next_element()? else {
769            bail!(TlvTruncated)
770        };
771        if first.value.container() != Some(ContainerKind::Structure) {
772            bail!(TlvWrongType)
773        }
774        Ok(Self { reader, depth: 1 })
775    }
776
777    /// The next member, or `None` at the end of the structure this cursor is reading.
778    ///
779    /// "The structure this cursor is reading" is the load-bearing part: [`Fields::nested`]
780    /// moves it one level down, and without that a decoder for a nested structure would run
781    /// past its own end-of-container and carry on consuming the *parent's* remaining
782    /// members as though they were its own.
783    pub(crate) fn next(&mut self) -> Result<Option<(u8, crate::tlv::Element<'a>)>> {
784        let Some(element) = self.reader.next_element()? else {
785            return Ok(None);
786        };
787        if matches!(element.value, Value::EndOfContainer) {
788            if self.reader.depth() < self.depth {
789                return Ok(None);
790            }
791            return self.next();
792        }
793        let Some(tag) = element.tag.context() else {
794            // A member of a Matter structure always has a context tag; the reader has
795            // already refused an anonymous one.
796            bail!(TlvInvalidTag)
797        };
798        Ok(Some((tag, element)))
799    }
800
801    /// Reads a nested structure's members, stopping at *its* end rather than the parent's.
802    ///
803    /// The caller has just taken the element that opens the nested container, so the reader
804    /// is one level deeper than this cursor thinks it is. `f` runs with the cursor moved to
805    /// match, and the level is restored afterwards whether `f` succeeded or not — a scoped
806    /// pair, because an `enter`/`leave` a caller could mismatch is the bug this exists to
807    /// prevent.
808    pub(crate) fn nested<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
809        self.depth = self.depth.saturating_add(1);
810        let out = f(self);
811        self.depth = self.depth.saturating_sub(1);
812        out
813    }
814
815    /// Skips a member's value, including a whole container.
816    pub(crate) fn skip(&mut self, element: &crate::tlv::Element<'a>) -> Result<()> {
817        self.reader.skip_value(element)
818    }
819}
820
821fn copy_of<const N: usize>(bytes: &[u8]) -> Result<heapless::Vec<u8, N>> {
822    heapless::Vec::from_slice(bytes).map_err(|_| Error::new(ErrorCode::NoSpace))
823}
824
825fn u16_of(value: u64) -> Result<u16> {
826    u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
827}
828
829fn u32_of(value: u64) -> Result<u32> {
830    u32::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
831}
832
833fn random_of(element: &crate::tlv::Element<'_>) -> Result<[u8; RANDOM_LEN]> {
834    <[u8; RANDOM_LEN]>::try_from(element.octets()?)
835        .map_err(|_| Error::new(ErrorCode::InvalidArgument))
836}
837
838fn point_of(element: &crate::tlv::Element<'_>) -> Result<[u8; PUBLIC_KEY_SIZE_BYTES]> {
839    <[u8; PUBLIC_KEY_SIZE_BYTES]>::try_from(element.octets()?)
840        .map_err(|_| Error::new(ErrorCode::InvalidArgument))
841}
842
843fn confirmation_of(element: &crate::tlv::Element<'_>) -> Result<Confirmation> {
844    <[u8; HASH_LEN_BYTES]>::try_from(element.octets()?)
845        .map_err(|_| Error::new(ErrorCode::InvalidArgument))
846}
847
848#[cfg(test)]
849mod tests {
850    use super::*;
851
852    fn parameters() -> PbkdfParameters {
853        PbkdfParameters::new(1_000, b"SPAKE2P Key Salt").expect("parameters")
854    }
855
856    fn round_trip<T, E, D>(value: &T, encode: E, decode: D)
857    where
858        T: core::fmt::Debug + PartialEq,
859        E: Fn(&T, &mut [u8]) -> Result<usize>,
860        D: Fn(&[u8]) -> Result<T>,
861    {
862        let mut buf = [0u8; 512];
863        let n = encode(value, &mut buf).expect("encode");
864        let decoded = decode(&buf[..n]).expect("decode");
865        assert_eq!(&decoded, value);
866        // And every truncation of it must be an error rather than a panic.
867        for cut in 0..n {
868            let _ = decode(&buf[..cut]);
869        }
870    }
871
872    #[test]
873    fn pbkdf_param_request_round_trips() {
874        round_trip(
875            &PbkdfParamRequest {
876                initiator_random: [0xAB; RANDOM_LEN],
877                initiator_session_id: SessionId(0x1234),
878                passcode_id: PASSCODE_ID_COMMISSIONING,
879                has_pbkdf_parameters: true,
880                session_params: None,
881            },
882            |v, b| v.encode(b),
883            PbkdfParamRequest::decode,
884        );
885        round_trip(
886            &PbkdfParamRequest {
887                initiator_random: [0x01; RANDOM_LEN],
888                initiator_session_id: SessionId(1),
889                passcode_id: PASSCODE_ID_COMMISSIONING,
890                has_pbkdf_parameters: false,
891                session_params: Some(SessionParams::announce(
892                    &crate::exchange::MrpParams::default(),
893                )),
894            },
895            |v, b| v.encode(b),
896            PbkdfParamRequest::decode,
897        );
898    }
899
900    #[test]
901    fn pbkdf_param_response_round_trips_with_and_without_parameters() {
902        // With: the manual-pairing-code path, where the device must tell the commissioner.
903        round_trip(
904            &PbkdfParamResponse {
905                initiator_random: [0x11; RANDOM_LEN],
906                responder_random: [0x22; RANDOM_LEN],
907                responder_session_id: SessionId(7),
908                pbkdf_parameters: Some(parameters()),
909                session_params: None,
910            },
911            |v, b| v.encode(b),
912            PbkdfParamResponse::decode,
913        );
914        // Without: the QR-code path, where §4.14.1.2 says the responder "SHALL NOT return
915        // the PBKDF parameters" — an *empty* parameter set, not an absent field.
916        round_trip(
917            &PbkdfParamResponse {
918                initiator_random: [0x11; RANDOM_LEN],
919                responder_random: [0x22; RANDOM_LEN],
920                responder_session_id: SessionId(7),
921                pbkdf_parameters: None,
922                session_params: None,
923            },
924            |v, b| v.encode(b),
925            PbkdfParamResponse::decode,
926        );
927    }
928
929    #[test]
930    fn the_pake_messages_round_trip() {
931        round_trip(
932            &Pake1 {
933                pa: [0x04; PUBLIC_KEY_SIZE_BYTES],
934            },
935            |v, b| v.encode(b),
936            Pake1::decode,
937        );
938        round_trip(
939            &Pake2 {
940                pb: [0x04; PUBLIC_KEY_SIZE_BYTES],
941                cb: [0x77; HASH_LEN_BYTES],
942            },
943            |v, b| v.encode(b),
944            Pake2::decode,
945        );
946        round_trip(
947            &Pake3 {
948                ca: [0x88; HASH_LEN_BYTES],
949            },
950            |v, b| v.encode(b),
951            Pake3::decode,
952        );
953    }
954
955    #[test]
956    fn unknown_context_tags_are_skipped() {
957        // §4.14.1.2: "any context-specific tags not listed in the associated TLV schemas
958        // SHALL be reserved for future use, and SHALL be silently ignored if seen by a
959        // recipient which cannot understand them." A node that refused them could not
960        // talk to a newer peer.
961        let mut buf = [0u8; 256];
962        let mut w = TlvWriter::new(&mut buf);
963        w.start_structure(Tag::Anonymous).expect("open");
964        w.octets(Tag::Context(1), &[0xAB; RANDOM_LEN])
965            .expect("random");
966        w.unsigned(Tag::Context(2), 9).expect("session");
967        w.unsigned(Tag::Context(3), 0).expect("passcode id");
968        w.bool(Tag::Context(4), true).expect("flag");
969        // A future scalar…
970        w.unsigned(Tag::Context(99), 1234).expect("unknown scalar");
971        // …and a future container, which has to be skipped whole.
972        w.start_structure(Tag::Context(100)).expect("open");
973        w.unsigned(Tag::Context(1), 1).expect("inner");
974        w.start_array(Tag::Context(2)).expect("array");
975        w.unsigned(Tag::Anonymous, 2).expect("item");
976        w.end_container().expect("close array");
977        w.end_container().expect("close struct");
978        w.end_container().expect("close");
979        let n = w.finish().expect("finish").len();
980
981        let decoded = PbkdfParamRequest::decode(&buf[..n]).expect("decode");
982        assert_eq!(decoded.initiator_session_id, SessionId(9));
983        assert!(decoded.has_pbkdf_parameters);
984    }
985
986    #[test]
987    fn a_missing_mandatory_field_is_refused() {
988        let mut buf = [0u8; 64];
989        let mut w = TlvWriter::new(&mut buf);
990        w.start_structure(Tag::Anonymous).expect("open");
991        w.unsigned(Tag::Context(2), 1).expect("session");
992        w.end_container().expect("close");
993        let n = w.finish().expect("finish").len();
994        assert_eq!(
995            PbkdfParamRequest::decode(&buf[..n]).unwrap_err().code(),
996            ErrorCode::TlvNotFound
997        );
998    }
999
1000    #[test]
1001    fn pbkdf_parameters_enforce_section_3_9() {
1002        // Below the minimum iteration count, above the maximum, and a salt outside
1003        // 16..=32 octets are all things a peer can send and a device must refuse.
1004        assert!(PbkdfParameters::new(999, b"0123456789abcdef").is_err());
1005        assert!(PbkdfParameters::new(100_001, b"0123456789abcdef").is_err());
1006        assert!(PbkdfParameters::new(1_000, b"tooshort").is_err());
1007        assert!(PbkdfParameters::new(1_000, &[0u8; 33]).is_err());
1008        assert!(PbkdfParameters::new(1_000, &[0u8; 16]).is_ok());
1009        assert!(PbkdfParameters::new(100_000, &[0u8; 32]).is_ok());
1010    }
1011
1012    #[test]
1013    fn half_a_parameter_set_is_refused() {
1014        // Iterations without a salt, or the other way round: guessing the missing half
1015        // would mean running a PBKDF with a value nobody agreed on.
1016        for (iterations, salt) in [(Some(1_000u32), None), (None, Some(&[0u8; 16]))] {
1017            let mut buf = [0u8; 256];
1018            let mut w = TlvWriter::new(&mut buf);
1019            w.start_structure(Tag::Anonymous).expect("open");
1020            w.octets(Tag::Context(1), &[0x11; RANDOM_LEN]).expect("r1");
1021            w.octets(Tag::Context(2), &[0x22; RANDOM_LEN]).expect("r2");
1022            w.unsigned(Tag::Context(3), 1).expect("session");
1023            w.start_structure(Tag::Context(4)).expect("params");
1024            if let Some(i) = iterations {
1025                w.unsigned(Tag::Context(1), u64::from(i)).expect("iters");
1026            }
1027            if let Some(s) = salt {
1028                w.octets(Tag::Context(2), s).expect("salt");
1029            }
1030            w.end_container().expect("close params");
1031            w.end_container().expect("close");
1032            let n = w.finish().expect("finish").len();
1033            assert!(
1034                PbkdfParamResponse::decode(&buf[..n]).is_err(),
1035                "iterations={iterations:?} salt={:?}",
1036                salt.map(|s| s.len())
1037            );
1038        }
1039    }
1040
1041    #[test]
1042    fn a_nonzero_passcode_id_is_refused() {
1043        // §4.14.1.2: "Verify passcodeID is set to 0."
1044        let verifier = Spake2pVerifierData::from_passcode(20_202_021, b"SPAKE2P Key Salt", 1_000)
1045            .expect("verifier");
1046        let mut device = PaseResponder::new(
1047            ResponderConfig {
1048                verifier,
1049                parameters: parameters(),
1050                session_params: None,
1051            },
1052            SessionId(1),
1053        );
1054
1055        let mut buf = [0u8; 256];
1056        let n = PbkdfParamRequest {
1057            initiator_random: [0; RANDOM_LEN],
1058            initiator_session_id: SessionId(2),
1059            passcode_id: 1,
1060            has_pbkdf_parameters: true,
1061            session_params: None,
1062        }
1063        .encode(&mut buf)
1064        .expect("encode");
1065
1066        let mut out = [0u8; 256];
1067        assert_eq!(
1068            device
1069                .on_pbkdf_param_request(&buf[..n], &[0; RANDOM_LEN], &mut out)
1070                .unwrap_err()
1071                .code(),
1072            ErrorCode::InvalidArgument
1073        );
1074        assert!(device.is_failed());
1075    }
1076
1077    #[test]
1078    fn messages_must_arrive_in_order() {
1079        // A peer that sends Pake1 before the parameters have been agreed has nothing to
1080        // build a transcript from.
1081        let verifier = Spake2pVerifierData::from_passcode(20_202_021, b"SPAKE2P Key Salt", 1_000)
1082            .expect("verifier");
1083        let mut device = PaseResponder::new(
1084            ResponderConfig {
1085                verifier,
1086                parameters: parameters(),
1087                session_params: None,
1088            },
1089            SessionId(1),
1090        );
1091        let mut out = [0u8; 256];
1092        let mut pake1 = [0u8; 256];
1093        let n = Pake1 {
1094            pa: [0x04; PUBLIC_KEY_SIZE_BYTES],
1095        }
1096        .encode(&mut pake1)
1097        .expect("encode");
1098        assert_eq!(
1099            device
1100                .on_pake1(&pake1[..n], &[1; 32], &mut out)
1101                .unwrap_err()
1102                .code(),
1103            ErrorCode::InvalidState
1104        );
1105    }
1106
1107    #[test]
1108    fn session_params_clamp_what_a_peer_sends() {
1109        // These decide how long this node waits before retransmitting, and they come from
1110        // a stranger.
1111        let hostile = SessionParams {
1112            idle_interval_ms: u32::MAX,
1113            active_interval_ms: u32::MAX,
1114            active_threshold_ms: u16::MAX,
1115            ..SessionParams::legacy_peer()
1116        };
1117        let mrp = hostile.to_mrp();
1118        assert_eq!(mrp.idle_interval.as_millis(), 3_600_000);
1119        assert_eq!(mrp.active_interval.as_millis(), 3_600_000);
1120        assert_eq!(mrp.active_threshold.as_millis(), 65_535);
1121    }
1122
1123    #[test]
1124    fn absent_session_params_take_the_defaults() {
1125        // A peer that sends nothing is a peer at Table 23's defaults, which are exactly the
1126        // MRP defaults — and, for the revisions, the 1.0-era floors rather than this node's.
1127        let peer = SessionParams::legacy_peer();
1128        assert_eq!(peer.to_mrp(), crate::exchange::MrpParams::default());
1129        assert_eq!(peer.data_model_revision, 16);
1130        assert_eq!(peer.interaction_model_revision, 10);
1131        assert_eq!(peer.max_paths_per_invoke, 1);
1132        assert!(peer.supported_transports.is_empty());
1133    }
1134}
1135
1136#[cfg(test)]
1137mod nesting_tests {
1138    use super::*;
1139    use crate::sc::SessionParams;
1140
1141    #[test]
1142    fn a_pbkdf_param_response_keeps_the_session_params_after_its_nested_parameter_set() {
1143        // `pbkdf_parameters` is tag 4 and `responderSessionParams` is tag 5, so the nested
1144        // decode has to stop at its own end-of-container. Without that the responder's MRP
1145        // announcement is eaten and both ends silently fall back to the default timings —
1146        // a wrong retransmission schedule, with no error raised anywhere.
1147        let parameters = PbkdfParameters::new(1_000, b"SPAKE2P Key Salt").expect("parameters");
1148        let response = PbkdfParamResponse {
1149            initiator_random: [1; RANDOM_LEN],
1150            responder_random: [2; RANDOM_LEN],
1151            responder_session_id: SessionId(0x4321),
1152            pbkdf_parameters: Some(parameters.clone()),
1153            session_params: Some(SessionParams {
1154                idle_interval_ms: 1234,
1155                active_interval_ms: 567,
1156                active_threshold_ms: 8901,
1157                ..SessionParams::legacy_peer()
1158            }),
1159        };
1160
1161        let mut buf = [0u8; 256];
1162        let len = response.encode(&mut buf).expect("encode");
1163        let mut round = [0u8; 256];
1164        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1165        let decoded =
1166            PbkdfParamResponse::decode(round.get(..len).expect("in range")).expect("decode");
1167
1168        assert_eq!(decoded.pbkdf_parameters, response.pbkdf_parameters);
1169        assert_eq!(
1170            decoded.session_params, response.session_params,
1171            "the session params come after a nested structure"
1172        );
1173        assert_eq!(decoded.responder_session_id, SessionId(0x4321));
1174    }
1175
1176    #[test]
1177    fn a_duplicate_tag_inside_the_parameter_set_is_refused() {
1178        // §A.5.1 applies to a nested structure as much as to the outer one.
1179        let mut buf = [0u8; 256];
1180        let mut w = TlvWriter::new(&mut buf);
1181        w.start_structure(Tag::Anonymous).expect("start");
1182        w.octets(Tag::Context(1), &[1u8; RANDOM_LEN])
1183            .expect("random");
1184        w.octets(Tag::Context(2), &[2u8; RANDOM_LEN])
1185            .expect("random");
1186        w.unsigned(Tag::Context(3), 1).expect("session id");
1187        w.start_structure(Tag::Context(4)).expect("parameters");
1188        w.unsigned(Tag::Context(1), 1_000).expect("iterations");
1189        w.unsigned(Tag::Context(1), 2_000)
1190            .expect("a second iterations");
1191        w.octets(Tag::Context(2), b"SPAKE2P Key Salt")
1192            .expect("salt");
1193        w.end_container().expect("end parameters");
1194        w.end_container().expect("end");
1195        let len = w.finish().expect("finish").len();
1196
1197        let mut round = [0u8; 256];
1198        round[..len].copy_from_slice(buf.get(..len).expect("in range"));
1199        assert_eq!(
1200            PbkdfParamResponse::decode(round.get(..len).expect("in range"))
1201                .map(|_| ())
1202                .unwrap_err()
1203                .code(),
1204            ErrorCode::TlvDuplicateTag
1205        );
1206    }
1207}