Skip to main content

matter_controller/
ca.rs

1//! The fabric's certificate authority.
2//!
3//! A Matter fabric is rooted in a CA: its root certificate (RCAC), usually an
4//! intermediate (ICAC), and the node operational certificates (NOCs) it signs
5//! for every node, the controller included. Where that CA lives is the
6//! deployer's choice, so it is a trait:
7//!
8//! - [`FileCa`] keeps the chain and the ICAC key in a directory. It is what a
9//!   standalone controller uses, and is its own root of trust.
10//! - A platform CA (an HTTP service, an HSM) keeps its keys elsewhere and
11//!   issues NOCs on request. Several controllers on one fabric then share the
12//!   root, and the CA hands out node ids so they never collide.
13//!
14//! Until rs-matter's `Commissioner` can await an issuer, commissioning signs
15//! NOCs in-process, so it needs [`CertificateAuthority::signing_key`]. A CA
16//! that cannot give one can still issue the controller's own certificate; see
17//! `docs/design.md`, "Upstream work".
18
19use std::future::Future;
20use std::path::{Path, PathBuf};
21
22use rs_matter::cert::gen::VALID_FOREVER;
23use rs_matter::cert::MAX_CERT_TLV_AND_ASN1_LEN;
24use rs_matter::crypto::{CanonPkcSecretKeyRef, Crypto};
25use rs_matter::onboard::cac::{IcacGenerator, RcacGenerator};
26use rs_matter::onboard::noc::NocGenerator;
27use serde::{Deserialize, Serialize};
28
29use crate::fsutil::{read_json, write_private};
30use crate::Error;
31
32/// The length of a P-256 secret key in its canonical form.
33pub const SECRET_KEY_LEN: usize = 32;
34
35/// Issues the fabric's operational certificates.
36pub trait CertificateAuthority {
37    /// The fabric id.
38    fn fabric_id(&self) -> u64;
39
40    /// The root certificate (RCAC), Matter TLV encoding.
41    fn root_cert(&self) -> &[u8];
42
43    /// The intermediate certificate (ICAC) NOCs are signed with, Matter TLV
44    /// encoding, or `None` when the root signs them directly.
45    fn intermediate_cert(&self) -> Option<&[u8]>;
46
47    /// Allocate a node id that no other node of the fabric has.
48    fn allocate_node_id(&self) -> impl Future<Output = Result<u64, Error>>;
49
50    /// Issue a NOC for the public key in `csr` (DER PKCS#10) and `node_id`,
51    /// with up to three CASE Authenticated Tags.
52    fn issue_noc<C: Crypto>(
53        &self,
54        crypto: C,
55        csr: &[u8],
56        node_id: u64,
57        cats: &[u32],
58    ) -> impl Future<Output = Result<Vec<u8>, Error>>;
59
60    /// The key NOCs are signed with, if this process holds it.
61    fn signing_key(&self) -> Option<&[u8; SECRET_KEY_LEN]>;
62
63    /// The fabric's identity protection key (IPK) epoch key. Every
64    /// controller and node of the fabric has the same one; CASE needs it.
65    fn ipk(&self) -> &[u8; IPK_LEN];
66
67    /// A CASE Authenticated Tag every controller of the fabric carries in
68    /// its certificate, if the fabric uses one.
69    fn admin_cat(&self) -> Option<u32> {
70        None
71    }
72}
73
74/// The length of an IPK epoch key.
75pub const IPK_LEN: usize = 16;
76
77#[derive(Serialize, Deserialize)]
78struct FileCaState {
79    fabric_id: u64,
80    #[serde(with = "hex::serde")]
81    root_cert: Vec<u8>,
82    #[serde(with = "hex::serde")]
83    root_key: Vec<u8>,
84    #[serde(with = "hex::serde")]
85    intermediate_cert: Vec<u8>,
86    #[serde(with = "hex::serde")]
87    intermediate_key: Vec<u8>,
88    #[serde(with = "hex::serde")]
89    ipk: Vec<u8>,
90    next_node_id: u64,
91}
92
93/// A CA kept in one file of the state directory, readable by its owner only.
94///
95/// It holds the root key too, so it can mint a new intermediate; a deployment
96/// that wants the root offline uses a CA of its own instead.
97pub struct FileCa {
98    path: PathBuf,
99    state: std::cell::RefCell<FileCaState>,
100    root_cert: Vec<u8>,
101    intermediate_cert: Vec<u8>,
102    intermediate_key: [u8; SECRET_KEY_LEN],
103    ipk: [u8; IPK_LEN],
104}
105
106impl FileCa {
107    /// The first node id handed out; the controller takes one before any
108    /// device does.
109    pub const FIRST_NODE_ID: u64 = 1;
110
111    /// Open the CA in `path`, creating a new fabric `fabric_id` (random if
112    /// `None`) with a new root and intermediate when there is none yet.
113    pub fn open_or_create<C: Crypto>(
114        path: &Path,
115        fabric_id: Option<u64>,
116        crypto: C,
117    ) -> Result<Self, Error> {
118        let state = match read_json::<FileCaState>(path)? {
119            Some(state) => state,
120            None => {
121                let state = Self::create(fabric_id, &crypto)?;
122                write_private(path, &serde_json::to_vec_pretty(&state)?)?;
123                log::info!(
124                    "created fabric {:016X} in {}",
125                    state.fabric_id,
126                    path.display()
127                );
128                state
129            }
130        };
131
132        let intermediate_key = state
133            .intermediate_key
134            .as_slice()
135            .try_into()
136            .map_err(|_| Error::Store(format!("{}: bad intermediate key", path.display())))?;
137
138        let ipk = state
139            .ipk
140            .as_slice()
141            .try_into()
142            .map_err(|_| Error::Store(format!("{}: bad IPK", path.display())))?;
143
144        Ok(Self {
145            ipk,
146            path: path.to_path_buf(),
147            root_cert: state.root_cert.clone(),
148            intermediate_cert: state.intermediate_cert.clone(),
149            intermediate_key,
150            state: std::cell::RefCell::new(state),
151        })
152    }
153
154    fn create<C: Crypto>(fabric_id: Option<u64>, crypto: C) -> Result<FileCaState, Error> {
155        // Operational fabric ids are any value but 0.
156        let fabric_id = match fabric_id {
157            Some(id) => id,
158            None => loop {
159                let id = rand::random::<u64>();
160                if id != 0 {
161                    break id;
162                }
163            },
164        };
165
166        let mut rcac_buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
167        let mut rcac_gen = RcacGenerator::new(&mut rcac_buf);
168        let (root_key, root_cert) = rcac_gen.generate(&crypto, fabric_id, VALID_FOREVER)?;
169        let root_cert = root_cert.to_vec();
170
171        let mut icac_buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
172        let mut icac_gen = IcacGenerator::new(&mut icac_buf);
173        let (icac_key, icac) =
174            icac_gen.generate(&crypto, root_key.reference(), &root_cert, VALID_FOREVER)?;
175
176        Ok(FileCaState {
177            fabric_id,
178            root_key: root_key.access().to_vec(),
179            intermediate_cert: icac.to_vec(),
180            intermediate_key: icac_key.access().to_vec(),
181            ipk: rand::random::<[u8; IPK_LEN]>().to_vec(),
182            root_cert,
183            next_node_id: Self::FIRST_NODE_ID,
184        })
185    }
186
187    fn save(&self) -> Result<(), Error> {
188        let state = self.state.borrow();
189        write_private(&self.path, &serde_json::to_vec_pretty(&*state)?)
190    }
191}
192
193impl CertificateAuthority for FileCa {
194    fn fabric_id(&self) -> u64 {
195        self.state.borrow().fabric_id
196    }
197
198    fn root_cert(&self) -> &[u8] {
199        &self.root_cert
200    }
201
202    fn intermediate_cert(&self) -> Option<&[u8]> {
203        Some(&self.intermediate_cert)
204    }
205
206    async fn allocate_node_id(&self) -> Result<u64, Error> {
207        let id = {
208            let mut state = self.state.borrow_mut();
209            let id = state.next_node_id;
210            // Operational node ids stop below the reserved ranges.
211            if id >= 0xFFFF_FFEF_FFFF_FFFF {
212                return Err(Error::Exhausted("node ids"));
213            }
214            state.next_node_id += 1;
215            id
216        };
217        self.save()?;
218        Ok(id)
219    }
220
221    async fn issue_noc<C: Crypto>(
222        &self,
223        crypto: C,
224        csr: &[u8],
225        node_id: u64,
226        cats: &[u32],
227    ) -> Result<Vec<u8>, Error> {
228        let mut buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
229        let mut noc_gen = NocGenerator::create(
230            CanonPkcSecretKeyRef::new(&self.intermediate_key),
231            &self.root_cert,
232            &self.intermediate_cert,
233            &mut buf,
234        )?;
235        Ok(noc_gen
236            .generate(&crypto, csr, node_id, cats, VALID_FOREVER)?
237            .to_vec())
238    }
239
240    fn signing_key(&self) -> Option<&[u8; SECRET_KEY_LEN]> {
241        Some(&self.intermediate_key)
242    }
243
244    fn ipk(&self) -> &[u8; IPK_LEN] {
245        &self.ipk
246    }
247}
248
249/// A range of node ids a root CA handed this controller.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251pub struct NodeIdRange {
252    /// The next id to hand out.
253    pub next: u64,
254    /// The last id of the range.
255    pub last: u64,
256}
257
258/// What a root CA returns for an intermediate's CSR.
259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260pub struct Issued {
261    /// The fabric id.
262    pub fabric_id: u64,
263    /// The root certificate, Matter TLV.
264    #[serde(with = "hex::serde")]
265    pub root_cert: Vec<u8>,
266    /// The intermediate certificate issued for our key, Matter TLV.
267    #[serde(with = "hex::serde")]
268    pub intermediate_cert: Vec<u8>,
269    /// The fabric's IPK epoch key.
270    #[serde(with = "hex::serde")]
271    pub ipk: Vec<u8>,
272    /// The node ids this controller may hand out.
273    pub node_ids: NodeIdRange,
274    /// A CASE Authenticated Tag every controller of the fabric carries, to
275    /// put in the controller's own certificate.
276    #[serde(default)]
277    pub admin_cat: Option<u32>,
278}
279
280#[derive(Serialize, Deserialize)]
281struct IntermediateState {
282    #[serde(flatten)]
283    issued: Issued,
284    #[serde(with = "hex::serde")]
285    intermediate_key: Vec<u8>,
286}
287
288#[derive(Serialize, Deserialize)]
289struct PendingKey {
290    #[serde(with = "hex::serde")]
291    key: Vec<u8>,
292    #[serde(with = "hex::serde")]
293    csr: Vec<u8>,
294}
295
296/// An intermediate CA whose certificate a root CA elsewhere issued (a
297/// platform's, holding one fabric's root for several controllers), for a key
298/// made here that never leaves this controller.
299///
300/// 1. [`IntermediateCa::csr`] makes the key (once) and returns its CSR.
301/// 2. The root CA issues the intermediate certificate and a range of node ids.
302/// 3. [`IntermediateCa::install`] stores them with the key; from then on the
303///    controller signs its own and its devices' certificates, and every
304///    controller of the fabric reaches every device of it.
305pub struct IntermediateCa {
306    path: PathBuf,
307    state: std::cell::RefCell<IntermediateState>,
308    root_cert: Vec<u8>,
309    intermediate_cert: Vec<u8>,
310    intermediate_key: [u8; SECRET_KEY_LEN],
311    ipk: [u8; IPK_LEN],
312    fabric_id: u64,
313    admin_cat: Option<u32>,
314}
315
316impl IntermediateCa {
317    fn pending_path(path: &Path) -> PathBuf {
318        path.with_extension("key.json")
319    }
320
321    /// The CSR (DER PKCS#10) for this controller's intermediate key, made on
322    /// the first call and the same on later ones until [`Self::install`].
323    pub fn csr<C: Crypto>(path: &Path, crypto: C) -> Result<Vec<u8>, Error> {
324        use rs_matter::crypto::{CanonPkcSecretKey, SecretKey as _, SigningSecretKey as _};
325
326        let pending_path = Self::pending_path(path);
327        if let Some(p) = read_json::<PendingKey>(&pending_path)? {
328            return Ok(p.csr);
329        }
330        let key = crypto.generate_secret_key()?;
331        let mut buf = [0u8; 256];
332        let csr = key.csr(&mut buf)?.to_vec();
333        let mut canon = CanonPkcSecretKey::new();
334        key.write_canon(&mut canon)?;
335        let pending = PendingKey {
336            key: canon.access().to_vec(),
337            csr: csr.clone(),
338        };
339        write_private(&pending_path, &serde_json::to_vec_pretty(&pending)?)?;
340        Ok(csr)
341    }
342
343    /// Store what the root CA issued for the CSR from [`Self::csr`].
344    pub fn install(path: &Path, issued: Issued) -> Result<(), Error> {
345        let pending_path = Self::pending_path(path);
346        let pending = read_json::<PendingKey>(&pending_path)?.ok_or_else(|| {
347            Error::Invalid("no key is waiting for a certificate: ask for a CSR first".into())
348        })?;
349        if issued.ipk.len() != IPK_LEN || issued.fabric_id == 0 {
350            return Err(Error::Invalid(
351                "the issued fabric credentials are malformed".into(),
352            ));
353        }
354        if issued.node_ids.next == 0 || issued.node_ids.next > issued.node_ids.last {
355            return Err(Error::Invalid("the node id range is empty".into()));
356        }
357        let state = IntermediateState {
358            issued,
359            intermediate_key: pending.key,
360        };
361        write_private(path, &serde_json::to_vec_pretty(&state)?)?;
362        std::fs::remove_file(&pending_path)?;
363        Ok(())
364    }
365
366    /// Whether credentials are installed at `path`.
367    pub fn installed(path: &Path) -> bool {
368        path.exists()
369    }
370
371    /// Open the installed intermediate CA at `path`.
372    pub fn open(path: &Path) -> Result<Self, Error> {
373        let state = read_json::<IntermediateState>(path)?.ok_or_else(|| {
374            Error::Invalid(format!(
375                "{}: no fabric credentials installed",
376                path.display()
377            ))
378        })?;
379        let bad = |what: &str| Error::Store(format!("{}: bad {what}", path.display()));
380        Ok(Self {
381            path: path.to_path_buf(),
382            root_cert: state.issued.root_cert.clone(),
383            intermediate_cert: state.issued.intermediate_cert.clone(),
384            intermediate_key: state
385                .intermediate_key
386                .as_slice()
387                .try_into()
388                .map_err(|_| bad("key"))?,
389            ipk: state
390                .issued
391                .ipk
392                .as_slice()
393                .try_into()
394                .map_err(|_| bad("IPK"))?,
395            fabric_id: state.issued.fabric_id,
396            admin_cat: state.issued.admin_cat,
397            state: std::cell::RefCell::new(state),
398        })
399    }
400
401    /// Node ids left in the range.
402    pub fn node_ids_left(&self) -> u64 {
403        let r = self.state.borrow().issued.node_ids;
404        (r.last + 1).saturating_sub(r.next)
405    }
406
407    /// Take a further range from the root CA.
408    pub fn extend_node_ids(&self, range: NodeIdRange) -> Result<(), Error> {
409        if range.next == 0 || range.next > range.last {
410            return Err(Error::Invalid("the node id range is empty".into()));
411        }
412        self.state.borrow_mut().issued.node_ids = range;
413        let state = self.state.borrow();
414        write_private(&self.path, &serde_json::to_vec_pretty(&*state)?)
415    }
416}
417
418impl CertificateAuthority for IntermediateCa {
419    fn fabric_id(&self) -> u64 {
420        self.fabric_id
421    }
422
423    fn root_cert(&self) -> &[u8] {
424        &self.root_cert
425    }
426
427    fn intermediate_cert(&self) -> Option<&[u8]> {
428        Some(&self.intermediate_cert)
429    }
430
431    async fn allocate_node_id(&self) -> Result<u64, Error> {
432        let id = {
433            let mut state = self.state.borrow_mut();
434            let range = &mut state.issued.node_ids;
435            if range.next > range.last {
436                return Err(Error::Exhausted(
437                    "node ids: the root CA has to issue a further range",
438                ));
439            }
440            let id = range.next;
441            range.next += 1;
442            id
443        };
444        let state = self.state.borrow();
445        write_private(&self.path, &serde_json::to_vec_pretty(&*state)?)?;
446        Ok(id)
447    }
448
449    async fn issue_noc<C: Crypto>(
450        &self,
451        crypto: C,
452        csr: &[u8],
453        node_id: u64,
454        cats: &[u32],
455    ) -> Result<Vec<u8>, Error> {
456        let mut buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
457        let mut noc_gen = NocGenerator::create(
458            CanonPkcSecretKeyRef::new(&self.intermediate_key),
459            &self.root_cert,
460            &self.intermediate_cert,
461            &mut buf,
462        )?;
463        Ok(noc_gen
464            .generate(&crypto, csr, node_id, cats, VALID_FOREVER)?
465            .to_vec())
466    }
467
468    fn signing_key(&self) -> Option<&[u8; SECRET_KEY_LEN]> {
469        Some(&self.intermediate_key)
470    }
471
472    fn ipk(&self) -> &[u8; IPK_LEN] {
473        &self.ipk
474    }
475
476    fn admin_cat(&self) -> Option<u32> {
477        self.admin_cat
478    }
479}
480
481/// [`IntermediateCa::csr`] for the controller whose state is in
482/// `state_dir` (where [`crate::CaChoice::Intermediate`] looks), with this
483/// crate's crypto.
484pub fn intermediate_csr(state_dir: &Path) -> Result<Vec<u8>, Error> {
485    let seed: [u8; SECRET_KEY_LEN] = rand::random();
486    let crypto = rs_matter::crypto::default_crypto(rand::rng(), CanonPkcSecretKeyRef::new(&seed));
487    IntermediateCa::csr(&intermediate_path(state_dir), &crypto)
488}
489
490/// Where a controller keeps its intermediate CA.
491pub fn intermediate_path(state_dir: &Path) -> PathBuf {
492    state_dir.join("intermediate.json")
493}
494
495/// Install (or replace) what a root CA issued for the controller in
496/// `state_dir`. With no new key waiting (no CSR since the last install), only
497/// a further node id range is taken.
498pub fn install_intermediate(state_dir: &Path, issued: Issued) -> Result<(), Error> {
499    let path = intermediate_path(state_dir);
500    if IntermediateCa::pending_path(&path).exists() || !path.exists() {
501        return IntermediateCa::install(&path, issued);
502    }
503    let ca = IntermediateCa::open(&path)?;
504    if ca.fabric_id() != issued.fabric_id {
505        return Err(Error::Invalid(
506            "another fabric's credentials: ask for a new CSR first".into(),
507        ));
508    }
509    ca.extend_node_ids(issued.node_ids)
510}
511
512/// The CA a controller runs with.
513pub enum AnyCa {
514    /// A standalone fabric.
515    File(FileCa),
516    /// An intermediate under a root CA elsewhere.
517    Intermediate(IntermediateCa),
518}
519
520impl CertificateAuthority for AnyCa {
521    fn fabric_id(&self) -> u64 {
522        match self {
523            AnyCa::File(c) => c.fabric_id(),
524            AnyCa::Intermediate(c) => c.fabric_id(),
525        }
526    }
527    fn root_cert(&self) -> &[u8] {
528        match self {
529            AnyCa::File(c) => c.root_cert(),
530            AnyCa::Intermediate(c) => c.root_cert(),
531        }
532    }
533    fn intermediate_cert(&self) -> Option<&[u8]> {
534        match self {
535            AnyCa::File(c) => c.intermediate_cert(),
536            AnyCa::Intermediate(c) => c.intermediate_cert(),
537        }
538    }
539    async fn allocate_node_id(&self) -> Result<u64, Error> {
540        match self {
541            AnyCa::File(c) => c.allocate_node_id().await,
542            AnyCa::Intermediate(c) => c.allocate_node_id().await,
543        }
544    }
545    async fn issue_noc<C: Crypto>(
546        &self,
547        crypto: C,
548        csr: &[u8],
549        node_id: u64,
550        cats: &[u32],
551    ) -> Result<Vec<u8>, Error> {
552        match self {
553            AnyCa::File(c) => c.issue_noc(crypto, csr, node_id, cats).await,
554            AnyCa::Intermediate(c) => c.issue_noc(crypto, csr, node_id, cats).await,
555        }
556    }
557    fn signing_key(&self) -> Option<&[u8; SECRET_KEY_LEN]> {
558        match self {
559            AnyCa::File(c) => c.signing_key(),
560            AnyCa::Intermediate(c) => c.signing_key(),
561        }
562    }
563    fn ipk(&self) -> &[u8; IPK_LEN] {
564        match self {
565            AnyCa::File(c) => c.ipk(),
566            AnyCa::Intermediate(c) => c.ipk(),
567        }
568    }
569    fn admin_cat(&self) -> Option<u32> {
570        match self {
571            AnyCa::File(c) => c.admin_cat(),
572            AnyCa::Intermediate(c) => c.admin_cat(),
573        }
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    fn crypto() -> impl Crypto {
582        static KEY: [u8; 32] = [7; 32];
583        rs_matter::crypto::default_crypto(rand::rng(), CanonPkcSecretKeyRef::new(&KEY))
584    }
585
586    /// A root CA elsewhere: a FileCa issuing an intermediate for a CSR.
587    #[test]
588    fn an_intermediate_issued_for_a_csr_signs_nocs() {
589        let crypto = crypto();
590        let dir = tempfile::tempdir().unwrap();
591        let root =
592            FileCa::open_or_create(&dir.path().join("root.json"), Some(0xAB), &crypto).unwrap();
593
594        let path = dir.path().join("intermediate.json");
595        let csr = IntermediateCa::csr(&path, &crypto).unwrap();
596        assert_eq!(
597            IntermediateCa::csr(&path, &crypto).unwrap(),
598            csr,
599            "the same key until installed"
600        );
601
602        // The root signs the intermediate's key. (A platform's CA issues an
603        // ICAC; for the test, a NOC-shaped certificate under the root's
604        // intermediate is enough to exercise install and signing.)
605        let state: FileCaState = read_json(&dir.path().join("root.json")).unwrap().unwrap();
606        let issued = Issued {
607            fabric_id: 0xAB,
608            root_cert: state.root_cert.clone(),
609            intermediate_cert: state.intermediate_cert.clone(),
610            ipk: state.ipk.clone(),
611            node_ids: NodeIdRange {
612                next: 100,
613                last: 101,
614            },
615            admin_cat: Some(0xFFFE_0001),
616        };
617        let _ = root;
618        // Install with the root's own intermediate key standing in.
619        write_private(
620            &IntermediateCa::pending_path(&path),
621            &serde_json::to_vec(&PendingKey {
622                key: state.intermediate_key.clone(),
623                csr,
624            })
625            .unwrap(),
626        )
627        .unwrap();
628        IntermediateCa::install(&path, issued).unwrap();
629
630        let ca = IntermediateCa::open(&path).unwrap();
631        assert_eq!(ca.fabric_id(), 0xAB);
632        assert_eq!(ca.admin_cat(), Some(0xFFFE_0001));
633        let block_on = |f| {
634            tokio::runtime::Builder::new_current_thread()
635                .build()
636                .unwrap()
637                .block_on(f)
638        };
639        assert_eq!(block_on(ca.allocate_node_id()).unwrap(), 100);
640        assert_eq!(block_on(ca.allocate_node_id()).unwrap(), 101);
641        assert!(
642            block_on(ca.allocate_node_id()).is_err(),
643            "the range is used up"
644        );
645        ca.extend_node_ids(NodeIdRange {
646            next: 200,
647            last: 300,
648        })
649        .unwrap();
650        assert_eq!(IntermediateCa::open(&path).unwrap().node_ids_left(), 101);
651
652        // It signs a NOC for a device's CSR.
653        use rs_matter::crypto::SigningSecretKey as _;
654        let device_key = crypto.generate_secret_key().unwrap();
655        let mut buf = [0u8; 256];
656        let device_csr = device_key.csr(&mut buf).unwrap();
657        let noc = tokio::runtime::Builder::new_current_thread()
658            .build()
659            .unwrap()
660            .block_on(ca.issue_noc(&crypto, device_csr, 200, &[]))
661            .unwrap();
662        assert!(!noc.is_empty());
663    }
664}