Skip to main content

matter_kit/commissioning/
commissioner.rs

1//! The commissioner's half of the commissioning flow (Core §5.5).
2//!
3//! §5.5 lists seventeen steps for the initial phase and four for the setup phase. Most are the
4//! commissioner's, and they are all one shape: invoke a command over the PASE session, check the
5//! response, invoke the next. This is that sequence, written as a state machine so the caller
6//! keeps the sockets and the crypto and this keeps the *order* — which is the part that is easy
7//! to get subtly wrong and hard to notice.
8//!
9//! # Why an order at all
10//!
11//! Every step depends on one before it, and several of the dependencies are security properties
12//! rather than data flow:
13//!
14//! * The **fail-safe** is armed first (§5.5 step 7) because everything after it is undone if the
15//!   commissioner walks away. A device that took a NOC with no fail-safe armed would keep a
16//!   fabric nobody finished joining.
17//! * **Attestation** comes before the CSR (§5.5 steps 10–11) because the CSR is signed by the
18//!   *same* DAC key the attestation proved possession of. Asking for a CSR first would mean
19//!   verifying a signature against a key nothing had vouched for.
20//! * The **root** is installed before the NOC (§11.18.6.8), and in the same fail-safe period, or
21//!   the device would be asked to trust a chain whose anchor it does not have.
22//!
23//! # What this does not do
24//!
25//! Own a socket, a clock or a key. [`Commissioner::step`](crate::commissioning::commissioner::Commissioner::step) hands back the command to send and
26//! [`Commissioner::on_response`](crate::commissioning::commissioner::Commissioner::on_response) takes what came back; PASE and CASE are
27//! [`PaseInitiator`](crate::sc::PaseInitiator) and [`CaseInitiator`](crate::sc::CaseInitiator),
28//! and the exchange underneath is [`messaging`](crate::messaging)'s.
29//!
30//! It also does not configure the operational network (§5.5 steps 15–16). That is the one step
31//! whose content is entirely device-specific — a Wi-Fi SSID, a Thread dataset — and a
32//! commissioner that guessed would be guessing about somebody's house. [`Commissioner::pause`](crate::commissioning::commissioner::Commissioner::pause)
33//! is where a caller does it, between the credentials and CASE.
34
35use crate::attestation::chain::verify_dac_chain;
36use crate::attestation::x509::X509Certificate;
37use crate::attestation::{
38    ATTESTATION_NONCE_LEN, AttestationElements, CSR_NONCE_LEN, Csr, NocsrElements,
39    verify_attestation, verify_nocsr,
40};
41use crate::ca::{CertAuthority, Identity, Validity};
42use crate::cert::CERT_TLV_MAX;
43use crate::clusters::generated::{general_commissioning, operational_credentials};
44use crate::crypto::{KeyStore, PublicKey, Signature, SymmetricKey};
45use crate::error::{Error, ErrorCode, Result};
46use crate::im::{ClusterId, CommandId, EndpointId};
47use crate::msg::{NodeId, VendorId};
48use crate::tlv::{ContainerKind, Tag, TlvWriter, ToTlv};
49
50/// The `RootNode` endpoint every commissioning cluster lives on (§9.2).
51pub const ROOT_ENDPOINT: EndpointId = 0;
52
53/// §5.5 step 6: "the Commissionee SHALL autonomously arm the Fail-safe timer for a timeout of
54/// 60 seconds", and step 7 gives the commissioner that long to re-arm it.
55pub const AUTONOMOUS_FAIL_SAFE_SECONDS: u16 = 60;
56
57/// The longest certificate a `CertificateChainResponse` may carry.
58///
59/// §11.18.6.3's constraint is "max 600" — a DER X.509 certificate, not the TLV form.
60pub const DER_CERT_MAX: usize = 600;
61
62/// How far commissioning has got.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64#[non_exhaustive]
65pub enum Stage {
66    /// §5.5 step 7 — re-arm the fail-safe the device armed for itself.
67    ArmFailSafe,
68    /// §5.5 step 8 — regulatory information, for a device with a Wi-Fi or Thread radio.
69    SetRegulatoryConfig,
70    /// §5.5 step 10 — fetch the Device Attestation Certificate.
71    RequestDac,
72    /// ...and the Product Attestation Intermediate that issued it.
73    RequestPai,
74    /// Prove the device holds the DAC's private key.
75    RequestAttestation,
76    /// §5.5 step 11 — ask for an operational key and a CSR over it.
77    RequestCsr,
78    /// §5.5 step 13 — install the fabric's root.
79    AddTrustedRoot,
80    /// ...and the NOC under it.
81    AddNoc,
82    /// §5.5's setup phase steps 2–3 — the caller configures the network, discovers the node and
83    /// opens a CASE session.
84    Operational,
85    /// §5.5 setup step 4 — the last command, and the only one that must be on CASE.
86    CommissioningComplete,
87    /// Nothing left.
88    Done,
89}
90
91/// What the caller should do next.
92#[derive(Debug, Clone, Copy)]
93#[non_exhaustive]
94pub enum Step<'a> {
95    /// Invoke this command and feed the response back to
96    /// [`Commissioner::on_response`].
97    Invoke {
98        /// The endpoint — always [`ROOT_ENDPOINT`] for the commissioning clusters.
99        endpoint: EndpointId,
100        /// The cluster.
101        cluster: ClusterId,
102        /// The command.
103        command: CommandId,
104        /// The encoded `CommandFields`, or empty for a command that takes none.
105        fields: &'a [u8],
106    },
107    /// The PASE phase is finished. Configure the operational network if the device needs it,
108    /// discover the node, and establish CASE — then call [`Commissioner::on_operational`].
109    ///
110    /// §5.5's setup phase exists as a separate phase precisely because the device may reboot
111    /// onto a different network in between, and the commissioner has to find it again.
112    Operational {
113        /// The node id the NOC gave the device, which is what operational discovery advertises.
114        node_id: NodeId,
115    },
116    /// Commissioning succeeded.
117    Done,
118}
119
120/// What the commissioner decided about the device's attestation (§6.2.3).
121///
122/// §5.5 step 10 is explicit that failing it is *not* automatically fatal: "the Commissioner MAY
123/// choose to either continue to the Commissioning, or terminate it, depending on
124/// implementation-dependent policies", and SHOULD warn the user. So the outcome is reported and
125/// the policy belongs to whoever is driving.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum Attestation {
128    /// The chain verified against a trusted PAA and the signatures held.
129    Trusted,
130    /// Something did not check out. `reason` is what.
131    Failed(ErrorCode),
132}
133
134/// What a commissioner needs to know before it starts.
135#[derive(Debug, Clone, Copy)]
136pub struct Plan {
137    /// The identity the node will have.
138    pub identity: Identity,
139    /// §11.18.6.9's `CaseAdminSubject` — the subject that gets Administer over CASE.
140    ///
141    /// Usually the commissioner's own node id, and §11.18.6.9 requires it to be an operational
142    /// node id or a CAT: "a CASE Authenticated Tag or an Operational Node ID". The single ACL
143    /// entry `AddNOC` creates is the only way in until somebody writes more, so getting this
144    /// wrong locks the fabric out of its own device.
145    pub case_admin_subject: u64,
146    /// §11.18.6.9's `AdminVendorId` — "a value for which the Vendor Schema in DCL contains the
147    /// name and other information of the Commissioner's manufacturer" (§5.5 step 13).
148    pub admin_vendor_id: VendorId,
149    /// How long the fail-safe should run (§5.5 step 7).
150    pub fail_safe_seconds: u16,
151    /// The certificate validity to issue.
152    pub validity: Validity,
153    /// Whether the device needs §5.5 step 8's regulatory configuration.
154    ///
155    /// "If the Commissionee has at least one instance of the Network Commissioning cluster on
156    /// any endpoint with either the WI ... or TH ... feature flags set" — a wired device does
157    /// not, and sending it anyway wastes a round trip on a device that has none.
158    pub needs_regulatory_config: bool,
159    /// The regulatory location to set, when it is needed.
160    pub regulatory_location: general_commissioning::RegulatoryLocationTypeEnum,
161}
162
163impl Plan {
164    /// A plan for `identity`, administered over CASE by `case_admin_subject`.
165    #[must_use]
166    pub const fn new(
167        identity: Identity,
168        case_admin_subject: u64,
169        admin_vendor_id: VendorId,
170        validity: Validity,
171    ) -> Self {
172        Self {
173            identity,
174            case_admin_subject,
175            admin_vendor_id,
176            // §5.5 step 7 gives the commissioner 60 seconds to re-arm; the value it re-arms
177            // *to* is its own choice, and 900 is what the CHIP SDK's controller uses — long
178            // enough for a Thread join, short enough that an abandoned attempt clears within
179            // a quarter of an hour.
180            fail_safe_seconds: 900,
181            validity,
182            needs_regulatory_config: false,
183            regulatory_location: general_commissioning::RegulatoryLocationTypeEnum::IndoorOutdoor,
184        }
185    }
186
187    /// The same plan, sending §5.5 step 8's regulatory configuration.
188    #[must_use]
189    pub const fn with_regulatory_config(
190        mut self,
191        location: general_commissioning::RegulatoryLocationTypeEnum,
192    ) -> Self {
193        self.needs_regulatory_config = true;
194        self.regulatory_location = location;
195        self
196    }
197
198    /// The same plan with a different fail-safe duration.
199    #[must_use]
200    pub const fn with_fail_safe(mut self, seconds: u16) -> Self {
201        self.fail_safe_seconds = seconds;
202        self
203    }
204}
205
206/// Drives §5.5's commissioning sequence.
207///
208/// Sans-I/O: [`Commissioner::step`] says what to send and [`Commissioner::on_response`] takes
209/// what came back. The buffers are the commissioner's, so nothing here allocates.
210#[derive(Debug)]
211pub struct Commissioner {
212    stage: Stage,
213    plan: Plan,
214    /// The PASE session's `AttestationChallenge` — §11.18.4.7 and §11.18.6.5 both sign over it,
215    /// which is what binds an attestation to *this* session rather than a recording of another.
216    challenge: SymmetricKey,
217    attestation_nonce: [u8; ATTESTATION_NONCE_LEN],
218    csr_nonce: [u8; CSR_NONCE_LEN],
219    dac: heapless::Vec<u8, DER_CERT_MAX>,
220    pai: heapless::Vec<u8, DER_CERT_MAX>,
221    /// The operational public key the device generated for its CSR.
222    operational_key: Option<PublicKey>,
223    attestation: Option<Attestation>,
224    /// Scratch for the command being sent.
225    fields: heapless::Vec<u8, 1024>,
226}
227
228impl Commissioner {
229    /// A commissioner about to run §5.5's initial phase over an established PASE session.
230    ///
231    /// `challenge` is that session's `AttestationChallenge` (§4.14.2.6.2) — the third key it
232    /// derived. `attestation_nonce` and `csr_nonce` are 32 octets each from the caller's own
233    /// [`Rng`](crate::platform::Rng): §11.18.6.1 and §11.18.6.5 make the device echo them back
234    /// inside the signed structure, which is what stops a recorded response being replayed.
235    #[must_use]
236    pub fn new(
237        plan: Plan,
238        challenge: SymmetricKey,
239        attestation_nonce: [u8; ATTESTATION_NONCE_LEN],
240        csr_nonce: [u8; CSR_NONCE_LEN],
241    ) -> Self {
242        Self {
243            stage: Stage::ArmFailSafe,
244            plan,
245            challenge,
246            attestation_nonce,
247            csr_nonce,
248            dac: heapless::Vec::new(),
249            pai: heapless::Vec::new(),
250            operational_key: None,
251            attestation: None,
252            fields: heapless::Vec::new(),
253        }
254    }
255
256    /// How far it has got.
257    #[must_use]
258    pub const fn stage(&self) -> Stage {
259        self.stage
260    }
261
262    /// What the device's attestation turned out to be, once it has been checked.
263    #[must_use]
264    pub const fn attestation(&self) -> Option<Attestation> {
265        self.attestation
266    }
267
268    /// The operational public key the device generated, once the CSR has arrived.
269    #[must_use]
270    pub const fn operational_key(&self) -> Option<PublicKey> {
271        self.operational_key
272    }
273
274    /// The node this commissioner is creating.
275    #[must_use]
276    pub const fn node_id(&self) -> NodeId {
277        self.plan.identity.node_id
278    }
279
280    /// The next thing to do.
281    ///
282    /// Borrows `self` mutably because the encoded command lives in the commissioner's own
283    /// buffer — a caller that wanted two outstanding at once would be running two
284    /// commissionings, which §5.5's fail-safe does not permit anyway.
285    pub fn step(&mut self) -> Result<Step<'_>> {
286        use operational_credentials::command as opcreds;
287        match self.stage {
288            Stage::ArmFailSafe => {
289                self.encode(&general_commissioning::ArmFailSafeFields {
290                    expiry_length_seconds: self.plan.fail_safe_seconds,
291                    // §11.10.7.2's breadcrumb is the commissioner's own progress marker; it
292                    // starts at zero and the caller may read it back after a resumed attempt.
293                    breadcrumb: 0,
294                })?;
295                Ok(self.invoke(
296                    general_commissioning::ID,
297                    general_commissioning::command::ARM_FAIL_SAFE,
298                ))
299            }
300            Stage::SetRegulatoryConfig => {
301                self.encode(&general_commissioning::SetRegulatoryConfigFields {
302                    new_regulatory_config: self.plan.regulatory_location,
303                    // §11.10.7.4's `CountryCode` is "the 2-character country code"; XX is
304                    // ISO 3166-1's user-assigned "unknown", which is what a commissioner with
305                    // no location knowledge should send rather than inventing a jurisdiction.
306                    country_code: "XX",
307                    breadcrumb: 0,
308                })?;
309                Ok(self.invoke(
310                    general_commissioning::ID,
311                    general_commissioning::command::SET_REGULATORY_CONFIG,
312                ))
313            }
314            Stage::RequestDac => {
315                self.encode(&operational_credentials::CertificateChainRequestFields {
316                    certificate_type:
317                        operational_credentials::CertificateChainTypeEnum::DACCertificate,
318                })?;
319                Ok(self.invoke(
320                    operational_credentials::ID,
321                    opcreds::CERTIFICATE_CHAIN_REQUEST,
322                ))
323            }
324            Stage::RequestPai => {
325                self.encode(&operational_credentials::CertificateChainRequestFields {
326                    certificate_type:
327                        operational_credentials::CertificateChainTypeEnum::PAICertificate,
328                })?;
329                Ok(self.invoke(
330                    operational_credentials::ID,
331                    opcreds::CERTIFICATE_CHAIN_REQUEST,
332                ))
333            }
334            Stage::RequestAttestation => {
335                let nonce = self.attestation_nonce;
336                self.encode(&operational_credentials::AttestationRequestFields {
337                    attestation_nonce: &nonce,
338                })?;
339                Ok(self.invoke(operational_credentials::ID, opcreds::ATTESTATION_REQUEST))
340            }
341            Stage::RequestCsr => {
342                let nonce = self.csr_nonce;
343                self.encode(&operational_credentials::CSRRequestFields {
344                    csr_nonce: &nonce,
345                    // §11.18.6.5: absent or false means a *new* fabric. `UpdateNOC`'s form is
346                    // a different flow entirely.
347                    is_for_update_noc: Some(false),
348                })?;
349                Ok(self.invoke(operational_credentials::ID, opcreds::CSR_REQUEST))
350            }
351            Stage::AddTrustedRoot | Stage::AddNoc => {
352                // Both need the CA, which `step` has no access to. `add_root` and `add_noc`
353                // take it; reaching here means the caller skipped them.
354                Err(Error::new(ErrorCode::InvalidState))
355            }
356            Stage::Operational => Ok(Step::Operational {
357                node_id: self.plan.identity.node_id,
358            }),
359            Stage::CommissioningComplete => {
360                self.fields.clear();
361                Ok(self.invoke(
362                    general_commissioning::ID,
363                    general_commissioning::command::COMMISSIONING_COMPLETE,
364                ))
365            }
366            Stage::Done => Ok(Step::Done),
367        }
368    }
369
370    /// §5.5 step 13's `AddTrustedRootCertificate`, with the fabric's own root.
371    ///
372    /// Separate from [`Commissioner::step`] because it needs the CA, and the CA holds a key
373    /// handle into a store this type deliberately does not own.
374    pub fn add_root<K: KeyStore>(&mut self, ca: &CertAuthority, keys: &K) -> Result<Step<'_>> {
375        if self.stage != Stage::AddTrustedRoot {
376            return Err(Error::new(ErrorCode::InvalidState));
377        }
378        let mut root = [0u8; CERT_TLV_MAX];
379        let root = ca.self_signed_root(keys, &mut root, self.plan.validity)?;
380        self.encode(&operational_credentials::AddTrustedRootCertificateFields {
381            root_ca_certificate: root,
382        })?;
383        Ok(self.invoke(
384            operational_credentials::ID,
385            operational_credentials::command::ADD_TRUSTED_ROOT_CERTIFICATE,
386        ))
387    }
388
389    /// §5.5 step 13's `AddNOC`, with a certificate issued for the key the device generated.
390    ///
391    /// `icac` is the intermediate to send alongside, when the deployment uses one; §6.4.5.1
392    /// permits a NOC issued straight by the root.
393    pub fn add_noc<K: KeyStore>(
394        &mut self,
395        ca: &CertAuthority,
396        keys: &K,
397        icac: Option<&[u8]>,
398    ) -> Result<Step<'_>> {
399        if self.stage != Stage::AddNoc {
400            return Err(Error::new(ErrorCode::InvalidState));
401        }
402        let public_key = self
403            .operational_key
404            .ok_or_else(|| Error::new(ErrorCode::InvalidState))?;
405        let mut noc = [0u8; CERT_TLV_MAX];
406        let noc = ca.issue_noc(
407            keys,
408            &mut noc,
409            &self.plan.identity,
410            &public_key,
411            self.plan.validity,
412        )?;
413        // §11.18.6.9's `IPKValue` is the fabric's Identity Protection Key — the epoch key that
414        // makes operational discovery unlinkable and group messages authenticable. It is
415        // derived from the CA's own signature over the fabric id, so every administrator on the
416        // fabric computes the same one without ever sending it in the clear.
417        let ipk = self.ipk(ca, keys)?;
418        self.encode(&operational_credentials::AddNOCFields {
419            noc_value: noc,
420            icac_value: icac,
421            ipk_value: &ipk,
422            case_admin_subject: self.plan.case_admin_subject,
423            admin_vendor_id: self.plan.admin_vendor_id,
424        })?;
425        Ok(self.invoke(
426            operational_credentials::ID,
427            operational_credentials::command::ADD_NOC,
428        ))
429    }
430
431    /// The fabric's Identity Protection Key (§4.15.2, §11.18.6.9).
432    ///
433    /// Derived rather than random so that every administrator on the fabric arrives at the same
434    /// value from the root key alone. A random IPK would have to be *transported* between
435    /// administrators, and §4.15.2's whole point is that it is a shared secret nobody needs to
436    /// send.
437    fn ipk<K: KeyStore>(&self, ca: &CertAuthority, keys: &K) -> Result<[u8; 16]> {
438        let mut material = [0u8; 8];
439        material.copy_from_slice(&self.plan.identity.fabric_id.0.to_be_bytes());
440        let signature = keys.sign(ca.key(), &material)?;
441        let digest = crate::crypto::hash(signature.as_bytes());
442        let mut ipk = [0u8; 16];
443        let head = digest
444            .get(..16)
445            .ok_or_else(|| Error::new(ErrorCode::InvalidState))?;
446        ipk.copy_from_slice(head);
447        Ok(ipk)
448    }
449
450    /// Takes the response to the command [`Commissioner::step`] handed out.
451    ///
452    /// `fields` is the response command's `CommandFields`, or `None` for a command whose
453    /// response is a bare status — which is `AddTrustedRootCertificate` and nothing else in
454    /// this flow (§11.18.6.13 defines no response command for it).
455    pub fn on_response(&mut self, fields: Option<&[u8]>) -> Result<()> {
456        match self.stage {
457            Stage::ArmFailSafe => {
458                self.check_commissioning_error(fields)?;
459                self.stage = if self.plan.needs_regulatory_config {
460                    Stage::SetRegulatoryConfig
461                } else {
462                    Stage::RequestDac
463                };
464            }
465            Stage::SetRegulatoryConfig => {
466                self.check_commissioning_error(fields)?;
467                self.stage = Stage::RequestDac;
468            }
469            Stage::RequestDac => {
470                let certificate = Self::certificate(fields)?;
471                self.dac = heapless::Vec::from_slice(certificate)
472                    .map_err(|_| Error::new(ErrorCode::BufferTooSmall))?;
473                self.stage = Stage::RequestPai;
474            }
475            Stage::RequestPai => {
476                let certificate = Self::certificate(fields)?;
477                self.pai = heapless::Vec::from_slice(certificate)
478                    .map_err(|_| Error::new(ErrorCode::BufferTooSmall))?;
479                self.stage = Stage::RequestAttestation;
480            }
481            Stage::RequestAttestation => {
482                self.check_attestation(fields)?;
483                self.stage = Stage::RequestCsr;
484            }
485            Stage::RequestCsr => {
486                self.check_csr(fields)?;
487                self.stage = Stage::AddTrustedRoot;
488            }
489            Stage::AddTrustedRoot => {
490                // §11.18.6.13 defines no response command for `AddTrustedRootCertificate`: it
491                // answers with a bare `SUCCESS`, and the caller reports that by passing `None`.
492                // A commissioner that expected a `NOCResponse` here would fail on a conformant
493                // device — which is exactly what the end-to-end test caught.
494                if fields.is_some_and(|fields| !fields.is_empty()) {
495                    return Err(Error::new(ErrorCode::InvalidState));
496                }
497                self.stage = Stage::AddNoc;
498            }
499            Stage::AddNoc => {
500                Self::check_noc_status(fields)?;
501                self.stage = Stage::Operational;
502            }
503            Stage::Operational => return Err(Error::new(ErrorCode::InvalidState)),
504            Stage::CommissioningComplete => {
505                self.check_commissioning_error(fields)?;
506                self.stage = Stage::Done;
507            }
508            Stage::Done => return Err(Error::new(ErrorCode::InvalidState)),
509        }
510        Ok(())
511    }
512
513    /// The caller has configured the network, found the node and established CASE.
514    ///
515    /// §5.5's setup phase step 4: `CommissioningComplete` "SHALL be invoked over a CASE
516    /// session", and §11.10.7.6 makes the device refuse it over PASE — which is what proves the
517    /// credentials just installed actually work before the fail-safe is allowed to lapse.
518    pub fn on_operational(&mut self) -> Result<()> {
519        if self.stage != Stage::Operational {
520            return Err(Error::new(ErrorCode::InvalidState));
521        }
522        self.stage = Stage::CommissioningComplete;
523        Ok(())
524    }
525
526    /// Whether the caller may do its own work here — §5.5 steps 14–16.
527    ///
528    /// True at [`Stage::Operational`], which sits between the credentials being installed and
529    /// CASE being established: the ACL, the Wi-Fi credentials and the Thread dataset all go in
530    /// this window, and all of them are the caller's because none of them is derivable.
531    #[must_use]
532    pub const fn pause(&self) -> bool {
533        matches!(self.stage, Stage::Operational)
534    }
535
536    /// Encodes a command's fields into the commissioner's buffer.
537    fn encode<T: ToTlv>(&mut self, fields: &T) -> Result<()> {
538        let mut buf = [0u8; 1024];
539        let mut writer = TlvWriter::new_in(&mut buf, ContainerKind::Structure);
540        fields.to_tlv(&mut writer, Tag::Context(1))?;
541        let encoded = writer.finish()?;
542        self.fields = heapless::Vec::from_slice(encoded)
543            .map_err(|_| Error::new(ErrorCode::BufferTooSmall))?;
544        Ok(())
545    }
546
547    fn invoke(&self, cluster: ClusterId, command: CommandId) -> Step<'_> {
548        Step::Invoke {
549            endpoint: ROOT_ENDPOINT,
550            cluster,
551            command,
552            fields: &self.fields,
553        }
554    }
555
556    /// §11.10.7.3, §11.10.7.5 and §11.10.7.7 all answer with the same shape.
557    fn check_commissioning_error(&self, fields: Option<&[u8]>) -> Result<()> {
558        let decoded: general_commissioning::ArmFailSafeResponseFields<'_> =
559            decode(fields.ok_or_else(|| Error::new(ErrorCode::InvalidState))?)?;
560        if decoded.error_code != general_commissioning::CommissioningErrorEnum::OK {
561            return Err(Error::new(ErrorCode::CommissioningFailed));
562        }
563        Ok(())
564    }
565
566    /// §11.18.6.10's `NOCResponse`.
567    fn check_noc_status(fields: Option<&[u8]>) -> Result<()> {
568        let decoded: operational_credentials::NOCResponseFields<'_> =
569            decode(fields.ok_or_else(|| Error::new(ErrorCode::InvalidState))?)?;
570        if decoded.status_code != operational_credentials::NodeOperationalCertStatusEnum::OK {
571            return Err(Error::new(ErrorCode::CommissioningFailed));
572        }
573        Ok(())
574    }
575
576    fn certificate(fields: Option<&[u8]>) -> Result<&[u8]> {
577        let decoded: operational_credentials::CertificateChainResponseFields<'_> =
578            decode(fields.ok_or_else(|| Error::new(ErrorCode::InvalidState))?)?;
579        Ok(decoded.certificate)
580    }
581
582    /// §6.2.3's Device Attestation Procedure, as far as a commissioner with no DCL can run it.
583    ///
584    /// The PAA is the one thing that cannot come from the device — §6.2.3 requires it from the
585    /// commissioner's own trust store — so [`Commissioner::verify_attestation_against`] takes it
586    /// and this records what happened. §5.5 step 10 makes the *decision* the caller's: a failure
587    /// here is reported, not fatal, because a development device with an uncertified PAA is a
588    /// case the specification explicitly wants to be commissionable with a warning.
589    fn check_attestation(&mut self, fields: Option<&[u8]>) -> Result<()> {
590        let decoded: operational_credentials::AttestationResponseFields<'_> =
591            decode(fields.ok_or_else(|| Error::new(ErrorCode::InvalidState))?)?;
592        let signature = Signature::from_slice(decoded.attestation_signature)?;
593        let outcome = (|| -> Result<()> {
594            let dac = X509Certificate::parse(&self.dac)?;
595            // §11.18.6.2: the signature is over the elements *and* the session's challenge, so
596            // a recording from another session does not verify here.
597            if !verify_attestation(
598                &dac.public_key,
599                decoded.attestation_elements,
600                &self.challenge,
601                &signature,
602            )? {
603                return Err(Error::new(ErrorCode::AttestationFailed));
604            }
605            // §11.18.6.1: "the Commissioner SHALL verify that the AttestationNonce ... matches
606            // the one it sent". Without this a device could replay any prior attestation.
607            let elements = AttestationElements::decode(decoded.attestation_elements)?;
608            if elements.attestation_nonce != self.attestation_nonce {
609                return Err(Error::new(ErrorCode::AttestationFailed));
610            }
611            Ok(())
612        })();
613        self.attestation = Some(match outcome {
614            Ok(()) => Attestation::Trusted,
615            Err(error) => Attestation::Failed(error.code()),
616        });
617        Ok(())
618    }
619
620    /// Completes §6.2.3 with a PAA from the commissioner's trust store.
621    ///
622    /// Call this after [`Stage::RequestAttestation`] and before deciding whether to go on.
623    /// §6.2.3's chain check needs a root the *commissioner* trusts, which is the whole point:
624    /// a device that supplied its own would be attesting to itself.
625    pub fn verify_attestation_against(&mut self, paa_der: &[u8]) -> Result<Attestation> {
626        let outcome = (|| -> Result<()> {
627            let dac = X509Certificate::parse(&self.dac)?;
628            let pai = X509Certificate::parse(&self.pai)?;
629            let paa = X509Certificate::parse(paa_der)?;
630            verify_dac_chain(&dac, &pai, &paa)?;
631            Ok(())
632        })();
633        let result = match (self.attestation, outcome) {
634            // A chain that verifies does not rescue a signature that did not.
635            (Some(Attestation::Failed(reason)), _) => Attestation::Failed(reason),
636            (_, Err(error)) => Attestation::Failed(error.code()),
637            (_, Ok(())) => Attestation::Trusted,
638        };
639        self.attestation = Some(result);
640        Ok(result)
641    }
642
643    /// §11.18.6.6's `CSRResponse`.
644    fn check_csr(&mut self, fields: Option<&[u8]>) -> Result<()> {
645        let decoded: operational_credentials::CSRResponseFields<'_> =
646            decode(fields.ok_or_else(|| Error::new(ErrorCode::InvalidState))?)?;
647        let signature = Signature::from_slice(decoded.attestation_signature)?;
648        let dac = X509Certificate::parse(&self.dac)?;
649        // §11.18.6.6: the NOCSR is signed by the *DAC* key, not the new operational key — which
650        // is what ties the freshly generated operational key to the device attestation already
651        // performed. Verifying it against the operational key inside would be circular.
652        if !verify_nocsr(
653            &dac.public_key,
654            decoded.nocsr_elements,
655            &self.challenge,
656            &signature,
657        )? {
658            return Err(Error::new(ErrorCode::AttestationFailed));
659        }
660        let elements = NocsrElements::decode(decoded.nocsr_elements)?;
661        // §11.18.6.6: "the Commissioner SHALL verify that the CSRNonce ... matches". Same replay
662        // argument as the attestation nonce, and it matters more here: a replayed CSR would put
663        // a *previous* device's key into this device's certificate.
664        if elements.csr_nonce != self.csr_nonce {
665            return Err(Error::new(ErrorCode::AttestationFailed));
666        }
667        let csr = Csr::parse(elements.csr)?;
668        // The CSR is self-signed by the operational key: PKCS#10's proof of possession, and
669        // without it a device could hand over somebody else's public key.
670        if !crate::crypto::verify(&csr.public_key, csr.tbs, &csr.signature)? {
671            return Err(Error::new(ErrorCode::AttestationFailed));
672        }
673        self.operational_key = Some(csr.public_key);
674        Ok(())
675    }
676}
677
678/// Decodes a response command's `CommandFields`.
679fn decode<'a, T: crate::tlv::FromTlv<'a>>(fields: &'a [u8]) -> Result<T> {
680    let mut reader = crate::tlv::TlvReader::new_in(fields, ContainerKind::Structure);
681    let element = reader
682        .next_element()?
683        .ok_or_else(|| Error::new(ErrorCode::TlvTruncated))?;
684    T::from_tlv(&mut reader, &element)
685}