use crate::pki;
use indicatrix_net::{tls::Fingerprint, token};
use std::{
fmt,
path::Path,
sync::Mutex,
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,
}
#[derive(Default)]
pub struct EnrollRegistry {
pub(super) pending: Mutex<Vec<PendingEnrollment>>,
}
impl EnrollRegistry {
#[must_use]
pub fn new() -> Self {
Self::default()
}
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 bundle = pki::issue_client_in_memory(pki_dir, name)?;
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.pending.lock().unwrap();
if pending.len() >= MAX_PENDING {
return Err(EnrollIssueError::TooManyPending);
}
pending.push(PendingEnrollment {
secret_hash: Zeroizing::new(secret_hash),
expires_at: Instant::now() + ttl,
name: name.to_string(),
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.pending.lock().unwrap();
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,
})
}
}
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();
}
}