Files
ianitor/crates/control/src/pki.rs
T

1256 lines
47 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The Domi CA on the server (ROADMAP §1.2, §3): the intermediate, the server certificates
//! of `tls = "domi"` hosts, device certificates and their install files, and the requests
//! that need an approval.
//!
//! Files, under `<state_dir>/pki/` (mode 0700):
//!
//! ```text
//! intermediate.crt the current intermediate (public)
//! intermediate.key its key, encrypted (IANITOR ENCRYPTED PRIVATE KEY, password from
//! the `pki-password` credential); never in plain text on disk
//! previous.crt the one before, while it is still valid (device CA bundle)
//! pending-<id>.key the new key of an open renewal, encrypted the same way
//! requests.json approval requests (devices, renewals)
//! devices.json issued device certificates
//! devices/<id>.key a device's key, encrypted, kept to make its install file again
//! approvals/<id>.approve written by `ianitor-control pki approve` (the manual approval)
//! approvals/<id>.deny written by `ianitor-control pki deny`
//! approvals/<id>.crt the signed intermediate, from `pki install` or the API
//! ```
//!
//! The root key is never here: control only reads the root *certificate* named in
//! control.toml, and refuses to start if a root key file appears in its state directory.
//!
//! Approvals: ROADMAP §4 says "approve in Custos". Custos has no such operation yet
//! (docs/custos-ticket.md), so until it does a request is approved on the server with the
//! match code the UI shows: `ianitor-control pki approve 47 19 83`. The intermediate is
//! signed offline (docs/pki.md).
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use ianitor_core::pki::{self, Intermediate, PkiError};
use serde::{Deserialize, Serialize};
use crate::config::PkiConfig;
use crate::util::{hex, random, read_json, remove_if_exists, write_atomic, write_json};
/// How long a device request waits for its approval.
pub const DEVICE_REQUEST_SECS: u64 = 600;
/// How long a renewal waits for the offline signature.
pub const RENEWAL_REQUEST_SECS: u64 = 7 * 86_400;
/// How long a device install link works.
pub const BUNDLE_SECS: u64 = 600;
/// Banner thresholds.
pub const DUE_DAYS: i64 = 30;
pub const URGENT_DAYS: i64 = 7;
/// Most open requests at once.
const MAX_OPEN: usize = 20;
/// Most devices with certificates (active or not) kept in the list.
const MAX_DEVICES: usize = 500;
/// Device kinds the UI offers.
pub const DEVICE_KINDS: [&str; 3] = ["phone", "computer", "app"];
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PkiFail {
/// A refusal with a stable code for the API (`pki.*`).
#[error("{0}")]
Code(&'static str),
#[error("{0}")]
Internal(String),
}
impl From<PkiError> for PkiFail {
fn from(e: PkiError) -> Self {
PkiFail::Internal(e.to_string())
}
}
fn io(e: impl std::fmt::Display) -> PkiFail {
PkiFail::Internal(e.to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Request {
pub id: String,
/// `device` or `intermediate`.
pub kind: String,
/// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`.
pub state: String,
pub match_code: String,
pub created_at: u64,
pub expires_at: u64,
#[serde(default)]
pub approved_at: Option<u64>,
/// Device requests: the name and kind asked for, and the device made.
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub device_kind: Option<String>,
#[serde(default)]
pub device_id: Option<String>,
/// Renewals: the CSR to sign offline.
#[serde(default)]
pub csr_pem: Option<String>,
/// Renewals: when the new intermediate expires, once installed.
#[serde(default)]
pub not_after: Option<i64>,
/// Why it failed, or why the last approval or install for it was not used (plain
/// English, no secrets). A request that is still waiting can carry one.
#[serde(default)]
pub error: Option<String>,
/// When `error` was last set for a request that is still waiting (the CLI waits for it).
#[serde(default)]
pub problem_at: Option<u64>,
/// Who asked (token name or signed-in user).
#[serde(default)]
pub actor: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Device {
pub id: String,
pub name: String,
pub kind: String,
pub serial: String,
pub sha256: String,
pub cert_pem: String,
pub created_at: u64,
pub not_after: i64,
#[serde(default)]
pub revoked_at: Option<u64>,
/// Which intermediate issued it (its SHA-256).
pub issuer_sha256: String,
}
impl Device {
pub fn state(&self, now: u64) -> &'static str {
if self.revoked_at.is_some() {
"revoked"
} else if self.not_after <= now as i64 {
"expired"
} else {
"valid"
}
}
}
/// A one-time install file waiting to be downloaded.
struct Bundle {
device_id: String,
password: String,
expires_at: u64,
}
/// What the main screen shows about the intermediate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntermediateStatus {
/// `ok`, `due`, `urgent`, `expired` or `missing` (no intermediate yet).
pub state: &'static str,
pub subject: Option<String>,
pub not_after: Option<i64>,
pub days_left: Option<i64>,
pub renewal: Option<Request>,
}
/// What changed in one poll.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Changes {
pub devices: bool,
pub intermediate: bool,
}
pub struct Pki {
dir: PathBuf,
root_pem: String,
password: Option<Vec<u8>>,
kdf_iterations: u32,
lock: Mutex<()>,
current: Mutex<Option<Arc<Intermediate>>>,
bundles: Mutex<HashMap<String, Bundle>>,
}
impl std::fmt::Debug for Pki {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pki").field("dir", &self.dir).finish()
}
}
fn id(prefix: &str) -> Result<String, PkiFail> {
Ok(format!("{prefix}{}", hex(&random::<6>().map_err(io)?)))
}
/// `47 19 83` from random bytes (device requests have no CSR to hash).
fn random_code() -> Result<String, PkiFail> {
let b = random::<3>().map_err(io)?;
Ok(format!(
"{:02} {:02} {:02}",
b[0] % 100,
b[1] % 100,
b[2] % 100
))
}
/// Digits only: `47 19 83`, `471983` and `47-19-83` are the same code.
pub fn normalise_code(c: &str) -> String {
c.chars().filter(char::is_ascii_digit).collect()
}
/// A readable one-time password for an install file: 4 groups of 4 from 30 letters and
/// digits without look-alikes (about 78 bits).
fn bundle_password() -> Result<String, PkiFail> {
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let b = random::<16>().map_err(io)?;
let mut s = String::new();
for (i, x) in b.iter().enumerate() {
if i > 0 && i % 4 == 0 {
s.push('-');
}
s.push(char::from(ALPHABET[(*x as usize) % ALPHABET.len()]));
}
Ok(s)
}
/// Private keys in `dir` that are not control's own: control refuses to run with one in its
/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`); the only keys
/// allowed are `pki/intermediate.key`, `pki/pending-*.key` and `pki/devices/*.key`, and those
/// must hold exactly one key in control's own encrypted armour, nothing else. A symbolic link
/// is never followed and never skipped: it is reported. Git's object store (`*.git/objects`,
/// compressed history) is not read.
pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
let allowed = |p: &Path| -> bool {
let Ok(rel) = p.strip_prefix(dir) else {
return false;
};
let parts: Vec<String> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
match parts
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.as_slice()
{
["pki", "intermediate.key"] => true,
["pki", f] => f.starts_with("pending-") && f.ends_with(".key"),
["pki", "devices", f] => f.ends_with(".key"),
_ => false,
}
};
let own_armour = |b: &[u8]| -> bool {
let t = String::from_utf8_lossy(b);
let begins = t.matches("-----BEGIN ").count();
let ours = t.matches(OWN_BEGIN).count();
begins == 1 && ours == 1 && t.matches(KEY_MARK).count() == 2
};
let mut found = Vec::new();
let mut stack = vec![(dir.to_path_buf(), 0)];
while let Some((d, depth)) = stack.pop() {
let Ok(rd) = std::fs::read_dir(&d) else {
continue;
};
for e in rd.flatten() {
let p = e.path();
// symlink_metadata: a link is looked at, not followed.
let Ok(meta) = std::fs::symlink_metadata(&p) else {
continue;
};
if meta.file_type().is_symlink() {
found.push(p);
continue;
}
if meta.is_dir() {
let git_objects =
e.file_name() == "objects" && d.extension().is_some_and(|x| x == "git");
if depth < 8 && !git_objects {
stack.push((p, depth + 1));
}
continue;
}
if !meta.is_file() {
continue;
}
let read = || {
(meta.len() <= 1 << 20)
.then(|| std::fs::read(&p).ok())
.flatten()
};
if allowed(&p) {
// Control's own key files: one key, in control's encrypted armour.
if !read().is_some_and(|b| own_armour(&b)) {
found.push(p);
}
continue;
}
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
let by_name = name.contains("root") && name.contains("key");
let by_content =
read().is_some_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
if by_name || by_content {
found.push(p);
}
}
}
found
}
// Split so that this file does not match the pre-commit hook itself.
const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----");
const OWN_BEGIN: &str = concat!("-----BEGIN IANITOR ENCRYPTED ", "PRIVATE KEY-----");
impl Pki {
/// Open the CA state. The root certificate must be a CA and self-signed; the password
/// credential may be missing (then nothing can be issued, and the UI says why).
pub fn open(
cfg: &PkiConfig,
state_dir: &Path,
password: Option<Vec<u8>>,
) -> Result<Pki, String> {
let keys = root_key_files(state_dir);
if !keys.is_empty() {
return Err(format!(
"{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.",
keys[0].display()
));
}
let root_pem = std::fs::read_to_string(&cfg.root_cert).map_err(|e| {
format!(
"cannot read the Domi root certificate {}: {e}",
cfg.root_cert.display()
)
})?;
let info =
pki::inspect(&root_pem).map_err(|e| format!("{}: {e}", cfg.root_cert.display()))?;
if !info.is_ca || !pki::issued_by(&root_pem, &root_pem).unwrap_or(false) {
return Err(format!(
"{} is not a self-signed CA certificate",
cfg.root_cert.display()
));
}
if root_pem.contains("PRIVATE KEY") {
return Err(format!(
"{} contains a private key; give control the root certificate only",
cfg.root_cert.display()
));
}
let dir = state_dir.join("pki");
for d in [dir.clone(), dir.join("devices"), dir.join("approvals")] {
std::fs::create_dir_all(&d)
.map_err(|e| format!("cannot create {}: {e}", d.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700))
.map_err(|e| format!("cannot make {} private: {e}", d.display()))?;
}
}
Ok(Pki {
dir,
root_pem: pki::first_pem(&root_pem).map_err(|e| e.to_string())?,
password: password.filter(|p| !p.is_empty()),
kdf_iterations: cfg.kdf_iterations,
lock: Mutex::new(()),
current: Mutex::new(None),
bundles: Mutex::new(HashMap::new()),
})
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn root_pem(&self) -> &str {
&self.root_pem
}
fn password(&self) -> Result<&[u8], PkiFail> {
self.password
.as_deref()
.ok_or(PkiFail::Code("pki.no_password"))
}
fn seal(&self, key: &pki::KeyPair) -> Result<String, PkiFail> {
Ok(pki::encrypt_key_with(
key,
self.password()?,
self.kdf_iterations,
)?)
}
fn open_key(&self, path: &Path) -> Result<pki::KeyPair, PkiFail> {
let sealed = std::fs::read_to_string(path).map_err(io)?;
pki::decrypt_key(&sealed, self.password()?).map_err(|e| match e {
PkiError::WrongPassword => PkiFail::Code("pki.wrong_password"),
other => PkiFail::Internal(other.to_string()),
})
}
fn guard(&self) -> Result<std::sync::MutexGuard<'_, ()>, PkiFail> {
self.lock.lock().map_err(|_| io("pki lock"))
}
fn requests(&self) -> Result<Vec<Request>, PkiFail> {
Ok(read_json(&self.dir.join("requests.json"))
.map_err(io)?
.unwrap_or_default())
}
fn save_requests(&self, r: &[Request]) -> Result<(), PkiFail> {
write_json(&self.dir.join("requests.json"), &r).map_err(io)
}
pub fn devices(&self) -> Result<Vec<Device>, PkiFail> {
Ok(read_json(&self.dir.join("devices.json"))
.map_err(io)?
.unwrap_or_default())
}
fn save_devices(&self, d: &[Device]) -> Result<(), PkiFail> {
write_json(&self.dir.join("devices.json"), &d).map_err(io)
}
// -------------------------------------------------------------- the intermediate
/// The current intermediate, unlocked once and kept in memory. `None` before the first
/// one is installed.
pub fn intermediate(&self) -> Result<Option<Arc<Intermediate>>, PkiFail> {
if let Some(i) = self.current.lock().map_err(|_| io("pki"))?.as_ref() {
return Ok(Some(i.clone()));
}
let crt = self.dir.join("intermediate.crt");
if !crt.exists() {
return Ok(None);
}
let pem = std::fs::read_to_string(&crt).map_err(io)?;
let key = self.open_key(&self.dir.join("intermediate.key"))?;
let int = Arc::new(Intermediate::new(&pem, key)?);
if !pki::issued_by(int.cert_pem(), &self.root_pem)? {
return Err(PkiFail::Code("pki.not_our_root"));
}
*self.current.lock().map_err(|_| io("pki"))? = Some(int.clone());
Ok(Some(int))
}
/// The intermediate's public certificate, readable without the password.
pub fn intermediate_info(&self) -> Option<pki::CertInfo> {
let pem = std::fs::read_to_string(self.dir.join("intermediate.crt")).ok()?;
pki::inspect(&pem).ok()
}
pub fn status(&self, now: u64) -> IntermediateStatus {
let renewal = self.requests().ok().and_then(|rs| {
rs.into_iter()
.rev()
.find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now)
});
match self.intermediate_info() {
None => IntermediateStatus {
state: "missing",
subject: None,
not_after: None,
days_left: None,
renewal,
},
Some(i) => {
let left = (i.not_after - now as i64).div_euclid(86_400);
let state = if i.not_after <= now as i64 {
"expired"
} else if left <= URGENT_DAYS {
"urgent"
} else if left <= DUE_DAYS {
"due"
} else {
"ok"
};
IntermediateStatus {
state,
subject: Some(i.subject_cn),
not_after: Some(i.not_after),
days_left: Some(left.max(0)),
renewal,
}
}
}
}
/// Start a renewal (or the first intermediate): a new key, encrypted at rest, and a CSR
/// to be signed by the root. An open renewal is returned again rather than replaced.
pub fn request_renewal(&self, now: u64, actor: &str) -> Result<Request, PkiFail> {
let _g = self.guard()?;
self.password()?;
let mut rs = self.requests()?;
if let Some(r) = rs
.iter()
.rev()
.find(|r| r.kind == "intermediate" && r.state == "waiting" && r.expires_at > now)
{
return Ok(r.clone());
}
let key = pki::generate_key()?;
let (y, m, _) = ymd(now);
let cn = format!("{} {y:04}-{m:02}", pki::INTERMEDIATE_CN);
let csr = pki::intermediate_csr(&key, &cn)?;
let code = pki::match_code(&pki::csr_der(&csr)?);
let rid = id("pr_")?;
write_atomic(
&self.dir.join(format!("pending-{rid}.key")),
self.seal(&key)?.as_bytes(),
0o600,
)
.map_err(io)?;
let r = Request {
id: rid,
kind: "intermediate".into(),
state: "waiting".into(),
match_code: code,
created_at: now,
expires_at: now + RENEWAL_REQUEST_SECS,
approved_at: None,
name: None,
device_kind: None,
device_id: None,
csr_pem: Some(csr),
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
prune(&mut rs, now);
rs.push(r.clone());
self.save_requests(&rs)?;
Ok(r)
}
/// Install a signed intermediate for an open renewal (from `pki install` or the API).
/// Checks: signed by our root, a CA with path length 0, for the pending key, valid now.
pub fn install_intermediate(
&self,
request_id: &str,
cert_pem: &str,
now: u64,
) -> Result<Request, PkiFail> {
let _g = self.guard()?;
let mut rs = self.requests()?;
let r = rs
.iter_mut()
.find(|r| r.id == request_id && r.kind == "intermediate")
.ok_or(PkiFail::Code("pki.request_not_found"))?;
if r.state != "waiting" || r.expires_at <= now {
return Err(PkiFail::Code("pki.request_closed"));
}
let first = pki::first_pem(cert_pem).map_err(|_| PkiFail::Code("pki.bad_certificate"))?;
let info = pki::inspect(&first).map_err(|_| PkiFail::Code("pki.bad_certificate"))?;
// Everything a hand-signed certificate can get wrong, before anything is reissued from it.
if let Some(problem) = pki::intermediate_problem(&first, &self.root_pem, now as i64) {
return Err(PkiFail::Code(match problem {
"not_root" => "pki.not_our_root",
"not_ca" => "pki.manual.not_ca",
"eku" => "pki.manual.eku",
"dates" => "pki.manual.dates",
_ => "pki.bad_certificate",
}));
}
let pending = self.dir.join(format!("pending-{request_id}.key"));
let key = self.open_key(&pending)?;
let int = Intermediate::new(&first, key).map_err(|e| match e {
PkiError::KeyMismatch => PkiFail::Code("pki.wrong_key"),
other => PkiFail::Internal(other.to_string()),
})?;
// Keep the old one for the device CA bundle while it is valid.
let crt = self.dir.join("intermediate.crt");
if let Ok(old) = std::fs::read_to_string(&crt) {
write_atomic(&self.dir.join("previous.crt"), old.as_bytes(), 0o644).map_err(io)?;
}
let sealed = std::fs::read(&pending).map_err(io)?;
write_atomic(&self.dir.join("intermediate.key"), &sealed, 0o600).map_err(io)?;
write_atomic(&crt, first.as_bytes(), 0o644).map_err(io)?;
remove_if_exists(&pending).map_err(io)?;
*self.current.lock().map_err(|_| io("pki"))? = Some(Arc::new(int));
r.state = "approved".into();
r.error = None;
r.problem_at = None;
r.approved_at = Some(now);
r.not_after = Some(info.not_after);
let out = r.clone();
self.save_requests(&rs)?;
Ok(out)
}
// -------------------------------------------------------------- server certificates
/// Make sure every `tls = "domi"` host has a certificate from the current intermediate
/// with at least [`pki::SERVER_RENEW_DAYS`] left. Returns the hosts that got a new one.
/// Files: `<cert_dir>/<host>.crt` (leaf + intermediate, 0644), `<host>.key` (0640).
pub fn ensure_host_certs(
&self,
hosts: &[String],
cert_dir: &Path,
now: u64,
) -> Result<Vec<String>, PkiFail> {
if hosts.is_empty() {
return Ok(Vec::new());
}
let int = self
.intermediate()?
.ok_or(PkiFail::Code("pki.no_intermediate"))?;
let mut issued = Vec::new();
for h in hosts {
let crt = cert_dir.join(format!("{h}.crt"));
let key = cert_dir.join(format!("{h}.key"));
let fine = std::fs::read_to_string(&crt).ok().is_some_and(|pem| {
pki::inspect(&pem).is_ok_and(|i| {
i.dns_names.iter().any(|n| n == h)
&& i.not_after - now as i64 > i64::from(pki::SERVER_RENEW_DAYS) * 86_400
&& i.not_before <= now as i64 + 300
}) && pki::issued_by(&pem, int.cert_pem()).unwrap_or(false)
}) && key.exists();
if fine {
continue;
}
let leaf = pki::issue_server(&int, h, now as i64).map_err(|e| match e {
PkiError::IssuerExpired => PkiFail::Code("pki.intermediate_expired"),
other => PkiFail::Internal(other.to_string()),
})?;
// Key first: a certificate never points at a key that is not there yet.
write_atomic(&key, leaf.key_pem.as_bytes(), 0o640).map_err(io)?;
write_atomic(&crt, leaf.chain_pem.as_bytes(), 0o644).map_err(io)?;
issued.push(h.clone());
}
Ok(issued)
}
/// Write the device CA bundle and allow list into the certificate directory (what both
/// engines read). Returns whether either changed.
pub fn write_device_files(&self, cert_dir: &Path, now: u64) -> Result<bool, PkiFail> {
let mut ca = String::new();
for f in ["intermediate.crt", "previous.crt"] {
if let Ok(pem) = std::fs::read_to_string(self.dir.join(f))
&& pki::inspect(&pem).is_ok_and(|i| i.not_after > now as i64)
{
ca.push_str(&pem);
}
}
if ca.is_empty() {
// Edge and Caddy refuse an empty bundle; the root keeps the bundle parseable
// while no intermediate exists, and the empty allow list still lets no one in.
ca.push_str(&self.root_pem);
}
let mut allow: String = self
.devices()?
.iter()
.filter(|d| d.state(now) == "valid")
.map(|d| d.cert_pem.as_str())
.collect();
if allow.is_empty() {
// Caddy refuses an empty leaf list (and the whole config with it): the list
// holds a certificate no one has the key to. Made once, so the file stays put.
let p = self.dir.join("no-device.crt");
allow = match std::fs::read_to_string(&p) {
Ok(pem) if pki::inspect(&pem).is_ok_and(|i| i.subject_cn == pki::NO_DEVICE_CN) => {
pem
}
_ => {
let pem = pki::no_device_placeholder(now as i64).map_err(|e| {
PkiFail::Internal(format!("cannot make the placeholder: {e}"))
})?;
write_atomic(&p, pem.as_bytes(), 0o644).map_err(io)?;
pem
}
};
}
let mut changed = false;
for (name, text) in [
(ianitor_core::compile::DEVICE_CA_FILE, ca),
(ianitor_core::compile::DEVICE_ALLOW_FILE, allow),
] {
let p = cert_dir.join(name);
if std::fs::read_to_string(&p).ok().as_deref() != Some(text.as_str()) {
write_atomic(&p, text.as_bytes(), 0o644).map_err(io)?;
changed = true;
}
}
Ok(changed)
}
// -------------------------------------------------------------- devices
pub fn request_device(
&self,
name: &str,
kind: &str,
now: u64,
actor: &str,
) -> Result<Request, PkiFail> {
let _g = self.guard()?;
let name = name.trim();
if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) {
return Err(PkiFail::Code("pki.device_name"));
}
if !DEVICE_KINDS.contains(&kind) {
return Err(PkiFail::Code("pki.device_kind"));
}
if self.intermediate_info().is_none() {
return Err(PkiFail::Code("pki.no_intermediate"));
}
self.password()?;
let taken = |n: &str| n.to_lowercase() == name.to_lowercase();
if self
.devices()?
.iter()
.any(|d| d.state(now) == "valid" && taken(&d.name))
{
return Err(PkiFail::Code("pki.device_name_taken"));
}
let mut rs = self.requests()?;
prune(&mut rs, now);
if rs.iter().any(|r| {
r.kind == "device" && r.state == "waiting" && r.name.as_deref().is_some_and(taken)
}) {
return Err(PkiFail::Code("pki.device_name_taken"));
}
if rs.iter().filter(|r| r.state == "waiting").count() >= MAX_OPEN {
return Err(PkiFail::Code("pki.too_many_requests"));
}
// A code no other open request has, so `pki approve <code>` is never ambiguous.
let mut code = random_code()?;
while rs
.iter()
.any(|r| r.state == "waiting" && normalise_code(&r.match_code) == normalise_code(&code))
{
code = random_code()?;
}
let r = Request {
id: id("pr_")?,
kind: "device".into(),
state: "waiting".into(),
match_code: code,
created_at: now,
expires_at: now + DEVICE_REQUEST_SECS,
approved_at: None,
name: Some(name.to_owned()),
device_kind: Some(kind.to_owned()),
device_id: None,
csr_pem: None,
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
rs.push(r.clone());
self.save_requests(&rs)?;
Ok(r)
}
pub fn request(&self, id: &str, now: u64) -> Result<Option<Request>, PkiFail> {
Ok(self
.requests()?
.into_iter()
.find(|r| r.id == id)
.map(|mut r| {
if r.state == "waiting" && r.expires_at <= now {
r.state = "expired".into();
}
r
}))
}
pub fn cancel(&self, id: &str) -> Result<Option<Request>, PkiFail> {
let _g = self.guard()?;
let mut rs = self.requests()?;
let Some(r) = rs.iter_mut().find(|r| r.id == id) else {
return Ok(None);
};
if r.state == "waiting" {
r.state = "cancelled".into();
if r.kind == "intermediate" {
remove_if_exists(&self.dir.join(format!("pending-{id}.key"))).map_err(io)?;
}
}
let out = r.clone();
self.save_requests(&rs)?;
Ok(Some(out))
}
/// Act on approvals and expiries. Called every couple of seconds by control.
pub fn poll(&self, now: u64) -> Result<Changes, PkiFail> {
let mut changes = Changes::default();
let approvals = self.dir.join("approvals");
let ids: Vec<String> = {
let mut v = Vec::new();
if let Ok(rd) = std::fs::read_dir(&approvals) {
for e in rd.flatten() {
v.push(e.file_name().to_string_lossy().into_owned());
}
}
v
};
for f in ids {
let path = approvals.join(&f);
let Some((rid, what)) = f.rsplit_once('.') else {
let _ = remove_if_exists(&path);
continue;
};
let rid = rid.to_owned();
match what {
"approve" => {
let code = std::fs::read_to_string(&path).unwrap_or_default();
let _ = remove_if_exists(&path);
if let Err(e) = self.approve_device(&rid, code.trim(), now) {
log::warn!(target: "ianitor::pki", "approval for {rid} not used: {e}");
self.note_problem(&rid, &e, now);
} else {
changes.devices = true;
}
}
"deny" => {
let _ = remove_if_exists(&path);
self.close(&rid, "denied", None)?;
}
"crt" => {
let pem = std::fs::read_to_string(&path).unwrap_or_default();
let _ = remove_if_exists(&path);
match self.install_intermediate(&rid, &pem, now) {
Ok(_) => changes.intermediate = true,
Err(e) => {
log::warn!(target: "ianitor::pki", "intermediate for {rid} not installed: {e}");
self.note_problem(&rid, &e, now);
}
}
}
_ => {
let _ = remove_if_exists(&path);
}
}
}
// Expire what waited too long.
let _g = self.guard()?;
let mut rs = self.requests()?;
let mut dirty = false;
for r in rs.iter_mut() {
if r.state == "waiting" && r.expires_at <= now {
r.state = "expired".into();
dirty = true;
if r.kind == "intermediate" {
let _ = remove_if_exists(&self.dir.join(format!("pending-{}.key", r.id)));
}
}
}
if dirty {
self.save_requests(&rs)?;
}
Ok(changes)
}
/// An approval or install for a waiting request was not used: say why on the request
/// (the UI and the CLI show it), and keep it open for another try.
fn note_problem(&self, rid: &str, e: &PkiFail, now: u64) {
let text = match e {
PkiFail::Code(c) => crate::messages::message(c, &crate::messages::Params::new()),
PkiFail::Internal(_) => {
crate::messages::message("internal", &crate::messages::Params::new())
}
};
let Ok(_g) = self.guard() else { return };
let Ok(mut rs) = self.requests() else { return };
if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") {
r.error = Some(text);
r.problem_at = Some(now);
if let Err(e) = self.save_requests(&rs) {
log::error!(target: "ianitor::pki", "cannot record the problem on {rid}: {e}");
}
}
}
fn close(&self, rid: &str, state: &str, error: Option<String>) -> Result<(), PkiFail> {
let _g = self.guard()?;
let mut rs = self.requests()?;
if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") {
r.state = state.into();
r.error = error;
if r.kind == "intermediate" {
let _ = remove_if_exists(&self.dir.join(format!("pending-{rid}.key")));
}
self.save_requests(&rs)?;
}
Ok(())
}
/// Issue the device certificate of an approved request. The code must match.
fn approve_device(&self, rid: &str, code: &str, now: u64) -> Result<Device, PkiFail> {
let int = self
.intermediate()?
.ok_or(PkiFail::Code("pki.no_intermediate"))?;
let _g = self.guard()?;
let mut rs = self.requests()?;
let r = rs
.iter_mut()
.find(|r| r.id == rid && r.kind == "device")
.ok_or(PkiFail::Code("pki.request_not_found"))?;
if r.state != "waiting" || r.expires_at <= now {
return Err(PkiFail::Code("pki.request_closed"));
}
if normalise_code(code) != normalise_code(&r.match_code) {
return Err(PkiFail::Code("pki.wrong_code"));
}
let name = r.name.clone().unwrap_or_default();
let kind = r.device_kind.clone().unwrap_or_else(|| "app".into());
let leaf = match pki::issue_device(&int, &name, now as i64) {
Ok(l) => l,
Err(e) => {
r.state = "failed".into();
r.error = Some(e.to_string());
self.save_requests(&rs)?;
return Err(e.into());
}
};
let did = id("dv_")?;
write_atomic(
&self.dir.join(format!("devices/{did}.key")),
self.seal(&leaf.key)?.as_bytes(),
0o600,
)
.map_err(io)?;
let d = Device {
id: did.clone(),
name,
kind,
serial: leaf.serial_hex.clone(),
sha256: leaf.sha256_hex.clone(),
cert_pem: leaf.cert_pem.clone(),
created_at: now,
not_after: leaf.not_after,
revoked_at: None,
issuer_sha256: int.info().sha256_hex.clone(),
};
let mut ds = self.devices()?;
ds.push(d.clone());
// Keep the list bounded: forget the oldest revoked or expired ones first.
while ds.len() > MAX_DEVICES {
match ds.iter().position(|x| x.state(now) != "valid") {
Some(i) => {
let gone = ds.remove(i);
let _ = remove_if_exists(&self.dir.join(format!("devices/{}.key", gone.id)));
}
None => break,
}
}
self.save_devices(&ds)?;
r.state = "approved".into();
r.error = None;
r.problem_at = None;
r.approved_at = Some(now);
r.device_id = Some(did);
self.save_requests(&rs)?;
Ok(d)
}
pub fn revoke(&self, device_id: &str, now: u64) -> Result<Option<Device>, PkiFail> {
let _g = self.guard()?;
let mut ds = self.devices()?;
let Some(d) = ds.iter_mut().find(|d| d.id == device_id) else {
return Ok(None);
};
if d.revoked_at.is_none() {
d.revoked_at = Some(now);
}
let out = d.clone();
self.save_devices(&ds)?;
// The key is no longer needed: no new install file for a revoked device.
remove_if_exists(&self.dir.join(format!("devices/{device_id}.key"))).map_err(io)?;
if let Ok(mut b) = self.bundles.lock() {
b.retain(|_, x| x.device_id != device_id);
}
Ok(Some(out))
}
// -------------------------------------------------------------- install files
/// A one-time install link for a device: `(token, password, expires_at)`.
pub fn make_bundle(&self, device_id: &str, now: u64) -> Result<(String, String, u64), PkiFail> {
let d = self
.devices()?
.into_iter()
.find(|d| d.id == device_id)
.ok_or(PkiFail::Code("pki.device_not_found"))?;
if d.state(now) != "valid" {
return Err(PkiFail::Code("pki.device_not_valid"));
}
if !self.dir.join(format!("devices/{device_id}.key")).exists() {
return Err(PkiFail::Code("pki.device_not_valid"));
}
let token = hex(&random::<32>().map_err(io)?);
let password = bundle_password()?;
let expires_at = now + BUNDLE_SECS;
let mut b = self.bundles.lock().map_err(|_| io("bundles"))?;
b.retain(|_, x| x.expires_at > now);
// One open link per device: a new one replaces the old.
b.retain(|_, x| x.device_id != device_id);
if b.len() >= 100 {
return Err(PkiFail::Code("pki.too_many_requests"));
}
b.insert(
token.clone(),
Bundle {
device_id: device_id.to_owned(),
password: password.clone(),
expires_at,
},
);
Ok((token, password, expires_at))
}
/// Hand out an install file once: the PKCS#12 bytes and the device name. The token is
/// gone afterwards, whatever happens.
/// Whether a one-time link is still unused and in time (the device name, for its page),
/// without using it up.
pub fn peek_bundle(&self, token: &str, now: u64) -> Option<String> {
let device_id = {
let m = self.bundles.lock().ok()?;
let b = m.get(token)?;
if b.expires_at <= now {
return None;
}
b.device_id.clone()
};
self.devices()
.ok()?
.into_iter()
.find(|d| d.id == device_id && d.state(now) == "valid")
.map(|d| d.name)
}
pub fn take_bundle(&self, token: &str, now: u64) -> Result<(Vec<u8>, String), PkiFail> {
let b = {
let mut m = self.bundles.lock().map_err(|_| io("bundles"))?;
m.remove(token)
};
let b = b.ok_or(PkiFail::Code("pki.bundle_used"))?;
if b.expires_at <= now {
return Err(PkiFail::Code("pki.bundle_used"));
}
let d = self
.devices()?
.into_iter()
.find(|d| d.id == b.device_id && d.state(now) == "valid")
.ok_or(PkiFail::Code("pki.device_not_valid"))?;
let key = self.open_key(&self.dir.join(format!("devices/{}.key", d.id)))?;
let issuer = if self
.intermediate_info()
.is_some_and(|i| i.sha256_hex == d.issuer_sha256)
{
std::fs::read_to_string(self.dir.join("intermediate.crt")).map_err(io)?
} else {
std::fs::read_to_string(self.dir.join("previous.crt")).map_err(io)?
};
let p12 = pkcs12(&d, &key, &issuer, &self.root_pem, &b.password)?;
Ok((p12, d.name))
}
}
/// A PKCS#12 file with the device key and its chain (leaf, intermediate, root), encrypted
/// with AES-256 (PBES2) and a SHA-256 MAC.
fn pkcs12(
d: &Device,
key: &pki::KeyPair,
issuer_pem: &str,
root_pem: &str,
password: &str,
) -> Result<Vec<u8>, PkiFail> {
use p12_keystore::{
Certificate, EncryptionAlgorithm, KeyStore, KeyStoreEntry, MacAlgorithm, PrivateKey,
PrivateKeyChain,
};
let mut certs = Vec::new();
for pem in [d.cert_pem.as_str(), issuer_pem, root_pem] {
for der in pki::chain_der(pem)? {
certs.push(Certificate::from_der(&der).map_err(io)?);
}
}
let local_id = ring::digest::digest(&ring::digest::SHA256, d.cert_pem.as_bytes());
let chain = PrivateKeyChain::new(
&local_id.as_ref()[..20],
PrivateKey::from_der(&key.serialize_der()).map_err(io)?,
certs,
);
let mut ks = KeyStore::new();
ks.add_entry(&d.name, KeyStoreEntry::PrivateKeyChain(chain));
ks.writer(password)
.encryption_algorithm(EncryptionAlgorithm::PbeWithHmacSha256AndAes256)
.encryption_iterations(10_000)
.mac_algorithm(MacAlgorithm::HmacSha256)
.mac_iterations(10_000)
.write()
.map_err(io)
}
/// A QR code (SVG) for a URL, for the install dialog.
pub fn qr_svg(data: &str) -> Result<String, PkiFail> {
let code = qrcode::QrCode::with_error_correction_level(data, qrcode::EcLevel::M).map_err(io)?;
Ok(code
.render::<qrcode::render::svg::Color<'_>>()
.min_dimensions(240, 240)
.quiet_zone(true)
.build())
}
/// Forget closed requests beyond the newest 200.
fn prune(rs: &mut Vec<Request>, _now: u64) {
let closed = rs.iter().filter(|r| r.state != "waiting").count();
if closed > 200 {
let mut drop = closed - 200;
rs.retain(|r| {
if drop > 0 && r.state != "waiting" {
drop -= 1;
false
} else {
true
}
});
}
}
fn ymd(unix: u64) -> (i64, u32, u32) {
// Reuse core's calendar via its RFC 3339 text.
let s = ianitor_core::time::rfc3339(unix);
let y = s.get(0..4).and_then(|v| v.parse().ok()).unwrap_or(1970);
let m = s.get(5..7).and_then(|v| v.parse().ok()).unwrap_or(1);
let d = s.get(8..10).and_then(|v| v.parse().ok()).unwrap_or(1);
(y, m, d)
}
// ------------------------------------------------------------------ the manual approval CLI
/// `ianitor-control pki approve <code>`: write an approval for the open device request with
/// this code. Run on the server by Mark, as the user control runs as.
pub fn cli_approve(state_dir: &Path, code: &str, deny: bool, now: u64) -> Result<Request, String> {
let dir = state_dir.join("pki");
let rs: Vec<Request> = read_json(&dir.join("requests.json"))?.unwrap_or_default();
let want = normalise_code(code);
if want.len() != 6 {
return Err("the code has six digits, like 47 19 83".into());
}
let r = rs
.into_iter()
.find(|r| {
r.kind == "device"
&& r.state == "waiting"
&& r.expires_at > now
&& normalise_code(&r.match_code) == want
})
.ok_or("no open device request has this code (it may have expired)")?;
let file = dir.join("approvals").join(format!(
"{}.{}",
r.id,
if deny { "deny" } else { "approve" }
));
write_atomic(&file, want.as_bytes(), 0o600).map_err(|e| e.to_string())?;
Ok(r)
}
/// `ianitor-control pki install <cert.pem>`: hand a signed intermediate to the open renewal
/// whose key it carries.
pub fn cli_install(state_dir: &Path, cert_pem: &str, now: u64) -> Result<Request, String> {
let dir = state_dir.join("pki");
let rs: Vec<Request> = read_json(&dir.join("requests.json"))?.unwrap_or_default();
let spki = pki::public_key_der(cert_pem).map_err(|e| e.to_string())?;
let r = rs
.into_iter()
.find(|r| {
r.kind == "intermediate"
&& r.state == "waiting"
&& r.expires_at > now
&& r
.csr_pem
.as_deref()
.and_then(|c| pki::csr_public_key_der(c).ok())
.is_some_and(|k| k == spki)
})
.ok_or("no open renewal matches this certificate's key (was it signed from the current request?)")?;
let file = dir.join("approvals").join(format!("{}.crt", r.id));
write_atomic(&file, cert_pem.as_bytes(), 0o600).map_err(|e| e.to_string())?;
Ok(r)
}
pub fn requests_path(state_dir: &Path) -> PathBuf {
state_dir.join("pki/requests.json")
}
/// After `pki approve` or `pki install`: wait (up to 20 s) for control to act on it. `Ok` with
/// the request's new state, or `Err` with why it was not used.
pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result<String, String> {
let path = requests_path(state_dir);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
loop {
let rs: Vec<Request> = read_json(&path)?.unwrap_or_default();
match rs.iter().find(|r| r.id == rid) {
None => return Err("the request is gone (it may have expired)".into()),
Some(r) if r.state != "waiting" => {
return match (&r.error, r.state.as_str()) {
(Some(e), s) if s != "approved" => Err(e.clone()),
_ => Ok(r.state.clone()),
};
}
Some(r) if r.problem_at.is_some_and(|t| t >= since) => {
return Err(r.error.clone().unwrap_or_else(|| "it was not used".into()));
}
Some(_) => {}
}
if std::time::Instant::now() >= deadline {
return Err(
"control has not acted on it within 20 s; is ianitor-control running? It still will when it starts"
.into(),
);
}
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
#[cfg(test)]
mod root_key_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn allowed_paths_hold_only_our_armour_links_are_reported_and_git_objects_are_not_read() {
let dir = std::env::temp_dir().join(format!("ianitor-rk-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("pki/devices")).unwrap();
std::fs::create_dir_all(dir.join("routes.git/objects/ab")).unwrap();
let key = pki::generate_key().unwrap();
let sealed = pki::encrypt_key_with(&key, b"pw", 1000).unwrap();
let plain = key.serialize_pem();
std::fs::write(dir.join("pki/intermediate.key"), &sealed).unwrap();
std::fs::write(dir.join("pki/devices/d1.key"), &sealed).unwrap();
// Git's store is not read (a blob could hold anything, compressed or not).
std::fs::write(dir.join("routes.git/objects/ab/cdef"), &plain).unwrap();
assert!(
root_key_files(&dir).is_empty(),
"{:?}",
root_key_files(&dir)
);
// A plain key, or a second block, in an allowed place is not ours.
std::fs::write(dir.join("pki/pending-x.key"), &plain).unwrap();
std::fs::write(dir.join("pki/devices/d2.key"), format!("{sealed}{plain}")).unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink("/nonexistent/domi-root.key", dir.join("pki/devices/d3.key"))
.unwrap();
let found = root_key_files(&dir);
assert!(found.contains(&dir.join("pki/pending-x.key")), "{found:?}");
assert!(found.contains(&dir.join("pki/devices/d2.key")), "{found:?}");
#[cfg(unix)]
assert!(found.contains(&dir.join("pki/devices/d3.key")), "{found:?}");
assert!(
!found.contains(&dir.join("pki/intermediate.key")),
"{found:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
}