matter_kit/cert/chain.rs
1//! Validating an operational certificate chain (Core §6.4.5).
2//!
3//! A node presents a NOC, optionally preceded by an ICAC. The verifier already holds the
4//! root: "A Root CA certificate is self-signed. They are not verified but rather trusted
5//! because they were provisioned by a trusted Commissioner" — §6.4.5.3, which is the whole
6//! reason the chain terminates somewhere.
7//!
8//! # What a chain check is, concretely
9//!
10//! Four things have to line up at every link, and each catches a different attack:
11//!
12//! | Check | What it stops |
13//! |---|---|
14//! | signature over the regenerated DER | a forged certificate |
15//! | issuer DN equals the issuer's subject DN | a certificate spliced under the wrong CA |
16//! | `is-ca`, key usage, path length | a leaf certificate used to sign others |
17//! | `matter-fabric-id` agreement | a valid certificate from a *different* fabric |
18//!
19//! The signature check is the one that needs [`der`]: §6.4.5's "The signature
20//! field of a certificate SHALL be calculated using the X.509v3 encoding of the
21//! certificate", so the DER has to be rebuilt before anything can be hashed.
22//!
23//! # Time
24//!
25//! [`verify_chain`] takes an `Option<u32>` for now, because §6.4.5.1 permits omitting the
26//! check: "For constrained or sleepy devices that lack accurate time, enforcement of an
27//! NOC's validity period MAY be omitted." Passing `None` is that choice, made explicitly,
28//! rather than a validity check that was quietly never written.
29
30use crate::cert::{CERT_DER_MAX, CertType, DnAttributeKind, MatterCertificate, der};
31use crate::crypto::verify;
32use crate::error::{Error, ErrorCode, Result};
33use crate::msg::{FabricId, NodeId};
34
35/// The operational identity a validated chain establishes.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct VerifiedIdentity {
38 /// The NOC's `matter-node-id`.
39 pub node_id: NodeId,
40 /// The `matter-fabric-id` shared by the chain.
41 pub fabric_id: FabricId,
42 /// Every `matter-noc-cat` the NOC carried (§6.6.2.1.2).
43 ///
44 /// Part of the *identity*, not a detail of the certificate: §6.6.6.3 builds the
45 /// access-control subject from a CASE session's node id **and** its CATs, so dropping
46 /// them here would leave every CAT-based access control entry unable to match anything —
47 /// silently, and in the direction that denies rather than grants.
48 pub cats: heapless::Vec<crate::msg::CaseAuthenticatedTag, { crate::cert::dn::MAX_NOC_CATS }>,
49}
50
51fn path_invalid() -> Error {
52 Error::new(ErrorCode::CertPathInvalid)
53}
54
55/// Verifies a Node Operational Certificate against a trusted root, through an optional
56/// intermediate.
57///
58/// `at` is the current time as a Matter `epoch-s`, or `None` on a node without a clock.
59///
60/// The root is assumed trusted and is **not** verified against itself: §6.4.5.3 says trust
61/// in it comes from the commissioner that installed it, not from its own self-signature.
62/// What *is* checked is that it is a well-formed RCAC, because a malformed one would let
63/// every later check pass vacuously.
64pub fn verify_chain(
65 noc: &MatterCertificate<'_>,
66 icac: Option<&MatterCertificate<'_>>,
67 root: &MatterCertificate<'_>,
68 at: Option<u32>,
69) -> Result<VerifiedIdentity> {
70 root.validate_as(CertType::Rcac)?;
71 noc.validate_as(CertType::Noc)?;
72 if let Some(icac) = icac {
73 icac.validate_as(CertType::Icac)?;
74 }
75
76 // The issuer of the NOC is the ICAC when there is one, and the root otherwise —
77 // §6.4.5.1: "issued by either a Root CA trusted within the Fabric or by an Intermediate
78 // Certificate Authority whose ICA certificate is directly issued by such a Root CA."
79 let noc_issuer = icac.unwrap_or(root);
80 check_link(noc, noc_issuer, at)?;
81 if let Some(icac) = icac {
82 check_link(icac, root, at)?;
83 // "An ICA certificate is directly issued by such a Root CA" — one level, so the
84 // root's path length constraint, if any, must permit exactly this.
85 if root
86 .extensions
87 .basic_constraints()
88 .and_then(|b| b.path_len_constraint)
89 .is_some_and(|limit| limit < 1)
90 {
91 return Err(path_invalid());
92 }
93 }
94 if let Some(at) = at {
95 check_validity(root, at)?;
96 }
97
98 // §6.5.6.3: "When any matter-fabric-id attributes are present in either the Matter Root
99 // CA Certificate or the Matter ICA Certificate, the value SHALL match the one present
100 // in the Matter Node Operational Certificate (NOC) within the same certificate chain."
101 let fabric_id = noc.fabric_id().ok_or_else(path_invalid)?;
102 for authority in [Some(root), icac].into_iter().flatten() {
103 if authority.subject.count(DnAttributeKind::MatterFabricId) != 0
104 && authority.fabric_id() != Some(fabric_id)
105 {
106 return Err(path_invalid());
107 }
108 }
109
110 Ok(VerifiedIdentity {
111 node_id: noc.node_id().ok_or_else(path_invalid)?,
112 fabric_id,
113 cats: noc.subject.noc_cats(),
114 })
115}
116
117/// Checks one certificate against the one that issued it.
118fn check_link(
119 subject: &MatterCertificate<'_>,
120 issuer: &MatterCertificate<'_>,
121 at: Option<u32>,
122) -> Result<()> {
123 // The issuer has to be able to sign, which for an RCAC or ICAC its own `validate`
124 // already established; asserting it here too makes this function safe to call on its
125 // own.
126 if !issuer.is_ca() {
127 return Err(path_invalid());
128 }
129 if subject.issuer != issuer.subject {
130 return Err(path_invalid());
131 }
132 // §6.5.11.5: the authority key identifier is "the 160-bit SHA-1 hash of the public key
133 // used to verify the certificate's signature" — so it names the issuer's subject key
134 // identifier. This is a cheap pre-filter, not a security check; the signature is.
135 match (
136 subject.extensions.authority_key_id(),
137 issuer.extensions.subject_key_id(),
138 ) {
139 (Some(authority), Some(subject_key)) if authority == subject_key => {}
140 _ => return Err(path_invalid()),
141 }
142 if let Some(at) = at {
143 check_validity(subject, at)?;
144 }
145
146 let mut buf = [0u8; CERT_DER_MAX];
147 let tbs = der::tbs_certificate(subject, &mut buf)?;
148 if !verify(&issuer.public_key, tbs, &subject.signature)? {
149 return Err(path_invalid());
150 }
151 Ok(())
152}
153
154fn check_validity(cert: &MatterCertificate<'_>, at: u32) -> Result<()> {
155 if cert.is_valid_at(at) {
156 Ok(())
157 } else {
158 Err(Error::new(ErrorCode::CertExpired))
159 }
160}
161
162/// Verifies that a root certificate's self-signature is consistent.
163///
164/// Not part of [`verify_chain`], and deliberately: §6.4.5.3 makes a root trusted by
165/// provenance, not by its own signature, and a self-signature proves only that whoever made
166/// the certificate held the key in it. It is worth running once when a root is *installed*
167/// — `AddTrustedRootCertificate` — where it catches a corrupted or mis-transcribed root
168/// before it is committed to the fabric table.
169pub fn verify_self_signed(root: &MatterCertificate<'_>) -> Result<bool> {
170 root.validate_as(CertType::Rcac)?;
171 if root.issuer != root.subject {
172 return Ok(false);
173 }
174 let mut buf = [0u8; CERT_DER_MAX];
175 let tbs = der::tbs_certificate(root, &mut buf)?;
176 verify(&root.public_key, tbs, &root.signature)
177}