Skip to main content

matter_kit/cert/
dn.rs

1//! Distinguished names in a Matter certificate (Core §6.1.1, §6.5.6).
2//!
3//! An X.509 DN is a sequence of Relative Distinguished Names, each of which may in
4//! principle hold a *set* of attributes. Matter narrows that: "The RDN in a Matter
5//! certificate SHALL be always a single DN attribute." So a DN here is a list of
6//! attributes, in order, and two DNs match when they have the same attributes in the same
7//! order.
8//!
9//! # The `+0x80` marker
10//!
11//! A Matter certificate has to reproduce the DER of the X.509 certificate it stands for,
12//! byte for byte, or the signature will not verify — §6.5.2: "validating the signature in a
13//! Matter certificate entails its logical conversion to the corresponding X.509
14//! certificate". DER distinguishes `UTF8String` from `PrintableString`, so the TLV has to
15//! carry that distinction too. It does it by logically OR-ing the tag with `0x80`: tag 1 is
16//! `common-name` as a `UTF8String`, tag 129 is the same attribute as a `PrintableString`.
17//!
18//! [`DnAttribute`] keeps that as a separate [`DnAttribute::printable_string`] flag rather
19//! than as thirty separate variants, so the round-trip is exact without the enum doubling.
20
21use heapless::Vec;
22
23use crate::error::{Error, ErrorCode, Result};
24use crate::msg::{CaseAuthenticatedTag, FabricId, NodeId};
25use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};
26
27/// "All implementations SHALL accept, parse, and handle Matter certificates with up to 5
28/// RDNs in a single DN" — and "SHALL reject" more (§6.5.6.3).
29pub const MAX_RDNS: usize = 5;
30
31/// "The subject DN MAY encode at most three matter-noc-cat attributes" (§6.5.6.3).
32pub const MAX_NOC_CATS: usize = 3;
33
34/// The tag added to a standard attribute whose X.509 form is a `PrintableString`.
35const PRINTABLE_STRING_OFFSET: u8 = 0x80;
36
37/// Which attribute type a [`DnAttribute`] carries (§6.5.6.1, Tables 85, 87 and 88).
38///
39/// The discriminants are the TLV context tags, so the encoding is the value itself.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41#[repr(u8)]
42#[non_exhaustive]
43pub enum DnAttributeKind {
44    /// `common-name` — X.520 `commonName`.
45    CommonName = 1,
46    /// `surname`.
47    Surname = 2,
48    /// `serial-num` — the DN attribute, not the certificate's serial number.
49    SerialNum = 3,
50    /// `country-name`.
51    CountryName = 4,
52    /// `locality-name`.
53    LocalityName = 5,
54    /// `state-or-province-name`.
55    StateOrProvinceName = 6,
56    /// `org-name`.
57    OrgName = 7,
58    /// `org-unit-name`.
59    OrgUnitName = 8,
60    /// `title`.
61    Title = 9,
62    /// `name`.
63    Name = 10,
64    /// `given-name`.
65    GivenName = 11,
66    /// `initials`.
67    Initials = 12,
68    /// `gen-qualifier`.
69    GenQualifier = 13,
70    /// `dn-qualifier`.
71    DnQualifier = 14,
72    /// `pseudonym`.
73    Pseudonym = 15,
74    /// `domain-component` — an `IA5String` in X.509, so it has no `-ps` form.
75    DomainComponent = 16,
76    /// `matter-node-id` — "Certifies the identity of a Matter Node Operational Certificate".
77    MatterNodeId = 17,
78    /// `matter-firmware-signing-id`.
79    MatterFirmwareSigningId = 18,
80    /// `matter-icac-id`.
81    MatterIcacId = 19,
82    /// `matter-rcac-id`.
83    MatterRcacId = 20,
84    /// `matter-fabric-id`.
85    MatterFabricId = 21,
86    /// `matter-noc-cat` — a [`CaseAuthenticatedTag`], 32 bits rather than 64.
87    MatterNocCat = 22,
88    /// `matter-vvs-id` — "Certifies the identity of a Vendor Verification Signer".
89    MatterVvsId = 23,
90}
91
92impl DnAttributeKind {
93    /// The kind a base tag names, or `None` if the tag is not one of Tables 85, 87 or 88.
94    #[must_use]
95    pub const fn from_tag(tag: u8) -> Option<Self> {
96        Some(match tag {
97            1 => Self::CommonName,
98            2 => Self::Surname,
99            3 => Self::SerialNum,
100            4 => Self::CountryName,
101            5 => Self::LocalityName,
102            6 => Self::StateOrProvinceName,
103            7 => Self::OrgName,
104            8 => Self::OrgUnitName,
105            9 => Self::Title,
106            10 => Self::Name,
107            11 => Self::GivenName,
108            12 => Self::Initials,
109            13 => Self::GenQualifier,
110            14 => Self::DnQualifier,
111            15 => Self::Pseudonym,
112            16 => Self::DomainComponent,
113            17 => Self::MatterNodeId,
114            18 => Self::MatterFirmwareSigningId,
115            19 => Self::MatterIcacId,
116            20 => Self::MatterRcacId,
117            21 => Self::MatterFabricId,
118            22 => Self::MatterNocCat,
119            23 => Self::MatterVvsId,
120            _ => return None,
121        })
122    }
123
124    /// The base TLV context tag.
125    #[must_use]
126    pub const fn tag(self) -> u8 {
127        self as u8
128    }
129
130    /// Whether the value is a string. The Matter-specific types, tags 17 through 23, are
131    /// "normatively defined as scalars" and encode as unsigned integers.
132    #[must_use]
133    pub const fn is_string(self) -> bool {
134        (self as u8) <= 16
135    }
136
137    /// Whether this is one of the `1.3.6.1.4.1.37244` private-arc types.
138    #[must_use]
139    pub const fn is_matter_specific(self) -> bool {
140        !self.is_string()
141    }
142
143    /// Whether a `PrintableString` form — the `+0x80` tag — exists for this type.
144    ///
145    /// Tables 87 covers tags 1 through 15. `domain-component` is an `IA5String` and the
146    /// Matter-specific types are integers, so neither has one.
147    #[must_use]
148    pub const fn has_printable_string_form(self) -> bool {
149        matches!(self as u8, 1..=15)
150    }
151
152    /// How many octets the scalar occupies in its X.509 hexadecimal form's *value*
153    /// (Table 85's "Length (octets)"), or `None` for a string type.
154    ///
155    /// Only `matter-noc-cat` is four; the rest are eight. This is what decides whether the
156    /// X.509 string is 8 or 16 characters.
157    #[must_use]
158    pub const fn scalar_octets(self) -> Option<usize> {
159        match self {
160            Self::MatterNocCat => Some(4),
161            _ if self.is_matter_specific() => Some(8),
162            _ => None,
163        }
164    }
165}
166
167/// One attribute of a distinguished name.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct DnAttribute<'a> {
170    /// Which attribute type this is.
171    pub kind: DnAttributeKind,
172    /// Whether the X.509 form encodes the value as a `PrintableString` rather than a
173    /// `UTF8String`. Only meaningful when
174    /// [`DnAttributeKind::has_printable_string_form`]; always `false` otherwise.
175    pub printable_string: bool,
176    /// The value.
177    pub value: DnValue<'a>,
178}
179
180/// The value of a DN attribute: a string, or a Matter-specific scalar.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum DnValue<'a> {
183    /// A string attribute's text, borrowed from the certificate.
184    Str(&'a str),
185    /// A Matter-specific attribute's scalar.
186    Uint(u64),
187}
188
189impl<'a> DnAttribute<'a> {
190    /// A string attribute in its `UTF8String` form.
191    #[must_use]
192    pub const fn string(kind: DnAttributeKind, value: &'a str) -> Self {
193        Self {
194            kind,
195            printable_string: false,
196            value: DnValue::Str(value),
197        }
198    }
199
200    /// A string attribute in its `PrintableString` form — the `+0x80` tag.
201    #[must_use]
202    pub const fn printable(kind: DnAttributeKind, value: &'a str) -> Self {
203        Self {
204            kind,
205            printable_string: true,
206            value: DnValue::Str(value),
207        }
208    }
209
210    /// A Matter-specific scalar attribute.
211    #[must_use]
212    pub const fn uint(kind: DnAttributeKind, value: u64) -> Self {
213        Self {
214            kind,
215            printable_string: false,
216            value: DnValue::Uint(value),
217        }
218    }
219
220    /// `matter-node-id`.
221    #[must_use]
222    pub const fn node_id(id: NodeId) -> Self {
223        Self::uint(DnAttributeKind::MatterNodeId, id.0)
224    }
225
226    /// `matter-fabric-id`.
227    #[must_use]
228    pub const fn fabric_id(id: FabricId) -> Self {
229        Self::uint(DnAttributeKind::MatterFabricId, id.0)
230    }
231
232    /// `matter-noc-cat`.
233    #[must_use]
234    pub const fn noc_cat(cat: CaseAuthenticatedTag) -> Self {
235        Self::uint(DnAttributeKind::MatterNocCat, cat.0 as u64)
236    }
237
238    /// The TLV context tag this attribute encodes under, `+0x80` included.
239    #[must_use]
240    pub const fn tag(&self) -> u8 {
241        if self.printable_string {
242            self.kind.tag().wrapping_add(PRINTABLE_STRING_OFFSET)
243        } else {
244            self.kind.tag()
245        }
246    }
247
248    /// The scalar, if this is a Matter-specific attribute.
249    #[must_use]
250    pub const fn as_uint(&self) -> Option<u64> {
251        match self.value {
252            DnValue::Uint(v) => Some(v),
253            DnValue::Str(_) => None,
254        }
255    }
256
257    /// The text, if this is a string attribute.
258    #[must_use]
259    pub const fn as_str(&self) -> Option<&'a str> {
260        match self.value {
261            DnValue::Str(s) => Some(s),
262            DnValue::Uint(_) => None,
263        }
264    }
265
266    /// Checks the attribute against the rules of §6.1.1 and §6.5.6.1.
267    ///
268    /// A scalar whose type says four octets must fit in 32 bits, a string type must carry
269    /// a string, and the `+0x80` form must only be used where Table 87 defines one.
270    pub fn validate(&self) -> Result<()> {
271        match (self.kind.is_string(), self.value) {
272            (true, DnValue::Str(_)) => {}
273            (false, DnValue::Uint(v)) => {
274                if self.kind.scalar_octets() == Some(4) && v > u64::from(u32::MAX) {
275                    return Err(Error::new(ErrorCode::CertInvalid));
276                }
277            }
278            _ => return Err(Error::new(ErrorCode::CertInvalid)),
279        }
280        if self.printable_string && !self.kind.has_printable_string_form() {
281            return Err(Error::new(ErrorCode::CertInvalid));
282        }
283        Ok(())
284    }
285
286    /// Writes the attribute into an open `issuer` or `subject` list.
287    pub fn encode(&self, writer: &mut TlvWriter<'_>) -> Result<()> {
288        self.validate()?;
289        let tag = Tag::Context(self.tag());
290        match self.value {
291            DnValue::Str(s) => writer.utf8(tag, s),
292            DnValue::Uint(v) => writer.unsigned(tag, v),
293        }
294    }
295
296    /// Reads one attribute from an element inside a DN list.
297    pub fn decode(element: &Element<'a>) -> Result<Self> {
298        let Some(raw_tag) = element.tag.context() else {
299            return Err(Error::new(ErrorCode::CertInvalid));
300        };
301        let printable_string = raw_tag >= PRINTABLE_STRING_OFFSET;
302        let base = raw_tag.wrapping_sub(if printable_string {
303            PRINTABLE_STRING_OFFSET
304        } else {
305            0
306        });
307        let Some(kind) = DnAttributeKind::from_tag(base) else {
308            return Err(Error::new(ErrorCode::CertInvalid));
309        };
310        let value = match element.value {
311            Value::Utf8(s) => DnValue::Str(s),
312            Value::Unsigned(v) => DnValue::Uint(v),
313            _ => return Err(Error::new(ErrorCode::CertInvalid)),
314        };
315        let attribute = Self {
316            kind,
317            printable_string,
318            value,
319        };
320        attribute.validate()?;
321        Ok(attribute)
322    }
323}
324
325/// A distinguished name: up to [`MAX_RDNS`] attributes, in order.
326#[derive(Debug, Clone, Default, PartialEq, Eq)]
327pub struct DistinguishedName<'a> {
328    attributes: Vec<DnAttribute<'a>, MAX_RDNS>,
329}
330
331impl<'a> DistinguishedName<'a> {
332    /// An empty name. A certificate with one is invalid — the schema says `length 1..` —
333    /// but building one up starts here.
334    #[must_use]
335    pub const fn new() -> Self {
336        Self {
337            attributes: Vec::new(),
338        }
339    }
340
341    /// Appends an attribute.
342    ///
343    /// Returns [`ErrorCode::CertInvalid`] past [`MAX_RDNS`], because §6.5.6.3 makes that a
344    /// rejection rather than a truncation.
345    pub fn push(&mut self, attribute: DnAttribute<'a>) -> Result<()> {
346        attribute.validate()?;
347        self.attributes
348            .push(attribute)
349            .map_err(|_| Error::new(ErrorCode::CertInvalid))
350    }
351
352    /// The attributes, in encoding order.
353    #[must_use]
354    pub fn attributes(&self) -> &[DnAttribute<'a>] {
355        &self.attributes
356    }
357
358    /// How many attributes there are.
359    #[must_use]
360    pub fn len(&self) -> usize {
361        self.attributes.len()
362    }
363
364    /// Whether there are none.
365    #[must_use]
366    pub fn is_empty(&self) -> bool {
367        self.attributes.is_empty()
368    }
369
370    /// How many attributes of a kind there are.
371    #[must_use]
372    pub fn count(&self, kind: DnAttributeKind) -> usize {
373        self.attributes.iter().filter(|a| a.kind == kind).count()
374    }
375
376    /// The scalar of the single attribute of this kind, or `None` if there is not exactly
377    /// one.
378    ///
379    /// "Not exactly one" rather than "the first": a subject with two `matter-fabric-id`
380    /// attributes is invalid, and answering with either one would hide that.
381    #[must_use]
382    pub fn single_uint(&self, kind: DnAttributeKind) -> Option<u64> {
383        let mut found = None;
384        for attribute in &self.attributes {
385            if attribute.kind == kind {
386                if found.is_some() {
387                    return None;
388                }
389                found = attribute.as_uint();
390            }
391        }
392        found
393    }
394
395    /// The `matter-node-id`, if the DN carries exactly one.
396    #[must_use]
397    pub fn node_id(&self) -> Option<NodeId> {
398        self.single_uint(DnAttributeKind::MatterNodeId).map(NodeId)
399    }
400
401    /// The `matter-fabric-id`, if the DN carries exactly one.
402    #[must_use]
403    pub fn fabric_id(&self) -> Option<FabricId> {
404        self.single_uint(DnAttributeKind::MatterFabricId)
405            .map(FabricId)
406    }
407
408    /// Every `matter-noc-cat` in the DN, in order.
409    #[must_use]
410    #[expect(
411        clippy::cast_possible_truncation,
412        reason = "a NOC CAT is the low 32 bits of a matter-noc-cat DN value (§6.5.6.3)"
413    )]
414    pub fn noc_cats(&self) -> Vec<CaseAuthenticatedTag, MAX_NOC_CATS> {
415        let mut out = Vec::new();
416        for attribute in &self.attributes {
417            if attribute.kind == DnAttributeKind::MatterNocCat
418                && let Some(value) = attribute.as_uint()
419            {
420                // The cast is lossless: `validate` has already refused a noc-cat above
421                // 32 bits.
422                let _ = out.push(CaseAuthenticatedTag(value as u32));
423            }
424        }
425        out
426    }
427
428    /// Writes the DN as a `LIST` under `tag`.
429    pub fn encode(&self, writer: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
430        if self.attributes.is_empty() {
431            return Err(Error::new(ErrorCode::CertInvalid));
432        }
433        writer.start_list(tag)?;
434        for attribute in &self.attributes {
435            attribute.encode(writer)?;
436        }
437        writer.end_container()
438    }
439
440    /// Reads a DN from a reader positioned just after the opening of its list.
441    pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
442        let mut dn = Self::new();
443        loop {
444            let Some(element) = reader.next_element()? else {
445                return Err(Error::new(ErrorCode::CertInvalid));
446            };
447            if element.value == Value::EndOfContainer {
448                break;
449            }
450            dn.push(DnAttribute::decode(&element)?)?;
451        }
452        if dn.attributes.is_empty() {
453            return Err(Error::new(ErrorCode::CertInvalid));
454        }
455        Ok(dn)
456    }
457}
458
459/// The kind of container a DN is: `LIST`, per §6.5.2's `LIST [ length 1.. ] OF dn-attribute`.
460pub const DN_CONTAINER: ContainerKind = ContainerKind::List;