matter_kit/attestation/factory.rs
1//! A development attestation chain (Core §6.2.2) — PAA, PAI and DAC that a test or a
2//! development device can actually use.
3//!
4//! Every Matter device carries a Device Attestation Certificate, provisioned in the factory and
5//! chaining to a Product Attestation Authority the CSA has approved. A device without one
6//! cannot be commissioned by a conformant commissioner without a warning, and a *test* device
7//! without one cannot exercise §6.2.3's procedure at all — which is most of what makes
8//! commissioning security rather than a handshake.
9//!
10//! So this builds one. It is the development counterpart of the real thing:
11//!
12//! ```text
13//! PAA self-signed, CA, path length 1 "Matter Development PAA"
14//! └── PAI CA, path length 0, Mvid "Matter Development PAI, Mvid:FFF1"
15//! └── DAC not a CA, Mvid + Mpid "Matter Development DAC, Mvid:FFF1 Mpid:8000"
16//! ```
17//!
18//! # This is not a certification path
19//!
20//! A PAA here is one this code made up, and no commissioner should trust it. §6.2.2.1 makes the
21//! trust decision the commissioner's — it holds the PAAs it accepts — so a chain from here is
22//! useful exactly where the commissioner has been told to accept it: a test, a development
23//! harness, a factory bring-up before the real credentials arrive. `0xFFF1`–`0xFFF4` are the
24//! vendor ids the CSA reserves for exactly this, and [`DevelopmentChain`] defaults to the first.
25//!
26//! # The VID and PID go in the Common Name
27//!
28//! §6.2.2.2 gives two ways to carry them, and this uses the *fallback*: the text form inside the
29//! Common Name, `"Mvid:FFF1 Mpid:8000"`. Not because it is better — §6.2.2.2 prefers the
30//! Matter-specific RDN attributes — but because it is the form that needs no OID this crate's
31//! certificate model does not already carry, and both are equally valid to a conformant
32//! verifier. §6.2.2.2 is explicit that the fallback exists for exactly this reason.
33
34use crate::cert::dn::{DistinguishedName, DnAttribute, DnAttributeKind};
35use crate::cert::{
36 BasicConstraints, CERT_DER_MAX, EllipticCurveId, Extension, Extensions, KEY_ID_LEN, KeyUsage,
37 MatterCertificate, PublicKeyAlgorithm, SignatureAlgorithm, der,
38};
39use crate::crypto::{KeyHandle, KeyStore, PublicKey, Signature};
40use crate::error::{Error, ErrorCode, Result};
41use crate::msg::VendorId;
42
43/// The longest Common Name this builds — a label, a VID and a PID.
44const CN_MAX: usize = 64;
45
46/// A vendor id the CSA reserves for test and development use.
47///
48/// §6.2.2.1 and the DCL both treat `0xFFF1`–`0xFFF4` as non-production. A device shipped with
49/// one of these will not pass certification, which is the point: a development chain should be
50/// visibly a development chain.
51pub const TEST_VENDOR_ID: VendorId = VendorId(0xFFF1);
52
53/// A development attestation authority.
54///
55/// Holds a key *handle*, never a key — the same argument as [`CertAuthority`](crate::ca::CertAuthority):
56/// a factory that keeps its PAA in an HSM and a test that keeps it in RAM run the same code.
57#[derive(Debug, Clone, Copy)]
58pub struct DevelopmentChain {
59 vendor_id: VendorId,
60 /// §6.2.2.4's `not-before`/`not-after`, in seconds since the Matter epoch.
61 not_before: u32,
62 not_after: u32,
63}
64
65impl DevelopmentChain {
66 /// A chain for [`TEST_VENDOR_ID`], valid from `not_before` for `years`.
67 #[must_use]
68 pub const fn new(not_before: u32, years: u32) -> Self {
69 Self {
70 vendor_id: TEST_VENDOR_ID,
71 not_before,
72 not_after: not_before.saturating_add(years.saturating_mul(31_557_600)),
73 }
74 }
75
76 /// The same chain for a different vendor id.
77 ///
78 /// Anything outside `0xFFF1`–`0xFFF4` is refused: a development chain claiming a real
79 /// vendor's id is a forgery, however well-intentioned, and §6.2.2 gives a commissioner no
80 /// way to tell the two apart except the id.
81 pub fn for_vendor(mut self, vendor_id: VendorId) -> Result<Self> {
82 if !(0xFFF1..=0xFFF4).contains(&vendor_id.0) {
83 return Err(Error::new(ErrorCode::InvalidArgument));
84 }
85 self.vendor_id = vendor_id;
86 Ok(self)
87 }
88
89 /// The vendor id this chain attests to.
90 #[must_use]
91 pub const fn vendor_id(&self) -> VendorId {
92 self.vendor_id
93 }
94
95 /// Writes a self-signed Product Attestation Authority certificate into `buf`.
96 ///
97 /// §6.2.2.4 rule 2: a PAA is a CA. `verify_dac_chain` additionally requires its path-length
98 /// constraint to be absent or exactly 1 — one intermediate between it and a DAC, which is
99 /// the shape §6.2.2 defines and no other.
100 pub fn paa<'b, K: KeyStore>(
101 &self,
102 keys: &K,
103 buf: &'b mut [u8],
104 key: KeyHandle,
105 ) -> Result<&'b [u8]> {
106 let public_key = keys.public_key(key)?;
107 let name = Name::plain("Matter Development PAA")?;
108 self.sign(
109 keys,
110 buf,
111 key,
112 name.dn()?,
113 name.dn()?,
114 &public_key,
115 &public_key,
116 BasicConstraints {
117 is_ca: true,
118 path_len_constraint: Some(1),
119 },
120 KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
121 )
122 }
123
124 /// Writes a Product Attestation Intermediate certificate into `buf`.
125 ///
126 /// §6.2.2.4 rule 5 puts the vendor id in the subject and rule 3 fixes the path length at 0:
127 /// a PAI signs DACs and nothing else.
128 pub fn pai<'b, K: KeyStore>(
129 &self,
130 keys: &K,
131 buf: &'b mut [u8],
132 paa_key: KeyHandle,
133 pai_public: &PublicKey,
134 ) -> Result<&'b [u8]> {
135 let paa_public = keys.public_key(paa_key)?;
136 let issuer = Name::plain("Matter Development PAA")?;
137 let subject = Name::with_vid("Matter Development PAI", self.vendor_id)?;
138 self.sign(
139 keys,
140 buf,
141 paa_key,
142 issuer.dn()?,
143 subject.dn()?,
144 pai_public,
145 &paa_public,
146 BasicConstraints {
147 is_ca: true,
148 path_len_constraint: Some(0),
149 },
150 KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
151 )
152 }
153
154 /// Writes a Device Attestation Certificate into `buf`.
155 ///
156 /// §6.2.2.4 rule 8 and 9: the subject carries exactly one vendor id and exactly one product
157 /// id, and rule 8a makes the vendor id match the issuer's — which is why the PAI's own name
158 /// is rebuilt here from the same `vendor_id` rather than passed in.
159 pub fn dac<'b, K: KeyStore>(
160 &self,
161 keys: &K,
162 buf: &'b mut [u8],
163 pai_key: KeyHandle,
164 dac_public: &PublicKey,
165 product_id: u16,
166 ) -> Result<&'b [u8]> {
167 let pai_public = keys.public_key(pai_key)?;
168 let issuer = Name::with_vid("Matter Development PAI", self.vendor_id)?;
169 let subject = Name::with_vid_pid("Matter Development DAC", self.vendor_id, product_id)?;
170 self.sign(
171 keys,
172 buf,
173 pai_key,
174 issuer.dn()?,
175 subject.dn()?,
176 dac_public,
177 &pai_public,
178 BasicConstraints {
179 is_ca: false,
180 path_len_constraint: None,
181 },
182 // §6.2.2.4 rule 12: "The KeyUsage bitstring SHALL only have the digitalSignature
183 // bit set." A DAC signs attestations; it is not a CA and does not do key agreement.
184 KeyUsage::DIGITAL_SIGNATURE,
185 )
186 }
187
188 #[allow(clippy::too_many_arguments)]
189 fn sign<'b, K: KeyStore>(
190 &self,
191 keys: &K,
192 buf: &'b mut [u8],
193 signing_key: KeyHandle,
194 issuer: DistinguishedName<'_>,
195 subject: DistinguishedName<'_>,
196 public_key: &PublicKey,
197 authority_key: &PublicKey,
198 constraints: BasicConstraints,
199 key_usage: KeyUsage,
200 ) -> Result<&'b [u8]> {
201 let mut extensions = Extensions::new();
202 extensions.push(Extension::BasicConstraints(constraints))?;
203 extensions.push(Extension::KeyUsage(key_usage))?;
204 extensions.push(Extension::SubjectKeyId(key_id(public_key)?))?;
205 extensions.push(Extension::AuthorityKeyId(key_id(authority_key)?))?;
206
207 // The subject key id doubles as the serial: a certificate is identified by (issuer,
208 // serial), and deriving it from the key makes reissuing the same key the same
209 // certificate rather than a second identity. `positive_serial` because §6.5.4 adopts
210 // RFC 5280's limitation on serial numbers, RFC 5280 §4.1.2.2 requires a positive
211 // integer, and a digest's top bit is the INTEGER's sign — and because one digest in 256
212 // is a redundant sign octet, which is not valid content at all.
213 let serial = crate::cert::positive_serial(key_id(public_key)?);
214 let mut cert = MatterCertificate {
215 serial_number: &serial,
216 signature_algorithm: SignatureAlgorithm::EcdsaWithSha256,
217 issuer,
218 not_before: self.not_before,
219 not_after: self.not_after,
220 subject,
221 public_key_algorithm: PublicKeyAlgorithm::EcPubKey,
222 elliptic_curve_id: EllipticCurveId::Prime256V1,
223 public_key: *public_key,
224 extensions,
225 signature: Signature::from_bytes([0u8; 64]),
226 };
227 let mut tbs_buf = [0u8; CERT_DER_MAX];
228 let tbs = der::tbs_certificate(&cert, &mut tbs_buf)?;
229 cert.signature = keys.sign(signing_key, tbs)?;
230 // The *X.509* form, not the Matter TLV one: §6.2.2 attestation certificates travel as
231 // DER, which is why `CertificateChainResponse` carries 600 octets and not 400.
232 der::certificate(&cert, buf)
233 }
234}
235
236/// A Common Name carrying §6.2.2.2's fallback VID/PID text.
237struct Name {
238 text: heapless::String<CN_MAX>,
239}
240
241impl Name {
242 fn plain(label: &str) -> Result<Self> {
243 let mut text = heapless::String::new();
244 text.push_str(label)
245 .map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
246 Ok(Self { text })
247 }
248
249 fn with_vid(label: &str, vendor_id: VendorId) -> Result<Self> {
250 let mut name = Self::plain(label)?;
251 name.push(" Mvid:", vendor_id.0)?;
252 Ok(name)
253 }
254
255 fn with_vid_pid(label: &str, vendor_id: VendorId, product_id: u16) -> Result<Self> {
256 let mut name = Self::with_vid(label, vendor_id)?;
257 name.push(" Mpid:", product_id)?;
258 Ok(name)
259 }
260
261 /// §6.2.2.2's fallback encoding: "uppercase hexadecimal, exactly 4 characters".
262 ///
263 /// Uppercase because §6.2.2.2's own example calls `Mvid:fff1` invalid, and this crate's
264 /// parser agrees — so a factory that wrote lowercase would produce a certificate its own
265 /// verifier rejects.
266 fn push(&mut self, prefix: &str, value: u16) -> Result<()> {
267 self.text
268 .push_str(prefix)
269 .map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
270 for shift in [12u32, 8, 4, 0] {
271 let nibble = u8::try_from((value >> shift) & 0xF).unwrap_or(0);
272 let digit = match nibble {
273 0..=9 => b'0'.saturating_add(nibble),
274 _ => b'A'.saturating_add(nibble.saturating_sub(10)),
275 };
276 self.text
277 .push(char::from(digit))
278 .map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
279 }
280 Ok(())
281 }
282
283 fn dn(&self) -> Result<DistinguishedName<'_>> {
284 let mut dn = DistinguishedName::new();
285 dn.push(DnAttribute::string(
286 DnAttributeKind::CommonName,
287 self.text.as_str(),
288 ))?;
289 Ok(dn)
290 }
291}
292
293/// The same 20-octet key identifier [`ca`](crate::ca) uses, and for the same reason: §6.2.2.4
294/// rules 11c and 11d require both identifiers, and they are a chain-building hint rather than a
295/// security check.
296fn key_id(public_key: &PublicKey) -> Result<[u8; KEY_ID_LEN]> {
297 let digest = crate::crypto::hash(public_key.as_bytes());
298 let prefix = digest
299 .get(..KEY_ID_LEN)
300 .ok_or_else(|| Error::new(ErrorCode::InvalidState))?;
301 <[u8; KEY_ID_LEN]>::try_from(prefix).map_err(|_| Error::new(ErrorCode::InvalidState))
302}