Skip to main content

matter_kit/
der.rs

1//! A minimal DER reader and writer, for the ASN.1 that Matter cannot avoid.
2//!
3//! Matter is a TLV protocol and would rather not speak ASN.1 at all, but three things force
4//! it to:
5//!
6//! * an operational certificate's signature is over the **X.509 DER** it stands for, not
7//!   over its TLV ([`cert::der`](crate::cert::der), Core §6.5.2);
8//! * a Certification Declaration is a **CMS `SignedData`** (§6.3.1);
9//! * a Node Operational CSR is a **PKCS#10 `CertificationRequest`** (§6.4.7).
10//!
11//! So this module exists, and is deliberately the smallest thing that can do those three
12//! jobs: definite lengths, the handful of universal tags Matter uses, and context tags by
13//! number. There is no OID arc arithmetic, no `ANY`, no BER, no indefinite lengths.
14//!
15//! # Reading
16//!
17//! [`DerReader`] walks a sequence of elements in place. It never allocates and never copies:
18//! every element's content is a borrow of the input, so a signature can be checked over
19//! exactly the bytes that arrived.
20//!
21//! DER is a *distinguished* encoding — there is one valid encoding per value — and the
22//! reader enforces the parts of that which matter for security: a length must be in its
23//! shortest form, and a length that runs past the end of its parent is an error rather than
24//! a truncation. A parser that accepted a non-minimal length would accept two encodings of
25//! the same certificate, which is exactly what a signature is supposed to prevent.
26//!
27//! # Writing
28//!
29//! [`DerWriter`] fills its buffer **from the end backwards**, because DER puts each
30//! element's length before its content and a forward writer would have to allocate or encode
31//! twice. Content is written first; the header is prepended once the length is a known
32//! difference of two positions. Every function that uses it therefore emits its fields in
33//! reverse order, which is flagged at each call site.
34
35use crate::error::{Error, ErrorCode, Result};
36
37// --- Identifier octets ---------------------------------------------------------------------
38
39/// `BOOLEAN`.
40pub const TAG_BOOLEAN: u8 = 0x01;
41/// `INTEGER`.
42pub const TAG_INTEGER: u8 = 0x02;
43/// `BIT STRING`.
44pub const TAG_BIT_STRING: u8 = 0x03;
45/// `OCTET STRING`.
46pub const TAG_OCTET_STRING: u8 = 0x04;
47/// `NULL`.
48pub const TAG_NULL: u8 = 0x05;
49/// `OBJECT IDENTIFIER`.
50pub const TAG_OID: u8 = 0x06;
51/// `UTF8String`.
52pub const TAG_UTF8_STRING: u8 = 0x0C;
53/// `PrintableString`.
54pub const TAG_PRINTABLE_STRING: u8 = 0x13;
55/// `IA5String`.
56pub const TAG_IA5_STRING: u8 = 0x16;
57/// `UTCTime`.
58pub const TAG_UTC_TIME: u8 = 0x17;
59/// `GeneralizedTime`.
60pub const TAG_GENERALIZED_TIME: u8 = 0x18;
61/// `SEQUENCE`, always constructed.
62pub const TAG_SEQUENCE: u8 = 0x30;
63/// `SET`, always constructed.
64pub const TAG_SET: u8 = 0x31;
65
66/// A context-specific tag, constructed — `[n] EXPLICIT`.
67#[must_use]
68pub const fn context_constructed(number: u8) -> u8 {
69    0xA0 | (number & 0x1F)
70}
71
72/// A context-specific tag, primitive — `[n] IMPLICIT` over a primitive type.
73#[must_use]
74pub const fn context_primitive(number: u8) -> u8 {
75    0x80 | (number & 0x1F)
76}
77
78// --- Object identifiers Matter uses, as DER content octets ---------------------------------
79
80/// `ecdsa-with-SHA256` — 1.2.840.10045.4.3.2.
81pub const OID_ECDSA_WITH_SHA256: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02];
82/// `id-ecPublicKey` — 1.2.840.10045.2.1.
83pub const OID_EC_PUBLIC_KEY: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01];
84/// `prime256v1` (secp256r1) — 1.2.840.10045.3.1.7.
85pub const OID_PRIME256V1: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07];
86/// `id-sha256` — 2.16.840.1.101.3.4.2.1.
87pub const OID_SHA256: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];
88/// `id-signedData` — 1.2.840.113549.1.7.2 (RFC 5652 §5.1).
89pub const OID_SIGNED_DATA: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02];
90/// `id-data` (`pkcs7-data`) — 1.2.840.113549.1.7.1.
91pub const OID_PKCS7_DATA: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01];
92/// `extensionRequest` — 1.2.840.113549.1.9.14 (RFC 2985), the PKCS#10 attribute.
93pub const OID_EXTENSION_REQUEST: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x0E];
94/// `organizationName` — 2.5.4.10.
95pub const OID_ORGANIZATION_NAME: &[u8] = &[0x55, 0x04, 0x0A];
96/// `commonName` — 2.5.4.3.
97pub const OID_COMMON_NAME: &[u8] = &[0x55, 0x04, 0x03];
98
99/// The prefix of every extension OID: `2.5.29`.
100pub const OID_CE_PREFIX: &[u8] = &[0x55, 0x1D];
101/// The prefix of every `key-purpose-id`: `1.3.6.1.5.5.7.3`.
102pub const OID_KP_PREFIX: &[u8] = &[0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03];
103/// Matter's private arc, `1.3.6.1.4.1.37244` (Core §6.1.1, Table 85).
104///
105/// Nothing is issued directly under it; the two sub-arcs below are what certificates use.
106pub const OID_MATTER_PREFIX: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C];
107
108/// `1.3.6.1.4.1.37244.1` — the operational distinguished-name attributes, whose final arc
109/// is the attribute number: `.1` is `matter-node-id`, `.4` is `matter-rcac-id` (Table 85).
110pub const OID_MATTER_DN_PREFIX: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x01];
111
112/// `1.3.6.1.4.1.37244.2` — the attestation distinguished-name attributes: `.1` is
113/// `matter-oid-vid` and `.2` is `matter-oid-pid` (Table 85, Core §6.2.2.2).
114pub const OID_MATTER_ATTESTATION_PREFIX: &[u8] =
115    &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02];
116/// `domainComponent` — 0.9.2342.19200300.100.1.25.
117pub const OID_DOMAIN_COMPONENT: &[u8] =
118    &[0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x19];
119
120fn malformed() -> Error {
121    Error::new(ErrorCode::DerMalformed)
122}
123
124// --- Reading ---------------------------------------------------------------------------------
125
126/// One DER element: its identifier octet and the content it wraps.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct Element<'a> {
129    /// The identifier octet — a [`TAG_SEQUENCE`] or a [`context_constructed`], say.
130    pub tag: u8,
131    /// The content octets, borrowed from the input.
132    pub content: &'a [u8],
133    /// The whole element including its header, which is what a signature covers when the
134    /// element is a `tbsCertificate` or a `certificationRequestInfo`.
135    pub raw: &'a [u8],
136}
137
138impl<'a> Element<'a> {
139    /// A reader over this element's content, for a constructed type.
140    #[must_use]
141    pub const fn content_reader(&self) -> DerReader<'a> {
142        DerReader::new(self.content)
143    }
144
145    /// The content as a `BIT STRING`'s bits, refusing any that are not whole octets.
146    ///
147    /// A `BIT STRING`'s first content octet counts the unused bits in its last octet.
148    /// Everything Matter puts in one — a public key, a signature — is whole octets, so a
149    /// non-zero count is a malformed encoding rather than something to round.
150    pub fn bit_string_octets(&self) -> Result<&'a [u8]> {
151        if self.tag != TAG_BIT_STRING {
152            return Err(malformed());
153        }
154        match self.content.split_first() {
155            Some((0, rest)) => Ok(rest),
156            _ => Err(malformed()),
157        }
158    }
159}
160
161/// A cursor over a sequence of DER elements.
162#[derive(Debug, Clone)]
163pub struct DerReader<'a> {
164    buf: &'a [u8],
165    pos: usize,
166}
167
168impl<'a> DerReader<'a> {
169    /// Starts reading at the beginning of `buf`.
170    #[must_use]
171    pub const fn new(buf: &'a [u8]) -> Self {
172        Self { buf, pos: 0 }
173    }
174
175    /// Whether every element has been consumed.
176    #[must_use]
177    pub const fn is_empty(&self) -> bool {
178        self.pos >= self.buf.len()
179    }
180
181    /// The octets not yet consumed.
182    #[must_use]
183    pub fn remaining(&self) -> &'a [u8] {
184        self.buf.get(self.pos..).unwrap_or(&[])
185    }
186
187    /// Returns the next element's identifier octet without consuming it.
188    #[must_use]
189    pub fn peek_tag(&self) -> Option<u8> {
190        self.buf.get(self.pos).copied()
191    }
192
193    /// Reads the next element, whatever it is.
194    pub fn next_element(&mut self) -> Result<Element<'a>> {
195        let start = self.pos;
196        let tag = *self.buf.get(self.pos).ok_or_else(malformed)?;
197        // A tag of 0x1F in the low five bits introduces a multi-octet tag number. Nothing
198        // Matter uses needs one, and accepting them would mean accepting structures this
199        // module cannot round-trip.
200        if tag & 0x1F == 0x1F {
201            return Err(Error::new(ErrorCode::Unsupported));
202        }
203        let mut at = self.pos.checked_add(1).ok_or_else(malformed)?;
204
205        let first = *self.buf.get(at).ok_or_else(malformed)?;
206        at = at.checked_add(1).ok_or_else(malformed)?;
207        let len = if first < 0x80 {
208            usize::from(first)
209        } else {
210            let count = usize::from(first & 0x7F);
211            // 0x80 is BER's indefinite length, which DER forbids; more than four octets is
212            // a length no buffer this crate handles could hold.
213            if count == 0 || count > 4 {
214                return Err(malformed());
215            }
216            let end = at.checked_add(count).ok_or_else(malformed)?;
217            let octets = self.buf.get(at..end).ok_or_else(malformed)?;
218            // DER requires the shortest form: a length below 128 must use the single-octet
219            // form, and a multi-octet length must not have a leading zero.
220            if octets.first() == Some(&0) {
221                return Err(malformed());
222            }
223            let mut value = 0usize;
224            for byte in octets {
225                value = value
226                    .checked_mul(256)
227                    .and_then(|v| v.checked_add(usize::from(*byte)))
228                    .ok_or_else(malformed)?;
229            }
230            if value < 0x80 {
231                return Err(malformed());
232            }
233            at = end;
234            value
235        };
236
237        let end = at.checked_add(len).ok_or_else(malformed)?;
238        let content = self.buf.get(at..end).ok_or_else(malformed)?;
239        let raw = self.buf.get(start..end).ok_or_else(malformed)?;
240        self.pos = end;
241        Ok(Element { tag, content, raw })
242    }
243
244    /// Reads the next element and requires it to have this identifier octet.
245    pub fn expect(&mut self, tag: u8) -> Result<Element<'a>> {
246        let element = self.next_element()?;
247        if element.tag == tag {
248            Ok(element)
249        } else {
250            Err(malformed())
251        }
252    }
253
254    /// Reads a `SEQUENCE` and returns a reader over its members.
255    pub fn expect_sequence(&mut self) -> Result<Self> {
256        Ok(self.expect(TAG_SEQUENCE)?.content_reader())
257    }
258
259    /// Reads a `SET` and returns a reader over its members.
260    pub fn expect_set(&mut self) -> Result<Self> {
261        Ok(self.expect(TAG_SET)?.content_reader())
262    }
263
264    /// Reads an `OBJECT IDENTIFIER` and requires it to be `expected`.
265    pub fn expect_oid(&mut self, expected: &[u8]) -> Result<()> {
266        if self.expect(TAG_OID)?.content == expected {
267            Ok(())
268        } else {
269            Err(malformed())
270        }
271    }
272
273    /// Reads a non-negative `INTEGER` and returns its magnitude with the sign octet removed.
274    ///
275    /// DER's `INTEGER` is two's-complement and minimally encoded, which means a positive
276    /// value whose top bit is set carries a leading `0x00` so that it does not read as
277    /// negative. That octet is part of the encoding, not of the number, so a 256-bit scalar
278    /// arrives as 33 octets about half the time.
279    ///
280    /// Both minimality rules are enforced: a leading `0x00` is legal only when the next
281    /// octet has its top bit set, and a leading `0x80`-or-above is a negative number.
282    pub fn expect_unsigned(&mut self) -> Result<&'a [u8]> {
283        let content = self.expect(TAG_INTEGER)?.content;
284        let (first, rest) = content.split_first().ok_or_else(malformed)?;
285        if *first & 0x80 != 0 {
286            // Negative. Nothing Matter encodes as an INTEGER is.
287            return Err(malformed());
288        }
289        if *first == 0 && rest.first().is_some_and(|b| *b < 0x80) {
290            // A leading zero that was not needed: not the distinguished encoding.
291            return Err(malformed());
292        }
293        Ok(if *first == 0 { rest } else { content })
294    }
295
296    /// Reads a non-negative `INTEGER` that must fit in a `u64`.
297    pub fn expect_uint(&mut self) -> Result<u64> {
298        let magnitude = self.expect_unsigned()?;
299        if magnitude.len() > 8 {
300            return Err(malformed());
301        }
302        let mut value = 0u64;
303        for byte in magnitude {
304            value = value
305                .checked_mul(256)
306                .and_then(|v| v.checked_add(u64::from(*byte)))
307                .ok_or_else(malformed)?;
308        }
309        Ok(value)
310    }
311
312    /// Reads the next element only if it has this identifier octet.
313    ///
314    /// This is how an `OPTIONAL` or a `DEFAULT` field is read: a look before the leap, since
315    /// what follows an absent field is the *next* field and consuming it would desynchronise
316    /// the parse.
317    pub fn take_if(&mut self, tag: u8) -> Result<Option<Element<'a>>> {
318        if self.peek_tag() == Some(tag) {
319            Ok(Some(self.next_element()?))
320        } else {
321            Ok(None)
322        }
323    }
324
325    /// Requires every element to have been consumed.
326    ///
327    /// Trailing octets after a complete structure are not a harmless suffix: in a signed
328    /// document they are data the signature does not cover.
329    pub fn finish(&self) -> Result<()> {
330        if self.is_empty() {
331            Ok(())
332        } else {
333            Err(malformed())
334        }
335    }
336}
337
338// --- Writing ----------------------------------------------------------------------------------
339
340/// A DER writer that fills its buffer from the end backwards, so that a length is always
341/// known by the time its header is written.
342#[derive(Debug)]
343pub struct DerWriter<'a> {
344    buf: &'a mut [u8],
345    /// The index of the first byte written; everything from here to the end is output.
346    pos: usize,
347}
348
349impl<'a> DerWriter<'a> {
350    /// Starts writing at the end of `buf`.
351    #[must_use]
352    pub fn new(buf: &'a mut [u8]) -> Self {
353        let pos = buf.len();
354        Self { buf, pos }
355    }
356
357    /// How many octets have been written.
358    #[must_use]
359    pub const fn len(&self) -> usize {
360        self.buf.len().saturating_sub(self.pos)
361    }
362
363    /// Whether nothing has been written.
364    #[must_use]
365    pub const fn is_empty(&self) -> bool {
366        self.len() == 0
367    }
368
369    /// Everything written, in the right order — the tail of the buffer.
370    #[must_use]
371    pub fn finish(self) -> &'a [u8] {
372        let pos = self.pos;
373        self.buf.get(pos..).unwrap_or(&[])
374    }
375
376    /// The current position, to be passed to [`DerWriter::header`] once an element's content
377    /// has been written.
378    #[must_use]
379    pub const fn mark(&self) -> usize {
380        self.pos
381    }
382
383    /// Prepends one octet.
384    pub fn byte(&mut self, value: u8) -> Result<()> {
385        let next = self
386            .pos
387            .checked_sub(1)
388            .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
389        let Some(slot) = self.buf.get_mut(next) else {
390            return Err(Error::new(ErrorCode::BufferTooSmall));
391        };
392        *slot = value;
393        self.pos = next;
394        Ok(())
395    }
396
397    /// Prepends a slice.
398    pub fn slice(&mut self, value: &[u8]) -> Result<()> {
399        let next = self
400            .pos
401            .checked_sub(value.len())
402            .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
403        let Some(slot) = self.buf.get_mut(next..self.pos) else {
404            return Err(Error::new(ErrorCode::BufferTooSmall));
405        };
406        slot.copy_from_slice(value);
407        self.pos = next;
408        Ok(())
409    }
410
411    /// Writes an identifier octet and the definite length of everything written since
412    /// `mark`, in DER's minimal form.
413    pub fn header(&mut self, tag: u8, mark: usize) -> Result<()> {
414        let len = mark
415            .checked_sub(self.pos)
416            .ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
417        // Lengths below 128 are a single octet; above, a count of length octets with the
418        // high bit set, then the length big-endian with no leading zeros.
419        if len < 0x80 {
420            let short = u8::try_from(len).map_err(|_| malformed())?;
421            self.byte(short)?;
422        } else {
423            let bytes = len.to_be_bytes();
424            let first = bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len());
425            let significant = bytes.get(first..).unwrap_or(&[]);
426            self.slice(significant)?;
427            let count = u8::try_from(significant.len()).map_err(|_| malformed())?;
428            self.byte(0x80 | count)?;
429        }
430        self.byte(tag)
431    }
432
433    /// Writes a complete primitive element.
434    pub fn primitive(&mut self, tag: u8, content: &[u8]) -> Result<()> {
435        let mark = self.mark();
436        self.slice(content)?;
437        self.header(tag, mark)
438    }
439
440    /// Writes an OID whose content is a prefix plus one final arc below 128.
441    pub fn oid_with_arc(&mut self, prefix: &[u8], arc: u8) -> Result<()> {
442        let mark = self.mark();
443        self.byte(arc)?;
444        self.slice(prefix)?;
445        self.header(TAG_OID, mark)
446    }
447
448    /// Writes a `BIT STRING` whose content is whole octets — a public key or a signature.
449    pub fn bit_string(&mut self, octets: &[u8]) -> Result<()> {
450        let mark = self.mark();
451        self.slice(octets)?;
452        // The count of unused bits in the final octet; zero for whole octets.
453        self.byte(0)?;
454        self.header(TAG_BIT_STRING, mark)
455    }
456
457    /// Writes a fixed-width big-endian scalar as an `INTEGER`: leading zeros dropped, and
458    /// one `0x00` put back if the top bit would otherwise make it negative.
459    pub fn unsigned_integer(&mut self, scalar: &[u8]) -> Result<()> {
460        let first = scalar
461            .iter()
462            .position(|b| *b != 0)
463            .unwrap_or(scalar.len().saturating_sub(1));
464        let trimmed = scalar.get(first..).unwrap_or(&[0]);
465        let mark = self.mark();
466        self.slice(trimmed)?;
467        if trimmed.first().is_some_and(|b| *b & 0x80 != 0) {
468            self.byte(0)?;
469        }
470        self.header(TAG_INTEGER, mark)
471    }
472
473    /// Writes an `AlgorithmIdentifier` with no parameters — `SEQUENCE { OID }`.
474    ///
475    /// `ecdsa-with-SHA256` and `sha256` both take this form. An `AlgorithmIdentifier` with a
476    /// spurious `NULL` here would hash differently and fail every signature.
477    pub fn algorithm_identifier(&mut self, oid: &[u8]) -> Result<()> {
478        let mark = self.mark();
479        self.primitive(TAG_OID, oid)?;
480        self.header(TAG_SEQUENCE, mark)
481    }
482
483    /// Writes a `SubjectPublicKeyInfo` for an uncompressed P-256 point.
484    pub fn subject_public_key_info(&mut self, public_key: &[u8]) -> Result<()> {
485        let mark = self.mark();
486        self.bit_string(public_key)?;
487        let algo = self.mark();
488        self.primitive(TAG_OID, OID_PRIME256V1)?;
489        self.primitive(TAG_OID, OID_EC_PUBLIC_KEY)?;
490        self.header(TAG_SEQUENCE, algo)?;
491        self.header(TAG_SEQUENCE, mark)
492    }
493
494    /// Writes an `ECDSA-Sig-Value` — `SEQUENCE { r INTEGER, s INTEGER }` — from the
495    /// fixed-width `r || s` that Core §3.5.3 uses.
496    pub fn ecdsa_sig_value(&mut self, raw: &[u8]) -> Result<()> {
497        let half = raw.len().checked_div(2).ok_or_else(malformed)?;
498        let (r, s) = raw.split_at(half);
499        let mark = self.mark();
500        self.unsigned_integer(s)?;
501        self.unsigned_integer(r)?;
502        self.header(TAG_SEQUENCE, mark)
503    }
504}
505
506/// Reads an `ECDSA-Sig-Value` back into the fixed-width `r || s` of Core §3.5.3.
507///
508/// The DER form drops leading zeros and may add one, so neither integer is a fixed width;
509/// this puts each back into its 32-octet slot right-aligned.
510pub fn ecdsa_sig_value_to_raw(der: &[u8], out: &mut [u8; 64]) -> Result<()> {
511    let mut reader = DerReader::new(der);
512    let mut seq = reader.expect_sequence()?;
513    reader.finish()?;
514    for half in 0..2usize {
515        let value = seq.expect_unsigned()?;
516        if value.len() > 32 {
517            return Err(malformed());
518        }
519        let start = half
520            .checked_mul(32)
521            .and_then(|s| s.checked_add(32))
522            .and_then(|e| e.checked_sub(value.len()))
523            .ok_or_else(malformed)?;
524        let end = start.checked_add(value.len()).ok_or_else(malformed)?;
525        out.get_mut(start..end)
526            .ok_or_else(malformed)?
527            .copy_from_slice(value);
528    }
529    seq.finish()?;
530    Ok(())
531}
532
533// --- Time -------------------------------------------------------------------------------------
534
535/// Seconds between the Unix epoch and the Matter epoch of 2000-01-01 00:00:00 UTC.
536///
537/// Matter times are `epoch-s` (Core §6.5.7), so a certificate's `not-before` of `0x271B17EF`
538/// is 2020-10-15 14:23:43 UTC — as the corresponding X.509 certificate's `UTCTime` says.
539pub const MATTER_EPOCH_UNIX: i64 = 946_684_800;
540
541/// The year at which X.509 switches from `UTCTime` to `GeneralizedTime` (RFC 5280 §4.1.2.5).
542pub const GENERALIZED_TIME_FROM: u32 = 2050;
543
544/// A civil date and time, broken out of a Matter `epoch-s`.
545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
546pub struct Civil {
547    /// The full year, e.g. 2020.
548    pub year: u32,
549    /// 1 through 12.
550    pub month: u32,
551    /// 1 through 31.
552    pub day: u32,
553    /// 0 through 23.
554    pub hour: u32,
555    /// 0 through 59.
556    pub minute: u32,
557    /// 0 through 59; leap seconds are not represented.
558    pub second: u32,
559}
560
561/// Converts a Matter `epoch-s` to a civil UTC date, by Howard Hinnant's `civil_from_days`.
562///
563/// The algorithm shifts the epoch to 0000-03-01 so that February's leap day lands at the
564/// end of a "year", which makes the whole thing branch-free arithmetic rather than a table
565/// of month lengths.
566///
567/// The plain arithmetic is deliberate and bounded. The input is a `u32`, so `unix` is at
568/// most about 5.2e9 and `days` at most about 60 000; every intermediate below stays under
569/// 2e8 in an `i64` whose range is 9.2e18. Rewriting the expressions with `checked_*` would
570/// obscure an algorithm whose correctness rests on being read against its published form,
571/// in exchange for branches that can never be taken.
572#[expect(
573    clippy::arithmetic_side_effects,
574    reason = "every intermediate is bounded by the u32 input; see above"
575)]
576pub fn civil_from_epoch_s(epoch_s: u32) -> Result<Civil> {
577    let unix = i64::from(epoch_s)
578        .checked_add(MATTER_EPOCH_UNIX)
579        .ok_or_else(malformed)?;
580    let days = unix.div_euclid(86_400);
581    let secs_of_day = unix.rem_euclid(86_400);
582
583    let z = days.checked_add(719_468).ok_or_else(malformed)?;
584    let era = z.div_euclid(146_097);
585    let doe = z.rem_euclid(146_097); // [0, 146096]
586    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
587    let y = yoe + era * 400;
588    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
589    let mp = (5 * doy + 2) / 153; // [0, 11], March = 0
590    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
591    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
592    let year = if m <= 2 { y + 1 } else { y };
593
594    Ok(Civil {
595        year: u32::try_from(year).map_err(|_| malformed())?,
596        month: u32::try_from(m).map_err(|_| malformed())?,
597        day: u32::try_from(d).map_err(|_| malformed())?,
598        hour: u32::try_from(secs_of_day / 3600).map_err(|_| malformed())?,
599        minute: u32::try_from((secs_of_day / 60) % 60).map_err(|_| malformed())?,
600        second: u32::try_from(secs_of_day % 60).map_err(|_| malformed())?,
601    })
602}
603
604/// A `Time`: `UTCTime` before 2050, `GeneralizedTime` from 2050 on (RFC 5280 §4.1.2.5).
605pub fn write_time(writer: &mut DerWriter<'_>, epoch_s: u32) -> Result<()> {
606    let civil = civil_from_epoch_s(epoch_s)?;
607    let mut out = [0u8; 15];
608    if civil.year < GENERALIZED_TIME_FROM {
609        // YYMMDDHHMMSSZ
610        let digits = out.get_mut(..13).ok_or_else(malformed)?;
611        write_two(digits, 0, civil.year % 100)?;
612        write_two(digits, 2, civil.month)?;
613        write_two(digits, 4, civil.day)?;
614        write_two(digits, 6, civil.hour)?;
615        write_two(digits, 8, civil.minute)?;
616        write_two(digits, 10, civil.second)?;
617        *digits.get_mut(12).ok_or_else(malformed)? = b'Z';
618        writer.primitive(TAG_UTC_TIME, digits)
619    } else {
620        // YYYYMMDDHHMMSSZ
621        write_two(&mut out, 0, civil.year / 100)?;
622        write_two(&mut out, 2, civil.year % 100)?;
623        write_two(&mut out, 4, civil.month)?;
624        write_two(&mut out, 6, civil.day)?;
625        write_two(&mut out, 8, civil.hour)?;
626        write_two(&mut out, 10, civil.minute)?;
627        write_two(&mut out, 12, civil.second)?;
628        *out.get_mut(14).ok_or_else(malformed)? = b'Z';
629        writer.primitive(TAG_GENERALIZED_TIME, &out)
630    }
631}
632
633fn write_two(out: &mut [u8], at: usize, value: u32) -> Result<()> {
634    if value > 99 {
635        return Err(malformed());
636    }
637    let tens = u8::try_from(value / 10).map_err(|_| malformed())?;
638    let ones = u8::try_from(value % 10).map_err(|_| malformed())?;
639    *out.get_mut(at).ok_or_else(malformed)? = b'0'.wrapping_add(tens);
640    *out.get_mut(at.checked_add(1).ok_or_else(malformed)?)
641        .ok_or_else(malformed)? = b'0'.wrapping_add(ones);
642    Ok(())
643}
644
645/// The Matter `epoch-s` of a civil UTC date, by Howard Hinnant's `days_from_civil`.
646///
647/// The inverse of [`civil_from_epoch_s`], and the direction an X.509 `UTCTime` has to go:
648/// a DAC's `notBefore` is a printed date, and chain validation happens "with respect to the
649/// notBefore timestamp of the DAC" (Core §6.2.3.1).
650///
651/// Returns `None` for a date before the Matter epoch of 2000-01-01 or beyond what a `u32`
652/// of seconds can reach — which includes X.509's `99991231235959Z` "no expiry" value, so a
653/// caller must handle that separately rather than treat it as an error.
654#[expect(
655    clippy::arithmetic_side_effects,
656    reason = "every intermediate is bounded by the validated field widths; see civil_from_epoch_s"
657)]
658#[must_use]
659pub fn epoch_s_from_civil(civil: &Civil) -> Option<u32> {
660    if civil.month < 1 || civil.month > 12 || civil.day < 1 || civil.day > 31 {
661        return None;
662    }
663    if civil.hour > 23 || civil.minute > 59 || civil.second > 59 {
664        return None;
665    }
666    let y = i64::from(civil.year) - i64::from(civil.month <= 2);
667    let era = y.div_euclid(400);
668    let yoe = y - era * 400; // [0, 399]
669    let m = i64::from(civil.month);
670    let d = i64::from(civil.day);
671    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; // [0, 365]
672    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
673    let days = era * 146_097 + doe - 719_468;
674
675    let secs = days * 86_400
676        + i64::from(civil.hour) * 3600
677        + i64::from(civil.minute) * 60
678        + i64::from(civil.second);
679    u32::try_from(secs - MATTER_EPOCH_UNIX).ok()
680}
681
682/// The `GeneralizedTime` X.509 uses for "no well-defined expiration date" (RFC 5280
683/// §4.1.2.5), which Matter's `not-after` represents as zero (Core §6.5.7).
684pub const NO_EXPIRY: &[u8] = b"99991231235959Z";
685
686/// Reads an X.509 `Time` — a `UTCTime` or a `GeneralizedTime` — as a Matter `epoch-s`.
687///
688/// Only the `Z` forms are accepted. RFC 5280 §4.1.2.5 requires them: "values MUST be
689/// expressed in Greenwich Mean Time (Zulu)", and a local-time offset would make two
690/// certificates with the same printed date compare differently.
691///
692/// Returns `Ok(None)` for the `99991231235959Z` that means no expiry, which is a value
693/// rather than an error: a PAA carries it routinely.
694pub fn read_time(element: &Element<'_>) -> Result<Option<u32>> {
695    let (text, century_from_yy) = match element.tag {
696        TAG_UTC_TIME => (element.content, true),
697        TAG_GENERALIZED_TIME => (element.content, false),
698        _ => return Err(malformed()),
699    };
700    if text == NO_EXPIRY {
701        return Ok(None);
702    }
703    let expected = if century_from_yy { 13 } else { 15 };
704    if text.len() != expected || text.last() != Some(&b'Z') {
705        return Err(malformed());
706    }
707
708    let mut at = 0usize;
709    let mut take = |digits: usize| -> Result<u32> {
710        let end = at.checked_add(digits).ok_or_else(malformed)?;
711        let slot = text.get(at..end).ok_or_else(malformed)?;
712        at = end;
713        let mut value = 0u32;
714        for byte in slot {
715            let digit = byte
716                .checked_sub(b'0')
717                .filter(|d| *d < 10)
718                .ok_or_else(malformed)?;
719            value = value
720                .checked_mul(10)
721                .and_then(|v| v.checked_add(u32::from(digit)))
722                .ok_or_else(malformed)?;
723        }
724        Ok(value)
725    };
726
727    let year = if century_from_yy {
728        let yy = take(2)?;
729        // RFC 5280 §4.1.2.5.1: "Where YY is greater than or equal to 50, the year SHALL be
730        // interpreted as 19YY; and where YY is less than 50, as 20YY."
731        if yy >= 50 {
732            yy.saturating_add(1900)
733        } else {
734            yy.saturating_add(2000)
735        }
736    } else {
737        take(4)?
738    };
739    let civil = Civil {
740        year,
741        month: take(2)?,
742        day: take(2)?,
743        hour: take(2)?,
744        minute: take(2)?,
745        second: take(2)?,
746    };
747    epoch_s_from_civil(&civil).map(Some).ok_or_else(malformed)
748}
749
750#[cfg(test)]
751mod tests {
752    use super::*;
753
754    #[test]
755    fn a_short_form_length_reads() {
756        let mut reader = DerReader::new(&[0x02, 0x01, 0x2A]);
757        let element = reader.next_element().expect("element");
758        assert_eq!(element.tag, TAG_INTEGER);
759        assert_eq!(element.content, &[0x2A]);
760        assert_eq!(element.raw, &[0x02, 0x01, 0x2A]);
761        reader.finish().expect("consumed");
762    }
763
764    #[test]
765    fn a_long_form_length_reads() {
766        let mut bytes = [0u8; 132];
767        bytes[0] = TAG_OCTET_STRING;
768        bytes[1] = 0x81;
769        bytes[2] = 129;
770        let mut reader = DerReader::new(&bytes);
771        assert_eq!(reader.next_element().expect("element").content.len(), 129);
772    }
773
774    #[test]
775    fn a_non_minimal_length_is_refused() {
776        // DER has exactly one encoding per value. Accepting a second one would mean two
777        // byte strings that are the same certificate — and a signature over only one.
778        for bytes in [
779            // 0x81 0x01: the long form for a length that fits the short form.
780            &[0x04, 0x81, 0x01, 0xAA][..],
781            // A leading zero in a multi-octet length.
782            &[0x04, 0x82, 0x00, 0x01, 0xAA][..],
783            // 0x80: BER's indefinite length, which DER forbids.
784            &[0x30, 0x80, 0x00, 0x00][..],
785        ] {
786            assert!(
787                DerReader::new(bytes).next_element().is_err(),
788                "{bytes:02x?}"
789            );
790        }
791    }
792
793    #[test]
794    fn a_length_past_the_end_is_an_error_not_a_truncation() {
795        assert!(DerReader::new(&[0x04, 0x05, 0xAA]).next_element().is_err());
796    }
797
798    #[test]
799    fn truncation_at_every_length_is_an_error_not_a_panic() {
800        let full = [0x30, 0x06, 0x02, 0x01, 0x2A, 0x04, 0x01, 0xFF];
801        for len in 0..full.len() {
802            let mut reader = DerReader::new(&full[..len]);
803            // Either it errors, or it reads fewer complete elements — never panics.
804            while let Ok(element) = reader.next_element() {
805                let _ = element;
806            }
807        }
808    }
809
810    #[test]
811    fn a_multi_octet_tag_is_refused_rather_than_misread() {
812        // Nothing in Matter needs one, and silently skipping it would desynchronise a parse
813        // that a signature is computed over.
814        assert_eq!(
815            DerReader::new(&[0x1F, 0x81, 0x00, 0x00])
816                .next_element()
817                .map(|_| ())
818                .unwrap_err()
819                .code(),
820            ErrorCode::Unsupported
821        );
822    }
823
824    #[test]
825    fn integers_are_read_as_der_defines_them() {
826        // Minimal, non-negative, and the sign octet stripped.
827        let cases: &[(&[u8], Option<u64>)] = &[
828            (&[0x02, 0x01, 0x00], Some(0)),
829            (&[0x02, 0x01, 0x7F], Some(127)),
830            (&[0x02, 0x02, 0x00, 0x80], Some(128)),
831            (&[0x02, 0x02, 0x01, 0x00], Some(256)),
832            // Negative.
833            (&[0x02, 0x01, 0x80], None),
834            // A redundant leading zero.
835            (&[0x02, 0x02, 0x00, 0x01], None),
836        ];
837        for (bytes, expected) in cases {
838            assert_eq!(
839                DerReader::new(bytes).expect_uint().ok(),
840                *expected,
841                "{bytes:02x?}"
842            );
843        }
844    }
845
846    #[test]
847    fn a_bit_string_with_unused_bits_is_refused() {
848        // Everything Matter puts in a BIT STRING is whole octets.
849        let element = DerReader::new(&[0x03, 0x02, 0x00, 0xAB])
850            .next_element()
851            .expect("element");
852        assert_eq!(element.bit_string_octets().expect("octets"), &[0xAB]);
853
854        let element = DerReader::new(&[0x03, 0x02, 0x04, 0xB0])
855            .next_element()
856            .expect("element");
857        assert!(element.bit_string_octets().is_err());
858    }
859
860    #[test]
861    fn take_if_does_not_consume_the_wrong_element() {
862        // An absent OPTIONAL field is followed by the next field, so a reader that consumed
863        // before looking would lose it.
864        let mut reader = DerReader::new(&[0x02, 0x01, 0x07, 0x04, 0x01, 0xFF]);
865        assert!(reader.take_if(TAG_OCTET_STRING).expect("look").is_none());
866        assert_eq!(reader.expect_uint().expect("int"), 7);
867        assert_eq!(
868            reader
869                .take_if(TAG_OCTET_STRING)
870                .expect("look")
871                .expect("present")
872                .content,
873            &[0xFF]
874        );
875    }
876
877    #[test]
878    fn trailing_octets_are_refused() {
879        // In a signed document, a trailing suffix is data the signature does not cover.
880        let mut reader = DerReader::new(&[0x02, 0x01, 0x07, 0xFF]);
881        reader.expect_uint().expect("int");
882        assert!(reader.finish().is_err());
883    }
884
885    #[test]
886    fn the_writer_and_the_reader_agree() {
887        let mut buf = [0u8; 128];
888        let mut w = DerWriter::new(&mut buf);
889        let mark = w.mark();
890        // Reverse order, as the writer requires.
891        w.primitive(TAG_OCTET_STRING, &[0xDE, 0xAD])
892            .expect("octets");
893        w.primitive(TAG_INTEGER, &[0x2A]).expect("int");
894        w.header(TAG_SEQUENCE, mark).expect("sequence");
895        let bytes = w.finish();
896        assert_eq!(
897            bytes,
898            &[0x30, 0x07, 0x02, 0x01, 0x2A, 0x04, 0x02, 0xDE, 0xAD]
899        );
900
901        let mut reader = DerReader::new(bytes);
902        let mut seq = reader.expect_sequence().expect("sequence");
903        assert_eq!(seq.expect_uint().expect("int"), 42);
904        assert_eq!(
905            seq.expect(TAG_OCTET_STRING).expect("octets").content,
906            &[0xDE, 0xAD]
907        );
908        seq.finish().expect("consumed");
909        reader.finish().expect("consumed");
910    }
911
912    #[test]
913    fn a_signature_survives_the_round_trip_through_der() {
914        // The fixed-width r || s of §3.5.3 and DER's minimal INTEGERs are different shapes,
915        // and a value with a high top byte or leading zeros exercises both directions.
916        let cases: [[u8; 64]; 4] = [
917            [0x01; 64],
918            [0xFF; 64],
919            {
920                let mut v = [0u8; 64];
921                v[31] = 1;
922                v[63] = 2;
923                v
924            },
925            {
926                let mut v = [0x7Fu8; 64];
927                v[0] = 0x80;
928                v[32] = 0x00;
929                v
930            },
931        ];
932        for raw in cases {
933            let mut buf = [0u8; 128];
934            let mut w = DerWriter::new(&mut buf);
935            w.ecdsa_sig_value(&raw).expect("write");
936            let der = w.finish();
937            let mut back = [0u8; 64];
938            ecdsa_sig_value_to_raw(der, &mut back).expect("read");
939            assert_eq!(back, raw, "{raw:02x?}");
940        }
941    }
942
943    #[test]
944    fn the_two_time_directions_are_inverses() {
945        // A date that survives epoch -> civil -> epoch is one where neither the leap-year
946        // arithmetic nor the month table went wrong. Stepping by a prime number of seconds
947        // lands on every weekday, month length and leap boundary over 60 years.
948        let mut at = 0u32;
949        while at < 1_900_000_000 {
950            let civil = civil_from_epoch_s(at).expect("civil");
951            assert_eq!(epoch_s_from_civil(&civil), Some(at), "{at}");
952            at = at.saturating_add(1_000_003);
953        }
954    }
955
956    #[test]
957    fn leap_days_land_where_they_should() {
958        // 2000 is a leap year (divisible by 400), 2100 would not be (divisible by 100 but
959        // not 400) — the case a naive rule gets wrong, and the reason the algorithm shifts
960        // its epoch to March.
961        let cases = [
962            (0u32, 2000, 1, 1),
963            (59 * 86_400, 2000, 2, 29),
964            (60 * 86_400, 2000, 3, 1),
965            (365 * 86_400, 2000, 12, 31),
966            (366 * 86_400, 2001, 1, 1),
967        ];
968        for (epoch, year, month, day) in cases {
969            let civil = civil_from_epoch_s(epoch).expect("civil");
970            assert_eq!(
971                (civil.year, civil.month, civil.day),
972                (year, month, day),
973                "{epoch}"
974            );
975        }
976    }
977
978    #[test]
979    fn an_x509_time_reads_as_the_spec_prints_it() {
980        // The RCAC of Core §6.5.15.1 carries `170d 3230313031353134323334335a`, which
981        // openssl prints as "Oct 15 14:23:43 2020 GMT" and whose Matter epoch-s the TLV
982        // gives as 0x271B17EF.
983        let element = DerReader::new(&[
984            0x17, 0x0D, b'2', b'0', b'1', b'0', b'1', b'5', b'1', b'4', b'2', b'3', b'4', b'3',
985            b'Z',
986        ])
987        .next_element()
988        .expect("element");
989        assert_eq!(read_time(&element).expect("time"), Some(0x271B_17EF));
990    }
991
992    #[test]
993    fn a_two_digit_year_uses_rfc_5280s_pivot() {
994        // "Where YY is greater than or equal to 50, the year SHALL be interpreted as 19YY;
995        // and where YY is less than 50, as 20YY." A 19xx date is before the Matter epoch and
996        // therefore has no epoch-s, which is an error rather than a wrap to a huge value.
997        let mut bytes = [
998            0x17, 0x0D, b'4', b'9', b'0', b'1', b'0', b'1', b'0', b'0', b'0', b'0', b'0', b'0',
999            b'Z',
1000        ];
1001        let element = DerReader::new(&bytes).next_element().expect("element");
1002        let civil =
1003            civil_from_epoch_s(read_time(&element).expect("time").expect("a time")).expect("civil");
1004        assert_eq!(civil.year, 2049);
1005
1006        bytes[2] = b'5';
1007        bytes[3] = b'0';
1008        let element = DerReader::new(&bytes).next_element().expect("element");
1009        assert!(
1010            read_time(&element).is_err(),
1011            "1950 is before the Matter epoch"
1012        );
1013    }
1014
1015    #[test]
1016    fn the_no_expiry_time_is_a_value_not_an_error() {
1017        // A PAA routinely carries 99991231235959Z, and treating it as a malformed date would
1018        // make every attestation chain fail at its root.
1019        let mut bytes = [0u8; 17];
1020        bytes[0] = TAG_GENERALIZED_TIME;
1021        bytes[1] = 15;
1022        bytes[2..17].copy_from_slice(NO_EXPIRY);
1023        let element = DerReader::new(&bytes).next_element().expect("element");
1024        assert_eq!(read_time(&element).expect("time"), None);
1025    }
1026
1027    #[test]
1028    fn a_time_that_is_not_zulu_is_refused() {
1029        // RFC 5280 §4.1.2.5: "values MUST be expressed in Greenwich Mean Time (Zulu)". An
1030        // offset would make two certificates with the same printed date compare differently.
1031        let element = DerReader::new(&[
1032            0x17, 0x0D, b'2', b'0', b'1', b'0', b'1', b'5', b'1', b'4', b'2', b'3', b'4', b'3',
1033            b'+',
1034        ])
1035        .next_element()
1036        .expect("element");
1037        assert!(read_time(&element).is_err());
1038    }
1039
1040    #[test]
1041    fn a_time_with_a_non_digit_is_refused() {
1042        let element = DerReader::new(&[
1043            0x17, 0x0D, b'2', b'0', b'1', b'0', b'1', b'5', b'1', b'4', b'2', b'3', b'4', b'x',
1044            b'Z',
1045        ])
1046        .next_element()
1047        .expect("element");
1048        assert!(read_time(&element).is_err());
1049    }
1050
1051    #[test]
1052    fn a_buffer_that_is_too_small_is_an_error_at_every_length() {
1053        let mut full = [0u8; 32];
1054        let written = {
1055            let mut w = DerWriter::new(&mut full);
1056            w.primitive(TAG_OCTET_STRING, &[0xAA; 8]).expect("write");
1057            w.len()
1058        };
1059        for len in 0..written {
1060            let mut small = [0u8; 32];
1061            let slot = small.get_mut(..len).expect("in range");
1062            let mut w = DerWriter::new(slot);
1063            assert!(w.primitive(TAG_OCTET_STRING, &[0xAA; 8]).is_err(), "{len}");
1064        }
1065    }
1066}