use core::cell::{Cell, RefCell};
use crate::im::Status;
use crate::msg::FabricIndex;
use crate::tlv::{Tag, TlvWriter};
pub mod certificate_management;
pub mod client_management;
pub type TlsCaid = u16;
pub type TlsCcdid = u16;
pub type TlsEndpointId = u16;
pub const ID_MAX: u16 = 65534;
pub const CERTIFICATE_MAX: usize = 3000;
pub const FINGERPRINT_LEN: usize = 32;
pub const FINGERPRINT_FIELD_MAX: usize = 64;
pub const HOSTNAME_MIN: usize = 4;
pub const HOSTNAME_MAX: usize = 253;
pub const INTERMEDIATES_MAX: usize = 10;
pub const NONCE_LEN: usize = 32;
pub const MIN_ROOTS_PER_FABRIC: u8 = 5;
pub const MIN_CLIENTS_PER_FABRIC: u8 = 2;
pub const MIN_ENDPOINTS_PER_FABRIC: u8 = 5;
#[must_use]
pub fn fingerprint(der: &[u8]) -> [u8; FINGERPRINT_LEN] {
crate::crypto::hash(der)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Slot {
Root {
fabric_index: FabricIndex,
caid: TlsCaid,
},
Client {
fabric_index: FabricIndex,
ccdid: TlsCcdid,
},
Intermediate {
fabric_index: FabricIndex,
ccdid: TlsCcdid,
index: u8,
},
}
pub trait TlsCertificateHooks {
fn is_valid_certificate(&self, der: &[u8]) -> bool;
fn save(&self, slot: Slot, der: &[u8]) -> core::result::Result<(), Status>;
fn write_certificate(
&self,
slot: Slot,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> core::result::Result<(), Status>;
fn clear(&self, slot: Slot);
fn generate_key(&self, ccdid: TlsCcdid) -> core::result::Result<(), Status>;
fn write_csr(
&self,
ccdid: TlsCcdid,
nonce: &[u8],
w: &mut TlvWriter<'_>,
csr_tag: Tag,
signature_tag: Tag,
) -> core::result::Result<(), Status>;
fn key_matches(&self, ccdid: TlsCcdid, certificate: &[u8]) -> bool;
fn remove_key(&self, ccdid: TlsCcdid);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RootEntry {
pub fabric_index: FabricIndex,
pub caid: TlsCaid,
pub fingerprint: [u8; FINGERPRINT_LEN],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClientEntry {
pub fabric_index: FabricIndex,
pub ccdid: TlsCcdid,
pub fingerprint: Option<[u8; FINGERPRINT_LEN]>,
pub intermediates: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointEntry {
pub fabric_index: FabricIndex,
pub endpoint_id: TlsEndpointId,
pub hostname: heapless::Vec<u8, HOSTNAME_MAX>,
pub port: u16,
pub caid: TlsCaid,
pub ccdid: Option<TlsCcdid>,
pub reference_count: u8,
}
#[derive(Debug)]
pub struct TlsTables<const R: usize, const C: usize, const E: usize> {
roots: RefCell<heapless::Vec<RootEntry, R>>,
clients: RefCell<heapless::Vec<ClientEntry, C>>,
endpoints: RefCell<heapless::Vec<EndpointEntry, E>>,
next_caid: Cell<u16>,
next_ccdid: Cell<u16>,
next_endpoint_id: Cell<u16>,
max_roots: u8,
max_clients: u8,
max_endpoints: u8,
time_known: Cell<bool>,
}
impl<const R: usize, const C: usize, const E: usize> TlsTables<R, C, E> {
#[must_use]
pub const fn new() -> Self {
Self::with_quotas(
MIN_ROOTS_PER_FABRIC,
MIN_CLIENTS_PER_FABRIC,
MIN_ENDPOINTS_PER_FABRIC,
)
}
#[must_use]
pub const fn with_quotas(max_roots: u8, max_clients: u8, max_endpoints: u8) -> Self {
Self {
roots: RefCell::new(heapless::Vec::new()),
clients: RefCell::new(heapless::Vec::new()),
endpoints: RefCell::new(heapless::Vec::new()),
next_caid: Cell::new(0),
next_ccdid: Cell::new(0),
next_endpoint_id: Cell::new(0),
max_roots,
max_clients,
max_endpoints,
time_known: Cell::new(false),
}
}
#[must_use]
pub const fn max_roots(&self) -> u8 {
self.max_roots
}
#[must_use]
pub const fn max_clients(&self) -> u8 {
self.max_clients
}
#[must_use]
pub const fn max_endpoints(&self) -> u8 {
self.max_endpoints
}
pub fn set_time_known(&self, known: bool) {
self.time_known.set(known);
}
#[must_use]
pub fn time_known(&self) -> bool {
self.time_known.get()
}
#[must_use]
pub fn roots(&self) -> core::cell::Ref<'_, heapless::Vec<RootEntry, R>> {
self.roots.borrow()
}
#[must_use]
pub fn clients(&self) -> core::cell::Ref<'_, heapless::Vec<ClientEntry, C>> {
self.clients.borrow()
}
#[must_use]
pub fn endpoints(&self) -> core::cell::Ref<'_, heapless::Vec<EndpointEntry, E>> {
self.endpoints.borrow()
}
pub fn set_reference_count(&self, endpoint_id: TlsEndpointId, count: u8) {
if let Some(entry) = self
.endpoints
.borrow_mut()
.iter_mut()
.find(|e| e.endpoint_id == endpoint_id)
{
entry.reference_count = count;
}
}
pub fn remove_fabric(&self, fabric: FabricIndex, hooks: &impl TlsCertificateHooks) {
self.endpoints
.borrow_mut()
.retain(|e| e.fabric_index != fabric);
for root in self
.roots
.borrow()
.iter()
.filter(|r| r.fabric_index == fabric)
{
hooks.clear(Slot::Root {
fabric_index: fabric,
caid: root.caid,
});
}
self.roots.borrow_mut().retain(|r| r.fabric_index != fabric);
for client in self
.clients
.borrow()
.iter()
.filter(|c| c.fabric_index == fabric)
{
clear_client(hooks, fabric, client.ccdid, client.intermediates);
hooks.remove_key(client.ccdid);
}
self.clients
.borrow_mut()
.retain(|c| c.fabric_index != fabric);
}
fn count_roots(&self, fabric: FabricIndex) -> usize {
self.roots
.borrow()
.iter()
.filter(|r| r.fabric_index == fabric)
.count()
}
fn count_clients(&self, fabric: FabricIndex) -> usize {
self.clients
.borrow()
.iter()
.filter(|c| c.fabric_index == fabric)
.count()
}
fn count_endpoints(&self, fabric: FabricIndex) -> usize {
self.endpoints
.borrow()
.iter()
.filter(|e| e.fabric_index == fabric)
.count()
}
fn allocate(next: &Cell<u16>, taken: impl Fn(u16) -> bool) -> Option<u16> {
let start = next.get();
let mut candidate = start;
for _ in 0..=u32::from(ID_MAX) {
if !taken(candidate) {
next.set(if candidate >= ID_MAX {
0
} else {
candidate.saturating_add(1)
});
return Some(candidate);
}
candidate = if candidate >= ID_MAX {
0
} else {
candidate.saturating_add(1)
};
}
None
}
}
impl<const R: usize, const C: usize, const E: usize> Default for TlsTables<R, C, E> {
fn default() -> Self {
Self::new()
}
}
fn clear_client(
hooks: &impl TlsCertificateHooks,
fabric_index: FabricIndex,
ccdid: TlsCcdid,
intermediates: u8,
) {
hooks.clear(Slot::Client {
fabric_index,
ccdid,
});
for index in 0..intermediates {
hooks.clear(Slot::Intermediate {
fabric_index,
ccdid,
index,
});
}
}
fn visible(ctx: &crate::im::InteractionContext<'_>, index: FabricIndex) -> bool {
!ctx.fabric_filtered || ctx.fabric_index == Some(index)
}
#[cfg(test)]
mod tests {
use super::*;
type Tables = TlsTables<4, 4, 4>;
#[test]
fn ids_start_at_zero_and_increase_by_one() {
let tables = Tables::new();
let none = |_: u16| false;
assert_eq!(Tables::allocate(&tables.next_caid, none), Some(0));
assert_eq!(Tables::allocate(&tables.next_caid, none), Some(1));
assert_eq!(Tables::allocate(&tables.next_caid, none), Some(2));
}
#[test]
fn an_id_past_65534_wraps_to_zero() {
let tables = Tables::new();
tables.next_caid.set(ID_MAX);
let none = |_: u16| false;
assert_eq!(Tables::allocate(&tables.next_caid, none), Some(ID_MAX));
assert_eq!(
Tables::allocate(&tables.next_caid, none),
Some(0),
"65535 is the null value, not an id"
);
}
#[test]
fn a_taken_id_is_skipped() {
let tables = Tables::new();
let taken = |id: u16| matches!(id, 0 | 1 | 3);
assert_eq!(Tables::allocate(&tables.next_caid, taken), Some(2));
assert_eq!(Tables::allocate(&tables.next_caid, taken), Some(4));
}
#[test]
fn a_full_id_space_allocates_nothing() {
let tables = Tables::new();
assert_eq!(Tables::allocate(&tables.next_caid, |_| true), None);
}
}