Skip to main content

matter_kit/attestation/
cd.rs

1//! The Certification Declaration (Core §6.3).
2//!
3//! A CD is the Connectivity Standards Alliance's signed statement that a device type passed
4//! certification: "Upon successful completion of certification by a device type, Connectivity
5//! Standards Alliance creates the CD for that device type so that it can be included in the
6//! device firmware by the manufacturer."
7//!
8//! It is the one place Matter uses CMS. The outer wrapper is an RFC 5652 `SignedData`; the
9//! content inside it is ordinary Matter TLV. So reading one is two parsers stacked:
10//! [`SignedData::parse`] peels the CMS, [`CertificationElements::decode`] reads the TLV.
11//!
12//! # What the signature covers
13//!
14//! The `SignerInfo` here carries no `signedAttrs`, and RFC 5652 §5.4 is explicit about what
15//! that means: with signed attributes absent, the signature is computed over the
16//! **eContent octets themselves**, not over a DER-encoded attribute set. So verification is
17//! `Crypto_Verify(CSA key, eContent, signature)` — and `eContent` is exactly the TLV
18//! [`SignedData::content`] hands back.
19//!
20//! Getting that wrong is the classic CMS mistake, and it fails in a way that looks like a
21//! bad key rather than a bad parse.
22//!
23//! # Who signs it
24//!
25//! §6.3.1 rule 5: "The subjectKeyIdentifier SHALL contain the subject key identifier (SKI)
26//! of a well-known Connectivity Standards Alliance certificate". So a CD does not carry the
27//! certificate that signed it — only a 20-octet hint. A commissioner looks the key up in a
28//! store it already trusts, which is why [`SignedData::signer_key_id`] is exposed and why
29//! verification takes a public key rather than finding one.
30
31use heapless::Vec;
32
33use crate::crypto::{PublicKey, Signature, verify};
34use crate::der::{
35    DerReader, OID_ECDSA_WITH_SHA256, OID_PKCS7_DATA, OID_SHA256, OID_SIGNED_DATA,
36    TAG_OCTET_STRING, TAG_SEQUENCE, TAG_SET, context_constructed, context_primitive,
37    ecdsa_sig_value_to_raw,
38};
39use crate::error::{Error, ErrorCode, Result, bail};
40use crate::msg::VendorId;
41use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value, set_once};
42
43/// `\[0\]` constructed — `content [0] EXPLICIT` in a `ContentInfo`, and `eContent [0]`.
44const TAG_EXPLICIT_0: u8 = context_constructed(0);
45/// `\[0\]` primitive — `subjectKeyIdentifier [0] IMPLICIT` in a `SignerIdentifier`.
46const TAG_SKI: u8 = context_primitive(0);
47
48/// "The format SHALL only support CMS version v3" (§6.3.1 rule 1).
49pub const CMS_VERSION: u64 = 3;
50
51/// A Subject Key Identifier is 20 octets — the SHA-1 length of RFC 5280's method (1).
52pub const KEY_ID_LEN: usize = 20;
53
54/// "product_id_array \[2\] : ARRAY \[ length 1..100 \]" (§6.3.1).
55pub const MAX_PRODUCT_IDS: usize = 100;
56
57/// "authorized_paa_list \[11, optional\] : ARRAY \[ length 1..10 \]" (§6.3.1).
58pub const MAX_AUTHORIZED_PAAS: usize = 10;
59
60/// "certificate_id \[4\] : STRING \[ length 19 \]" (§6.3.1).
61pub const CERTIFICATE_ID_LEN: usize = 19;
62
63/// The largest Certification Declaration this crate will parse.
64///
65/// 100 product ids, ten PAA identifiers and the fixed fields, plus the CMS wrapper. The
66/// specification sets no explicit cap; this one is derived from the field limits it does
67/// set, so a declaration that fits the schema fits here.
68pub const MAX_CD_LEN: usize = 1024;
69
70fn malformed() -> Error {
71    Error::new(ErrorCode::DerMalformed)
72}
73
74/// What kind of certification a declaration attests to (§6.3.1).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum CertificationType {
78    /// `0` — "used for development and test purposes".
79    DevelopmentAndTest,
80    /// `1` — "provisional - used to allow production and distribution to occur in parallel
81    /// with certification". A product may ship with one "if the Certification Declaration
82    /// can be replaced via software update".
83    Provisional,
84    /// `2` — "official - allocated after passing certification".
85    Official,
86    /// Anything else; the specification says "reserved".
87    Reserved(u8),
88}
89
90impl CertificationType {
91    /// The value a declaration carries.
92    #[must_use]
93    pub const fn from_value(value: u8) -> Self {
94        match value {
95            0 => Self::DevelopmentAndTest,
96            1 => Self::Provisional,
97            2 => Self::Official,
98            other => Self::Reserved(other),
99        }
100    }
101
102    /// The encoded value.
103    #[must_use]
104    pub const fn value(self) -> u8 {
105        match self {
106            Self::DevelopmentAndTest => 0,
107            Self::Provisional => 1,
108            Self::Official => 2,
109            Self::Reserved(v) => v,
110        }
111    }
112}
113
114/// `certification-elements` — the TLV inside a CD's `eContent` (§6.3.1).
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct CertificationElements<'a> {
117    /// `format_version \[0\]`. "SHALL contain the value 1."
118    pub format_version: u16,
119    /// `vendor_id \[1\]`.
120    pub vendor_id: VendorId,
121    /// `product_id_array \[2\]` — "a number of Product IDs which are covered by the same
122    /// certification (e.g. certification by similarity)".
123    pub product_ids: Vec<u16, MAX_PRODUCT_IDS>,
124    /// `device_type_id \[3\]` — "the device type identifier for the primary function".
125    pub device_type_id: u32,
126    /// `certificate_id \[4\]` — "a globally unique serial number allocated by the Connectivity
127    /// Standards Alliance".
128    pub certificate_id: &'a str,
129    /// `security_level \[5\]`. "Reserved for future use and SHALL be ignored at read time."
130    pub security_level: u8,
131    /// `security_information \[6\]`. Also reserved and ignored.
132    pub security_information: u16,
133    /// `version_number \[7\]` — the CD's own version, assigned by the CSA.
134    pub version_number: u16,
135    /// `certification_type \[8\]`.
136    pub certification_type: CertificationType,
137    /// `dac_origin_vendor_id \[9\]` — present only together with the product id.
138    pub dac_origin_vendor_id: Option<VendorId>,
139    /// `dac_origin_product_id \[10\]`.
140    pub dac_origin_product_id: Option<u16>,
141    /// `authorized_paa_list \[11\]` — the Subject Key Identifiers of the PAAs allowed to root
142    /// this product's DAC chain.
143    pub authorized_paas: Option<Vec<[u8; KEY_ID_LEN], MAX_AUTHORIZED_PAAS>>,
144}
145
146impl<'a> CertificationElements<'a> {
147    /// Decodes the TLV of a `eContent`.
148    pub fn decode(buf: &'a [u8]) -> Result<Self> {
149        let mut reader = TlvReader::new(buf);
150        let Some(head) = reader.next_element()? else {
151            bail!(TlvTruncated)
152        };
153        if head.value.container() != Some(ContainerKind::Structure) || !head.tag.is_anonymous() {
154            bail!(TlvWrongType)
155        }
156
157        let mut format_version = None;
158        let mut vendor_id = None;
159        let mut product_ids = Vec::new();
160        let mut has_product_ids = false;
161        let mut device_type_id = None;
162        let mut certificate_id = None;
163        let mut security_level = None;
164        let mut security_information = None;
165        let mut version_number = None;
166        let mut certification_type = None;
167        let mut dac_origin_vendor_id = None;
168        let mut dac_origin_product_id = None;
169        let mut authorized_paas = None;
170
171        loop {
172            let Some(element) = reader.next_element()? else {
173                bail!(TlvTruncated)
174            };
175            if element.value == Value::EndOfContainer {
176                break;
177            }
178            let Some(tag) = element.tag.context() else {
179                bail!(TlvInvalidTag)
180            };
181            match tag {
182                0 => set_once(&mut format_version, narrow_u16(element.unsigned()?)?)?,
183                1 => set_once(&mut vendor_id, VendorId(narrow_u16(element.unsigned()?)?))?,
184                2 => {
185                    if element.value.container() != Some(ContainerKind::Array) {
186                        bail!(TlvWrongType)
187                    }
188                    if has_product_ids {
189                        bail!(TlvDuplicateTag)
190                    }
191                    has_product_ids = true;
192                    read_u16_array(&mut reader, &mut product_ids)?;
193                }
194                3 => {
195                    let value = u32::try_from(element.unsigned()?)
196                        .map_err(|_| Error::new(ErrorCode::TlvOutOfRange))?;
197                    set_once(&mut device_type_id, value)?;
198                }
199                4 => {
200                    let text = element.utf8()?;
201                    // "certificate_id [4] : STRING [ length 19 ]" — a fixed length, so a
202                    // different one is a malformed declaration rather than a short id.
203                    if text.len() != CERTIFICATE_ID_LEN {
204                        bail!(TlvOutOfRange)
205                    }
206                    set_once(&mut certificate_id, text)?;
207                }
208                5 => {
209                    let value = u8::try_from(element.unsigned()?)
210                        .map_err(|_| Error::new(ErrorCode::TlvOutOfRange))?;
211                    set_once(&mut security_level, value)?;
212                }
213                6 => set_once(&mut security_information, narrow_u16(element.unsigned()?)?)?,
214                7 => set_once(&mut version_number, narrow_u16(element.unsigned()?)?)?,
215                8 => {
216                    let value = CertificationType::from_value(
217                        u8::try_from(element.unsigned()?)
218                            .map_err(|_| Error::new(ErrorCode::TlvOutOfRange))?,
219                    );
220                    set_once(&mut certification_type, value)?;
221                }
222                9 => {
223                    set_once(
224                        &mut dac_origin_vendor_id,
225                        VendorId(narrow_u16(element.unsigned()?)?),
226                    )?;
227                }
228                10 => set_once(&mut dac_origin_product_id, narrow_u16(element.unsigned()?)?)?,
229                11 => {
230                    if element.value.container() != Some(ContainerKind::Array) {
231                        bail!(TlvWrongType)
232                    }
233                    set_once(&mut authorized_paas, read_key_id_array(&mut reader)?)?;
234                }
235                // "Any context-specific tags not listed in the above schema for
236                // Certification Elements SHALL be reserved for future use, and SHALL be
237                // silently ignored if seen by a Commissioner which cannot understand them."
238                _ => reader.skip_value(&element)?,
239            }
240        }
241        reader.finish()?;
242
243        if !has_product_ids || product_ids.is_empty() {
244            // `ARRAY [ length 1.. ]`.
245            bail!(TlvNotFound)
246        }
247        // "The dac_origin_vendor_id and dac_origin_product_id SHALL only be present
248        // together" — and §6.2.3.1 makes a declaration "valid only if it contains both or
249        // neither".
250        if dac_origin_vendor_id.is_some() != dac_origin_product_id.is_some() {
251            bail!(TlvNotFound)
252        }
253
254        Ok(Self {
255            format_version: format_version.ok_or(Error::new(ErrorCode::TlvNotFound))?,
256            vendor_id: vendor_id.ok_or(Error::new(ErrorCode::TlvNotFound))?,
257            product_ids,
258            device_type_id: device_type_id.ok_or(Error::new(ErrorCode::TlvNotFound))?,
259            certificate_id: certificate_id.ok_or(Error::new(ErrorCode::TlvNotFound))?,
260            security_level: security_level.ok_or(Error::new(ErrorCode::TlvNotFound))?,
261            security_information: security_information.ok_or(Error::new(ErrorCode::TlvNotFound))?,
262            version_number: version_number.ok_or(Error::new(ErrorCode::TlvNotFound))?,
263            certification_type: certification_type.ok_or(Error::new(ErrorCode::TlvNotFound))?,
264            dac_origin_vendor_id,
265            dac_origin_product_id,
266            authorized_paas,
267        })
268    }
269
270    /// Encodes the TLV, in the `[tag-order]` the schema requires.
271    ///
272    /// A node never generates a CD — "Certification Declarations SHALL NOT be generated by
273    /// any Node" — so this exists for a test harness, a factory tool, and for proving the
274    /// decoder against the specification's vectors by round trip.
275    ///
276    /// **This output is not what a signature is checked against**, and that is deliberate.
277    /// The CMS signature covers the `eContent` octets exactly as they arrived, and
278    /// [`SignedData::content`] is a borrow of them rather than a re-encoding — so the one
279    /// thing this encoder normalises, integer width, can never reach a verification. Matter
280    /// TLV admits several widths for the same value and this writes the narrowest; the
281    /// specification's own declarations are already minimal and re-encode byte for byte.
282    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
283        let mut w = TlvWriter::new(buf);
284        w.start_structure(Tag::Anonymous)?;
285        w.unsigned(Tag::Context(0), u64::from(self.format_version))?;
286        w.unsigned(Tag::Context(1), u64::from(self.vendor_id.0))?;
287        w.start_array(Tag::Context(2))?;
288        for pid in &self.product_ids {
289            w.unsigned(Tag::Anonymous, u64::from(*pid))?;
290        }
291        w.end_container()?;
292        w.unsigned(Tag::Context(3), u64::from(self.device_type_id))?;
293        w.utf8(Tag::Context(4), self.certificate_id)?;
294        w.unsigned(Tag::Context(5), u64::from(self.security_level))?;
295        w.unsigned(Tag::Context(6), u64::from(self.security_information))?;
296        w.unsigned(Tag::Context(7), u64::from(self.version_number))?;
297        w.unsigned(Tag::Context(8), u64::from(self.certification_type.value()))?;
298        if let Some(vid) = self.dac_origin_vendor_id {
299            w.unsigned(Tag::Context(9), u64::from(vid.0))?;
300        }
301        if let Some(pid) = self.dac_origin_product_id {
302            w.unsigned(Tag::Context(10), u64::from(pid))?;
303        }
304        if let Some(paas) = self.authorized_paas.as_ref() {
305            w.start_array(Tag::Context(11))?;
306            for ski in paas {
307                w.octets(Tag::Anonymous, ski)?;
308            }
309            w.end_container()?;
310        }
311        w.end_container()?;
312        w.finish()
313    }
314
315    /// Whether `product_id` is one of those this declaration covers.
316    #[must_use]
317    pub fn covers_product(&self, product_id: u16) -> bool {
318        self.product_ids.contains(&product_id)
319    }
320
321    /// Whether `ski` is an authorised PAA, or the declaration does not restrict them.
322    ///
323    /// §6.2.3.1: "If the Certification Declaration contains the authorized_paa_list field …
324    /// The Subject Key Identifier (SKI) extension value of the PAA certificate, which is the
325    /// root of trust of the DAC, SHALL be present as one of the values". An absent list
326    /// authorises any PAA the commissioner already trusts.
327    #[must_use]
328    pub fn authorizes_paa(&self, ski: &[u8; KEY_ID_LEN]) -> bool {
329        self.authorized_paas
330            .as_ref()
331            .is_none_or(|list| list.contains(ski))
332    }
333}
334
335fn narrow_u16(value: u64) -> Result<u16> {
336    u16::try_from(value).map_err(|_| Error::new(ErrorCode::TlvOutOfRange))
337}
338
339fn read_u16_array(reader: &mut TlvReader<'_>, out: &mut Vec<u16, MAX_PRODUCT_IDS>) -> Result<()> {
340    loop {
341        let Some(element) = reader.next_element()? else {
342            bail!(TlvTruncated)
343        };
344        if element.value == Value::EndOfContainer {
345            return Ok(());
346        }
347        if !element.tag.is_anonymous() {
348            bail!(TlvInvalidTag)
349        }
350        out.push(narrow_u16(element.unsigned()?)?)
351            .map_err(|_| Error::new(ErrorCode::NoSpace))?;
352    }
353}
354
355fn read_key_id_array(
356    reader: &mut TlvReader<'_>,
357) -> Result<Vec<[u8; KEY_ID_LEN], MAX_AUTHORIZED_PAAS>> {
358    let mut out = Vec::new();
359    loop {
360        let Some(element) = reader.next_element()? else {
361            bail!(TlvTruncated)
362        };
363        if element.value == Value::EndOfContainer {
364            if out.is_empty() {
365                // `ARRAY [ length 1..10 ]`.
366                bail!(TlvNotFound)
367            }
368            return Ok(out);
369        }
370        if !element.tag.is_anonymous() {
371            bail!(TlvInvalidTag)
372        }
373        let ski = <[u8; KEY_ID_LEN]>::try_from(element.octets()?)
374            .map_err(|_| Error::new(ErrorCode::TlvOutOfRange))?;
375        out.push(ski).map_err(|_| Error::new(ErrorCode::NoSpace))?;
376    }
377}
378
379/// A parsed CMS `SignedData` carrying a Certification Declaration (RFC 5652 §5).
380///
381/// Only the profile §6.3.1 permits is accepted: version 3, a single SHA-256 digest
382/// algorithm, `pkcs7-data` content, one signer identified by Subject Key Identifier, and
383/// ECDSA-with-SHA256. Anything broader would be a parser for CMS rather than for a CD, with
384/// a correspondingly larger attack surface for no benefit.
385#[derive(Debug, Clone, PartialEq, Eq)]
386pub struct SignedData<'a> {
387    /// The `eContent` octets — the TLV of [`CertificationElements`], and the exact bytes the
388    /// signature covers.
389    pub content: &'a [u8],
390    /// The signer's Subject Key Identifier, which names a CSA key the commissioner must
391    /// already hold.
392    pub signer_key_id: [u8; KEY_ID_LEN],
393    /// The signature, converted from the DER `ECDSA-Sig-Value` to the `r || s` of §3.5.3.
394    pub signature: Signature,
395}
396
397impl<'a> SignedData<'a> {
398    /// Parses a CD.
399    pub fn parse(der: &'a [u8]) -> Result<Self> {
400        if der.len() > MAX_CD_LEN {
401            return Err(malformed());
402        }
403        // ContentInfo ::= SEQUENCE { contentType OID, content [0] EXPLICIT ANY }
404        let mut outer = DerReader::new(der);
405        let mut content_info = outer.expect_sequence()?;
406        outer.finish()?;
407        content_info.expect_oid(OID_SIGNED_DATA)?;
408        let mut explicit = content_info.expect(TAG_EXPLICIT_0)?.content_reader();
409        content_info.finish()?;
410
411        // SignedData ::= SEQUENCE { version, digestAlgorithms, encapContentInfo,
412        //                           certificates [0] OPTIONAL, crls [1] OPTIONAL,
413        //                           signerInfos }
414        let mut signed = explicit.expect_sequence()?;
415        explicit.finish()?;
416        if signed.expect_uint()? != CMS_VERSION {
417            return Err(malformed());
418        }
419
420        // digestAlgorithms: exactly one, sha256.
421        let mut digests = signed.expect_set()?;
422        let mut digest = digests.expect_sequence()?;
423        digest.expect_oid(OID_SHA256)?;
424        // An AlgorithmIdentifier may carry parameters; sha256's are absent or NULL, and
425        // neither changes anything, so whatever is there is skipped rather than refused.
426        digests.finish()?;
427
428        // encapContentInfo ::= SEQUENCE { eContentType OID, eContent [0] EXPLICIT OCTET
429        //                                 STRING OPTIONAL }
430        let mut encap = signed.expect_sequence()?;
431        encap.expect_oid(OID_PKCS7_DATA)?;
432        let mut econtent = encap.expect(TAG_EXPLICIT_0)?.content_reader();
433        let content = econtent.expect(TAG_OCTET_STRING)?.content;
434        econtent.finish()?;
435        encap.finish()?;
436
437        // certificates [0] and crls [1] are optional and not used by a CD; §6.3.1 names the
438        // signer by key identifier instead. Skipping rather than refusing keeps a
439        // declaration that carries its certificate readable.
440        let _ = signed.take_if(context_constructed(0))?;
441        let _ = signed.take_if(context_constructed(1))?;
442
443        // signerInfos: exactly one.
444        let mut signers = signed.expect(TAG_SET)?.content_reader();
445        signed.finish()?;
446        let mut signer = signers.expect_sequence()?;
447        // "there SHALL be exactly one signer" is implied by §6.3.1's single
448        // subjectKeyIdentifier rule; a second signer would leave it ambiguous which key
449        // verified the declaration.
450        signers.finish()?;
451
452        if signer.expect_uint()? != CMS_VERSION {
453            return Err(malformed());
454        }
455        // SignerIdentifier ::= CHOICE { issuerAndSerialNumber, subjectKeyIdentifier [0] }.
456        // §6.3.1 rule 5 requires the second.
457        let signer_key_id = <[u8; KEY_ID_LEN]>::try_from(signer.expect(TAG_SKI)?.content)
458            .map_err(|_| malformed())?;
459
460        let mut signer_digest = signer.expect_sequence()?;
461        signer_digest.expect_oid(OID_SHA256)?;
462
463        // signedAttrs [0] IMPLICIT. Its presence changes what the signature covers — see the
464        // module documentation — so it is refused rather than ignored.
465        if signer.peek_tag() == Some(context_constructed(0)) {
466            return Err(Error::new(ErrorCode::Unsupported));
467        }
468
469        let mut sig_algo = signer.expect_sequence()?;
470        sig_algo.expect_oid(OID_ECDSA_WITH_SHA256)?;
471
472        let signature_der = signer.expect(TAG_OCTET_STRING)?.content;
473        let mut raw = [0u8; 64];
474        ecdsa_sig_value_to_raw(signature_der, &mut raw)?;
475
476        // unsignedAttrs [1] IMPLICIT is optional and covered by nothing; its presence does
477        // not affect the signature, so it is ignored.
478
479        Ok(Self {
480            content,
481            signer_key_id,
482            signature: Signature::from_bytes(raw),
483        })
484    }
485
486    /// Verifies the signature against a CSA signing key.
487    ///
488    /// The caller supplies the key, because a CD names its signer only by key identifier and
489    /// the set of trusted CSA keys is the commissioner's policy, not this crate's.
490    pub fn verify(&self, csa_public_key: &PublicKey) -> Result<bool> {
491        verify(csa_public_key, self.content, &self.signature)
492    }
493
494    /// Parses the `eContent` as certification elements.
495    pub fn elements(&self) -> Result<CertificationElements<'a>> {
496        CertificationElements::decode(self.content)
497    }
498}
499
500/// A `SEQUENCE` tag, re-exported so a caller building a CMS fixture does not reach into
501/// [`crate::der`].
502pub const TAG_CMS_SEQUENCE: u8 = TAG_SEQUENCE;