Skip to main content

matter_kit/cert/
mod.rs

1//! Matter operational certificates (Core §6.1, §6.5).
2//!
3//! A Matter certificate is an X.509 certificate with everything Matter does not use taken
4//! out, re-encoded as TLV. It is not a different certificate: "every Matter certificate can
5//! be represented as a corresponding X.509 certificate. However, the converse is not true."
6//! The point of the exercise is size — §6.1.3 caps a Matter certificate at
7//! [`CERT_TLV_MAX`] octets against [`CERT_DER_MAX`] for the DER it stands for.
8//!
9//! # The signature is not over these bytes
10//!
11//! This is the one thing about the format that surprises everybody, and it is worth
12//! knowing before reading any of the rest. §6.5.2:
13//!
14//! > The signature included in a Matter certificate is the signatureValue of the
15//! > corresponding X.509 certificate, **not** a signature of the preceding Matter TLV data
16//! > in the Matter certificate structure. Accordingly, validating the signature in a Matter
17//! > certificate entails its logical conversion to the corresponding X.509 certificate to
18//! > recover the original tbsCertificate.
19//!
20//! So verifying a certificate means regenerating DER, which is why the DN module keeps the
21//! `UTF8String`/`PrintableString` distinction ([`dn`]) and why element order is preserved
22//! rather than normalised: both change the DER, and a changed DER is a signature that does
23//! not verify. Parsing and validating the *encoding* — what this module does — is
24//! independent of that, and is a prerequisite for it.
25//!
26//! # What this module does
27//!
28//! [`MatterCertificate::decode`] parses, borrowing from the buffer; [`encode`] writes the
29//! same certificate back; [`MatterCertificate::validate`] applies §6.5.6.3's DN rules and
30//! §6.5.12's extension rules for the certificate's [`CertType`].
31//!
32//! # What survives a round trip, exactly
33//!
34//! Everything the DER depends on: the order of DN attributes, the order of extensions, the
35//! `UTF8String`/`PrintableString` distinction, the serial number's leading zeros, and every
36//! value. The specification's three worked examples re-encode byte for byte
37//! (`tests/cert_vectors.rs`).
38//!
39//! One thing does not: **integer width**. Matter TLV lets the same value be encoded in 1, 2,
40//! 4 or 8 octets, and [`encode`] always writes the narrowest — as every Matter
41//! implementation does, and as all three published examples already are. A certificate that
42//! arrived with a wider encoding therefore re-encodes to fewer bytes.
43//!
44//! That is safe, and the reason is worth being precise about: the signature is not over
45//! these bytes. §6.5.2's DER is regenerated from the *values* — a `matter-node-id` becomes a
46//! fixed 16-character hex string regardless of how many octets the TLV spent on it — so a
47//! width change cannot alter the `tbsCertificate` and cannot affect verification. Nothing
48//! else about the encoding is normalised, because everything else can.
49//!
50//! [`encode`]: MatterCertificate::encode
51
52pub mod chain;
53pub mod der;
54pub mod dn;
55
56use heapless::Vec;
57
58pub use chain::{VerifiedIdentity, verify_chain, verify_self_signed};
59pub use dn::{DistinguishedName, DnAttribute, DnAttributeKind, DnValue, MAX_NOC_CATS, MAX_RDNS};
60
61use crate::crypto::{PUBLIC_KEY_SIZE_BYTES, PublicKey, SIGNATURE_LEN_BYTES, Signature};
62use crate::error::{Error, ErrorCode, Result};
63use crate::msg::{FabricId, NodeId};
64use crate::tlv::{Tag, TlvReader, TlvWriter, Value};
65
66/// "Wherever Matter Operational Certificate Encoding representation is used, all
67/// certificates SHALL NOT be longer than 400 bytes in their TLV form" (§6.1.3).
68pub const CERT_TLV_MAX: usize = 400;
69
70/// "All certificates SHALL NOT be longer than 600 bytes in their uncompressed DER format"
71/// (§6.1.3).
72pub const CERT_DER_MAX: usize = 600;
73
74/// "implementations SHALL admit serial numbers up to 20 octets in length" (§6.5.4).
75pub const SERIAL_MAX: usize = 20;
76
77/// A key identifier is "the 160-bit SHA-1 hash of the certificate's subject public key
78/// value" — 20 octets, and §6.1.2 makes the length normative.
79pub const KEY_ID_LEN: usize = 20;
80
81/// Turns 20 arbitrary octets — a key identifier, a digest, a counter — into serial number
82/// content a Matter certificate will accept.
83///
84/// §6.5.4's `serial-num` **is** the DER INTEGER's content, carried through unchanged, so a
85/// digest handed straight to it is wrong twice:
86///
87/// - the top bit of the first octet is the INTEGER's *sign*, so half of all digests encode a
88///   **negative** serial. §6.5.4 says a Matter certificate "follows the same limitation on
89///   admissible serial numbers as in [RFC 5280]", and RFC 5280 §4.1.2.2 is where that
90///   limitation is written: "The serial number MUST be a positive integer";
91/// - DER requires the shortest two's-complement form, so `0x00` followed by an octet below
92///   `0x80` — or `0xFF` followed by one at or above it — is a redundant sign octet and not
93///   valid content at all. One digest in 256, so a chain that builds every time until it does
94///   not.
95///
96/// Clearing the sign bit answers both, and lifting a resulting `0x00` to `0x01` keeps the
97/// value out of the redundant-zero case.
98///
99/// ```
100/// use matter_kit::cert::positive_serial;
101///
102/// // Negative: the sign bit is cleared.
103/// assert_eq!(positive_serial([0xFF; 20])[0], 0x7F);
104/// // Redundant leading zero: lifted out of it.
105/// let mut digest = [0x00; 20];
106/// digest[1] = 0x01;
107/// assert_eq!(positive_serial(digest)[0], 0x01);
108/// // Already valid: unchanged.
109/// let mut digest = [0x00; 20];
110/// digest[0] = 0x42;
111/// assert_eq!(positive_serial(digest), digest);
112/// ```
113#[must_use]
114pub const fn positive_serial(mut bytes: [u8; SERIAL_MAX]) -> [u8; SERIAL_MAX] {
115    bytes[0] &= 0x7F;
116    if bytes[0] == 0x00 {
117        bytes[0] = 0x01;
118    }
119    bytes
120}
121
122/// How many extensions one certificate's list can hold here: the five defined ones plus
123/// room for future extensions, which "MAY be more than one".
124pub const MAX_EXTENSIONS: usize = 8;
125
126/// How many `key-purpose-id` values an extended key usage array can hold: Table 93 defines
127/// six, and the extension "SHALL NOT contain more than one instance".
128pub const MAX_KEY_PURPOSES: usize = 6;
129
130/// The `not-after` value that stands for X.509's `99991231235959Z` — "no well-defined
131/// expiration date" (§6.5.7).
132pub const NOT_AFTER_NEVER: u32 = 0;
133
134// --- The small enumerations of §6.5.5, §6.5.8, §6.5.9 ------------------------------------
135
136/// `signature-algorithm` (§6.5.5, Table 86).
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
138#[repr(u8)]
139pub enum SignatureAlgorithm {
140    /// `ecdsa-with-sha256` — the only value, because §3.5.3 has only one signature scheme.
141    EcdsaWithSha256 = 1,
142}
143
144/// `public-key-algorithm` (§6.5.8, Table 90).
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
146#[repr(u8)]
147pub enum PublicKeyAlgorithm {
148    /// `ec-pub-key` — `id-ecPublicKey`.
149    EcPubKey = 1,
150}
151
152/// `elliptic-curve-id` (§6.5.9, Table 91).
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
154#[repr(u8)]
155pub enum EllipticCurveId {
156    /// `prime256v1` — NIST P-256, the curve of §3.5.1.
157    Prime256V1 = 1,
158}
159
160/// `key-purpose-id` (§6.5.11.3, Table 93).
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
162#[repr(u8)]
163#[non_exhaustive]
164pub enum KeyPurposeId {
165    /// `id-kp-serverAuth`.
166    ServerAuth = 1,
167    /// `id-kp-clientAuth`.
168    ClientAuth = 2,
169    /// `id-kp-codeSigning`.
170    CodeSigning = 3,
171    /// `id-kp-emailProtection`.
172    EmailProtection = 4,
173    /// `id-kp-timeStamping`.
174    TimeStamping = 5,
175    /// `id-kp-OCSPSigning`.
176    OcspSigning = 6,
177}
178
179impl KeyPurposeId {
180    /// The value a TLV element carries, or `None` if it is outside Table 93 — which
181    /// §6.5.14 lists as invalidating the certificate.
182    #[must_use]
183    pub const fn from_value(value: u64) -> Option<Self> {
184        Some(match value {
185            1 => Self::ServerAuth,
186            2 => Self::ClientAuth,
187            3 => Self::CodeSigning,
188            4 => Self::EmailProtection,
189            5 => Self::TimeStamping,
190            6 => Self::OcspSigning,
191            _ => return None,
192        })
193    }
194}
195
196bitflags::bitflags! {
197    /// `key-usage-flag` (§6.5.11.2) — "derived as a logical OR of all key-usage-flag
198    /// values that apply to the corresponding public key".
199    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
200    pub struct KeyUsage: u16 {
201        /// `digitalSignature`.
202        const DIGITAL_SIGNATURE = 0x0001;
203        /// `nonRepudiation`.
204        const NON_REPUDIATION = 0x0002;
205        /// `keyEncipherment`.
206        const KEY_ENCIPHERMENT = 0x0004;
207        /// `dataEncipherment`.
208        const DATA_ENCIPHERMENT = 0x0008;
209        /// `keyAgreement`.
210        const KEY_AGREEMENT = 0x0010;
211        /// `keyCertSign`.
212        const KEY_CERT_SIGN = 0x0020;
213        /// `CRLSign`.
214        const CRL_SIGN = 0x0040;
215        /// `encipherOnly`.
216        const ENCIPHER_ONLY = 0x0080;
217        /// `decipherOnly`.
218        const DECIPHER_ONLY = 0x0100;
219    }
220}
221
222/// `basic-constraints` (§6.5.11.1).
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
224pub struct BasicConstraints {
225    /// Whether the subject is a CA. "SHALL be encoded regardless of the value."
226    pub is_ca: bool,
227    /// The maximum depth of a path through this certificate. "MAY be present only when
228    /// is-ca == true."
229    pub path_len_constraint: Option<u8>,
230}
231
232/// One entry of a certificate's extensions list (§6.5.11).
233#[derive(Debug, Clone, PartialEq, Eq)]
234#[non_exhaustive]
235pub enum Extension<'a> {
236    /// `basic-cnstr [1]`.
237    BasicConstraints(BasicConstraints),
238    /// `key-usage [2]`.
239    KeyUsage(KeyUsage),
240    /// `extended-key-usage [3]`, in the order it appeared.
241    ExtendedKeyUsage(Vec<KeyPurposeId, MAX_KEY_PURPOSES>),
242    /// `subject-key-id [4]` — the SHA-1 of the subject public key (§6.5.11.4).
243    SubjectKeyId([u8; KEY_ID_LEN]),
244    /// `authority-key-id [5]` — the SHA-1 of the key that signed this certificate.
245    AuthorityKeyId([u8; KEY_ID_LEN]),
246    /// `future-extension [6]`, kept verbatim.
247    ///
248    /// An implementation that does not understand one still needs its bytes: they are part
249    /// of the DER the signature was computed over. "If ignored extension is marked as
250    /// critical then validation of the corresponding Matter certificate SHALL fail" — which
251    /// is a decision for the DER layer, since criticality is not encoded here.
252    Future(&'a [u8]),
253}
254
255impl Extension<'_> {
256    /// The context tag this entry encodes under.
257    #[must_use]
258    pub const fn tag(&self) -> u8 {
259        match self {
260            Self::BasicConstraints(_) => TAG_BASIC_CONSTRAINTS,
261            Self::KeyUsage(_) => TAG_KEY_USAGE,
262            Self::ExtendedKeyUsage(_) => TAG_EXTENDED_KEY_USAGE,
263            Self::SubjectKeyId(_) => TAG_SUBJECT_KEY_ID,
264            Self::AuthorityKeyId(_) => TAG_AUTHORITY_KEY_ID,
265            Self::Future(_) => TAG_FUTURE_EXTENSION,
266        }
267    }
268}
269
270/// The extensions of a Matter certificate, **in the order they were encoded** (§6.5.11).
271///
272/// The order is not incidental. §6.5.12: "The extensions SHALL appear in the same order in
273/// the Matter certificate and in the corresponding X.509 certificates" — and an X.509
274/// certificate's extension order is the issuer's choice. Sorting them here would change the
275/// DER regenerated from this certificate, and a changed DER is a signature that does not
276/// verify. So this is a sequence with accessors, not a record with fields.
277///
278/// What *is* enforced is uniqueness: "The extensions list SHALL NOT contain more than one
279/// instance of a particular extension", with `future-extension` excepted because "There MAY
280/// be more than one".
281#[derive(Debug, Clone, Default, PartialEq, Eq)]
282pub struct Extensions<'a> {
283    entries: Vec<Extension<'a>, MAX_EXTENSIONS>,
284}
285
286impl<'a> Extensions<'a> {
287    /// An empty list.
288    #[must_use]
289    pub const fn new() -> Self {
290        Self {
291            entries: Vec::new(),
292        }
293    }
294
295    /// Appends an extension, refusing a second instance of anything but `future-extension`.
296    pub fn push(&mut self, extension: Extension<'a>) -> Result<()> {
297        let tag = extension.tag();
298        if tag != TAG_FUTURE_EXTENSION && self.entries.iter().any(|e| e.tag() == tag) {
299            return Err(invalid());
300        }
301        self.entries.push(extension).map_err(|_| invalid())
302    }
303
304    /// The entries, in encoding order.
305    #[must_use]
306    pub fn entries(&self) -> &[Extension<'a>] {
307        &self.entries
308    }
309
310    /// The `basic-cnstr` extension, if present.
311    #[must_use]
312    pub fn basic_constraints(&self) -> Option<BasicConstraints> {
313        self.entries.iter().find_map(|e| match e {
314            Extension::BasicConstraints(v) => Some(*v),
315            _ => None,
316        })
317    }
318
319    /// The `key-usage` extension, if present.
320    #[must_use]
321    pub fn key_usage(&self) -> Option<KeyUsage> {
322        self.entries.iter().find_map(|e| match e {
323            Extension::KeyUsage(v) => Some(*v),
324            _ => None,
325        })
326    }
327
328    /// The `extended-key-usage` array, if present, in its encoded order.
329    #[must_use]
330    pub fn extended_key_usage(&self) -> Option<&[KeyPurposeId]> {
331        self.entries.iter().find_map(|e| match e {
332            Extension::ExtendedKeyUsage(v) => Some(v.as_slice()),
333            _ => None,
334        })
335    }
336
337    /// The `subject-key-id`, if present.
338    #[must_use]
339    pub fn subject_key_id(&self) -> Option<[u8; KEY_ID_LEN]> {
340        self.entries.iter().find_map(|e| match e {
341            Extension::SubjectKeyId(v) => Some(*v),
342            _ => None,
343        })
344    }
345
346    /// The `authority-key-id`, if present.
347    #[must_use]
348    pub fn authority_key_id(&self) -> Option<[u8; KEY_ID_LEN]> {
349        self.entries.iter().find_map(|e| match e {
350            Extension::AuthorityKeyId(v) => Some(*v),
351            _ => None,
352        })
353    }
354
355    /// Every `future-extension`, in order.
356    pub fn future(&self) -> impl Iterator<Item = &'a [u8]> + '_ {
357        self.entries.iter().filter_map(|e| match e {
358            Extension::Future(bytes) => Some(*bytes),
359            _ => None,
360        })
361    }
362}
363
364/// What a certificate is, as its subject DN declares (§6.5.6.2, Table 89).
365#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
366#[non_exhaustive]
367pub enum CertType {
368    /// A Node Operational Certificate: the subject carries a `matter-node-id`.
369    Noc,
370    /// An Intermediate CA Certificate: a `matter-icac-id`.
371    Icac,
372    /// A Root CA Certificate: a `matter-rcac-id`.
373    Rcac,
374    /// A Vendor Verification Signer Certificate: a `matter-vvs-id`.
375    Vvsc,
376    /// A firmware signing certificate: a `matter-firmware-signing-id`. Matter "doesn't
377    /// specify how firmware images are signed", but the format has room for it.
378    FirmwareSigning,
379}
380
381/// A decoded Matter certificate, borrowing from the buffer it was read from.
382///
383/// Fields appear in the tag order §6.5.2's `[tag-order]` requires, which is also the order
384/// [`MatterCertificate::encode`] writes them in.
385#[derive(Debug, Clone, PartialEq, Eq)]
386pub struct MatterCertificate<'a> {
387    /// `serial-num [1]` — at most [`SERIAL_MAX`] octets, and not normalised: a leading zero
388    /// is part of the DER.
389    pub serial_number: &'a [u8],
390    /// `sig-algo [2]`.
391    pub signature_algorithm: SignatureAlgorithm,
392    /// `issuer [3]`.
393    pub issuer: DistinguishedName<'a>,
394    /// `not-before [4]` — a Matter epoch-s time.
395    pub not_before: u32,
396    /// `not-after [5]`, where [`NOT_AFTER_NEVER`] means no expiry.
397    pub not_after: u32,
398    /// `subject [6]`.
399    pub subject: DistinguishedName<'a>,
400    /// `pub-key-algo [7]`.
401    pub public_key_algorithm: PublicKeyAlgorithm,
402    /// `ec-curve-id [8]`.
403    pub elliptic_curve_id: EllipticCurveId,
404    /// `ec-pub-key [9]` — an uncompressed SEC 1 point.
405    pub public_key: PublicKey,
406    /// `extensions [10]`.
407    pub extensions: Extensions<'a>,
408    /// `signature [11]` — `r || s`, and *not* a signature over this TLV; see the module
409    /// documentation.
410    pub signature: Signature,
411}
412
413// The context tags of §6.5.2.
414const TAG_SERIAL_NUM: u8 = 1;
415const TAG_SIG_ALGO: u8 = 2;
416const TAG_ISSUER: u8 = 3;
417const TAG_NOT_BEFORE: u8 = 4;
418const TAG_NOT_AFTER: u8 = 5;
419const TAG_SUBJECT: u8 = 6;
420const TAG_PUB_KEY_ALGO: u8 = 7;
421const TAG_EC_CURVE_ID: u8 = 8;
422const TAG_EC_PUB_KEY: u8 = 9;
423const TAG_EXTENSIONS: u8 = 10;
424const TAG_SIGNATURE: u8 = 11;
425
426// The context tags of §6.5.11's `extension` choice.
427const TAG_BASIC_CONSTRAINTS: u8 = 1;
428const TAG_KEY_USAGE: u8 = 2;
429const TAG_EXTENDED_KEY_USAGE: u8 = 3;
430const TAG_SUBJECT_KEY_ID: u8 = 4;
431const TAG_AUTHORITY_KEY_ID: u8 = 5;
432const TAG_FUTURE_EXTENSION: u8 = 6;
433
434// The context tags of §6.5.11.1's `basic-constraints`.
435const TAG_IS_CA: u8 = 1;
436const TAG_PATH_LEN_CONSTRAINT: u8 = 2;
437
438fn invalid() -> Error {
439    Error::new(ErrorCode::CertInvalid)
440}
441
442impl<'a> MatterCertificate<'a> {
443    /// Decodes a certificate from its TLV form.
444    ///
445    /// This checks the *encoding* — element order, types, ranges, and the enumerations of
446    /// Tables 86, 90, 91 and 93 — which is §6.5.14's list of what invalidates a
447    /// certificate. It does not check the DN or extension rules that depend on what kind of
448    /// certificate this is; that is [`MatterCertificate::validate`], because the caller
449    /// usually knows which kind it is expecting and a mismatch is a different error.
450    pub fn decode(buf: &'a [u8]) -> Result<Self> {
451        if buf.len() > CERT_TLV_MAX {
452            return Err(invalid());
453        }
454        let mut reader = TlvReader::new(buf);
455        let Some(head) = reader.next_element()? else {
456            return Err(invalid());
457        };
458        if head.value.container() != Some(crate::tlv::ContainerKind::Structure)
459            || !head.tag.is_anonymous()
460        {
461            return Err(invalid());
462        }
463
464        let mut serial_number = None;
465        let mut signature_algorithm = None;
466        let mut issuer = None;
467        let mut not_before = None;
468        let mut not_after = None;
469        let mut subject = None;
470        let mut public_key_algorithm = None;
471        let mut elliptic_curve_id = None;
472        let mut public_key = None;
473        let mut extensions = None;
474        let mut signature = None;
475
476        // `[tag-order]`: "Matter certificate elements are encoded in a wrong order" is one
477        // of §6.5.14's invalidating errors, so the tags must ascend strictly.
478        let mut previous_tag = 0u8;
479
480        loop {
481            let Some(element) = reader.next_element()? else {
482                return Err(invalid());
483            };
484            if element.value == Value::EndOfContainer {
485                break;
486            }
487            let Some(tag) = element.tag.context() else {
488                return Err(invalid());
489            };
490            if tag <= previous_tag {
491                return Err(invalid());
492            }
493            previous_tag = tag;
494
495            match tag {
496                TAG_SERIAL_NUM => {
497                    let octets = element.octets()?;
498                    if octets.len() > SERIAL_MAX {
499                        return Err(invalid());
500                    }
501                    serial_number = Some(octets);
502                }
503                TAG_SIG_ALGO => {
504                    signature_algorithm = Some(match element.unsigned()? {
505                        1 => SignatureAlgorithm::EcdsaWithSha256,
506                        _ => return Err(invalid()),
507                    });
508                }
509                TAG_ISSUER => {
510                    expect_list(&element)?;
511                    issuer = Some(DistinguishedName::decode(&mut reader)?);
512                }
513                TAG_NOT_BEFORE => not_before = Some(u32_of(&element)?),
514                TAG_NOT_AFTER => not_after = Some(u32_of(&element)?),
515                TAG_SUBJECT => {
516                    expect_list(&element)?;
517                    subject = Some(DistinguishedName::decode(&mut reader)?);
518                }
519                TAG_PUB_KEY_ALGO => {
520                    public_key_algorithm = Some(match element.unsigned()? {
521                        1 => PublicKeyAlgorithm::EcPubKey,
522                        _ => return Err(invalid()),
523                    });
524                }
525                TAG_EC_CURVE_ID => {
526                    elliptic_curve_id = Some(match element.unsigned()? {
527                        1 => EllipticCurveId::Prime256V1,
528                        _ => return Err(invalid()),
529                    });
530                }
531                TAG_EC_PUB_KEY => {
532                    let octets = element.octets()?;
533                    if octets.len() != PUBLIC_KEY_SIZE_BYTES {
534                        return Err(invalid());
535                    }
536                    public_key = Some(PublicKey::from_slice(octets)?);
537                }
538                TAG_EXTENSIONS => {
539                    expect_list(&element)?;
540                    extensions = Some(decode_extensions(&mut reader)?);
541                }
542                TAG_SIGNATURE => {
543                    let octets = element.octets()?;
544                    if octets.len() != SIGNATURE_LEN_BYTES {
545                        return Err(invalid());
546                    }
547                    signature = Some(Signature::from_slice(octets)?);
548                }
549                // "Matter certificate structure includes elements that are not defined in
550                // this section" — §6.5.14.
551                _ => return Err(invalid()),
552            }
553        }
554        reader.finish()?;
555
556        Ok(Self {
557            serial_number: serial_number.ok_or_else(invalid)?,
558            signature_algorithm: signature_algorithm.ok_or_else(invalid)?,
559            issuer: issuer.ok_or_else(invalid)?,
560            not_before: not_before.ok_or_else(invalid)?,
561            not_after: not_after.ok_or_else(invalid)?,
562            subject: subject.ok_or_else(invalid)?,
563            public_key_algorithm: public_key_algorithm.ok_or_else(invalid)?,
564            elliptic_curve_id: elliptic_curve_id.ok_or_else(invalid)?,
565            public_key: public_key.ok_or_else(invalid)?,
566            extensions: extensions.ok_or_else(invalid)?,
567            signature: signature.ok_or_else(invalid)?,
568        })
569    }
570
571    /// Encodes the certificate back to TLV, returning the written bytes.
572    ///
573    /// The output is identical to the input a [`MatterCertificate::decode`] came from:
574    /// tag order is fixed by the schema, integer widths are the minimum TLV would ever
575    /// use, and nothing here normalises a value.
576    pub fn encode<'b>(&self, buf: &'b mut [u8]) -> Result<&'b [u8]> {
577        let mut writer = TlvWriter::new(buf);
578        writer.start_structure(Tag::Anonymous)?;
579        writer.octets(Tag::Context(TAG_SERIAL_NUM), self.serial_number)?;
580        writer.unsigned(
581            Tag::Context(TAG_SIG_ALGO),
582            self.signature_algorithm as u8 as u64,
583        )?;
584        self.issuer.encode(&mut writer, Tag::Context(TAG_ISSUER))?;
585        writer.unsigned(Tag::Context(TAG_NOT_BEFORE), u64::from(self.not_before))?;
586        writer.unsigned(Tag::Context(TAG_NOT_AFTER), u64::from(self.not_after))?;
587        self.subject
588            .encode(&mut writer, Tag::Context(TAG_SUBJECT))?;
589        writer.unsigned(
590            Tag::Context(TAG_PUB_KEY_ALGO),
591            self.public_key_algorithm as u8 as u64,
592        )?;
593        writer.unsigned(
594            Tag::Context(TAG_EC_CURVE_ID),
595            self.elliptic_curve_id as u8 as u64,
596        )?;
597        writer.octets(Tag::Context(TAG_EC_PUB_KEY), self.public_key.as_bytes())?;
598        encode_extensions(&self.extensions, &mut writer)?;
599        writer.octets(Tag::Context(TAG_SIGNATURE), self.signature.as_bytes())?;
600        writer.end_container()?;
601        let written = writer.finish()?;
602        if written.len() > CERT_TLV_MAX {
603            return Err(invalid());
604        }
605        Ok(written)
606    }
607
608    /// What kind of certificate this is, from the Matter-specific attribute in its subject
609    /// DN (§6.5.6.2).
610    ///
611    /// `None` when the subject carries none of them, or more than one kind — both of which
612    /// §6.5.14 lists as invalidating ("Certificate Subject DN encodes matter-node-id and
613    /// matter-rcac-id, which contradict each other").
614    #[must_use]
615    pub fn cert_type(&self) -> Option<CertType> {
616        use DnAttributeKind as K;
617        let candidates = [
618            (K::MatterNodeId, CertType::Noc),
619            (K::MatterIcacId, CertType::Icac),
620            (K::MatterRcacId, CertType::Rcac),
621            (K::MatterVvsId, CertType::Vvsc),
622            (K::MatterFirmwareSigningId, CertType::FirmwareSigning),
623        ];
624        let mut found = None;
625        for (kind, cert_type) in candidates {
626            match self.subject.count(kind) {
627                0 => {}
628                1 if found.is_none() => found = Some(cert_type),
629                _ => return None,
630            }
631        }
632        found
633    }
634
635    /// The subject's `matter-node-id`, for a NOC.
636    #[must_use]
637    pub fn node_id(&self) -> Option<NodeId> {
638        self.subject.node_id()
639    }
640
641    /// The subject's `matter-fabric-id`, which a NOC always has and a CA certificate may.
642    #[must_use]
643    pub fn fabric_id(&self) -> Option<FabricId> {
644        self.subject.fabric_id()
645    }
646
647    /// Whether this certificate is a CA — `basic-constraints.is-ca`.
648    #[must_use]
649    pub fn is_ca(&self) -> bool {
650        self.extensions
651            .basic_constraints()
652            .is_some_and(|bc| bc.is_ca)
653    }
654
655    /// Whether `at` (Matter epoch-s) falls inside the validity window (§6.5.7).
656    ///
657    /// A `not-after` of [`NOT_AFTER_NEVER`] stands for `99991231235959Z`, so it never
658    /// expires.
659    #[must_use]
660    pub const fn is_valid_at(&self, at: u32) -> bool {
661        at >= self.not_before && (self.not_after == NOT_AFTER_NEVER || at <= self.not_after)
662    }
663
664    /// Applies the rules of §6.5.6.3 and §6.5.12 for this certificate's type.
665    ///
666    /// Separate from [`MatterCertificate::decode`] because the two answer different
667    /// questions: decode asks whether these bytes are a certificate at all, validate asks
668    /// whether the certificate they encode is one Matter would accept.
669    pub fn validate(&self) -> Result<()> {
670        let Some(cert_type) = self.cert_type() else {
671            return Err(invalid());
672        };
673        self.validate_as(cert_type)
674    }
675
676    /// Applies the §6.5 rules for a *specific* expected type.
677    ///
678    /// Use this where the caller knows what it asked for — a trusted root, say — so that a
679    /// certificate of the wrong kind is refused rather than validated on its own terms.
680    pub fn validate_as(&self, cert_type: CertType) -> Result<()> {
681        if self.cert_type() != Some(cert_type) {
682            return Err(invalid());
683        }
684        self.validate_subject_dn(cert_type)?;
685        self.validate_extensions(cert_type)
686    }
687
688    /// §6.5.6.3's per-type subject DN rules.
689    fn validate_subject_dn(&self, cert_type: CertType) -> Result<()> {
690        use DnAttributeKind as K;
691        let dn = &self.subject;
692
693        // "All implementations SHALL reject Matter certificates with more than 5 RDNs in a
694        // single DN" — `DistinguishedName` cannot hold more, so this holds by
695        // construction; the issuer is checked for emptiness the same way on decode.
696        if dn.is_empty() || self.issuer.is_empty() {
697            return Err(invalid());
698        }
699
700        // Rules shared by every type: nothing may carry an attribute another type owns.
701        let forbidden: &[K] = match cert_type {
702            CertType::Noc => &[K::MatterIcacId, K::MatterRcacId, K::MatterVvsId],
703            CertType::Icac => &[
704                K::MatterNodeId,
705                K::MatterRcacId,
706                K::MatterNocCat,
707                K::MatterVvsId,
708            ],
709            CertType::Rcac => &[
710                K::MatterNodeId,
711                K::MatterIcacId,
712                K::MatterNocCat,
713                K::MatterVvsId,
714            ],
715            CertType::Vvsc => &[K::MatterNodeId, K::MatterFabricId, K::MatterNocCat],
716            CertType::FirmwareSigning => &[],
717        };
718        for kind in forbidden {
719            if dn.count(*kind) != 0 {
720                return Err(invalid());
721            }
722        }
723
724        match cert_type {
725            CertType::Noc => {
726                // "SHALL encode exactly one matter-node-id", in the Operational range.
727                let Some(node_id) = dn.node_id() else {
728                    return Err(invalid());
729                };
730                if !node_id.is_operational() {
731                    return Err(invalid());
732                }
733                // "SHALL encode exactly one matter-fabric-id", not 0.
734                let Some(fabric_id) = dn.fabric_id() else {
735                    return Err(invalid());
736                };
737                if fabric_id.0 == 0 {
738                    return Err(invalid());
739                }
740                validate_noc_cats(dn)?;
741            }
742            CertType::Icac | CertType::Rcac => {
743                // "MAY encode at most one matter-fabric-id … SHALL NOT be 0."
744                match dn.count(K::MatterFabricId) {
745                    0 => {}
746                    1 => {
747                        if dn.fabric_id().is_none_or(|f| f.0 == 0) {
748                            return Err(invalid());
749                        }
750                    }
751                    _ => return Err(invalid()),
752                }
753            }
754            CertType::Vvsc | CertType::FirmwareSigning => {}
755        }
756        Ok(())
757    }
758
759    /// §6.5.12's per-type extension rules.
760    fn validate_extensions(&self, cert_type: CertType) -> Result<()> {
761        let ext = &self.extensions;
762
763        // Every type: both key identifiers "SHALL be present".
764        let (Some(subject_key_id), Some(authority_key_id)) =
765            (ext.subject_key_id(), ext.authority_key_id())
766        else {
767            return Err(invalid());
768        };
769
770        let Some(basic) = ext.basic_constraints() else {
771            return Err(invalid());
772        };
773        // "The path-len-constraint MAY be present only when is-ca == true."
774        if !basic.is_ca && basic.path_len_constraint.is_some() {
775            return Err(invalid());
776        }
777
778        let Some(key_usage) = ext.key_usage() else {
779            return Err(invalid());
780        };
781
782        let expected_eku: Option<&[KeyPurposeId]> = match cert_type {
783            CertType::Noc => Some(&[KeyPurposeId::ServerAuth, KeyPurposeId::ClientAuth]),
784            CertType::FirmwareSigning => Some(&[KeyPurposeId::CodeSigning]),
785            // "For Matter ICA Certificate and Matter Root CA Certificate: the extended key
786            // usage extension SHALL NOT be present." §6.5.12 says nothing about a VVSC's,
787            // so it is not constrained either way.
788            CertType::Icac | CertType::Rcac => Some(&[]),
789            CertType::Vvsc => None,
790        };
791
792        match cert_type {
793            CertType::Noc | CertType::Vvsc | CertType::FirmwareSigning => {
794                if basic.is_ca {
795                    return Err(invalid());
796                }
797                // "SHALL be encoded with exactly one flag: digitalSignature."
798                if key_usage != KeyUsage::DIGITAL_SIGNATURE {
799                    return Err(invalid());
800                }
801            }
802            CertType::Icac | CertType::Rcac => {
803                if !basic.is_ca {
804                    return Err(invalid());
805                }
806                // "at least the two flags keyCertSign and CRLSign … MAY include a third
807                // flag: digitalSignature. No additional flags are permitted."
808                let required = KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN;
809                let permitted = required | KeyUsage::DIGITAL_SIGNATURE;
810                if !key_usage.contains(required) || !permitted.contains(key_usage) {
811                    return Err(invalid());
812                }
813                // "For the Matter Root CA Certificate the authority key identifier
814                // extension SHALL be equal to the subject key identifier extension."
815                if cert_type == CertType::Rcac && authority_key_id != subject_key_id {
816                    return Err(invalid());
817                }
818            }
819        }
820
821        if let Some(expected) = expected_eku {
822            match (expected.is_empty(), ext.extended_key_usage()) {
823                (true, None) => {}
824                (true, Some(_)) => return Err(invalid()),
825                (false, None) => return Err(invalid()),
826                (false, Some(present)) => {
827                    // The order is the X.509 certificate's, not a fixed one — the spec's
828                    // own NOC example encodes [clientAuth, serverAuth] — so compare as
829                    // sets of the required length.
830                    if present.len() != expected.len()
831                        || !expected.iter().all(|p| present.contains(p))
832                    {
833                        return Err(invalid());
834                    }
835                }
836            }
837        }
838        Ok(())
839    }
840}
841
842/// "Multiple matter-cat-id with the same identifier value and different version numbers, or
843/// any matter-cat-id with a version number of 0" invalidate a certificate (§6.5.14).
844fn validate_noc_cats(dn: &DistinguishedName<'_>) -> Result<()> {
845    // At most three, which the DN's own capacity does not bound — five RDNs could hold
846    // four.
847    if dn.count(DnAttributeKind::MatterNocCat) > MAX_NOC_CATS {
848        return Err(invalid());
849    }
850    let cats = dn.noc_cats();
851    for (index, cat) in cats.iter().enumerate() {
852        if !cat.is_valid() {
853            return Err(invalid());
854        }
855        // "Each matter-noc-cat attribute present, if any, SHALL encode a different CASE
856        // Authenticated Tag identifier (upper 16 bits of value)".
857        if cats.get(index.saturating_add(1)..).is_some_and(|rest| {
858            rest.iter()
859                .any(|other| other.identifier() == cat.identifier())
860        }) {
861            return Err(invalid());
862        }
863    }
864    Ok(())
865}
866
867fn expect_list(element: &crate::tlv::Element<'_>) -> Result<()> {
868    if element.value.container() == Some(crate::tlv::ContainerKind::List) {
869        Ok(())
870    } else {
871        Err(invalid())
872    }
873}
874
875/// "not-before or not-after field is longer than 32-bits" invalidates (§6.5.14).
876fn u32_of(element: &crate::tlv::Element<'_>) -> Result<u32> {
877    u32::try_from(element.unsigned()?).map_err(|_| invalid())
878}
879
880fn decode_extensions<'a>(reader: &mut TlvReader<'a>) -> Result<Extensions<'a>> {
881    let mut out = Extensions::new();
882    loop {
883        let Some(element) = reader.next_element()? else {
884            return Err(invalid());
885        };
886        if element.value == Value::EndOfContainer {
887            break;
888        }
889        let Some(tag) = element.tag.context() else {
890            return Err(invalid());
891        };
892        let extension = match tag {
893            TAG_BASIC_CONSTRAINTS => {
894                if element.value.container() != Some(crate::tlv::ContainerKind::Structure) {
895                    return Err(invalid());
896                }
897                Extension::BasicConstraints(decode_basic_constraints(reader)?)
898            }
899            TAG_KEY_USAGE => {
900                let raw = u16::try_from(element.unsigned()?).map_err(|_| invalid())?;
901                // "key-usage field of the Key Usage Extension has undefined flags"
902                // invalidates the certificate (§6.5.14).
903                Extension::KeyUsage(KeyUsage::from_bits(raw).ok_or_else(invalid)?)
904            }
905            TAG_EXTENDED_KEY_USAGE => {
906                if element.value.container() != Some(crate::tlv::ContainerKind::Array) {
907                    return Err(invalid());
908                }
909                Extension::ExtendedKeyUsage(decode_key_purposes(reader)?)
910            }
911            TAG_SUBJECT_KEY_ID => Extension::SubjectKeyId(key_id(&element)?),
912            TAG_AUTHORITY_KEY_ID => Extension::AuthorityKeyId(key_id(&element)?),
913            TAG_FUTURE_EXTENSION => Extension::Future(element.octets()?),
914            _ => return Err(invalid()),
915        };
916        // `push` is what refuses a duplicate and a list that is too long.
917        out.push(extension)?;
918    }
919    Ok(out)
920}
921
922fn key_id(element: &crate::tlv::Element<'_>) -> Result<[u8; KEY_ID_LEN]> {
923    // "subject-key-id or authority-key-id field is different from 20 octets" invalidates.
924    <[u8; KEY_ID_LEN]>::try_from(element.octets()?).map_err(|_| invalid())
925}
926
927fn decode_basic_constraints(reader: &mut TlvReader<'_>) -> Result<BasicConstraints> {
928    let mut is_ca = None;
929    let mut path_len_constraint = None;
930    let mut previous_tag = 0u8;
931    loop {
932        let Some(element) = reader.next_element()? else {
933            return Err(invalid());
934        };
935        if element.value == Value::EndOfContainer {
936            break;
937        }
938        let Some(tag) = element.tag.context() else {
939            return Err(invalid());
940        };
941        if tag <= previous_tag {
942            return Err(invalid());
943        }
944        previous_tag = tag;
945        match tag {
946            TAG_IS_CA => is_ca = Some(element.bool()?),
947            TAG_PATH_LEN_CONSTRAINT => {
948                path_len_constraint =
949                    Some(u8::try_from(element.unsigned()?).map_err(|_| invalid())?);
950            }
951            _ => return Err(invalid()),
952        }
953    }
954    Ok(BasicConstraints {
955        // "The is-ca field SHALL be encoded regardless of the value."
956        is_ca: is_ca.ok_or_else(invalid)?,
957        path_len_constraint,
958    })
959}
960
961fn decode_key_purposes(reader: &mut TlvReader<'_>) -> Result<Vec<KeyPurposeId, MAX_KEY_PURPOSES>> {
962    let mut out = Vec::new();
963    loop {
964        let Some(element) = reader.next_element()? else {
965            return Err(invalid());
966        };
967        if element.value == Value::EndOfContainer {
968            break;
969        }
970        if !element.tag.is_anonymous() {
971            return Err(invalid());
972        }
973        let purpose = KeyPurposeId::from_value(element.unsigned()?).ok_or_else(invalid)?;
974        out.push(purpose).map_err(|_| invalid())?;
975    }
976    // `ARRAY [ length 1.. ]`.
977    if out.is_empty() {
978        return Err(invalid());
979    }
980    Ok(out)
981}
982
983fn encode_extensions(extensions: &Extensions<'_>, writer: &mut TlvWriter<'_>) -> Result<()> {
984    writer.start_list(Tag::Context(TAG_EXTENSIONS))?;
985    for extension in extensions.entries() {
986        let tag = Tag::Context(extension.tag());
987        match extension {
988            Extension::BasicConstraints(basic) => {
989                writer.start_structure(tag)?;
990                writer.bool(Tag::Context(TAG_IS_CA), basic.is_ca)?;
991                if let Some(path_len) = basic.path_len_constraint {
992                    writer.unsigned(Tag::Context(TAG_PATH_LEN_CONSTRAINT), u64::from(path_len))?;
993                }
994                writer.end_container()?;
995            }
996            Extension::KeyUsage(key_usage) => {
997                writer.unsigned(tag, u64::from(key_usage.bits()))?;
998            }
999            Extension::ExtendedKeyUsage(purposes) => {
1000                writer.start_array(tag)?;
1001                for purpose in purposes {
1002                    writer.unsigned(Tag::Anonymous, *purpose as u8 as u64)?;
1003                }
1004                writer.end_container()?;
1005            }
1006            Extension::SubjectKeyId(id) | Extension::AuthorityKeyId(id) => {
1007                writer.octets(tag, id)?;
1008            }
1009            Extension::Future(bytes) => writer.octets(tag, bytes)?,
1010        }
1011    }
1012    writer.end_container()
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018    use crate::msg::CaseAuthenticatedTag;
1019
1020    const KEY_A: [u8; KEY_ID_LEN] = [0xAA; KEY_ID_LEN];
1021    const KEY_B: [u8; KEY_ID_LEN] = [0xBB; KEY_ID_LEN];
1022
1023    /// A P-256 point that is never parsed as one here — `decode` checks the length, and
1024    /// only the crypto layer checks the curve.
1025    fn a_public_key() -> PublicKey {
1026        let mut bytes = [0x11u8; PUBLIC_KEY_SIZE_BYTES];
1027        bytes[0] = 0x04;
1028        PublicKey::from_bytes(bytes)
1029    }
1030
1031    fn extensions(entries: &[Extension<'static>]) -> Extensions<'static> {
1032        let mut out = Extensions::new();
1033        for entry in entries {
1034            out.push(entry.clone()).expect("fits");
1035        }
1036        out
1037    }
1038
1039    /// A well-formed certificate of `cert_type`, which each test then breaks in one way.
1040    fn cert(cert_type: CertType) -> MatterCertificate<'static> {
1041        let mut subject = DistinguishedName::new();
1042        let mut ext = heapless::Vec::<Extension<'static>, MAX_EXTENSIONS>::new();
1043        let is_ca = matches!(cert_type, CertType::Icac | CertType::Rcac);
1044
1045        match cert_type {
1046            CertType::Noc => {
1047                subject.push(DnAttribute::node_id(NodeId(1))).expect("push");
1048                subject
1049                    .push(DnAttribute::fabric_id(FabricId(0xFAB0_0000_0000_001D)))
1050                    .expect("push");
1051            }
1052            CertType::Icac => subject
1053                .push(DnAttribute::uint(DnAttributeKind::MatterIcacId, 3))
1054                .expect("push"),
1055            CertType::Rcac => subject
1056                .push(DnAttribute::uint(DnAttributeKind::MatterRcacId, 1))
1057                .expect("push"),
1058            CertType::Vvsc => subject
1059                .push(DnAttribute::uint(DnAttributeKind::MatterVvsId, 7))
1060                .expect("push"),
1061            CertType::FirmwareSigning => subject
1062                .push(DnAttribute::uint(
1063                    DnAttributeKind::MatterFirmwareSigningId,
1064                    9,
1065                ))
1066                .expect("push"),
1067        }
1068
1069        ext.push(Extension::BasicConstraints(BasicConstraints {
1070            is_ca,
1071            path_len_constraint: None,
1072        }))
1073        .expect("fits");
1074        ext.push(Extension::KeyUsage(if is_ca {
1075            KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN
1076        } else {
1077            KeyUsage::DIGITAL_SIGNATURE
1078        }))
1079        .expect("fits");
1080        match cert_type {
1081            CertType::Noc => {
1082                let mut purposes = Vec::new();
1083                purposes.push(KeyPurposeId::ServerAuth).expect("fits");
1084                purposes.push(KeyPurposeId::ClientAuth).expect("fits");
1085                ext.push(Extension::ExtendedKeyUsage(purposes))
1086                    .expect("fits");
1087            }
1088            CertType::FirmwareSigning => {
1089                let mut purposes = Vec::new();
1090                purposes.push(KeyPurposeId::CodeSigning).expect("fits");
1091                ext.push(Extension::ExtendedKeyUsage(purposes))
1092                    .expect("fits");
1093            }
1094            _ => {}
1095        }
1096        ext.push(Extension::SubjectKeyId(KEY_A)).expect("fits");
1097        // A root is its own authority; everything else is signed by something above it.
1098        ext.push(Extension::AuthorityKeyId(if cert_type == CertType::Rcac {
1099            KEY_A
1100        } else {
1101            KEY_B
1102        }))
1103        .expect("fits");
1104
1105        let mut issuer = DistinguishedName::new();
1106        issuer
1107            .push(DnAttribute::uint(DnAttributeKind::MatterRcacId, 1))
1108            .expect("push");
1109
1110        MatterCertificate {
1111            serial_number: &[0x01, 0x02],
1112            signature_algorithm: SignatureAlgorithm::EcdsaWithSha256,
1113            issuer,
1114            not_before: 100,
1115            not_after: 200,
1116            subject,
1117            public_key_algorithm: PublicKeyAlgorithm::EcPubKey,
1118            elliptic_curve_id: EllipticCurveId::Prime256V1,
1119            public_key: a_public_key(),
1120            extensions: extensions(&ext),
1121            signature: Signature::from_bytes([0x22; SIGNATURE_LEN_BYTES]),
1122        }
1123    }
1124
1125    #[test]
1126    fn the_built_certificates_are_valid_to_begin_with() {
1127        // Otherwise every rejection test below would pass for the wrong reason.
1128        for cert_type in [
1129            CertType::Noc,
1130            CertType::Icac,
1131            CertType::Rcac,
1132            CertType::Vvsc,
1133            CertType::FirmwareSigning,
1134        ] {
1135            let c = cert(cert_type);
1136            assert_eq!(c.cert_type(), Some(cert_type), "{cert_type:?}");
1137            c.validate()
1138                .unwrap_or_else(|e| panic!("{cert_type:?}: {e}"));
1139        }
1140    }
1141
1142    #[test]
1143    fn a_noc_with_fabric_id_zero_is_refused() {
1144        // §6.5.6.3: "The matter-fabric-id attribute's value SHALL NOT be 0."
1145        let mut c = cert(CertType::Noc);
1146        c.subject = DistinguishedName::new();
1147        c.subject
1148            .push(DnAttribute::node_id(NodeId(1)))
1149            .expect("push");
1150        c.subject
1151            .push(DnAttribute::fabric_id(FabricId(0)))
1152            .expect("push");
1153        assert!(c.validate().is_err());
1154    }
1155
1156    #[test]
1157    fn a_noc_without_a_fabric_id_is_refused() {
1158        // "The subject DN SHALL encode exactly one matter-fabric-id attribute."
1159        let mut c = cert(CertType::Noc);
1160        c.subject = DistinguishedName::new();
1161        c.subject
1162            .push(DnAttribute::node_id(NodeId(1)))
1163            .expect("push");
1164        assert!(c.validate().is_err());
1165    }
1166
1167    #[test]
1168    fn a_noc_whose_node_id_is_not_operational_is_refused() {
1169        // A group Node ID is a legal 64-bit value and an illegal NOC subject.
1170        let mut c = cert(CertType::Noc);
1171        c.subject = DistinguishedName::new();
1172        c.subject
1173            .push(DnAttribute::node_id(NodeId(0xFFFF_FFFF_FFFF_0001)))
1174            .expect("push");
1175        c.subject
1176            .push(DnAttribute::fabric_id(FabricId(1)))
1177            .expect("push");
1178        assert!(c.validate().is_err());
1179    }
1180
1181    #[test]
1182    fn a_subject_that_claims_two_certificate_types_has_no_type() {
1183        // §6.5.14: "Certificate Subject DN encodes matter-node-id and matter-rcac-id,
1184        // which contradict each other."
1185        let mut c = cert(CertType::Noc);
1186        c.subject
1187            .push(DnAttribute::uint(DnAttributeKind::MatterRcacId, 1))
1188            .expect("push");
1189        assert_eq!(c.cert_type(), None);
1190        assert!(c.validate().is_err());
1191    }
1192
1193    #[test]
1194    fn a_ca_certificate_must_say_it_is_one() {
1195        // "CA certificate doesn't have Basic Constraints Extension is-ca field set to
1196        // 'true'" — §6.5.14.
1197        for cert_type in [CertType::Icac, CertType::Rcac] {
1198            let mut c = cert(cert_type);
1199            c.extensions = extensions(&[
1200                Extension::BasicConstraints(BasicConstraints {
1201                    is_ca: false,
1202                    path_len_constraint: None,
1203                }),
1204                Extension::KeyUsage(KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN),
1205                Extension::SubjectKeyId(KEY_A),
1206                Extension::AuthorityKeyId(KEY_A),
1207            ]);
1208            assert!(c.validate().is_err(), "{cert_type:?}");
1209        }
1210    }
1211
1212    #[test]
1213    fn a_leaf_certificate_must_not_claim_to_be_a_ca() {
1214        let mut c = cert(CertType::Noc);
1215        c.extensions = extensions(&[
1216            Extension::BasicConstraints(BasicConstraints {
1217                is_ca: true,
1218                path_len_constraint: None,
1219            }),
1220            Extension::KeyUsage(KeyUsage::DIGITAL_SIGNATURE),
1221            Extension::SubjectKeyId(KEY_A),
1222            Extension::AuthorityKeyId(KEY_B),
1223        ]);
1224        assert!(c.validate().is_err());
1225    }
1226
1227    #[test]
1228    fn a_path_len_constraint_needs_is_ca() {
1229        // "The path-len-constraint MAY be present only when is-ca == true."
1230        let mut c = cert(CertType::Noc);
1231        c.extensions = extensions(&[
1232            Extension::BasicConstraints(BasicConstraints {
1233                is_ca: false,
1234                path_len_constraint: Some(0),
1235            }),
1236            Extension::KeyUsage(KeyUsage::DIGITAL_SIGNATURE),
1237            Extension::SubjectKeyId(KEY_A),
1238            Extension::AuthorityKeyId(KEY_B),
1239        ]);
1240        assert!(c.validate().is_err());
1241    }
1242
1243    #[test]
1244    fn a_roots_authority_key_id_must_equal_its_subject_key_id() {
1245        // §6.5.12, and the reason a root is recognisable as self-issued.
1246        let mut c = cert(CertType::Rcac);
1247        c.extensions = extensions(&[
1248            Extension::BasicConstraints(BasicConstraints {
1249                is_ca: true,
1250                path_len_constraint: None,
1251            }),
1252            Extension::KeyUsage(KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN),
1253            Extension::SubjectKeyId(KEY_A),
1254            Extension::AuthorityKeyId(KEY_B),
1255        ]);
1256        assert!(c.validate().is_err());
1257        // An ICAC's, by contrast, is expected to differ.
1258        cert(CertType::Icac).validate().expect("icac");
1259    }
1260
1261    #[test]
1262    fn the_key_usage_flags_a_type_allows_are_exactly_those() {
1263        // A NOC: "exactly one flag: digitalSignature."
1264        for usage in [
1265            KeyUsage::DIGITAL_SIGNATURE | KeyUsage::KEY_AGREEMENT,
1266            KeyUsage::KEY_CERT_SIGN,
1267            KeyUsage::empty(),
1268        ] {
1269            let mut c = cert(CertType::Noc);
1270            let mut ext = Extensions::new();
1271            ext.push(Extension::BasicConstraints(BasicConstraints {
1272                is_ca: false,
1273                path_len_constraint: None,
1274            }))
1275            .expect("fits");
1276            ext.push(Extension::KeyUsage(usage)).expect("fits");
1277            let mut purposes = Vec::new();
1278            purposes.push(KeyPurposeId::ServerAuth).expect("fits");
1279            purposes.push(KeyPurposeId::ClientAuth).expect("fits");
1280            ext.push(Extension::ExtendedKeyUsage(purposes))
1281                .expect("fits");
1282            ext.push(Extension::SubjectKeyId(KEY_A)).expect("fits");
1283            ext.push(Extension::AuthorityKeyId(KEY_B)).expect("fits");
1284            c.extensions = ext;
1285            assert!(c.validate().is_err(), "{usage:?}");
1286        }
1287    }
1288
1289    #[test]
1290    fn a_ca_may_add_digital_signature_but_nothing_else() {
1291        let base = KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN;
1292        for (usage, ok) in [
1293            (base, true),
1294            (base | KeyUsage::DIGITAL_SIGNATURE, true),
1295            (base | KeyUsage::KEY_AGREEMENT, false),
1296            (KeyUsage::KEY_CERT_SIGN, false),
1297            (KeyUsage::CRL_SIGN, false),
1298        ] {
1299            let mut c = cert(CertType::Icac);
1300            c.extensions = extensions(&[
1301                Extension::BasicConstraints(BasicConstraints {
1302                    is_ca: true,
1303                    path_len_constraint: None,
1304                }),
1305                Extension::KeyUsage(usage),
1306                Extension::SubjectKeyId(KEY_A),
1307                Extension::AuthorityKeyId(KEY_B),
1308            ]);
1309            assert_eq!(c.validate().is_ok(), ok, "{usage:?}");
1310        }
1311    }
1312
1313    #[test]
1314    fn a_ca_must_not_carry_an_extended_key_usage() {
1315        // "For Matter ICA Certificate and Matter Root CA Certificate: the extended key
1316        // usage extension SHALL NOT be present."
1317        let mut c = cert(CertType::Icac);
1318        let mut purposes = Vec::new();
1319        purposes.push(KeyPurposeId::ServerAuth).expect("fits");
1320        c.extensions = extensions(&[
1321            Extension::BasicConstraints(BasicConstraints {
1322                is_ca: true,
1323                path_len_constraint: None,
1324            }),
1325            Extension::KeyUsage(KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN),
1326            Extension::ExtendedKeyUsage(purposes),
1327            Extension::SubjectKeyId(KEY_A),
1328            Extension::AuthorityKeyId(KEY_B),
1329        ]);
1330        assert!(c.validate().is_err());
1331    }
1332
1333    #[test]
1334    fn a_nocs_extended_key_usage_is_both_purposes_in_either_order() {
1335        // "exactly two key-purpose-id values: serverAuth and clientAuth" — and the spec's
1336        // own NOC example encodes them the other way round, so order is not the rule.
1337        for (purposes, ok) in [
1338            (
1339                &[KeyPurposeId::ServerAuth, KeyPurposeId::ClientAuth][..],
1340                true,
1341            ),
1342            (
1343                &[KeyPurposeId::ClientAuth, KeyPurposeId::ServerAuth][..],
1344                true,
1345            ),
1346            (&[KeyPurposeId::ServerAuth][..], false),
1347            (
1348                &[KeyPurposeId::ServerAuth, KeyPurposeId::CodeSigning][..],
1349                false,
1350            ),
1351            (
1352                &[
1353                    KeyPurposeId::ServerAuth,
1354                    KeyPurposeId::ClientAuth,
1355                    KeyPurposeId::CodeSigning,
1356                ][..],
1357                false,
1358            ),
1359        ] {
1360            let mut c = cert(CertType::Noc);
1361            let mut list = Vec::new();
1362            for p in purposes {
1363                list.push(*p).expect("fits");
1364            }
1365            c.extensions = extensions(&[
1366                Extension::BasicConstraints(BasicConstraints {
1367                    is_ca: false,
1368                    path_len_constraint: None,
1369                }),
1370                Extension::KeyUsage(KeyUsage::DIGITAL_SIGNATURE),
1371                Extension::ExtendedKeyUsage(list),
1372                Extension::SubjectKeyId(KEY_A),
1373                Extension::AuthorityKeyId(KEY_B),
1374            ]);
1375            assert_eq!(c.validate().is_ok(), ok, "{purposes:?}");
1376        }
1377    }
1378
1379    #[test]
1380    fn a_missing_key_identifier_is_refused() {
1381        // Both "SHALL be present", for every type.
1382        for present in [
1383            &[Extension::SubjectKeyId(KEY_A)][..],
1384            &[Extension::AuthorityKeyId(KEY_B)][..],
1385            &[][..],
1386        ] {
1387            let mut c = cert(CertType::Icac);
1388            let mut ext = Extensions::new();
1389            ext.push(Extension::BasicConstraints(BasicConstraints {
1390                is_ca: true,
1391                path_len_constraint: None,
1392            }))
1393            .expect("fits");
1394            ext.push(Extension::KeyUsage(
1395                KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
1396            ))
1397            .expect("fits");
1398            for e in present {
1399                ext.push(e.clone()).expect("fits");
1400            }
1401            c.extensions = ext;
1402            assert!(c.validate().is_err());
1403        }
1404    }
1405
1406    #[test]
1407    fn a_duplicate_extension_is_refused_on_push() {
1408        // "The extensions list SHALL NOT contain more than one instance of a particular
1409        // extension."
1410        let mut ext = Extensions::new();
1411        ext.push(Extension::KeyUsage(KeyUsage::DIGITAL_SIGNATURE))
1412            .expect("first");
1413        assert!(
1414            ext.push(Extension::KeyUsage(KeyUsage::CRL_SIGN)).is_err(),
1415            "a second key-usage"
1416        );
1417        // But "There MAY be more than one" future-extension.
1418        ext.push(Extension::Future(&[1])).expect("first future");
1419        ext.push(Extension::Future(&[2])).expect("second future");
1420        assert_eq!(ext.future().count(), 2);
1421    }
1422
1423    #[test]
1424    fn noc_cats_must_be_versioned_and_distinct() {
1425        let cases: &[(&[u32], bool)] = &[
1426            (&[0xABCD_0002], true),
1427            (&[0xABCD_0004, 0xABCE_0018, 0xABCF_0002], true),
1428            // §6.5.14: "any matter-cat-id with a version number of 0".
1429            (&[0xABCD_0000], false),
1430            // "the same CASE Authenticated Tag value with two different version numbers".
1431            (&[0xABCD_0004, 0xABCD_0002], false),
1432        ];
1433        for (cats, ok) in cases {
1434            let mut c = cert(CertType::Noc);
1435            c.subject = DistinguishedName::new();
1436            c.subject
1437                .push(DnAttribute::node_id(NodeId(1)))
1438                .expect("push");
1439            c.subject
1440                .push(DnAttribute::fabric_id(FabricId(1)))
1441                .expect("push");
1442            for cat in *cats {
1443                c.subject
1444                    .push(DnAttribute::noc_cat(CaseAuthenticatedTag(*cat)))
1445                    .expect("push");
1446            }
1447            assert_eq!(c.validate().is_ok(), *ok, "{cats:02x?}");
1448        }
1449    }
1450
1451    #[test]
1452    fn a_dn_refuses_a_sixth_attribute() {
1453        // "All implementations SHALL reject Matter certificates with more than 5 RDNs in a
1454        // single DN."
1455        let mut dn = DistinguishedName::new();
1456        for _ in 0..MAX_RDNS {
1457            dn.push(DnAttribute::string(DnAttributeKind::CommonName, "x"))
1458                .expect("fits");
1459        }
1460        assert!(
1461            dn.push(DnAttribute::string(DnAttributeKind::CommonName, "x"))
1462                .is_err()
1463        );
1464    }
1465
1466    #[test]
1467    fn a_round_trip_survives_a_printable_string_attribute() {
1468        // The +0x80 marker has to come back, or the regenerated DER uses the wrong ASN.1
1469        // string type and the signature fails.
1470        let mut c = cert(CertType::Rcac);
1471        c.subject = DistinguishedName::new();
1472        c.subject
1473            .push(DnAttribute::uint(DnAttributeKind::MatterRcacId, 1))
1474            .expect("push");
1475        c.subject
1476            .push(DnAttribute::printable(
1477                DnAttributeKind::CommonName,
1478                "ROOT CA HOME 3",
1479            ))
1480            .expect("push");
1481
1482        let mut buf = [0u8; CERT_TLV_MAX];
1483        let bytes = c.encode(&mut buf).expect("encode");
1484        // Tag 1 + 0x80 = 129, so the control octet's tag byte is 0x81.
1485        assert!(
1486            bytes.contains(&0x81),
1487            "the printable-string tag is on the wire"
1488        );
1489
1490        let mut round = [0u8; CERT_TLV_MAX];
1491        round[..bytes.len()].copy_from_slice(bytes);
1492        let decoded = MatterCertificate::decode(&round[..bytes.len()]).expect("decode");
1493        let attribute = decoded.subject.attributes()[1];
1494        assert!(attribute.printable_string);
1495        assert_eq!(attribute.as_str(), Some("ROOT CA HOME 3"));
1496        assert_eq!(decoded.subject, c.subject);
1497    }
1498
1499    #[test]
1500    fn the_printable_string_form_only_exists_where_table_87_defines_it() {
1501        // domain-component is an IA5String and the Matter-specific types are integers, so
1502        // neither has a +0x80 spelling.
1503        let mut dn = DistinguishedName::new();
1504        assert!(
1505            dn.push(DnAttribute::printable(
1506                DnAttributeKind::DomainComponent,
1507                "example"
1508            ))
1509            .is_err()
1510        );
1511        assert!(
1512            dn.push(DnAttribute {
1513                kind: DnAttributeKind::MatterNodeId,
1514                printable_string: true,
1515                value: DnValue::Uint(1),
1516            })
1517            .is_err()
1518        );
1519        // And a string type may not carry a scalar, nor a scalar type a string.
1520        assert!(
1521            dn.push(DnAttribute::uint(DnAttributeKind::CommonName, 1))
1522                .is_err()
1523        );
1524        assert!(
1525            dn.push(DnAttribute::string(DnAttributeKind::MatterNodeId, "x"))
1526                .is_err()
1527        );
1528    }
1529
1530    #[test]
1531    fn a_noc_cat_above_32_bits_is_refused() {
1532        // Table 85 gives matter-noc-cat 4 octets; the others 8.
1533        let mut dn = DistinguishedName::new();
1534        assert!(
1535            dn.push(DnAttribute::uint(
1536                DnAttributeKind::MatterNocCat,
1537                0x1_0000_0000
1538            ))
1539            .is_err()
1540        );
1541        dn.push(DnAttribute::uint(
1542            DnAttributeKind::MatterNodeId,
1543            0x0123_4567_89AB_CDEF,
1544        ))
1545        .expect("64 bits is fine for a node id");
1546    }
1547
1548    #[test]
1549    fn a_serial_number_longer_than_20_octets_is_refused() {
1550        // §6.5.4, and §6.5.14 lists it explicitly.
1551        let mut c = cert(CertType::Rcac);
1552        const LONG: [u8; SERIAL_MAX + 1] = [0x01; SERIAL_MAX + 1];
1553        c.serial_number = &LONG;
1554        let mut buf = [0u8; CERT_TLV_MAX];
1555        // The writer will happily emit it; the decoder is what must refuse it.
1556        let bytes = c.encode(&mut buf).expect("encode");
1557        let mut round = [0u8; CERT_TLV_MAX];
1558        round[..bytes.len()].copy_from_slice(bytes);
1559        assert_eq!(
1560            MatterCertificate::decode(&round[..bytes.len()])
1561                .map(|_| ())
1562                .unwrap_err()
1563                .code(),
1564            ErrorCode::CertInvalid
1565        );
1566    }
1567
1568    #[test]
1569    fn elements_out_of_order_are_refused() {
1570        // §6.5.2's `[tag-order]`, and §6.5.14's "Matter certificate elements are encoded in
1571        // a wrong order". Written by hand because the encoder cannot produce it.
1572        let mut buf = [0u8; 64];
1573        let mut writer = TlvWriter::new(&mut buf);
1574        writer.start_structure(Tag::Anonymous).expect("start");
1575        writer
1576            .unsigned(Tag::Context(TAG_SIG_ALGO), 1)
1577            .expect("sig-algo first");
1578        writer
1579            .octets(Tag::Context(TAG_SERIAL_NUM), &[1])
1580            .expect("serial second");
1581        writer.end_container().expect("end");
1582        let bytes = writer.finish().expect("finish");
1583        let mut round = [0u8; 64];
1584        round[..bytes.len()].copy_from_slice(bytes);
1585        assert!(MatterCertificate::decode(&round[..bytes.len()]).is_err());
1586    }
1587
1588    #[test]
1589    fn an_undefined_algorithm_or_curve_is_refused() {
1590        // §6.5.14 lists each of these as invalidating.
1591        for (tag, value) in [
1592            (TAG_SIG_ALGO, 2u64),
1593            (TAG_PUB_KEY_ALGO, 2),
1594            (TAG_EC_CURVE_ID, 2),
1595        ] {
1596            let mut buf = [0u8; 64];
1597            let mut writer = TlvWriter::new(&mut buf);
1598            writer.start_structure(Tag::Anonymous).expect("start");
1599            writer.unsigned(Tag::Context(tag), value).expect("value");
1600            writer.end_container().expect("end");
1601            let bytes = writer.finish().expect("finish");
1602            let mut round = [0u8; 64];
1603            round[..bytes.len()].copy_from_slice(bytes);
1604            assert!(
1605                MatterCertificate::decode(&round[..bytes.len()]).is_err(),
1606                "tag {tag} value {value}"
1607            );
1608        }
1609    }
1610
1611    #[test]
1612    fn undefined_key_usage_flags_are_refused() {
1613        // "key-usage field of the Key Usage Extension has undefined flags" — bit 9 and up
1614        // are not allocated.
1615        assert!(KeyUsage::from_bits(0x0200).is_none());
1616        assert_eq!(KeyUsage::from_bits(0x01FF).map(|k| k.bits()), Some(0x01FF));
1617    }
1618
1619    #[test]
1620    fn a_certificate_larger_than_400_octets_is_refused() {
1621        // §6.1.3, which is what keeps a NOC chain inside a CASE message.
1622        let oversized = [0u8; CERT_TLV_MAX + 1];
1623        assert!(MatterCertificate::decode(&oversized).is_err());
1624    }
1625
1626    #[test]
1627    fn a_not_after_of_zero_never_expires() {
1628        // §6.5.7: it stands for X.509's 99991231235959Z.
1629        let mut c = cert(CertType::Noc);
1630        c.not_after = NOT_AFTER_NEVER;
1631        assert!(c.is_valid_at(u32::MAX));
1632        assert!(!c.is_valid_at(c.not_before.saturating_sub(1)));
1633    }
1634
1635    /// Does this serial survive the writer that has to encode it?
1636    ///
1637    /// The certificate is rebuilt per call so the borrow of `serial` ends with it; that is the
1638    /// only reason this is a function and not two lines in the loop below.
1639    fn encodes(serial: &[u8]) -> bool {
1640        let mut c = cert(CertType::Noc);
1641        c.serial_number = serial;
1642        let mut buf = [0u8; CERT_DER_MAX];
1643        der::tbs_certificate(&c, &mut buf).is_ok()
1644    }
1645
1646    /// Every digest a key identifier could be, through the writer that has to encode it.
1647    ///
1648    /// The serial is the first 20 octets of SHA-256 over a public key, so its first two octets
1649    /// are uniformly distributed and the encoder's rules bite on exactly those two: the sign
1650    /// bit, and DER's shortest-form requirement. Sweeping all 65 536 prefixes is the whole
1651    /// space, so this is a proof rather than a sample — and it is the test that would have
1652    /// caught a device failing to generate its own attestation chain one boot in 256.
1653    #[test]
1654    fn a_normalised_digest_always_encodes_as_a_serial_number() {
1655        for first in 0..=u8::MAX {
1656            for second in 0..=u8::MAX {
1657                let mut digest = [0x5Au8; SERIAL_MAX];
1658                digest[0] = first;
1659                digest[1] = second;
1660                let serial = positive_serial(digest);
1661
1662                assert_ne!(serial[0] & 0x80, 0x80, "a serial is a *positive* integer");
1663                assert_ne!(serial[0], 0x00, "0x00 would be a redundant sign octet");
1664                assert!(encodes(&serial), "digest {first:#04x}{second:#04x}");
1665            }
1666        }
1667    }
1668
1669    /// The other half of the same claim: the writer really does refuse what `positive_serial`
1670    /// removes, so the sweep above is not passing because nothing was ever checked.
1671    #[test]
1672    fn the_writer_refuses_a_redundant_sign_octet() {
1673        for raw in [
1674            // 0x00 followed by a value below 0x80: the zero says nothing.
1675            [0x00, 0x01],
1676            // 0xFF followed by one at or above it: likewise for a negative value.
1677            [0xFF, 0x80],
1678        ] {
1679            let mut digest = [0x5Au8; SERIAL_MAX];
1680            digest[..2].copy_from_slice(&raw);
1681            assert!(!encodes(&digest), "{raw:02x?}");
1682            assert!(encodes(&positive_serial(digest)), "{raw:02x?}");
1683        }
1684    }
1685}