use indicatrix_net::{messages::PeerRole, tls};
use rcgen::{
BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair,
KeyUsagePurpose,
};
use std::{
fmt,
net::IpAddr,
path::{Path, PathBuf},
};
use time::{Duration, OffsetDateTime};
pub mod role;
#[cfg(test)]
mod tests;
pub use role::{
LEGACY_ALLOWLIST_FILE, VIEWER_ALLOWLIST_FILE, WORKER_ALLOWLIST_FILE, WORKER_CN_PREFIX,
allowlist_in, role_of_certificate, viewer_allowlist_in, worker_allowlist_in,
worker_label_of_certificate,
};
pub const CA_CERT_FILE: &str = "ca.pem";
pub const CA_KEY_FILE: &str = "ca.key";
pub const SERVER_CERT_FILE: &str = "server.pem";
pub const SERVER_KEY_FILE: &str = "server.key";
pub const CLIENT_CERT_FILE: &str = "client.pem";
pub const CLIENT_KEY_FILE: &str = "client.key";
const CA_LIFETIME_DAYS: i64 = 365 * 10;
const LEAF_LIFETIME_DAYS: i64 = 365 * 5;
const NOT_BEFORE_SLACK_DAYS: i64 = 1;
#[derive(Debug)]
pub enum PkiError {
Io {
verb: &'static str,
path: PathBuf,
source: std::io::Error,
},
CaAlreadyExists { dir: PathBuf },
CaFileUnreadable {
path: PathBuf,
dir: PathBuf,
source: std::io::Error,
},
NoServerSan,
EmptyClientName,
ReservedRolePrefix { name: String },
Rcgen {
context: &'static str,
source: rcgen::Error,
},
RcgenAtPath { path: PathBuf, source: rcgen::Error },
Message(String),
Certificate {
path: PathBuf,
source: tls::TlsError,
},
AllowlistUpdate {
out_dir: PathBuf,
path: PathBuf,
fingerprint_hex: String,
name: String,
source: tls::TlsError,
},
}
impl fmt::Display for PkiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { verb, path, source } => {
write!(f, "could not {verb} {}: {source}", path.display())
}
Self::CaAlreadyExists { dir } => write!(
f,
"{} already contains a CA ({CA_CERT_FILE} and/or {CA_KEY_FILE}) -- refusing to overwrite it, since \
that would invalidate every certificate already issued from it. Remove those files yourself first \
if you really mean to start over.",
dir.display()
),
Self::CaFileUnreadable { path, dir, source } => write!(
f,
"could not read {}: {source} (run `indicatrix-worker cert init --dir {}` first)",
path.display(),
dir.display()
),
Self::NoServerSan => write!(
f,
"issue-server requires at least one --host or --ip: rustls ignores Common Name entirely, so a \
certificate with no Subject Alternative Name can never be validated by a mutual-TLS client -- see \
--help"
),
Self::EmptyClientName => write!(f, "--name must not be empty"),
Self::ReservedRolePrefix { name } => write!(
f,
"--name {name:?} starts with {WORKER_CN_PREFIX:?}, which marks WORKER certificates -- pick \
another name for a viewer, or pass --role worker for a worker certificate"
),
Self::Rcgen { context, source } => write!(f, "{context}: {source}"),
Self::RcgenAtPath { path, source } => write!(f, "{}: {source}", path.display()),
Self::Message(msg) => f.write_str(msg),
Self::Certificate { path, source } => write!(f, "{}: {source}", path.display()),
Self::AllowlistUpdate {
out_dir,
path,
fingerprint_hex,
name,
source,
} => write!(
f,
"issued the certificate at {} but could not update {}: {source} -- add this line to it by hand: \
{fingerprint_hex} # {name}",
out_dir.display(),
path.display()
),
}
}
}
impl std::error::Error for PkiError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } | Self::CaFileUnreadable { source, .. } => Some(source),
Self::Rcgen { source, .. } | Self::RcgenAtPath { source, .. } => Some(source),
Self::Certificate { source, .. } | Self::AllowlistUpdate { source, .. } => Some(source),
Self::CaAlreadyExists { .. }
| Self::NoServerSan
| Self::EmptyClientName
| Self::ReservedRolePrefix { .. }
| Self::Message(_) => None,
}
}
}
impl From<String> for PkiError {
fn from(msg: String) -> Self {
Self::Message(msg)
}
}
fn not_before_with_skew_slack() -> OffsetDateTime {
OffsetDateTime::now_utc() - Duration::days(NOT_BEFORE_SLACK_DAYS)
}
fn not_after(lifetime_days: i64) -> OffsetDateTime {
OffsetDateTime::now_utc() + Duration::days(lifetime_days)
}
pub fn init(dir: &Path) -> Result<(), PkiError> {
std::fs::create_dir_all(dir).map_err(|source| PkiError::Io {
verb: "create",
path: dir.to_path_buf(),
source,
})?;
let ca_cert_path = dir.join(CA_CERT_FILE);
let ca_key_path = dir.join(CA_KEY_FILE);
if ca_cert_path.exists() || ca_key_path.exists() {
return Err(PkiError::CaAlreadyExists {
dir: dir.to_path_buf(),
});
}
let key_pair = KeyPair::generate().map_err(|source| PkiError::Rcgen {
context: "CA key generation failed",
source,
})?;
let mut params =
CertificateParams::new(Vec::<String>::new()).map_err(|source| PkiError::Rcgen {
context: "unexpected error building an empty SAN list",
source,
})?;
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
params
.distinguished_name
.push(DnType::CommonName, "indicatrix-worker private CA");
params.not_before = not_before_with_skew_slack();
params.not_after = not_after(CA_LIFETIME_DAYS);
let cert = params
.self_signed(&key_pair)
.map_err(|source| PkiError::Rcgen {
context: "CA self-signing failed",
source,
})?;
std::fs::write(&ca_cert_path, cert.pem()).map_err(|source| PkiError::Io {
verb: "write",
path: ca_cert_path.clone(),
source,
})?;
tls::write_private_key_pem(&ca_key_path, &key_pair.serialize_pem())?;
tracing::info!(
"indicatrix-worker cert init: wrote {} and {} -- CA expires {} (UTC)",
ca_cert_path.display(),
ca_key_path.display(),
params.not_after.date()
);
Ok(())
}
pub(crate) fn load_ca(dir: &Path) -> Result<Issuer<'static, KeyPair>, PkiError> {
let ca_cert_path = dir.join(CA_CERT_FILE);
let ca_key_path = dir.join(CA_KEY_FILE);
let ca_pem =
std::fs::read_to_string(&ca_cert_path).map_err(|source| PkiError::CaFileUnreadable {
path: ca_cert_path.clone(),
dir: dir.to_path_buf(),
source,
})?;
let ca_key_pem =
std::fs::read_to_string(&ca_key_path).map_err(|source| PkiError::CaFileUnreadable {
path: ca_key_path.clone(),
dir: dir.to_path_buf(),
source,
})?;
let ca_key = KeyPair::from_pem(&ca_key_pem).map_err(|source| PkiError::RcgenAtPath {
path: ca_key_path.clone(),
source,
})?;
let issuer =
Issuer::from_ca_cert_pem(&ca_pem, ca_key).map_err(|source| PkiError::RcgenAtPath {
path: ca_cert_path.clone(),
source,
})?;
Ok(issuer)
}
pub fn issue_server(dir: &Path, hosts: &[String], ips: &[IpAddr]) -> Result<(), PkiError> {
if hosts.is_empty() && ips.is_empty() {
return Err(PkiError::NoServerSan);
}
let ca_issuer = load_ca(dir)?;
let mut sans: Vec<String> = hosts.to_vec();
sans.extend(ips.iter().map(IpAddr::to_string));
let mut params = CertificateParams::new(sans).map_err(|source| PkiError::Rcgen {
context: "invalid --host/--ip value",
source,
})?;
let common_name = hosts.first().cloned().unwrap_or_else(|| ips[0].to_string());
params
.distinguished_name
.push(DnType::CommonName, common_name);
params.not_before = not_before_with_skew_slack();
params.not_after = not_after(LEAF_LIFETIME_DAYS);
params.use_authority_key_identifier_extension = true;
params.key_usages = vec![
KeyUsagePurpose::DigitalSignature,
KeyUsagePurpose::KeyEncipherment,
];
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
let key_pair = KeyPair::generate().map_err(|source| PkiError::Rcgen {
context: "server key generation failed",
source,
})?;
let cert = params
.signed_by(&key_pair, &ca_issuer)
.map_err(|source| PkiError::Rcgen {
context: "failed to sign the server certificate",
source,
})?;
let cert_path = dir.join(SERVER_CERT_FILE);
let key_path = dir.join(SERVER_KEY_FILE);
std::fs::write(&cert_path, cert.pem()).map_err(|source| PkiError::Io {
verb: "write",
path: cert_path.clone(),
source,
})?;
tls::write_private_key_pem(&key_path, &key_pair.serialize_pem())?;
tracing::info!(
"indicatrix-worker cert issue-server: wrote {} and {} (SANs: {}{}{}) -- expires {} (UTC)",
cert_path.display(),
key_path.display(),
hosts.join(", "),
if hosts.is_empty() || ips.is_empty() {
""
} else {
", "
},
ips.iter()
.map(IpAddr::to_string)
.collect::<Vec<_>>()
.join(", "),
params.not_after.date()
);
Ok(())
}
pub fn issue_client(dir: &Path, name: &str, out: &Path) -> Result<(), PkiError> {
issue_client_with_role(dir, name, out, PeerRole::Viewer)
}
pub fn issue_client_with_role(
dir: &Path,
name: &str,
out: &Path,
role: PeerRole,
) -> Result<(), PkiError> {
let ca_issuer = load_ca(dir)?;
let (cert, key_pair, not_after, common_name) = sign_client_leaf(&ca_issuer, name, role)?;
std::fs::create_dir_all(out).map_err(|source| PkiError::Io {
verb: "create",
path: out.to_path_buf(),
source,
})?;
let ca_source_path = dir.join(CA_CERT_FILE);
let ca_pem = std::fs::read_to_string(&ca_source_path).map_err(|source| PkiError::Io {
verb: "read",
path: ca_source_path.clone(),
source,
})?;
let out_ca_path = out.join(CA_CERT_FILE);
let out_cert_path = out.join(CLIENT_CERT_FILE);
let out_key_path = out.join(CLIENT_KEY_FILE);
std::fs::write(&out_ca_path, &ca_pem).map_err(|source| PkiError::Io {
verb: "write",
path: out_ca_path.clone(),
source,
})?;
std::fs::write(&out_cert_path, cert.pem()).map_err(|source| PkiError::Io {
verb: "write",
path: out_cert_path.clone(),
source,
})?;
tls::write_private_key_pem(&out_key_path, &key_pair.serialize_pem())?;
let fingerprint = tls::fingerprint(cert.der());
let fingerprint_hex = tls::fingerprint_to_hex(&fingerprint);
let allowlist_path = allowlist_in(dir, role);
tls::append_to_allowlist(&allowlist_path, &fingerprint, &common_name).map_err(|source| {
PkiError::AllowlistUpdate {
out_dir: out.to_path_buf(),
path: allowlist_path.clone(),
fingerprint_hex: fingerprint_hex.clone(),
name: common_name.clone(),
source,
}
})?;
tracing::info!(
"indicatrix-worker cert issue-client: wrote {} bundle {common_name:?} to {} ({CA_CERT_FILE}, {CLIENT_CERT_FILE}, \
{CLIENT_KEY_FILE}) -- fingerprint {fingerprint_hex} added to {} -- expires {} (UTC)",
role::role_name(role),
out.display(),
allowlist_path.display(),
not_after.date()
);
Ok(())
}
fn sign_client_leaf(
ca_issuer: &Issuer<'static, KeyPair>,
name: &str,
role: PeerRole,
) -> Result<(rcgen::Certificate, KeyPair, OffsetDateTime, String), PkiError> {
let label = name.strip_prefix(WORKER_CN_PREFIX).unwrap_or(name);
if label.trim().is_empty() {
return Err(PkiError::EmptyClientName);
}
let common_name =
role::common_name_for(role, name).ok_or_else(|| PkiError::ReservedRolePrefix {
name: name.to_string(),
})?;
let mut params =
CertificateParams::new(Vec::<String>::new()).map_err(|source| PkiError::Rcgen {
context: "unexpected error building an empty SAN list",
source,
})?;
params
.distinguished_name
.push(DnType::CommonName, common_name.as_str());
params.not_before = not_before_with_skew_slack();
params.not_after = not_after(LEAF_LIFETIME_DAYS);
params.use_authority_key_identifier_extension = true;
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
let key_pair = KeyPair::generate().map_err(|source| PkiError::Rcgen {
context: "client key generation failed",
source,
})?;
let cert = params
.signed_by(&key_pair, ca_issuer)
.map_err(|source| PkiError::Rcgen {
context: "failed to sign the client certificate",
source,
})?;
Ok((cert, key_pair, params.not_after, common_name))
}
pub struct InMemoryClientBundle {
pub ca_pem: String,
pub ca_fingerprint: tls::Fingerprint,
pub client_cert_pem: String,
pub client_key_pem: String,
pub client_fingerprint: tls::Fingerprint,
pub common_name: String,
}
pub fn issue_client_in_memory(
dir: &Path,
name: &str,
role: PeerRole,
) -> Result<InMemoryClientBundle, PkiError> {
let ca_issuer = load_ca(dir)?;
let (cert, key_pair, _not_after, common_name) = sign_client_leaf(&ca_issuer, name, role)?;
let ca_cert_path = dir.join(CA_CERT_FILE);
let ca_pem = std::fs::read_to_string(&ca_cert_path).map_err(|source| PkiError::Io {
verb: "read",
path: ca_cert_path.clone(),
source,
})?;
let ca_der = tls::load_certs(&ca_cert_path).map_err(|source| PkiError::Certificate {
path: ca_cert_path.clone(),
source,
})?;
let ca_fingerprint = tls::fingerprint(&ca_der[0]);
let client_fingerprint = tls::fingerprint(cert.der());
Ok(InMemoryClientBundle {
ca_pem,
ca_fingerprint,
client_cert_pem: cert.pem(),
client_key_pem: key_pair.serialize_pem(),
client_fingerprint,
common_name,
})
}
#[must_use]
pub fn default_viewer_allowlist_path(ca_path: &Path) -> PathBuf {
viewer_allowlist_in(&role::pki_dir_of(ca_path))
}
#[must_use]
pub fn default_worker_allowlist_path(ca_path: &Path) -> PathBuf {
worker_allowlist_in(&role::pki_dir_of(ca_path))
}