Skip to main content

matter_kit/clusters/tls/
mod.rs

1//! TLS on a Matter node (Core ch. 14): the certificates and the endpoints.
2//!
3//! Needs the `rustcrypto` feature: §14.2.2.1 identifies every certificate by its SHA-256
4//! fingerprint, which is [`crypto`](crate::crypto).
5//!
6//! Some application clusters — Camera AV Stream Management, WebRTC — reach outside the fabric
7//! over TLS. Chapter 14 is how the administrator provisions that: which root CAs the node
8//! trusts, which client certificate it presents, and which host and port each of them is for.
9//!
10//! Two clusters share the job and this module's [`TlsTables`] is why they can:
11//!
12//! * [`certificate_management`] (`0x0801`) holds the trust material — root CAs and client
13//!   certificate details, each with an id and a fingerprint.
14//! * [`client_management`] (`0x0802`) holds the endpoints, each naming a host, a port, and the
15//!   certificates from the other cluster to use with them.
16//!
17//! The two are not independent, and the rules that link them are the ones an implementation
18//! gets wrong. §14.4.6.7 refuses to remove a root certificate an endpoint still names;
19//! §14.5.7.1 refuses to provision an endpoint naming a certificate that does not exist. Each
20//! check has to see both tables, so both clusters are views onto one.
21//!
22//! # Certificates do not live in RAM
23//!
24//! §14.4.4.3 caps a certificate at 3000 octets and §14.3.3.1 asks for five root certificates
25//! *per fabric*, plus two client certificates and up to ten intermediates each. That is tens of
26//! kilobytes, and no `no_std` node holds it in a `heapless::Vec`.
27//!
28//! So this module holds the *index* — ids, fingerprints, fabric associations, reference counts
29//! — and the certificate bytes belong to the application through [`TlsCertificateHooks`], which
30//! writes them straight into the response's TLV rather than through a buffer in between. The
31//! index is where every rule lives; the bytes are just bytes.
32//!
33//! # Large Message, and why this is where TCP earns its place
34//!
35//! §14.4: "Commands in this cluster uniformly use the Large Message qualifier, even when the
36//! command doesn't require it, to reduce the testing matrix." A 3000-octet certificate does not
37//! fit in §4.4.4's 1280-octet datagram, so these commands need
38//! [`Peer::Tcp`](crate::platform::Peer::Tcp) underneath — and the attributes say so themselves:
39//!
40//! > When this field exists and is read over a Large Message capable transport, it SHALL be
41//! > included. When this field exists and is read over a non Large Message capable transport,
42//! > it SHALL NOT be included.
43//!
44//! A read over UDP returns the ids without the certificates, which is not an error and not a
45//! truncation — it is the attribute having a different shape on a transport that cannot carry
46//! the whole of it.
47
48use core::cell::{Cell, RefCell};
49
50use crate::im::Status;
51use crate::msg::FabricIndex;
52use crate::tlv::{Tag, TlvWriter};
53
54pub mod certificate_management;
55pub mod client_management;
56
57/// §14.4.4.1: a `TLSCAID` has "valid values from 0 to 65534".
58pub type TlsCaid = u16;
59/// §14.4.4.2: a `TLSCCDID`, over the same range.
60pub type TlsCcdid = u16;
61/// §14.5.4.1: a `TLSEndpointID`, over the same range.
62pub type TlsEndpointId = u16;
63
64/// The largest id any of chapter 14's three types may take. `0xFFFF` is not one of them: it is
65/// the null value every one of these fields uses when it is nullable.
66pub const ID_MAX: u16 = 65534;
67
68/// §14.4.4.3's constraint on a certificate: "max 3000".
69pub const CERTIFICATE_MAX: usize = 3000;
70
71/// §14.2.2.1: a fingerprint is SHA-256 over the DER, so 32 octets.
72pub const FINGERPRINT_LEN: usize = 32;
73
74/// §14.4.6.5's constraint on a `Fingerprint` field: "max 64", which leaves room for a longer
75/// hash than 1.6 defines.
76pub const FINGERPRINT_FIELD_MAX: usize = 64;
77
78/// §14.5.4.2's constraint on a `Hostname`: "4 to 253".
79pub const HOSTNAME_MIN: usize = 4;
80/// The other end of it — a DNS name's own limit.
81pub const HOSTNAME_MAX: usize = 253;
82
83/// §14.4.4.4's constraint on `IntermediateCertificates`: "max 10".
84pub const INTERMEDIATES_MAX: usize = 10;
85
86/// §14.4.6.8's constraint on `Nonce`: exactly 32 octets, "generated using Crypto_DRBG()".
87pub const NONCE_LEN: usize = 32;
88
89/// §14.3.3.1: "Nodes SHALL provide enough storage space for at least 5 Root certificates per
90/// Fabric on a Node."
91pub const MIN_ROOTS_PER_FABRIC: u8 = 5;
92
93/// §14.3.3.1: "at least 2 Client Certificate Details per Fabric".
94pub const MIN_CLIENTS_PER_FABRIC: u8 = 2;
95
96/// The smallest `MaxProvisioned` §14.5.6 allows: its constraint is "5 to 254".
97///
98/// §14.3.3.2 asks only for "at least 2 TLS Endpoints per Fabric" and for "at least 2 concurrent
99/// TLS client connections per Fabric"; the attribute's own constraint is the higher of the two,
100/// and it is the one a client reads.
101pub const MIN_ENDPOINTS_PER_FABRIC: u8 = 5;
102
103/// §14.2.2.1's certificate fingerprint: "the SHA-256 hash algorithm … using the DER (binary)
104/// encoding format of the certificate".
105#[must_use]
106pub fn fingerprint(der: &[u8]) -> [u8; FINGERPRINT_LEN] {
107    crate::crypto::hash(der)
108}
109
110/// Which stored certificate a [`TlsCertificateHooks`] call is about.
111///
112/// Every slot is fabric-scoped: §14.4.4.3 and §14.4.4.4 are both "Access Modifier: Fabric
113/// Scoped", and two fabrics may hold the same id.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub enum Slot {
116    /// A root CA certificate (`TLSRCAC`), by its `TLSCAID`.
117    Root {
118        /// The fabric that provisioned it.
119        fabric_index: FabricIndex,
120        /// Its Certificate Authority ID.
121        caid: TlsCaid,
122    },
123    /// A client certificate, by its `TLSCCDID`.
124    Client {
125        /// The fabric that provisioned it.
126        fabric_index: FabricIndex,
127        /// Its Client Certificate Details ID.
128        ccdid: TlsCcdid,
129    },
130    /// One intermediate certificate of a client certificate's chain, in chain order.
131    Intermediate {
132        /// The fabric that provisioned it.
133        fabric_index: FabricIndex,
134        /// The client certificate this chain belongs to.
135        ccdid: TlsCcdid,
136        /// Its position in the chain, `0..`[`INTERMEDIATES_MAX`].
137        index: u8,
138    },
139}
140
141/// Where the certificate bytes actually live, and who does the cryptography.
142///
143/// Every method that produces a certificate writes it into the outgoing TLV rather than
144/// returning it: a node that keeps its certificates in flash streams them straight out, and one
145/// that keeps them in RAM writes a slice. Neither needs a 3000-octet buffer in between, which
146/// is the whole reason this is a trait.
147pub trait TlsCertificateHooks {
148    /// Whether `der` is a certificate this node will accept.
149    ///
150    /// §14.4.6.1: "If the passed in Certificate is an invalid TLS Certificate: Fail the command
151    /// with the status code DYNAMIC_CONSTRAINT_ERROR". What "valid" means is the product's —
152    /// chapter 14 is standard Web PKI, not [`cert`](crate::cert)'s Matter profile.
153    fn is_valid_certificate(&self, der: &[u8]) -> bool;
154
155    /// Stores a certificate, replacing whatever the slot held.
156    ///
157    /// [`Status::ResourceExhausted`] when there is no room for it — the index had room, the
158    /// flash did not.
159    fn save(&self, slot: Slot, der: &[u8]) -> core::result::Result<(), Status>;
160
161    /// Writes a stored certificate into the response as an octet string under `tag`.
162    ///
163    /// A slot the index knows about but the store has lost is [`Status::Failure`]: the two
164    /// have disagreed, and answering with a truncated chain would be worse.
165    fn write_certificate(
166        &self,
167        slot: Slot,
168        w: &mut TlvWriter<'_>,
169        tag: Tag,
170    ) -> core::result::Result<(), Status>;
171
172    /// Forgets a stored certificate. Called for a slot that may never have held one.
173    fn clear(&self, slot: Slot);
174
175    /// §14.4.6.8: generates a key pair for a new `TLSCCDID`.
176    ///
177    /// > If a key collision is detected against any other TLS key pair or Operational
178    /// > credential key pair: Discard the new key pair. Fail the command with the status code
179    /// > DYNAMIC_CONSTRAINT_ERROR.
180    fn generate_key(&self, ccdid: TlsCcdid) -> core::result::Result<(), Status>;
181
182    /// §14.4.6.8: writes the `CSR` and `NonceSignature` fields of a `ClientCSRResponse`.
183    ///
184    /// Two tags rather than two buffers, for the same reason as
185    /// [`write_certificate`](Self::write_certificate): a PKCS #10 request may be 3000 octets and
186    /// there is nowhere to put it. `csr_tag` takes "a DER-encoded octet string of a PKCS #10
187    /// format Certificate Signing Request"; `signature_tag` takes `Crypto_Sign(nonce)` under
188    /// the same key, which is the freshness proof §14.3.1.2 has the client check against the
189    /// CSR's own inner signature.
190    fn write_csr(
191        &self,
192        ccdid: TlsCcdid,
193        nonce: &[u8],
194        w: &mut TlvWriter<'_>,
195        csr_tag: Tag,
196        signature_tag: Tag,
197    ) -> core::result::Result<(), Status>;
198
199    /// §14.4.6.10: "If the public key of the passed in ClientCertificate does not correspond to
200    /// the private key of the matching entry" — a certificate for somebody else's key.
201    fn key_matches(&self, ccdid: TlsCcdid, certificate: &[u8]) -> bool;
202
203    /// §14.4.6.15: "Remove the TLS Key Pair belonging to the passed in CCDID."
204    fn remove_key(&self, ccdid: TlsCcdid);
205}
206
207/// One provisioned root CA certificate, as the index knows it (§14.4.4.3).
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub struct RootEntry {
210    /// The fabric that provisioned it, and the only one that can see it.
211    pub fabric_index: FabricIndex,
212    /// Its `TLSCAID`.
213    pub caid: TlsCaid,
214    /// §14.2.2.1's SHA-256 over the DER, which is what `LookupRootCertificate` searches and
215    /// what `ProvisionRootCertificate` refuses a duplicate of.
216    pub fingerprint: [u8; FINGERPRINT_LEN],
217}
218
219/// One provisioned client certificate (§14.4.4.4).
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
221pub struct ClientEntry {
222    /// The fabric that provisioned it.
223    pub fabric_index: FabricIndex,
224    /// Its `TLSCCDID`.
225    pub ccdid: TlsCcdid,
226    /// The certificate's fingerprint, or `None` while there is no certificate.
227    ///
228    /// §14.4.4.4: "A NULL value indicates that the TLS Client Certificate Signing Request (CSR)
229    /// Procedure has not yet completed" — a `ClientCSR` has allocated the id and the key pair,
230    /// and `ProvisionClientCertificate` has not run yet.
231    pub fingerprint: Option<[u8; FINGERPRINT_LEN]>,
232    /// How many intermediates the chain holds, `0..=`[`INTERMEDIATES_MAX`].
233    pub intermediates: u8,
234}
235
236/// One provisioned TLS endpoint (§14.5.4.2).
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub struct EndpointEntry {
239    /// The fabric that provisioned it.
240    pub fabric_index: FabricIndex,
241    /// Its `TLSEndpointID`.
242    pub endpoint_id: TlsEndpointId,
243    /// The TLS hostname, 4 to 253 octets.
244    pub hostname: heapless::Vec<u8, HOSTNAME_MAX>,
245    /// The TLS port, 1 to 65535.
246    pub port: u16,
247    /// The root CA to authenticate the server with.
248    pub caid: TlsCaid,
249    /// The client certificate to present, or `None` for "no client certificate is used with
250    /// this endpoint".
251    pub ccdid: Option<TlsCcdid>,
252    /// §14.5.4.2: "a reference count of the number of entities currently using this TLS
253    /// Endpoint", which blocks removal while it is non-zero.
254    pub reference_count: u8,
255}
256
257/// The three tables chapter 14's two clusters share.
258///
259/// `R`, `C` and `E` are totals across every fabric; the `max_*` figures are the per-fabric
260/// quotas the `Max…` attributes report, so that the first fabric to provision cannot leave a
261/// later one unable to. §14.3.3's minima — five roots, two client certificates, two endpoints
262/// per fabric — are what a certifiable node sizes these from.
263#[derive(Debug)]
264pub struct TlsTables<const R: usize, const C: usize, const E: usize> {
265    roots: RefCell<heapless::Vec<RootEntry, R>>,
266    clients: RefCell<heapless::Vec<ClientEntry, C>>,
267    endpoints: RefCell<heapless::Vec<EndpointEntry, E>>,
268    next_caid: Cell<u16>,
269    next_ccdid: Cell<u16>,
270    next_endpoint_id: Cell<u16>,
271    max_roots: u8,
272    max_clients: u8,
273    max_endpoints: u8,
274    time_known: Cell<bool>,
275}
276
277impl<const R: usize, const C: usize, const E: usize> TlsTables<R, C, E> {
278    /// Empty tables with the per-fabric quotas §14.3.3 sets as minima.
279    #[must_use]
280    pub const fn new() -> Self {
281        Self::with_quotas(
282            MIN_ROOTS_PER_FABRIC,
283            MIN_CLIENTS_PER_FABRIC,
284            MIN_ENDPOINTS_PER_FABRIC,
285        )
286    }
287
288    /// Empty tables with explicit per-fabric quotas, which §14.3.3 lets a device type raise.
289    #[must_use]
290    pub const fn with_quotas(max_roots: u8, max_clients: u8, max_endpoints: u8) -> Self {
291        Self {
292            roots: RefCell::new(heapless::Vec::new()),
293            clients: RefCell::new(heapless::Vec::new()),
294            endpoints: RefCell::new(heapless::Vec::new()),
295            next_caid: Cell::new(0),
296            next_ccdid: Cell::new(0),
297            next_endpoint_id: Cell::new(0),
298            max_roots,
299            max_clients,
300            max_endpoints,
301            time_known: Cell::new(false),
302        }
303    }
304
305    /// `MaxRootCertificates` (§14.4.5.1).
306    #[must_use]
307    pub const fn max_roots(&self) -> u8 {
308        self.max_roots
309    }
310
311    /// `MaxClientCertificates` (§14.4.5.3).
312    #[must_use]
313    pub const fn max_clients(&self) -> u8 {
314        self.max_clients
315    }
316
317    /// `MaxProvisioned` (§14.5.6.1).
318    #[must_use]
319    pub const fn max_endpoints(&self) -> u8 {
320        self.max_endpoints
321    }
322
323    /// Whether the Time Synchronization cluster has a `UTCTime`.
324    ///
325    /// §14.3.1: a node doing TLS "SHALL support the Time Synchronization cluster", because "Web
326    /// PKI and TLS policy performs time and date validation of all X.509 certificates". Both
327    /// `ProvisionRootCertificate` and `ProvisionEndpoint` refuse to run before it is set —
328    /// provisioning a certificate whose expiry cannot be judged is how a node ends up trusting
329    /// an expired CA for ever.
330    pub fn set_time_known(&self, known: bool) {
331        self.time_known.set(known);
332    }
333
334    /// Whether the clock is set.
335    #[must_use]
336    pub fn time_known(&self) -> bool {
337        self.time_known.get()
338    }
339
340    /// Every provisioned root certificate, for a device about to persist them.
341    #[must_use]
342    pub fn roots(&self) -> core::cell::Ref<'_, heapless::Vec<RootEntry, R>> {
343        self.roots.borrow()
344    }
345
346    /// Every provisioned client certificate.
347    #[must_use]
348    pub fn clients(&self) -> core::cell::Ref<'_, heapless::Vec<ClientEntry, C>> {
349        self.clients.borrow()
350    }
351
352    /// Every provisioned endpoint.
353    #[must_use]
354    pub fn endpoints(&self) -> core::cell::Ref<'_, heapless::Vec<EndpointEntry, E>> {
355        self.endpoints.borrow()
356    }
357
358    /// Sets an endpoint's `ReferenceCount` (§14.5.4.2).
359    ///
360    /// "The node SHALL recompute this field to reflect the correct value at runtime (e.g., when
361    /// restored from a persisted value after a reboot)" — so it is the application's number,
362    /// and the cluster's job is only to refuse to remove an endpoint that still has one.
363    pub fn set_reference_count(&self, endpoint_id: TlsEndpointId, count: u8) {
364        if let Some(entry) = self
365            .endpoints
366            .borrow_mut()
367            .iter_mut()
368            .find(|e| e.endpoint_id == endpoint_id)
369        {
370            entry.reference_count = count;
371        }
372    }
373
374    /// Forgets everything one fabric provisioned — what `RemoveFabric` must do.
375    ///
376    /// The endpoints go first: every interlock in chapter 14 is "a certificate an endpoint
377    /// still names", and removing the fabric removes both sides at once.
378    pub fn remove_fabric(&self, fabric: FabricIndex, hooks: &impl TlsCertificateHooks) {
379        self.endpoints
380            .borrow_mut()
381            .retain(|e| e.fabric_index != fabric);
382        for root in self
383            .roots
384            .borrow()
385            .iter()
386            .filter(|r| r.fabric_index == fabric)
387        {
388            hooks.clear(Slot::Root {
389                fabric_index: fabric,
390                caid: root.caid,
391            });
392        }
393        self.roots.borrow_mut().retain(|r| r.fabric_index != fabric);
394        for client in self
395            .clients
396            .borrow()
397            .iter()
398            .filter(|c| c.fabric_index == fabric)
399        {
400            clear_client(hooks, fabric, client.ccdid, client.intermediates);
401            hooks.remove_key(client.ccdid);
402        }
403        self.clients
404            .borrow_mut()
405            .retain(|c| c.fabric_index != fabric);
406    }
407
408    /// How many entries one fabric holds in each table.
409    fn count_roots(&self, fabric: FabricIndex) -> usize {
410        self.roots
411            .borrow()
412            .iter()
413            .filter(|r| r.fabric_index == fabric)
414            .count()
415    }
416
417    fn count_clients(&self, fabric: FabricIndex) -> usize {
418        self.clients
419            .borrow()
420            .iter()
421            .filter(|c| c.fabric_index == fabric)
422            .count()
423    }
424
425    fn count_endpoints(&self, fabric: FabricIndex) -> usize {
426        self.endpoints
427            .borrow()
428            .iter()
429            .filter(|e| e.fabric_index == fabric)
430            .count()
431    }
432
433    /// §14.4.4.1's id allocation: "start at 0 and monotonically increase by 1 with each new
434    /// allocation … A value incremented past 65534 SHOULD wrap to 0. The Node SHALL verify that
435    /// a new value does not match any other value for this type."
436    ///
437    /// The uniqueness check is across *every* fabric, not just the accessing one. Two fabrics
438    /// sharing an id would still be told apart by the fabric association, but §14.4.4.1 says a
439    /// new value must not match "any other value for this type", and an id that means two
440    /// things is the sort of thing that survives until the day something indexes by it alone.
441    fn allocate(next: &Cell<u16>, taken: impl Fn(u16) -> bool) -> Option<u16> {
442        let start = next.get();
443        let mut candidate = start;
444        for _ in 0..=u32::from(ID_MAX) {
445            if !taken(candidate) {
446                next.set(if candidate >= ID_MAX {
447                    0
448                } else {
449                    candidate.saturating_add(1)
450                });
451                return Some(candidate);
452            }
453            candidate = if candidate >= ID_MAX {
454                0
455            } else {
456                candidate.saturating_add(1)
457            };
458        }
459        None
460    }
461}
462
463impl<const R: usize, const C: usize, const E: usize> Default for TlsTables<R, C, E> {
464    fn default() -> Self {
465        Self::new()
466    }
467}
468
469/// Clears a client certificate and every intermediate behind it.
470fn clear_client(
471    hooks: &impl TlsCertificateHooks,
472    fabric_index: FabricIndex,
473    ccdid: TlsCcdid,
474    intermediates: u8,
475) {
476    hooks.clear(Slot::Client {
477        fabric_index,
478        ccdid,
479    });
480    for index in 0..intermediates {
481        hooks.clear(Slot::Intermediate {
482            fabric_index,
483            ccdid,
484            index,
485        });
486    }
487}
488
489/// Whether a fabric's entries belong in this read (§7.19.1.8.2).
490fn visible(ctx: &crate::im::InteractionContext<'_>, index: FabricIndex) -> bool {
491    !ctx.fabric_filtered || ctx.fabric_index == Some(index)
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497
498    type Tables = TlsTables<4, 4, 4>;
499
500    /// §14.4.4.1: "This value SHOULD start at 0 and monotonically increase by 1 with each new
501    /// allocation … A value incremented past 65534 SHOULD wrap to 0. The Node SHALL verify that
502    /// a new value does not match any other value for this type."
503    ///
504    /// The wrap needs a counter at 65534 and an id already taken there — neither reachable by
505    /// provisioning four certificates, which is what the integration tests can do.
506    #[test]
507    fn ids_start_at_zero_and_increase_by_one() {
508        let tables = Tables::new();
509        let none = |_: u16| false;
510        assert_eq!(Tables::allocate(&tables.next_caid, none), Some(0));
511        assert_eq!(Tables::allocate(&tables.next_caid, none), Some(1));
512        assert_eq!(Tables::allocate(&tables.next_caid, none), Some(2));
513    }
514
515    #[test]
516    fn an_id_past_65534_wraps_to_zero() {
517        let tables = Tables::new();
518        tables.next_caid.set(ID_MAX);
519        let none = |_: u16| false;
520        assert_eq!(Tables::allocate(&tables.next_caid, none), Some(ID_MAX));
521        assert_eq!(
522            Tables::allocate(&tables.next_caid, none),
523            Some(0),
524            "65535 is the null value, not an id"
525        );
526    }
527
528    #[test]
529    fn a_taken_id_is_skipped() {
530        // "The Node SHALL verify that a new value does not match any other value for this type.
531        // If such a match is found, the value SHALL be changed until a unique value is found."
532        let tables = Tables::new();
533        let taken = |id: u16| matches!(id, 0 | 1 | 3);
534        assert_eq!(Tables::allocate(&tables.next_caid, taken), Some(2));
535        assert_eq!(Tables::allocate(&tables.next_caid, taken), Some(4));
536    }
537
538    #[test]
539    fn a_full_id_space_allocates_nothing() {
540        // Rather than looping for ever, or handing out an id that is already in use.
541        let tables = Tables::new();
542        assert_eq!(Tables::allocate(&tables.next_caid, |_| true), None);
543    }
544}