[control] QC minors: device install links open a page and download on POST (never listed), approve and install failures show on the request and the CLI waits, PBKDF2 floor, private pki dirs or an error, trusted_proxies for a proxy in front, a placeholder keeps the device allow list from being empty (Caddy refuses that)

This commit is contained in:
2026-11-08 11:02:50 +01:00
parent bc336d1188
commit 3bf5fa0e1a
27 changed files with 548 additions and 46 deletions
+3
View File
@@ -1189,6 +1189,9 @@ pub async fn list_share_links(State(st): Shared) -> Result<Response, ApiError> {
.links
.iter()
.rev()
// A device install link carries its one-time token in the path: never listed. It
// expires within minutes, and "Stop all" stops it with the others.
.filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/"))
.map(|l| ShareLinkView {
id: l.id.clone(),
hostname: l.hostname.clone(),
+80 -3
View File
@@ -616,9 +616,86 @@ async fn bundle_url(st: &AppState, token: &str) -> String {
format!("https://{authority}{path}")
}
/// The one-time download itself. The link is the secret: no token or sign-in is needed, and
/// it works once.
#[utoipa::path(get, path = "/api/v1/device-bundles/{token}", tag = "certs",
/// `GET` on a one-time link: a small page with a Download button that posts back. Link
/// previews and prefetchers only ever GET, so they cannot use up the download.
pub async fn bundle_page(st: Arc<AppState>, token: String) -> Response {
let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit());
let name = if valid {
let ctl = st.ctl.clone();
tokio::task::spawn_blocking(move || {
ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now()))
})
.await
.ok()
.flatten()
} else {
None
};
let (status, body) = match name {
Some(n) => (
StatusCode::OK,
format!(
"<h1>Install the certificate for {}</h1>\
<p>This link works once. After the download, open the file and enter the \
one-time password shown in Ianitor.</p>\
<form method=\"post\"><button type=\"submit\">Download domi-device.p12</button></form>",
html_escape(&n)
),
),
None => (
StatusCode::GONE,
format!(
"<h1>This link has been used</h1><p>{}</p>",
html_escape(&message("pki.bundle_used", &Params::new()))
),
),
};
let page = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
<meta name=\"robots\" content=\"noindex\"><title>Ianitor: device certificate</title>\
<style>body{{margin:0;padding:24px 16px;background:#0f1115;color:#e6e8ee;\
font:16px/1.5 system-ui,sans-serif}}main{{max-width:32rem;margin:0 auto}}\
h1{{font-size:1.25rem}}button{{font:inherit;padding:10px 16px;border-radius:8px;\
border:0;background:#7aa2ff;color:#0f1115;cursor:pointer}}\
button:focus-visible{{outline:2px solid #e6e8ee;outline-offset:2px}}</style>\
</head><body><main>{body}</main></body></html>"
);
let mut r = (status, page).into_response();
let h = r.headers_mut();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
h.insert(
"content-security-policy",
HeaderValue::from_static(
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
),
);
r
}
fn html_escape(s: &str) -> String {
let mut o = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => o.push_str("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&#39;"),
c => o.push(c),
}
}
o
}
/// The one-time download itself (`POST`, from the link's page). The link is the secret: no
/// token or sign-in is needed, and it works once.
#[utoipa::path(post, path = "/api/v1/device-bundles/{token}", tag = "certs",
responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))]
pub async fn download_bundle(
State(st): Shared,
+10 -8
View File
@@ -28,18 +28,20 @@ pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) ->
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
.into_response();
}
if req.method() != axum::http::Method::GET {
return ApiError::new(
let token = token.to_owned();
// GET shows the page; only its button (POST) uses the link up.
return match req.method().as_str() {
"GET" | "HEAD" => super::pki::bundle_page(st, token).await,
"POST" => super::pki::download_bundle(State(st), AxPath(token))
.await
.unwrap_or_else(IntoResponse::into_response),
_ => ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
.into_response();
}
let token = token.to_owned();
return super::pki::download_bundle(State(st), AxPath(token))
.await
.unwrap_or_else(IntoResponse::into_response);
.into_response(),
};
}
if path.starts_with("/api/") || path == "/api" {
return next.run(req).await;
+16
View File
@@ -113,6 +113,9 @@ pub struct Compile {
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
#[serde(default)]
pub trusted_proxies: Vec<std::net::IpAddr>,
}
impl Compile {
@@ -126,6 +129,7 @@ impl Compile {
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
}
}
}
@@ -227,6 +231,15 @@ impl Config {
"routes.push_credential must be a plain credential name".into(),
));
}
// The keys at rest are only as strong as this; only test builds may lower it.
if let Some(p) = &self.pki
&& p.kdf_iterations < MIN_KDF_ITERATIONS
&& !cfg!(feature = "test-hooks")
{
return Err(ConfigError::Invalid(format!(
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
)));
}
if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options())
@@ -295,6 +308,9 @@ fn empty_model() -> Option<ianitor_core::Model> {
.ok()
}
/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256).
pub const MIN_KDF_ITERATIONS: u32 = 600_000;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkiConfig {
+7 -1
View File
@@ -149,13 +149,19 @@ pub async fn run(args: &[String]) -> Result<(), String> {
caddy_credentials_dir: s("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
},
compile_caddy: None,
pki: Some(ianitor_control::config::PkiConfig {
root_cert: dir.join("offline-root/domi-root.crt"),
password_credential: "pki-password".into(),
approval: "manual".into(),
kdf_iterations: 10_000,
// Fast in test builds; the real floor in a release build.
kdf_iterations: if cfg!(feature = "test-hooks") {
10_000
} else {
ianitor_control::config::MIN_KDF_ITERATIONS
},
}),
ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
hostname: None,
+10 -4
View File
@@ -330,10 +330,13 @@ fn pki_cli(args: &[String]) -> Result<(), String> {
.collect::<Vec<_>>()
.join("");
let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
let name = r.name.clone().unwrap_or_default();
eprintln!("Handed to control; waiting for it ...");
let state = ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?;
eprintln!(
"{} the request for \"{}\" ({}). Control acts on it within a few seconds.",
if verb == "deny" { "Turned down" } else { "Approved" },
r.name.unwrap_or_default(),
"{} the request for \"{name}\" ({}).",
if state == "approved" { "Approved" } else { "Turned down" },
r.id
);
Ok(())
@@ -342,7 +345,10 @@ fn pki_cli(args: &[String]) -> Result<(), String> {
let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install <intermediate.crt>")?;
let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
eprintln!("Handed to renewal {}. Control installs it within a few seconds.", r.id);
eprintln!("Handed to renewal {}; waiting for control to install it ...", r.id);
ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not installed: {e}"))?;
eprintln!("Installed. Server certificates are reissued from it now.");
Ok(())
}
Some("status") => {
+101 -3
View File
@@ -100,9 +100,13 @@ pub struct Request {
/// Renewals: when the new intermediate expires, once installed.
#[serde(default)]
pub not_after: Option<i64>,
/// Why it failed (plain English, no secrets).
/// 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,
@@ -314,7 +318,8 @@ impl Pki {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700));
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700))
.map_err(|e| format!("cannot make {} private: {e}", d.display()))?;
}
}
Ok(Pki {
@@ -485,6 +490,7 @@ impl Pki {
csr_pem: Some(csr),
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
prune(&mut rs, now);
@@ -539,6 +545,8 @@ impl Pki {
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();
@@ -605,12 +613,29 @@ impl Pki {
// while no intermediate exists, and the empty allow list still lets no one in.
ca.push_str(&self.root_pem);
}
let allow: String = self
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),
@@ -686,6 +711,7 @@ impl Pki {
csr_pem: None,
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
rs.push(r.clone());
@@ -749,6 +775,7 @@ impl Pki {
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;
}
@@ -764,6 +791,7 @@ impl Pki {
Ok(_) => changes.intermediate = true,
Err(e) => {
log::warn!(target: "ianitor::pki", "intermediate for {rid} not installed: {e}");
self.note_problem(&rid, &e, now);
}
}
}
@@ -791,6 +819,26 @@ impl Pki {
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()?;
@@ -866,6 +914,8 @@ impl Pki {
}
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)?;
@@ -929,6 +979,24 @@ impl Pki {
/// 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"))?;
@@ -1084,3 +1152,33 @@ pub fn cli_install(state_dir: &Path, cert_pem: &str, now: u64) -> Result<Request
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));
}
}