Skip to main content

matter_kit/
ca.rs

1//! A fabric's certificate authority (Core §6.5) — issuing the identities a fabric is made of.
2//!
3//! Every Matter fabric is rooted in one self-signed certificate, and every node on it holds a
4//! Node Operational Certificate chaining back to that root. §6.4.5.3 is blunt about what the
5//! root's authority rests on:
6//!
7//! > Trust in the Root CA is established by provenance, not by the self-signature.
8//!
9//! So a root is trusted because a commissioner installed it, and the CA's real job is the
10//! *other* two: issuing an ICAC when the deployment wants one, and issuing a NOC for each node
11//! it commissions.
12//!
13//! # This is the administrator's half of commissioning
14//!
15//! §11.18 gives the device's half — it generates a key, signs a CSR, and takes back a NOC. The
16//! CSR carries a public key and nothing else the CA is obliged to believe, which is the point:
17//! the *commissioner* decides the node id, the fabric id and the CATs, and the device is told
18//! what it has become. A CA that echoed a subject from the CSR would let a device name itself.
19//!
20//! # Keys stay in the store
21//!
22//! Nothing here takes a private key. [`CertAuthority`](crate::ca::CertAuthority) holds a [`KeyHandle`](crate::crypto::KeyHandle)
23//! and signs through the [`KeyStore`](crate::crypto::KeyStore), so a deployment with the CA key in a secure element works the same way as
24//! one with it in RAM — which is the case that matters, because this key is the fabric.
25//!
26//! ```rust,ignore
27//! use matter_kit::ca::{CertAuthority, Validity};
28//!
29//! // A fabric's root, self-signed, valid for ten years.
30//! let mut buf = [0u8; matter_kit::cert::CERT_TLV_MAX];
31//! let root = ca.self_signed_root(&keys, &mut buf, Validity::years(epoch_now, 10))?;
32//!
33//! // ...and a node's operational certificate under it.
34//! let mut buf = [0u8; matter_kit::cert::CERT_TLV_MAX];
35//! let noc = ca.issue_noc(&keys, &mut buf, &Identity::new(fabric_id, node_id), &csr_key, validity)?;
36//! ```
37
38use crate::cert::dn::{DistinguishedName, DnAttribute, DnAttributeKind};
39use crate::cert::{
40    BasicConstraints, CERT_DER_MAX, EllipticCurveId, Extension, Extensions, KEY_ID_LEN,
41    KeyPurposeId, KeyUsage, MatterCertificate, PublicKeyAlgorithm, SignatureAlgorithm, der,
42};
43use crate::crypto::{KeyHandle, KeyStore, PublicKey};
44use crate::error::{Error, ErrorCode, Result};
45use crate::msg::{CaseAuthenticatedTag, FabricId, NodeId};
46
47/// §6.5.5's `not-before`/`not-after`, in seconds since the Matter epoch (2000-01-01 UTC).
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct Validity {
50    /// `not-before`.
51    pub not_before: u32,
52    /// `not-after`. Zero is §6.5.5's "no well-defined expiration time".
53    pub not_after: u32,
54}
55
56impl Validity {
57    /// A window of `years` starting at `from`.
58    ///
59    /// §6.5.5 permits `not-after` to be zero, meaning "no well-defined expiration time", and
60    /// this never produces one: a fabric certificate that cannot expire is one that cannot be
61    /// rotated on a schedule, and the deployments that need that are rare enough to say so
62    /// explicitly with [`Validity::forever`].
63    #[must_use]
64    pub const fn years(from: u32, years: u32) -> Self {
65        Self {
66            not_before: from,
67            // 365.25 days, so a decade does not drift a fortnight early.
68            not_after: from.saturating_add(years.saturating_mul(31_557_600)),
69        }
70    }
71
72    /// §6.5.5's open-ended certificate — `not-after` of zero.
73    #[must_use]
74    pub const fn forever(from: u32) -> Self {
75        Self {
76            not_before: from,
77            not_after: 0,
78        }
79    }
80}
81
82/// Who a NOC is for.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct Identity {
85    /// The fabric.
86    pub fabric_id: FabricId,
87    /// The node.
88    pub node_id: NodeId,
89    /// §6.6.2.1.2's CASE Authenticated Tags, at most three (§6.5.6.3).
90    pub cats: [Option<CaseAuthenticatedTag>; MAX_CATS],
91}
92
93/// §6.5.6.3, on a NOC's subject DN: "The subject DN MAY encode at most three matter-noc-cat
94/// attributes."
95pub const MAX_CATS: usize = 3;
96
97impl Identity {
98    /// A plain identity with no CATs.
99    #[must_use]
100    pub const fn new(fabric_id: FabricId, node_id: NodeId) -> Self {
101        Self {
102            fabric_id,
103            node_id,
104            cats: [None; MAX_CATS],
105        }
106    }
107
108    /// The same identity carrying `cats`.
109    ///
110    /// Refuses more than [`MAX_CATS`], and refuses two tags with the same *identifier*: §6.6.2.1.2
111    /// makes the low sixteen bits a version, so two tags sharing an identifier are two versions
112    /// of one group, and an ACL matching on the higher would be silently satisfied by the lower.
113    pub fn with_cats(mut self, cats: &[CaseAuthenticatedTag]) -> Result<Self> {
114        if cats.len() > MAX_CATS {
115            return Err(Error::new(ErrorCode::InvalidArgument));
116        }
117        for (index, tag) in cats.iter().enumerate() {
118            if cats
119                .iter()
120                .skip(index.saturating_add(1))
121                .any(|other| other.identifier() == tag.identifier())
122            {
123                return Err(Error::new(ErrorCode::InvalidArgument));
124            }
125            if let Some(slot) = self.cats.get_mut(index) {
126                *slot = Some(*tag);
127            }
128        }
129        Ok(self)
130    }
131}
132
133/// Which kind of authority a [`CertAuthority`] is.
134///
135/// It decides one thing that matters: which DN attribute goes in the `issuer` of everything it
136/// signs. §6.5.6.3 gives a root `matter-rcac-id` and an intermediate `matter-icac-id`, and
137/// [`verify_chain`](crate::cert::verify_chain) compares `subject.issuer` to the issuer's own
138/// `subject` attribute for attribute — so getting this wrong produces a certificate that is
139/// individually valid and chains to nothing.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Authority {
142    /// A self-signed Root CA (§6.5.6.2), identified by `matter-rcac-id`.
143    Root,
144    /// An Intermediate CA (§6.5.6.2), identified by `matter-icac-id`.
145    ///
146    /// §6.4.5.1 permits exactly one level — "an Intermediate Certificate Authority whose ICA
147    /// certificate is directly issued by such a Root CA" — so an intermediate may issue NOCs
148    /// and nothing else. [`CertAuthority::issue_icac`] and
149    /// [`CertAuthority::self_signed_root`] refuse on one.
150    Intermediate,
151}
152
153/// A fabric's certificate authority.
154///
155/// Holds the CA's key *handle*, never the key. Signing goes through the [`KeyStore`], so a
156/// deployment that keeps the fabric root in a secure element and one that keeps it in RAM use
157/// the same code — and the first is the one that matters, because this key is the fabric.
158#[derive(Debug, Clone, Copy)]
159pub struct CertAuthority {
160    key: KeyHandle,
161    kind: Authority,
162    /// The `matter-rcac-id` or `matter-icac-id` in this CA's own subject (§6.5.6.2).
163    rcac_id: u64,
164    /// The fabric the root is scoped to, when it is scoped at all.
165    ///
166    /// §6.5.6.3 permits a root with no `matter-fabric-id`, and then it may sign NOCs for any
167    /// fabric. One *with* the attribute is pinned, and [`verify_chain`](crate::cert::verify_chain)
168    /// enforces that every NOC under it names the same fabric.
169    fabric_id: Option<FabricId>,
170}
171
172impl CertAuthority {
173    /// A root CA over a key already in the store, identified by `rcac_id`.
174    #[must_use]
175    pub const fn new(key: KeyHandle, rcac_id: u64) -> Self {
176        Self {
177            key,
178            kind: Authority::Root,
179            rcac_id,
180            fabric_id: None,
181        }
182    }
183
184    /// An intermediate CA over a key already in the store, identified by `icac_id`.
185    ///
186    /// `icac_id` must be the one that went into the ICAC's subject — this is what the NOCs it
187    /// signs name as their issuer, and `verify_chain` compares the two.
188    #[must_use]
189    pub const fn intermediate(key: KeyHandle, icac_id: u64) -> Self {
190        Self {
191            key,
192            kind: Authority::Intermediate,
193            rcac_id: icac_id,
194            fabric_id: None,
195        }
196    }
197
198    /// Which kind of authority this is.
199    #[must_use]
200    pub const fn kind(&self) -> Authority {
201        self.kind
202    }
203
204    /// The same CA, pinned to one fabric (§6.5.6.3).
205    #[must_use]
206    pub const fn for_fabric(mut self, fabric_id: FabricId) -> Self {
207        self.fabric_id = Some(fabric_id);
208        self
209    }
210
211    /// The key handle this CA signs with.
212    #[must_use]
213    pub const fn key(&self) -> KeyHandle {
214        self.key
215    }
216
217    /// Writes the fabric's self-signed root certificate (§6.5.6.2) into `buf`.
218    ///
219    /// The root is a CA with no path-length constraint, so it may sign an ICAC or a NOC
220    /// directly — §6.4.5.1 permits both, and which one a deployment uses is its own choice.
221    pub fn self_signed_root<'b, K: KeyStore>(
222        &self,
223        keys: &K,
224        buf: &'b mut [u8],
225        validity: Validity,
226    ) -> Result<&'b [u8]> {
227        if self.kind != Authority::Root {
228            return Err(Error::new(ErrorCode::InvalidArgument));
229        }
230        let public_key = keys.public_key(self.key)?;
231        let mut subject = DistinguishedName::new();
232        subject.push(DnAttribute::uint(
233            DnAttributeKind::MatterRcacId,
234            self.rcac_id,
235        ))?;
236        if let Some(fabric_id) = self.fabric_id {
237            subject.push(DnAttribute::uint(
238                DnAttributeKind::MatterFabricId,
239                fabric_id.0,
240            ))?;
241        }
242        // §6.5.11.2: an RCAC's key usage is "keyCertSign and CRLSign" — no digitalSignature,
243        // because the root signs certificates and revocation lists and nothing else. A root
244        // that could also sign arbitrary messages would be usable for more than it is trusted
245        // for.
246        self.sign_into(
247            keys,
248            buf,
249            &subject.clone(),
250            &subject,
251            &public_key,
252            validity,
253            Extension::BasicConstraints(BasicConstraints {
254                is_ca: true,
255                path_len_constraint: None,
256            }),
257            KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
258            // §6.5.12: "For Matter ICA Certificate and Matter Root CA Certificate: the extended
259            // key usage extension SHALL NOT be present." A CA is not an endpoint.
260            &[],
261            &public_key,
262        )
263    }
264
265    /// Writes an intermediate CA certificate (§6.5.6.2) for `public_key` into `buf`.
266    ///
267    /// §6.4.5.1 allows exactly one level: "an Intermediate Certificate Authority whose ICA
268    /// certificate is directly issued by such a Root CA", so this sets a path-length constraint
269    /// of zero. Without it a compromised ICAC could mint further CAs and the chain would stop
270    /// meaning what the root said it meant.
271    pub fn issue_icac<'b, K: KeyStore>(
272        &self,
273        keys: &K,
274        buf: &'b mut [u8],
275        icac_id: u64,
276        public_key: &PublicKey,
277        validity: Validity,
278    ) -> Result<&'b [u8]> {
279        // §6.4.5.1 permits one level: "an Intermediate Certificate Authority whose ICA
280        // certificate is directly issued by such a Root CA". An intermediate that could mint
281        // further intermediates would make the chain's depth unbounded, and the path-length
282        // constraint this very function writes says it must not.
283        if self.kind != Authority::Root {
284            return Err(Error::new(ErrorCode::InvalidArgument));
285        }
286        let root_key = keys.public_key(self.key)?;
287        let mut subject = DistinguishedName::new();
288        subject.push(DnAttribute::uint(DnAttributeKind::MatterIcacId, icac_id))?;
289        if let Some(fabric_id) = self.fabric_id {
290            subject.push(DnAttribute::uint(
291                DnAttributeKind::MatterFabricId,
292                fabric_id.0,
293            ))?;
294        }
295        self.sign_into(
296            keys,
297            buf,
298            &self.issuer()?,
299            &subject,
300            public_key,
301            validity,
302            Extension::BasicConstraints(BasicConstraints {
303                is_ca: true,
304                path_len_constraint: Some(0),
305            }),
306            KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
307            &[],
308            &root_key,
309        )
310    }
311
312    /// Writes a Node Operational Certificate (§6.5.6.1) into `buf`.
313    ///
314    /// `public_key` is the one the node generated and put in its `CSRRequest` response
315    /// (§11.18.6.5), and it is the *only* thing the CSR contributes: §6.5.6.1's subject is the
316    /// authority's to choose. A CA that echoed a subject the device proposed would let a device
317    /// name itself, and a device that could name itself could name itself as somebody else.
318    pub fn issue_noc<'b, K: KeyStore>(
319        &self,
320        keys: &K,
321        buf: &'b mut [u8],
322        identity: &Identity,
323        public_key: &PublicKey,
324        validity: Validity,
325    ) -> Result<&'b [u8]> {
326        // §6.5.6.3: a root pinned to one fabric may only sign for that fabric. Catching it here
327        // rather than at `verify_chain` means the CA never emits a certificate that cannot be
328        // used, instead of the device discovering it at `AddNOC`.
329        if self
330            .fabric_id
331            .is_some_and(|pinned| pinned != identity.fabric_id)
332        {
333            return Err(Error::new(ErrorCode::InvalidArgument));
334        }
335        // §6.5.6.1: "A Node Operational Certificate SHALL have exactly one matter-node-id and
336        // exactly one matter-fabric-id attribute." And §2.5.5 forbids a group or an unspecified
337        // node id as an operational identity.
338        if !identity.node_id.is_operational() {
339            return Err(Error::new(ErrorCode::InvalidArgument));
340        }
341        let root_key = keys.public_key(self.key)?;
342        let mut subject = DistinguishedName::new();
343        subject.push(DnAttribute::uint(
344            DnAttributeKind::MatterFabricId,
345            identity.fabric_id.0,
346        ))?;
347        subject.push(DnAttribute::uint(
348            DnAttributeKind::MatterNodeId,
349            identity.node_id.0,
350        ))?;
351        for cat in identity.cats.iter().flatten() {
352            subject.push(DnAttribute::uint(
353                DnAttributeKind::MatterNocCat,
354                u64::from(cat.0),
355            ))?;
356        }
357        // §6.5.11.2 and §6.5.11.3: a NOC signs and does key agreement for CASE, and is not a
358        // CA. `id-kp-serverAuth` and `id-kp-clientAuth` because a node is both — it answers
359        // interactions and initiates them.
360        self.sign_into(
361            keys,
362            buf,
363            &self.issuer()?,
364            &subject,
365            public_key,
366            validity,
367            Extension::BasicConstraints(BasicConstraints {
368                is_ca: false,
369                path_len_constraint: None,
370            }),
371            KeyUsage::DIGITAL_SIGNATURE,
372            // §6.5.12: a NOC's extended key usage is "exactly two key-purpose-id values:
373            // id-kp-serverAuth and id-kp-clientAuth". A node is both — it answers interactions
374            // and initiates them — and a certificate carrying only one would be refused by
375            // every conformant peer.
376            &[KeyPurposeId::ServerAuth, KeyPurposeId::ClientAuth],
377            &root_key,
378        )
379    }
380
381    /// The issuer DN this CA writes into the certificates it signs.
382    ///
383    /// The same attributes as this CA's own subject — §6.5.6.3 makes the link, and
384    /// [`verify_chain`](crate::cert::verify_chain) compares them attribute for attribute. A root
385    /// is named by `matter-rcac-id` and an intermediate by `matter-icac-id`, so an authority
386    /// that wrote the wrong one would produce certificates that are individually valid and
387    /// chain to nothing.
388    fn issuer(&self) -> Result<DistinguishedName<'static>> {
389        let mut issuer = DistinguishedName::new();
390        issuer.push(DnAttribute::uint(
391            match self.kind {
392                Authority::Root => DnAttributeKind::MatterRcacId,
393                Authority::Intermediate => DnAttributeKind::MatterIcacId,
394            },
395            self.rcac_id,
396        ))?;
397        if let Some(fabric_id) = self.fabric_id {
398            issuer.push(DnAttribute::uint(
399                DnAttributeKind::MatterFabricId,
400                fabric_id.0,
401            ))?;
402        }
403        Ok(issuer)
404    }
405
406    /// Builds, signs and encodes a certificate.
407    #[allow(clippy::too_many_arguments)]
408    fn sign_into<'b, K: KeyStore>(
409        &self,
410        keys: &K,
411        buf: &'b mut [u8],
412        issuer: &DistinguishedName<'_>,
413        subject: &DistinguishedName<'_>,
414        public_key: &PublicKey,
415        validity: Validity,
416        constraints: Extension<'static>,
417        key_usage: KeyUsage,
418        extended_key_usage: &[KeyPurposeId],
419        authority_key: &PublicKey,
420    ) -> Result<&'b [u8]> {
421        let mut extensions = Extensions::new();
422        extensions.push(constraints)?;
423        extensions.push(Extension::KeyUsage(key_usage))?;
424        if !extended_key_usage.is_empty() {
425            let purposes = heapless::Vec::from_slice(extended_key_usage)
426                .map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
427            extensions.push(Extension::ExtendedKeyUsage(purposes))?;
428        }
429        // §6.5.11.4 and §6.5.11.5: both key identifiers are "the 160-bit SHA-1 hash", and this
430        // crate has no SHA-1 — deliberately. §6.5.11.4 permits any method that produces a
431        // distinct 20-octet value ("other methods of generating unique key identifiers are also
432        // acceptable"), so these are the first 20 octets of SHA-256 over the public key, which
433        // is what rs-matter and the CHIP SDK's test CA both do. The identifiers are a
434        // *pre-filter* for chain building, never a security check — `verify_chain` says so and
435        // then checks the signature.
436        extensions.push(Extension::SubjectKeyId(key_id(public_key)?))?;
437        extensions.push(Extension::AuthorityKeyId(key_id(authority_key)?))?;
438
439        // §6.5.4: "A Matter certificate follows the same limitation on admissible serial
440        // numbers as in [RFC 5280]", and RFC 5280 §4.1.2.2 is where "The serial number MUST be
441        // a positive integer" lives — the Matter text delegates rather than restating it. The
442        // subject key id is already unique per key, and a certificate is identified by
443        // (issuer, serial) — so deriving it from the subject key makes two certificates for the
444        // same key and issuer collide, which is what we want: reissuing is not a new identity.
445        //
446        // Through `positive_serial`, because a digest is not a positive integer: its top bit is
447        // the INTEGER's sign, and one digest in 256 is not even valid DER content.
448        let serial = crate::cert::positive_serial(key_id(public_key)?);
449        let mut cert = MatterCertificate {
450            serial_number: &serial,
451            signature_algorithm: SignatureAlgorithm::EcdsaWithSha256,
452            issuer: issuer.clone(),
453            not_before: validity.not_before,
454            not_after: validity.not_after,
455            subject: subject.clone(),
456            public_key_algorithm: PublicKeyAlgorithm::EcPubKey,
457            elliptic_curve_id: EllipticCurveId::Prime256V1,
458            public_key: *public_key,
459            extensions,
460            // Filled in below; the signature covers everything above it.
461            signature: crate::crypto::Signature::from_bytes([0u8; 64]),
462        };
463        let mut der_buf = [0u8; CERT_DER_MAX];
464        let tbs = der::tbs_certificate(&cert, &mut der_buf)?;
465        cert.signature = keys.sign(self.key, tbs)?;
466        cert.encode(buf)
467    }
468}
469
470/// §6.5.11.4's key identifier: 20 octets derived from the public key.
471fn key_id(public_key: &PublicKey) -> Result<[u8; KEY_ID_LEN]> {
472    let digest = crate::crypto::hash(public_key.as_bytes());
473    // Unreachable: SHA-256 is 32 octets and `KEY_ID_LEN` is 20. `InvalidState` rather than a
474    // panic because the crate denies `panic` and a truncation that cannot happen should not
475    // be the one place that could.
476    let prefix = digest
477        .get(..KEY_ID_LEN)
478        .ok_or_else(|| Error::new(ErrorCode::InvalidState))?;
479    <[u8; KEY_ID_LEN]>::try_from(prefix).map_err(|_| Error::new(ErrorCode::InvalidState))
480}