use crate::pki;
use indicatrix_net::{messages::PeerRole, tls::Fingerprint, token};
use std::{
fmt,
path::Path,
sync::{Mutex, MutexGuard, PoisonError},
time::{Duration, Instant},
};
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;
use super::{MAX_PENDING, TOKEN_TTL_SECS};
#[derive(Debug)]
pub enum EnrollIssueError {
Pki(pki::PkiError),
Csprng,
TooManyPending,
}
impl fmt::Display for EnrollIssueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pki(e) => write!(f, "{e}"),
Self::Csprng => write!(f, "system CSPRNG failed to produce randomness"),
Self::TooManyPending => write!(
f,
"{MAX_PENDING} enrollments are already pending -- claim or wait for one to expire before issuing \
another"
),
}
}
}
impl std::error::Error for EnrollIssueError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Pki(e) => Some(e),
Self::Csprng | Self::TooManyPending => None,
}
}
}
impl From<pki::PkiError> for EnrollIssueError {
fn from(e: pki::PkiError) -> Self {
Self::Pki(e)
}
}
pub(super) struct EnrollBundle {
pub(super) ca_pem: String,
pub(super) client_cert_pem: String,
pub(super) client_key_pem: Zeroizing<String>,
pub(super) client_fingerprint: Fingerprint,
}
impl From<pki::InMemoryClientBundle> for EnrollBundle {
fn from(b: pki::InMemoryClientBundle) -> Self {
Self {
ca_pem: b.ca_pem,
client_cert_pem: b.client_cert_pem,
client_key_pem: Zeroizing::new(b.client_key_pem),
client_fingerprint: b.client_fingerprint,
}
}
}
pub(super) struct PendingEnrollment {
secret_hash: Zeroizing<[u8; 32]>,
expires_at: Instant,
name: String,
bundle: EnrollBundle,
}
pub(super) struct ClaimedEnrollment {
pub(super) name: String,
pub(super) bundle: EnrollBundle,
}
pub struct EnrollRegistry {
pub(super) pending: Mutex<Vec<PendingEnrollment>>,
role: PeerRole,
operator_secret: Option<Zeroizing<[u8; token::SECRET_LEN]>>,
}
impl Default for EnrollRegistry {
fn default() -> Self {
Self::for_role(PeerRole::Viewer)
}
}
impl EnrollRegistry {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn for_role(role: PeerRole) -> Self {
Self {
pending: Mutex::new(Vec::new()),
role,
operator_secret: None,
}
}
#[must_use]
pub fn with_operator_secret(mut self, secret: Zeroizing<[u8; token::SECRET_LEN]>) -> Self {
self.operator_secret = Some(secret);
self
}
#[must_use]
pub fn operator_secret_matches(&self, presented: &[u8; token::SECRET_LEN]) -> bool {
self.operator_secret
.as_ref()
.is_some_and(|secret| bool::from(secret.ct_eq(presented)))
}
fn lock_pending(&self) -> MutexGuard<'_, Vec<PendingEnrollment>> {
self.pending.lock().unwrap_or_else(PoisonError::into_inner)
}
#[must_use]
pub const fn role(&self) -> PeerRole {
self.role
}
pub fn issue(&self, pki_dir: &Path, name: &str) -> Result<(String, u64), EnrollIssueError> {
self.issue_with_ttl(pki_dir, name, Duration::from_secs(TOKEN_TTL_SECS))
}
pub(super) fn issue_with_ttl(
&self,
pki_dir: &Path,
name: &str,
ttl: Duration,
) -> Result<(String, u64), EnrollIssueError> {
let label = indicatrix_net::tls::sanitize_allowlist_label(name);
let bundle = pki::issue_client_in_memory(pki_dir, &label, self.role)?;
let name = bundle.common_name.clone();
let mut secret = [0u8; token::SECRET_LEN];
random_bytes(&mut secret)?;
let secret_hash = sha256(&secret);
let encoded = token::encode(&secret, &bundle.ca_fingerprint);
secret.zeroize_local();
let mut pending = self.lock_pending();
let now = Instant::now();
pending.retain(|p| p.expires_at > now);
if pending.len() >= MAX_PENDING {
return Err(EnrollIssueError::TooManyPending);
}
pending.push(PendingEnrollment {
secret_hash: Zeroizing::new(secret_hash),
expires_at: Instant::now() + ttl,
name,
bundle: EnrollBundle::from(bundle),
});
drop(pending);
Ok((encoded, ttl.as_secs()))
}
pub(super) fn claim(&self, secret: &[u8; token::SECRET_LEN]) -> Option<ClaimedEnrollment> {
let candidate_hash = sha256(secret);
let now = Instant::now();
let mut pending = self.lock_pending();
pending.retain(|p| p.expires_at > now);
let mut matched_index = None;
for (i, p) in pending.iter().enumerate() {
let is_match: bool = candidate_hash.ct_eq(&*p.secret_hash).into();
if is_match {
matched_index = Some(i);
}
}
let entry = pending.remove(matched_index?);
drop(pending);
Some(ClaimedEnrollment {
name: entry.name,
bundle: entry.bundle,
})
}
}
pub(super) fn random_bytes(dest: &mut [u8]) -> Result<(), EnrollIssueError> {
use ring::rand::SecureRandom;
ring::rand::SystemRandom::new()
.fill(dest)
.map_err(|_| EnrollIssueError::Csprng)
}
fn sha256(data: &[u8]) -> [u8; 32] {
use sha2::{Digest, Sha256};
Sha256::digest(data).into()
}
pub(super) trait ZeroizeLocal {
fn zeroize_local(&mut self);
}
impl<const N: usize> ZeroizeLocal for [u8; N] {
fn zeroize_local(&mut self) {
use zeroize::Zeroize;
self.zeroize();
}
}