Skip to main content

matter_controller/
x509.rs

1//! X.509 DER certificates in the Matter certificate profile, as a CA built on
2//! common PKI tooling issues them, converted to the Matter TLV encoding that
3//! Matter nodes exchange (Matter Core spec, "Certificate Encoding").
4//!
5//! A Matter TLV certificate carries the same fields as the X.509 one and the
6//! same signature, which is over the X.509 encoding: a node verifying it
7//! rebuilds the DER from the TLV. So every conversion is checked by rebuilding
8//! the DER with rs-matter and comparing it with the input byte for byte. A
9//! certificate outside the profile (another string type, an extension
10//! encoded otherwise) is refused here rather than installed with a signature
11//! no node would accept.
12
13use der::{Decode, Encode, Tagged as _};
14use rs_matter::cert::CertRef;
15use rs_matter::tlv::{TLVElement, TLVTag, TLVWrite};
16use rs_matter::utils::storage::WriteBuf;
17use x509_cert::ext::pkix::{
18    AuthorityKeyIdentifier, BasicConstraints, ExtendedKeyUsage, KeyUsage, SubjectKeyIdentifier,
19};
20use x509_cert::name::Name;
21use x509_cert::time::Time;
22use x509_cert::Certificate;
23
24use crate::Error;
25
26/// Seconds from the Unix epoch to the Matter epoch (2000-01-01T00:00:00Z).
27const MATTER_EPOCH: u64 = 946_684_800;
28/// `99991231235959Z`: "no well-defined expiration date", 0 in Matter TLV.
29const NO_EXPIRY: u64 = 253_402_300_799;
30
31fn invalid(what: impl std::fmt::Display) -> Error {
32    Error::Invalid(format!("certificate: {what}"))
33}
34
35fn tlv(e: rs_matter::error::Error) -> Error {
36    invalid(format!("encoding: {e:?}"))
37}
38
39/// Convert an X.509 DER certificate in the Matter profile (an RCAC, ICAC or
40/// NOC) to Matter TLV.
41pub fn to_matter_tlv(der: &[u8]) -> Result<Vec<u8>, Error> {
42    let cert = Certificate::from_der(der).map_err(|e| invalid(format!("not X.509 DER: {e}")))?;
43    let tbs = cert.tbs_certificate();
44
45    const ECDSA_WITH_SHA256: &str = "1.2.840.10045.4.3.2";
46    const EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";
47    const PRIME256V1: &str = "1.2.840.10045.3.1.7";
48    if cert.signature_algorithm().oid.to_string() != ECDSA_WITH_SHA256 {
49        return Err(invalid("not signed with ECDSA with SHA-256"));
50    }
51    let spki = tbs.subject_public_key_info();
52    let curve = spki
53        .algorithm
54        .parameters
55        .as_ref()
56        .and_then(|p| p.decode_as::<der::asn1::ObjectIdentifier>().ok())
57        .map(|o| o.to_string());
58    if spki.algorithm.oid.to_string() != EC_PUBLIC_KEY || curve.as_deref() != Some(PRIME256V1) {
59        return Err(invalid("not a P-256 public key"));
60    }
61    let public_key = spki
62        .subject_public_key
63        .as_bytes()
64        .filter(|k| k.len() == 65)
65        .ok_or_else(|| invalid("not an uncompressed P-256 public key"))?;
66
67    let mut buf = vec![0u8; 1024];
68    let mut w = WriteBuf::new(&mut buf);
69    let ctx = TLVTag::Context;
70    w.start_struct(&TLVTag::Anonymous).map_err(tlv)?;
71    w.str(&ctx(1), tbs.serial_number().as_bytes())
72        .map_err(tlv)?;
73    w.u8(&ctx(2), 1).map_err(tlv)?; // ecdsa-with-SHA256
74    name(&mut w, 3, tbs.issuer())?;
75    w.u32(&ctx(4), matter_time(&tbs.validity().not_before)?)
76        .map_err(tlv)?;
77    w.u32(&ctx(5), matter_time(&tbs.validity().not_after)?)
78        .map_err(tlv)?;
79    name(&mut w, 6, tbs.subject())?;
80    w.u8(&ctx(7), 1).map_err(tlv)?; // EC public key
81    w.u8(&ctx(8), 1).map_err(tlv)?; // prime256v1
82    w.str(&ctx(9), public_key).map_err(tlv)?;
83
84    w.start_list(&ctx(10)).map_err(tlv)?;
85    for ext in tbs.extensions().into_iter().flatten() {
86        let value = ext.extn_value.as_bytes();
87        match ext.extn_id.to_string().as_str() {
88            "2.5.29.19" => {
89                let bc = BasicConstraints::from_der(value).map_err(invalid)?;
90                w.start_struct(&ctx(1)).map_err(tlv)?;
91                w.bool(&ctx(1), bc.ca).map_err(tlv)?;
92                if let Some(len) = bc.path_len_constraint {
93                    w.u8(&ctx(2), len).map_err(tlv)?;
94                }
95                w.end_container().map_err(tlv)?;
96            }
97            "2.5.29.15" => {
98                // Matter's key usage bits are X.509's, in the same order.
99                let ku = KeyUsage::from_der(value).map_err(invalid)?;
100                w.u16(&ctx(2), ku.0.bits()).map_err(tlv)?;
101            }
102            "2.5.29.37" => {
103                let eku = ExtendedKeyUsage::from_der(value).map_err(invalid)?;
104                w.start_array(&ctx(3)).map_err(tlv)?;
105                for oid in eku.0 {
106                    let id = match oid.to_string().as_str() {
107                        "1.3.6.1.5.5.7.3.1" => 1, // serverAuth
108                        "1.3.6.1.5.5.7.3.2" => 2, // clientAuth
109                        "1.3.6.1.5.5.7.3.3" => 3, // codeSigning
110                        "1.3.6.1.5.5.7.3.4" => 4, // emailProtection
111                        "1.3.6.1.5.5.7.3.8" => 5, // timeStamping
112                        "1.3.6.1.5.5.7.3.9" => 6, // OCSPSigning
113                        other => return Err(invalid(format!("extended key usage {other}"))),
114                    };
115                    w.u8(&TLVTag::Anonymous, id).map_err(tlv)?;
116                }
117                w.end_container().map_err(tlv)?;
118            }
119            "2.5.29.14" => {
120                let skid = SubjectKeyIdentifier::from_der(value).map_err(invalid)?;
121                w.str(&ctx(4), skid.0.as_bytes()).map_err(tlv)?;
122            }
123            "2.5.29.35" => {
124                let akid = AuthorityKeyIdentifier::from_der(value).map_err(invalid)?;
125                let id = akid
126                    .key_identifier
127                    .ok_or_else(|| invalid("authority key identifier without a key identifier"))?;
128                w.str(&ctx(5), id.as_bytes()).map_err(tlv)?;
129            }
130            _ => {
131                let whole = ext.to_der().map_err(invalid)?;
132                w.str(&ctx(6), &whole).map_err(tlv)?;
133            }
134        }
135    }
136    w.end_container().map_err(tlv)?;
137
138    let signature = cert
139        .signature()
140        .as_bytes()
141        .ok_or_else(|| invalid("signature"))?;
142    let signature = p256::ecdsa::Signature::from_der(signature)
143        .map_err(|_| invalid("not an ECDSA P-256 signature"))?;
144    w.str(&ctx(11), &signature.to_bytes()).map_err(tlv)?;
145    w.end_container().map_err(tlv)?;
146    let len = w.get_tail();
147    buf.truncate(len);
148
149    // A node rebuilds the signed DER from the TLV: it must be the DER that
150    // was signed.
151    let signed = tbs.to_der().map_err(invalid)?;
152    let mut rebuilt = vec![0u8; signed.len() + 64];
153    let n = CertRef::new(TLVElement::new(&buf))
154        .as_asn1(&mut rebuilt)
155        .map_err(|e| invalid(format!("rebuilding the DER: {e:?}")))?;
156    if rebuilt[..n] != signed[..] {
157        return Err(invalid(
158            "not in the Matter certificate profile: as Matter TLV it would not verify",
159        ));
160    }
161    Ok(buf)
162}
163
164fn matter_time(t: &Time) -> Result<u32, Error> {
165    let unix = t.to_unix_duration().as_secs();
166    if unix == NO_EXPIRY {
167        return Ok(0);
168    }
169    unix.checked_sub(MATTER_EPOCH)
170        .and_then(|s| u32::try_from(s).ok())
171        .ok_or_else(|| invalid("a validity date outside 2000 to 2135"))
172}
173
174fn name(w: &mut WriteBuf<'_>, tag: u8, name: &Name) -> Result<(), Error> {
175    w.start_list(&TLVTag::Context(tag)).map_err(tlv)?;
176    for atv in name.iter() {
177        let value = &atv.value;
178        let text = || {
179            std::str::from_utf8(value.value())
180                .map_err(|_| invalid("a name attribute that is not text"))
181        };
182        let hex = |len: usize| -> Result<u64, Error> {
183            let t = text()?;
184            if t.len() != len || value.tag() != der::Tag::Utf8String {
185                return Err(invalid(format!(
186                    "a Matter id that is not {len} hex digits in a UTF8String"
187                )));
188            }
189            u64::from_str_radix(t, 16).map_err(|_| invalid("a Matter id that is not hex"))
190        };
191        let ctx = TLVTag::Context;
192        match atv.oid.to_string().as_str() {
193            "1.3.6.1.4.1.37244.1.1" => w.u64(&ctx(17), hex(16)?).map_err(tlv)?,
194            "1.3.6.1.4.1.37244.1.2" => w.u64(&ctx(18), hex(16)?).map_err(tlv)?,
195            "1.3.6.1.4.1.37244.1.3" => w.u64(&ctx(19), hex(16)?).map_err(tlv)?,
196            "1.3.6.1.4.1.37244.1.4" => w.u64(&ctx(20), hex(16)?).map_err(tlv)?,
197            "1.3.6.1.4.1.37244.1.5" => w.u64(&ctx(21), hex(16)?).map_err(tlv)?,
198            "1.3.6.1.4.1.37244.1.6" => w.u32(&ctx(22), hex(8)? as u32).map_err(tlv)?,
199            oid => {
200                let base = match oid {
201                    "2.5.4.3" => 1,                     // commonName
202                    "2.5.4.4" => 2,                     // surname
203                    "2.5.4.5" => 3,                     // serialNumber
204                    "2.5.4.6" => 4,                     // countryName
205                    "2.5.4.7" => 5,                     // localityName
206                    "2.5.4.8" => 6,                     // stateOrProvinceName
207                    "2.5.4.10" => 7,                    // organizationName
208                    "2.5.4.11" => 8,                    // organizationalUnitName
209                    "2.5.4.12" => 9,                    // title
210                    "2.5.4.41" => 10,                   // name
211                    "2.5.4.42" => 11,                   // givenName
212                    "2.5.4.43" => 12,                   // initials
213                    "2.5.4.44" => 13,                   // generationQualifier
214                    "2.5.4.46" => 14,                   // dnQualifier
215                    "2.5.4.65" => 15,                   // pseudonym
216                    "0.9.2342.19200300.100.1.25" => 16, // domainComponent
217                    other => return Err(invalid(format!("name attribute {other}"))),
218                };
219                // A PrintableString attribute has its own tags, 0x80 above.
220                let tag = match value.tag() {
221                    der::Tag::PrintableString => base | 0x80,
222                    der::Tag::Utf8String | der::Tag::Ia5String => base,
223                    other => return Err(invalid(format!("a name attribute as {other}"))),
224                };
225                w.utf8(&ctx(tag), text()?).map_err(tlv)?;
226            }
227        }
228    }
229    w.end_container().map_err(tlv)
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    #[test]
237    fn rejects_what_is_not_a_certificate() {
238        assert!(to_matter_tlv(&[]).is_err());
239        assert!(to_matter_tlv(&[0x30, 0x03, 0x02, 0x01, 0x01]).is_err());
240        assert!(to_matter_tlv(&[0x15, 0x18]).is_err());
241    }
242
243    /// A certificate rs-matter made (TLV), as X.509 DER, back to the same TLV.
244    #[test]
245    fn round_trips_a_matter_certificate() {
246        use rs_matter::cert::gen::VALID_FOREVER;
247        use rs_matter::cert::MAX_CERT_TLV_AND_ASN1_LEN;
248        use rs_matter::crypto::CanonPkcSecretKeyRef;
249        use rs_matter::onboard::cac::RcacGenerator;
250
251        static KEY: [u8; 32] = [3; 32];
252        let crypto =
253            rs_matter::crypto::default_crypto(rand::rng(), CanonPkcSecretKeyRef::new(&KEY));
254        let mut buf = vec![0u8; MAX_CERT_TLV_AND_ASN1_LEN];
255        let mut gen = RcacGenerator::new(&mut buf);
256        let (_, rcac) = gen.generate(&crypto, 0x1234, VALID_FOREVER).unwrap();
257        let rcac = rcac.to_vec();
258
259        // Rebuild the whole X.509 certificate: the TBS rs-matter encodes,
260        // the algorithm, and the signature as DER.
261        let cert = CertRef::new(TLVElement::new(&rcac));
262        let mut tbs = vec![0u8; 1024];
263        let n = cert.as_asn1(&mut tbs).unwrap();
264        let tbs = &tbs[..n];
265        let raw_sig = TLVElement::new(&rcac)
266            .structure()
267            .unwrap()
268            .ctx(11)
269            .unwrap()
270            .str()
271            .unwrap()
272            .to_vec();
273        let sig = p256::ecdsa::Signature::from_slice(&raw_sig)
274            .unwrap()
275            .to_der();
276        let algo = [
277            0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02,
278        ];
279        let sig_bits = der::asn1::BitString::from_bytes(sig.as_bytes())
280            .unwrap()
281            .to_der()
282            .unwrap();
283        let body: Vec<u8> = [tbs, &algo[..], &sig_bits[..]].concat();
284        let mut der = vec![0x30, 0x82, (body.len() >> 8) as u8, body.len() as u8];
285        der.extend_from_slice(&body);
286
287        assert_eq!(to_matter_tlv(&der).unwrap(), rcac);
288    }
289}