use core::marker::PhantomData;
use heapless::{String, Vec};
use crate::config::{AssertValid, Config};
use crate::crypto::{
HASH_LEN_BYTES, KeyHandle, PUBLIC_KEY_SIZE_BYTES, PublicKey, SymmetricKey, ct_eq, hmac, kdf,
kdf_key,
};
use crate::error::{Error, ErrorCode, Result, bail};
use crate::msg::{FabricId, FabricIndex, NodeId, VendorId};
pub const COMPRESSED_FABRIC_INFO: &[u8] = b"CompressedFabric";
pub const GROUP_KEY_INFO: &[u8] = b"GroupKey v1.0";
pub const INITIATOR_RANDOM_LEN: usize = 32;
pub const FABRIC_LABEL_MAX: usize = 32;
pub const OPERATIONAL_CERT_MAX: usize = 400;
pub const VID_VERIFICATION_STATEMENT_LEN: usize = 85;
pub const VID_VERIFICATION_STATEMENT_VERSION: u8 = 0x21;
pub const FABRIC_BINDING_VERSION: u8 = 0x01;
#[derive(Debug, Clone, Default)]
pub struct Credentials {
pub noc: Vec<u8, OPERATIONAL_CERT_MAX>,
pub icac: Option<Vec<u8, OPERATIONAL_CERT_MAX>>,
pub rcac: Vec<u8, OPERATIONAL_CERT_MAX>,
pub vvsc: Option<Vec<u8, OPERATIONAL_CERT_MAX>>,
}
impl Credentials {
pub fn new(noc: &[u8], rcac: &[u8]) -> Result<Self> {
Ok(Self {
noc: copy_cert(noc)?,
icac: None,
rcac: copy_cert(rcac)?,
vvsc: None,
})
}
pub fn with_icac(mut self, icac: &[u8]) -> Result<Self> {
self.icac = Some(copy_cert(icac)?);
Ok(self)
}
pub fn set_vvsc(&mut self, vvsc: &[u8]) -> Result<()> {
if vvsc.is_empty() {
self.vvsc = None;
return Ok(());
}
if self.icac.is_some() {
bail!(InvalidArgument)
}
self.vvsc = Some(copy_cert(vvsc)?);
Ok(())
}
#[must_use]
pub fn is_valid(&self) -> bool {
!self.noc.is_empty()
&& !self.rcac.is_empty()
&& !(self.icac.is_some() && self.vvsc.is_some())
}
}
fn copy_cert(bytes: &[u8]) -> Result<Vec<u8, OPERATIONAL_CERT_MAX>> {
Vec::from_slice(bytes).map_err(|_| Error::new(ErrorCode::NoSpace))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CompressedFabricId(pub u64);
impl CompressedFabricId {
#[must_use]
pub const fn to_bytes(self) -> [u8; 8] {
self.0.to_be_bytes()
}
#[must_use]
pub fn to_hex(self) -> String<16> {
let mut out = String::new();
push_hex(&mut out, &self.to_bytes());
out
}
#[must_use]
pub fn subtype(self) -> String<18> {
let mut out = String::new();
let _ = out.push_str("_I");
let _ = out.push_str(&self.to_hex());
out
}
}
fn push_hex<const N: usize>(out: &mut String<N>, bytes: &[u8]) {
const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
for byte in bytes {
for nibble in [byte >> 4, byte & 0x0F] {
let digit = DIGITS.get(usize::from(nibble)).copied().unwrap_or(b'?');
let _ = out.push(char::from(digit));
}
}
}
pub fn compressed_fabric_id(
root_public_key: &PublicKey,
fabric_id: FabricId,
) -> Result<CompressedFabricId> {
let Some(raw) = root_public_key.as_bytes().get(1..) else {
bail!(InvalidArgument)
};
let mut out = [0u8; 8];
kdf(
raw,
&fabric_id.0.to_be_bytes(),
COMPRESSED_FABRIC_INFO,
&mut out,
)?;
Ok(CompressedFabricId(u64::from_be_bytes(out)))
}
pub fn operational_group_key(
epoch_key: &SymmetricKey,
compressed: CompressedFabricId,
) -> Result<SymmetricKey> {
kdf_key(epoch_key.as_bytes(), &compressed.to_bytes(), GROUP_KEY_INFO)
}
pub fn destination_identifier(
ipk: &SymmetricKey,
initiator_random: &[u8; INITIATOR_RANDOM_LEN],
root_public_key: &PublicKey,
fabric_id: FabricId,
node_id: NodeId,
) -> Result<[u8; HASH_LEN_BYTES]> {
const LEN: usize = INITIATOR_RANDOM_LEN + PUBLIC_KEY_SIZE_BYTES + 8 + 8;
let mut message = [0u8; LEN];
{
let mut at = 0usize;
let mut put = |src: &[u8]| -> Result<()> {
let end = at
.checked_add(src.len())
.ok_or_else(|| Error::new(ErrorCode::BufferTooSmall))?;
let Some(slot) = message.get_mut(at..end) else {
bail!(BufferTooSmall)
};
slot.copy_from_slice(src);
at = end;
Ok(())
};
put(initiator_random)?;
put(root_public_key.as_bytes())?;
put(&fabric_id.0.to_le_bytes())?;
put(&node_id.0.to_le_bytes())?;
}
hmac(ipk.as_bytes(), &message)
}
pub const VENDOR_ID_VERIFICATION_TBS_MAX: usize = 1
+ 32
+ crate::crypto::SYMMETRIC_KEY_LENGTH_BYTES
+ 1
+ (1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2)
+ VID_VERIFICATION_STATEMENT_LEN;
pub fn vendor_fabric_binding_message(
root_public_key: &PublicKey,
fabric_id: FabricId,
vendor_id: VendorId,
) -> [u8; 1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2] {
let mut out = [0u8; 1 + PUBLIC_KEY_SIZE_BYTES + 8 + 2];
let mut at = 0usize;
let mut put = |bytes: &[u8]| {
if let Some(slot) = out.get_mut(at..at.saturating_add(bytes.len())) {
slot.copy_from_slice(bytes);
}
at = at.saturating_add(bytes.len());
};
put(&[FABRIC_BINDING_VERSION]);
put(root_public_key.as_bytes());
put(&fabric_id.0.to_be_bytes());
put(&vendor_id.0.to_be_bytes());
out
}
#[derive(Debug, Clone, Copy)]
pub struct VendorIdBinding<'a> {
pub root_public_key: &'a PublicKey,
pub fabric_id: FabricId,
pub vendor_id: VendorId,
pub statement: Option<&'a [u8; VID_VERIFICATION_STATEMENT_LEN]>,
}
pub fn vendor_id_verification_tbs<'b>(
out: &'b mut [u8; VENDOR_ID_VERIFICATION_TBS_MAX],
challenges: (&[u8; 32], &SymmetricKey),
fabric_index: FabricIndex,
binding: &VendorIdBinding<'_>,
) -> &'b [u8] {
let (client_challenge, attestation_challenge) = challenges;
let bound = vendor_fabric_binding_message(
binding.root_public_key,
binding.fabric_id,
binding.vendor_id,
);
let mut at = 0usize;
{
let mut put = |bytes: &[u8]| {
if let Some(slot) = out.get_mut(at..at.saturating_add(bytes.len())) {
slot.copy_from_slice(bytes);
}
at = at.saturating_add(bytes.len());
};
put(&[FABRIC_BINDING_VERSION]);
put(client_challenge);
put(attestation_challenge.as_bytes());
put(&[fabric_index.0]);
put(&bound);
if let Some(statement) = binding.statement {
put(statement);
}
}
out.get(..at).unwrap_or(&[])
}
#[derive(Debug, Clone)]
pub struct FabricIdentity {
pub fabric_id: FabricId,
pub node_id: NodeId,
pub root_public_key: PublicKey,
pub admin_vendor_id: VendorId,
}
#[derive(Debug, Clone)]
pub struct Fabric {
pub index: FabricIndex,
pub fabric_id: FabricId,
pub node_id: NodeId,
pub root_public_key: PublicKey,
pub compressed: CompressedFabricId,
pub ipk: SymmetricKey,
pub admin_vendor_id: VendorId,
pub label: String<FABRIC_LABEL_MAX>,
pub operational_key: KeyHandle,
pub credentials: Credentials,
pub vid_verification_statement: Option<[u8; VID_VERIFICATION_STATEMENT_LEN]>,
}
impl Fabric {
pub fn new(
index: FabricIndex,
identity: FabricIdentity,
ipk_epoch_key: &SymmetricKey,
operational_key: KeyHandle,
credentials: Credentials,
) -> Result<Self> {
let FabricIdentity {
fabric_id,
node_id,
root_public_key,
admin_vendor_id,
} = identity;
if !index.is_some() {
bail!(InvalidArgument)
}
if fabric_id.0 == 0 {
bail!(InvalidArgument)
}
if !node_id.is_operational() {
bail!(InvalidArgument)
}
if !credentials.is_valid() {
bail!(InvalidArgument)
}
let compressed = compressed_fabric_id(&root_public_key, fabric_id)?;
let ipk = operational_group_key(ipk_epoch_key, compressed)?;
Ok(Self {
index,
fabric_id,
node_id,
root_public_key,
compressed,
ipk,
admin_vendor_id,
label: String::new(),
operational_key,
credentials,
vid_verification_statement: None,
})
}
pub fn set_label(&mut self, label: &str) -> Result<()> {
let mut next = String::new();
next.push_str(label)
.map_err(|_| Error::new(ErrorCode::InvalidArgument))?;
self.label = next;
Ok(())
}
#[must_use]
pub fn instance_name(&self) -> String<33> {
let mut out = String::new();
let _ = out.push_str(&self.compressed.to_hex());
let _ = out.push('-');
push_hex(&mut out, &self.node_id.0.to_be_bytes());
out
}
#[must_use]
pub fn vendor_id_binding(&self) -> VendorIdBinding<'_> {
VendorIdBinding {
root_public_key: &self.root_public_key,
fabric_id: self.fabric_id,
vendor_id: self.admin_vendor_id,
statement: self.vid_verification_statement.as_ref(),
}
}
pub fn vendor_id_verification_tbs<'b>(
&self,
out: &'b mut [u8; VENDOR_ID_VERIFICATION_TBS_MAX],
client_challenge: &[u8; 32],
attestation_challenge: &SymmetricKey,
) -> &'b [u8] {
vendor_id_verification_tbs(
out,
(client_challenge, attestation_challenge),
self.index,
&self.vendor_id_binding(),
)
}
pub fn destination_identifier(
&self,
initiator_random: &[u8; INITIATOR_RANDOM_LEN],
) -> Result<[u8; HASH_LEN_BYTES]> {
destination_identifier(
&self.ipk,
initiator_random,
&self.root_public_key,
self.fabric_id,
self.node_id,
)
}
}
#[derive(Debug)]
pub struct FabricTable<C: Config, const N: usize = 5> {
fabrics: Vec<Fabric, N>,
last_index: u8,
_config: PhantomData<C>,
}
impl<C: Config, const N: usize> Default for FabricTable<C, N> {
fn default() -> Self {
Self::new()
}
}
impl<C: Config, const N: usize> crate::config::Capacity for FabricTable<C, N> {
const TOTAL: usize = N;
const PER_FABRIC: usize = 1;
}
impl<C: Config, const N: usize> FabricTable<C, N> {
pub const CHECK: () = {
let () = AssertValid::<C>::CHECK;
assert!(
N >= C::FABRICS,
"FabricTable: the table must hold Config::FABRICS fabrics — \
raise the table's N, or lower Config::FABRICS"
);
assert!(
N <= 254,
"FabricTable: Core §11.18.5.3 constrains SupportedFabrics to 5..=254"
);
};
#[must_use]
pub fn new() -> Self {
let () = Self::CHECK;
Self {
fabrics: Vec::new(),
last_index: 0,
_config: PhantomData,
}
}
#[must_use]
pub fn len(&self) -> usize {
self.fabrics.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.fabrics.is_empty()
}
#[must_use]
pub const fn capacity(&self) -> usize {
N
}
pub fn allocate_index(&mut self) -> Result<FabricIndex> {
let mut candidate = self.last_index;
for _ in 0..254u16 {
candidate = if candidate >= 254 {
1
} else {
candidate.saturating_add(1)
};
let index = FabricIndex(candidate);
if self.find(index).is_none() {
self.last_index = candidate;
return Ok(index);
}
}
Err(Error::new(ErrorCode::NoSpace))
}
pub fn insert(&mut self, fabric: Fabric) -> Result<FabricIndex> {
if self.find(fabric.index).is_some() {
bail!(InvalidState)
}
if self
.fabrics
.iter()
.any(|f| f.compressed == fabric.compressed && f.node_id == fabric.node_id)
{
bail!(AlreadyExists)
}
let index = fabric.index;
self.fabrics
.push(fabric)
.map_err(|_| Error::new(ErrorCode::NoSpace))?;
Ok(index)
}
#[must_use]
pub fn find(&self, index: FabricIndex) -> Option<&Fabric> {
self.fabrics.iter().find(|f| f.index == index)
}
pub fn find_mut(&mut self, index: FabricIndex) -> Option<&mut Fabric> {
self.fabrics.iter_mut().find(|f| f.index == index)
}
#[must_use]
pub fn find_by_compressed(&self, compressed: CompressedFabricId) -> Option<&Fabric> {
self.fabrics.iter().find(|f| f.compressed == compressed)
}
pub fn find_by_destination_identifier(
&self,
initiator_random: &[u8; INITIATOR_RANDOM_LEN],
destination_id: &[u8; HASH_LEN_BYTES],
) -> Result<Option<&Fabric>> {
let mut found = None;
for fabric in &self.fabrics {
let candidate = fabric.destination_identifier(initiator_random)?;
if ct_eq(&candidate, destination_id) {
found = Some(fabric);
}
}
Ok(found)
}
pub fn remove(&mut self, index: FabricIndex) -> Option<Fabric> {
let position = self.fabrics.iter().position(|f| f.index == index)?;
Some(self.fabrics.swap_remove(position))
}
pub fn iter(&self) -> impl Iterator<Item = &Fabric> {
self.fabrics.iter()
}
}
pub type IpkEpochKey = SymmetricKey;
#[cfg(test)]
mod tests {
use hex_literal::hex;
use super::*;
use crate::DefaultConfig;
const ROOT_PUBLIC_KEY: [u8; 65] = hex!(
"044a9f42b1ca4840d37292bbc7f6a7e11e22200c976fc900dbc98a7a383a641c"
"b8254a2e56d4e295a847943b4e3897c4a773e930277b4d9fbede8a052686bfac"
"fa"
);
const FABRIC: FabricId = FabricId(0x2906_C908_D115_D362);
const IPK_EPOCH: [u8; 16] = hex!("4a71cdd7b2a3ca9024f96f3c96a19dee");
fn root_key() -> PublicKey {
PublicKey::from_bytes(ROOT_PUBLIC_KEY)
}
#[test]
fn the_compressed_fabric_id_matches_the_specs_worked_example() {
let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
assert_eq!(compressed.to_bytes(), hex!("87e1b004e235a130"));
assert_eq!(compressed.to_hex().as_str(), "87E1B004E235A130");
assert_eq!(compressed.subtype().as_str(), "_I87E1B004E235A130");
}
#[test]
fn the_operational_group_key_matches_the_specs_worked_example() {
let epoch = SymmetricKey::new(hex!("235bf7e62823d358dca4ba50b1535f4b"));
let key =
operational_group_key(&epoch, CompressedFabricId(0x87E1_B004_E235_A130)).expect("kdf");
assert_eq!(key.as_bytes(), &hex!("a6f5306baf6d050af23ba4bd6b9dd960"));
}
#[test]
fn the_ipk_matches_the_specs_worked_example() {
let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
assert_eq!(ipk.as_bytes(), &hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4"));
}
#[test]
fn the_destination_identifier_matches_the_specs_worked_example() {
let compressed = compressed_fabric_id(&root_key(), FABRIC).expect("derive");
let ipk = operational_group_key(&SymmetricKey::new(IPK_EPOCH), compressed).expect("kdf");
let initiator_random =
hex!("7e171231568dfa17206b3accf8faec2f4d21b580113196f47c7c4deb810a73dc");
let id = destination_identifier(
&ipk,
&initiator_random,
&root_key(),
FABRIC,
NodeId(0xCD55_44AA_7B13_EF14),
)
.expect("hmac");
assert_eq!(
id,
hex!("dc35dd5fc9134cc5544538c9c3fc4297c1ec3370c839136a80e10796451d4c53")
);
}
fn example_credentials() -> Credentials {
Credentials::new(b"noc", b"rcac").expect("fits")
}
fn example_fabric(index: u8, node: u64) -> Fabric {
Fabric::new(
FabricIndex(index),
FabricIdentity {
fabric_id: FABRIC,
node_id: NodeId(node),
root_public_key: root_key(),
admin_vendor_id: VendorId(0xFFF1),
},
&SymmetricKey::new(IPK_EPOCH),
KeyHandle(u32::from(index)),
example_credentials(),
)
.expect("fabric")
}
#[test]
fn a_fabric_derives_both_values_on_construction() {
let fabric = example_fabric(1, 0xCD55_44AA_7B13_EF14);
assert_eq!(fabric.compressed, CompressedFabricId(0x87E1_B004_E235_A130));
assert_eq!(
fabric.ipk.as_bytes(),
&hex!("9bc61cd9c62a2df6d64dfcaa9dc472d4")
);
assert_eq!(fabric.label.as_str(), "", "§11.18.4.5's fallback");
}
#[test]
fn the_instance_name_is_the_dns_sd_form() {
let mut fabric = example_fabric(1, 0x8FC7_7724_01CD_0696);
fabric.compressed = CompressedFabricId(0x2906_C908_D115_D362);
assert_eq!(
fabric.instance_name().as_str(),
"2906C908D115D362-8FC7772401CD0696"
);
}
#[test]
fn a_fabric_refuses_the_identities_6_5_6_3_forbids() {
let key = SymmetricKey::new([0; 16]);
let cases = [
("fabric id 0", FabricIndex(1), FabricId(0), NodeId(1)),
(
"a group node id, not an operational one",
FabricIndex(1),
FabricId(1),
NodeId(0xFFFF_FFFF_FFFF_0001),
),
(
"fabric index 0 means no fabric",
FabricIndex(0),
FabricId(1),
NodeId(1),
),
];
for (why, index, fabric_id, node_id) in cases {
let built = Fabric::new(
index,
FabricIdentity {
fabric_id,
node_id,
root_public_key: root_key(),
admin_vendor_id: VendorId(1),
},
&key,
KeyHandle(1),
example_credentials(),
);
assert_eq!(
built.map(|_| ()).unwrap_err().code(),
ErrorCode::InvalidArgument,
"{why}"
);
}
}
#[test]
fn a_label_longer_than_32_is_a_constraint_error() {
let mut fabric = example_fabric(1, 1);
fabric.set_label("Living room").expect("fits");
assert_eq!(fabric.label.as_str(), "Living room");
assert_eq!(
fabric.set_label(&"x".repeat(33)).unwrap_err().code(),
ErrorCode::InvalidArgument
);
assert_eq!(fabric.label.as_str(), "Living room", "and nothing changed");
fabric.set_label(&"x".repeat(32)).expect("exactly 32 fits");
}
type Table = FabricTable<DefaultConfig, 5>;
#[test]
fn indices_are_allocated_from_one_and_never_zero() {
let mut t = Table::new();
assert!(t.is_empty());
assert_eq!(t.allocate_index().expect("a"), FabricIndex(1));
t.insert(example_fabric(1, 1)).expect("insert");
assert_eq!(t.allocate_index().expect("b"), FabricIndex(2));
t.insert(example_fabric(2, 2)).expect("insert");
t.remove(FabricIndex(1)).expect("removed");
assert_eq!(t.allocate_index().expect("c"), FabricIndex(3));
}
#[test]
fn fabric_indices_wrap_from_254_to_1_and_skip_what_is_in_use() {
let mut t = Table::new();
t.insert(example_fabric(1, 1)).expect("insert");
for _ in 0..253 {
let index = t.allocate_index().expect("space");
assert_ne!(index, FabricIndex(0));
assert_ne!(index, FabricIndex(0xFF));
}
assert_eq!(t.allocate_index().expect("wrapped"), FabricIndex(2));
}
#[test]
fn a_duplicate_fabric_is_refused() {
let mut t = Table::new();
t.insert(example_fabric(1, 7)).expect("first");
assert_eq!(
t.insert(example_fabric(2, 7)).unwrap_err().code(),
ErrorCode::AlreadyExists
);
t.insert(example_fabric(2, 8)).expect("different node");
assert_eq!(t.len(), 2);
assert_eq!(
t.insert(example_fabric(2, 9)).unwrap_err().code(),
ErrorCode::InvalidState
);
}
#[test]
fn a_full_table_is_a_value_not_an_abort() {
let mut t = Table::new();
for i in 1..=5u8 {
t.insert(example_fabric(i, u64::from(i))).expect("fits");
}
assert_eq!(
t.insert(example_fabric(6, 6)).unwrap_err().code(),
ErrorCode::NoSpace
);
assert_eq!(t.capacity(), 5);
}
#[test]
fn a_destination_identifier_finds_its_fabric_and_only_its_fabric() {
let mut t = Table::new();
for i in 1..=3u8 {
t.insert(example_fabric(i, u64::from(i))).expect("insert");
}
let random = [0x42u8; INITIATOR_RANDOM_LEN];
for i in 1..=3u8 {
let id = t
.find(FabricIndex(i))
.expect("fabric")
.destination_identifier(&random)
.expect("id");
let found = t
.find_by_destination_identifier(&random, &id)
.expect("search")
.expect("a match");
assert_eq!(found.index, FabricIndex(i));
}
assert!(
t.find_by_destination_identifier(&random, &[0u8; HASH_LEN_BYTES])
.expect("search")
.is_none()
);
}
#[test]
fn a_different_initiator_random_gives_a_different_identifier() {
let fabric = example_fabric(1, 1);
assert_ne!(
fabric.destination_identifier(&[1; 32]).expect("a"),
fabric.destination_identifier(&[2; 32]).expect("b")
);
}
#[test]
fn removing_a_fabric_hands_back_its_key_handle() {
let mut t = Table::new();
t.insert(example_fabric(1, 1)).expect("insert");
let removed = t.remove(FabricIndex(1)).expect("removed");
assert_eq!(removed.operational_key, KeyHandle(1));
assert!(t.is_empty());
assert!(t.remove(FabricIndex(1)).is_none());
}
#[test]
fn different_roots_and_different_fabric_ids_compress_differently() {
let mut other = ROOT_PUBLIC_KEY;
other[1] ^= 0xFF;
let a = compressed_fabric_id(&root_key(), FabricId(1)).expect("a");
let b = compressed_fabric_id(&PublicKey::from_bytes(other), FabricId(1)).expect("b");
let c = compressed_fabric_id(&root_key(), FabricId(2)).expect("c");
assert_ne!(a, b);
assert_ne!(a, c);
}
#[test]
fn find_by_compressed_picks_the_right_fabric() {
let mut t = Table::new();
t.insert(example_fabric(1, 1)).expect("insert");
let found = t
.find_by_compressed(CompressedFabricId(0x87E1_B004_E235_A130))
.expect("found");
assert_eq!(found.index, FabricIndex(1));
assert!(t.find_by_compressed(CompressedFabricId(0)).is_none());
}
}