use crate::cert::dn::{DistinguishedName, DnAttribute, DnAttributeKind};
use crate::cert::{
BasicConstraints, CERT_DER_MAX, EllipticCurveId, Extension, Extensions, KEY_ID_LEN, KeyUsage,
MatterCertificate, PublicKeyAlgorithm, SignatureAlgorithm, der,
};
use crate::crypto::{KeyHandle, KeyStore, PublicKey, Signature};
use crate::error::{Error, ErrorCode, Result};
use crate::msg::VendorId;
const CN_MAX: usize = 64;
pub const TEST_VENDOR_ID: VendorId = VendorId(0xFFF1);
#[derive(Debug, Clone, Copy)]
pub struct DevelopmentChain {
vendor_id: VendorId,
not_before: u32,
not_after: u32,
}
impl DevelopmentChain {
#[must_use]
pub const fn new(not_before: u32, years: u32) -> Self {
Self {
vendor_id: TEST_VENDOR_ID,
not_before,
not_after: not_before.saturating_add(years.saturating_mul(31_557_600)),
}
}
pub fn for_vendor(mut self, vendor_id: VendorId) -> Result<Self> {
if !(0xFFF1..=0xFFF4).contains(&vendor_id.0) {
return Err(Error::new(ErrorCode::InvalidArgument));
}
self.vendor_id = vendor_id;
Ok(self)
}
#[must_use]
pub const fn vendor_id(&self) -> VendorId {
self.vendor_id
}
pub fn paa<'b, K: KeyStore>(
&self,
keys: &K,
buf: &'b mut [u8],
key: KeyHandle,
) -> Result<&'b [u8]> {
let public_key = keys.public_key(key)?;
let name = Name::plain("Matter Development PAA")?;
self.sign(
keys,
buf,
key,
name.dn()?,
name.dn()?,
&public_key,
&public_key,
BasicConstraints {
is_ca: true,
path_len_constraint: Some(1),
},
KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
)
}
pub fn pai<'b, K: KeyStore>(
&self,
keys: &K,
buf: &'b mut [u8],
paa_key: KeyHandle,
pai_public: &PublicKey,
) -> Result<&'b [u8]> {
let paa_public = keys.public_key(paa_key)?;
let issuer = Name::plain("Matter Development PAA")?;
let subject = Name::with_vid("Matter Development PAI", self.vendor_id)?;
self.sign(
keys,
buf,
paa_key,
issuer.dn()?,
subject.dn()?,
pai_public,
&paa_public,
BasicConstraints {
is_ca: true,
path_len_constraint: Some(0),
},
KeyUsage::KEY_CERT_SIGN | KeyUsage::CRL_SIGN,
)
}
pub fn dac<'b, K: KeyStore>(
&self,
keys: &K,
buf: &'b mut [u8],
pai_key: KeyHandle,
dac_public: &PublicKey,
product_id: u16,
) -> Result<&'b [u8]> {
let pai_public = keys.public_key(pai_key)?;
let issuer = Name::with_vid("Matter Development PAI", self.vendor_id)?;
let subject = Name::with_vid_pid("Matter Development DAC", self.vendor_id, product_id)?;
self.sign(
keys,
buf,
pai_key,
issuer.dn()?,
subject.dn()?,
dac_public,
&pai_public,
BasicConstraints {
is_ca: false,
path_len_constraint: None,
},
KeyUsage::DIGITAL_SIGNATURE,
)
}
#[allow(clippy::too_many_arguments)]
fn sign<'b, K: KeyStore>(
&self,
keys: &K,
buf: &'b mut [u8],
signing_key: KeyHandle,
issuer: DistinguishedName<'_>,
subject: DistinguishedName<'_>,
public_key: &PublicKey,
authority_key: &PublicKey,
constraints: BasicConstraints,
key_usage: KeyUsage,
) -> Result<&'b [u8]> {
let mut extensions = Extensions::new();
extensions.push(Extension::BasicConstraints(constraints))?;
extensions.push(Extension::KeyUsage(key_usage))?;
extensions.push(Extension::SubjectKeyId(key_id(public_key)?))?;
extensions.push(Extension::AuthorityKeyId(key_id(authority_key)?))?;
let serial = crate::cert::positive_serial(key_id(public_key)?);
let mut cert = MatterCertificate {
serial_number: &serial,
signature_algorithm: SignatureAlgorithm::EcdsaWithSha256,
issuer,
not_before: self.not_before,
not_after: self.not_after,
subject,
public_key_algorithm: PublicKeyAlgorithm::EcPubKey,
elliptic_curve_id: EllipticCurveId::Prime256V1,
public_key: *public_key,
extensions,
signature: Signature::from_bytes([0u8; 64]),
};
let mut tbs_buf = [0u8; CERT_DER_MAX];
let tbs = der::tbs_certificate(&cert, &mut tbs_buf)?;
cert.signature = keys.sign(signing_key, tbs)?;
der::certificate(&cert, buf)
}
}
struct Name {
text: heapless::String<CN_MAX>,
}
impl Name {
fn plain(label: &str) -> Result<Self> {
let mut text = heapless::String::new();
text.push_str(label)
.map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
Ok(Self { text })
}
fn with_vid(label: &str, vendor_id: VendorId) -> Result<Self> {
let mut name = Self::plain(label)?;
name.push(" Mvid:", vendor_id.0)?;
Ok(name)
}
fn with_vid_pid(label: &str, vendor_id: VendorId, product_id: u16) -> Result<Self> {
let mut name = Self::with_vid(label, vendor_id)?;
name.push(" Mpid:", product_id)?;
Ok(name)
}
fn push(&mut self, prefix: &str, value: u16) -> Result<()> {
self.text
.push_str(prefix)
.map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
for shift in [12u32, 8, 4, 0] {
let nibble = u8::try_from((value >> shift) & 0xF).unwrap_or(0);
let digit = match nibble {
0..=9 => b'0'.saturating_add(nibble),
_ => b'A'.saturating_add(nibble.saturating_sub(10)),
};
self.text
.push(char::from(digit))
.map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
}
Ok(())
}
fn dn(&self) -> Result<DistinguishedName<'_>> {
let mut dn = DistinguishedName::new();
dn.push(DnAttribute::string(
DnAttributeKind::CommonName,
self.text.as_str(),
))?;
Ok(dn)
}
}
fn key_id(public_key: &PublicKey) -> Result<[u8; KEY_ID_LEN]> {
let digest = crate::crypto::hash(public_key.as_bytes());
let prefix = digest
.get(..KEY_ID_LEN)
.ok_or_else(|| Error::new(ErrorCode::InvalidState))?;
<[u8; KEY_ID_LEN]>::try_from(prefix).map_err(|_| Error::new(ErrorCode::InvalidState))
}