// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! ```text //! ianitor-control --config run the control plane //! ianitor-control --dev [--edge-bin ] temporary everything on 127.0.0.1 //! ianitor-control token create --name [--expires-days | --never] (--config | --state-dir ) //! ianitor-control token list (--config | --state-dir ) //! ianitor-control token revoke (--config | --state-dir ) //! ianitor-control openapi print the OpenAPI document //! ianitor-control pki approve|deny (--config | --state-dir ) approve a device request //! ianitor-control pki install (--config ) install a signed intermediate //! ianitor-control pki status (--config ) open requests //! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) //! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), //! the binary answers git's prompt from the push credential file. use std::path::PathBuf; use std::process::ExitCode; use ianitor_control::{Config, logger, tokens::Tokens}; mod dev; fn usage() -> ExitCode { eprintln!( "usage: ianitor-control --config | --dev [--edge-bin ] | \ token create --name [--expires-days | --never] (--config | --state-dir ) | \ token list (...) | token revoke (...) | openapi | check --config | \ caddy-revert --config | caddy-guard --config " ); ExitCode::from(2) } fn askpass() -> ExitCode { // git asks "Username for 'https://…':" and "Password for 'https://…':". let prompt = std::env::args().nth(1).unwrap_or_default(); if prompt.starts_with("Username") { println!( "{}", std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default() ); return ExitCode::SUCCESS; } // Answer only the password prompt; anything else (a passphrase, a host key question) // gets no answer, so the push fails instead of handing out the token. if !prompt.starts_with("Password for") { eprintln!("ianitor-control askpass: not answering {prompt:?}"); return ExitCode::FAILURE; } let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else { return ExitCode::FAILURE; }; match std::fs::read_to_string(file) { Ok(v) => { println!("{}", v.trim_end_matches(['\r', '\n'])); ExitCode::SUCCESS } Err(_) => ExitCode::FAILURE, } } fn state_dir(args: &[String]) -> Result { let mut it = args.iter(); while let Some(a) = it.next() { match a.as_str() { "--state-dir" => { return it .next() .map(PathBuf::from) .ok_or("--state-dir needs a path".into()); } "--config" => { let p = it.next().ok_or("--config needs a path")?; return Config::load(&PathBuf::from(p)) .map(|c| c.state_dir) .map_err(|e| e.to_string()); } _ => {} } } Err("give --config or --state-dir ".into()) } /// The token files must stay owned by the user control runs as: refuse to touch them as /// anyone else (typically root), instead of leaving root-owned files control cannot open. #[cfg(unix)] fn same_owner(dir: &std::path::Path) -> Result<(), String> { use std::os::unix::fs::MetadataExt; let existing = dir .ancestors() .find(|p| p.is_dir()) .ok_or_else(|| format!("no part of {} exists", dir.display()))?; let owner = std::fs::metadata(existing) .map_err(|e| format!("cannot read {}: {e}", existing.display()))? .uid(); // Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is // created in the state dir by the wrong user). let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id())); // create_new: never follows or reuses a file someone else put there. let me = std::fs::File::create_new(&probe) .and_then(|f| f.metadata()) .map(|m| m.uid()); if me.is_ok() { let _ = std::fs::remove_file(&probe); } let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?; if me == 0 && !dir.is_dir() { return Err(format!( "{} does not exist; create it as the user control runs as (or run this as that user), not as root", dir.display() )); } if me != owner { return Err(format!( "{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)", existing.display() )); } Ok(()) } #[cfg(not(unix))] fn same_owner(_: &std::path::Path) -> Result<(), String> { Ok(()) } fn token(args: &[String]) -> Result<(), String> { let dir = state_dir(args)?; // Check the owner before creating anything: the nearest existing ancestor must belong to // whoever runs this (so root does not create a state dir control cannot use). same_owner(&dir)?; std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; let tokens = Tokens::new(&dir); match args.first().map(String::as_str) { Some("create") => { let mut name = None; let mut expires = Some(ianitor_control::util::now() + 365 * 86_400); let mut it = args.iter().skip(1); while let Some(a) = it.next() { match a.as_str() { "--name" => name = it.next().cloned(), "--never" => expires = None, "--expires-days" => { let d: u64 = it .next() .and_then(|d| d.parse().ok()) .filter(|d| (1..=3650).contains(d)) .ok_or("--expires-days must be 1 to 3650")?; expires = Some(ianitor_control::util::now() + d * 86_400); } _ => {} } } let name = name.ok_or("--name is required")?; let (rec, value) = tokens.create(&name, expires).map_err(|e| { if e == "token.name" { "the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores" .to_owned() } else { e } })?; eprintln!( "Token {} ({}) created. It is shown once; save it in Custos now:", rec.id, rec.name ); println!("{value}"); Ok(()) } Some("list") => { for t in tokens.list()? { println!( "{} {} created {}{}{}", t.id, t.name, ianitor_control::util::rfc3339(t.created_at), t.expires_at .map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e))) .unwrap_or_default(), t.revoked_at .map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e))) .unwrap_or_default() ); } Ok(()) } Some("revoke") => { let id = args.get(1).ok_or("token revoke ")?; match tokens.revoke(id)? { Some(_) => { eprintln!("Token {id} revoked."); Ok(()) } None => Err(format!("there is no token {id}")), } } _ => Err("token create | list | revoke".into()), } } fn arg_after(args: &[String], name: &str) -> Option { let mut it = args.iter(); while let Some(a) = it.next() { if a == name { return it.next().cloned(); } } None } /// A passphrase from `--passphrase-file`, or asked on the terminal without echo. fn passphrase(args: &[String], confirm: bool) -> Result { if let Some(f) = arg_after(args, "--passphrase-file") { let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?; let v = v.trim_end_matches(['\r', '\n']).to_owned(); if v.chars().count() < 12 { return Err("the passphrase must have at least 12 characters".into()); } return Ok(v); } let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?; if p.chars().count() < 12 { return Err("the passphrase must have at least 12 characters".into()); } if confirm { let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?; if again != p { return Err("the two passphrases differ".into()); } } Ok(p) } /// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the /// server. fn ca(args: &[String]) -> Result<(), String> { use ianitor_core::pki; let now = ianitor_control::util::now() as i64; match args.first().map(String::as_str) { Some("init") => { let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out ")?); let crt = out.join("domi-root.crt"); let key = out.join("domi-root.key"); if crt.exists() || key.exists() { return Err(format!( "{} already has a root; refusing to replace it", out.display() )); } std::fs::create_dir_all(&out).map_err(|e| e.to_string())?; let pass = passphrase(args, true)?; let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?; let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?; ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600) .map_err(|e| e.to_string())?; ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644) .map_err(|e| e.to_string())?; let info = pki::inspect(&cert).map_err(|e| e.to_string())?; eprintln!( "Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\ Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\ Keep domi-root.key and its passphrase offline (Custos, once it can hold it).", out.display(), info.subject_cn, ianitor_core::time::long_date(info.not_after.max(0) as u64), info.sha256_hex ); Ok(()) } Some("sign") => { let root = PathBuf::from( arg_after(args, "--root") .ok_or("ca sign --root --csr --out ")?, ); let csr_path = arg_after(args, "--csr").ok_or("--csr is required")?; let out = PathBuf::from(arg_after(args, "--out").ok_or("--out is required")?); let csr = std::fs::read_to_string(&csr_path) .map_err(|e| format!("cannot read {csr_path}: {e}"))?; let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?); eprintln!("This request's code is {code}. It must be the code Ianitor shows."); if !args.iter().any(|a| a == "--yes") { let typed = rpassword::prompt_password("Type the code to sign (no echo): ") .map_err(|e| e.to_string())?; if ianitor_control::pki::normalise_code(&typed) != ianitor_control::pki::normalise_code(&code) { return Err("the code does not match; nothing was signed".into()); } } let cert = std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?; let sealed = std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?; let pass = passphrase(args, false)?; let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?; let signed = pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?; ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644) .map_err(|e| e.to_string())?; let info = pki::inspect(&signed).map_err(|e| e.to_string())?; eprintln!( "Signed {} until {}. Install it on the server: ianitor-control pki install {}", info.subject_cn, ianitor_core::time::long_date(info.not_after.max(0) as u64), out.display() ); Ok(()) } _ => Err("ca init --out | ca sign --root --csr --out ".into()), } } /// `pki approve|deny|install|status` on the server, as the user control runs as. fn pki_cli(args: &[String]) -> Result<(), String> { let dir = state_dir(args)?; same_owner(&dir)?; let now = ianitor_control::util::now(); match args.first().map(String::as_str) { Some(verb @ ("approve" | "deny")) => { // The code may be given as one word or three (47 19 83). let code: String = args .iter() .skip(1) .take_while(|a| !a.starts_with("--")) .cloned() .collect::>() .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 \"{name}\" ({}).", if state == "approved" { "Approved" } else { "Turned down" }, r.id ); Ok(()) } Some("install") => { let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install ")?; 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 {}; 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") => { let rs: Vec = ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default(); for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) { println!( "{} {} {} code {} until {}", r.id, r.kind, r.name.clone().unwrap_or_default(), r.match_code, ianitor_control::util::rfc3339(r.expires_at) ); } Ok(()) } _ => Err("pki approve | pki deny | pki install | pki status (--config | --state-dir )".into()), } } fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); } logger::init(std::env::var("IANITOR_LOG").ok().as_deref()); let args: Vec = std::env::args().skip(1).collect(); let rt = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() { Ok(r) => r, Err(e) => { eprintln!("ianitor-control: cannot start: {e}"); return ExitCode::FAILURE; } }; let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), Some("pki") => pki_cli(&args[1..]), Some("ca") => ca(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); Ok(()) } Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), // Caddy trial deadline (ianitor_control::caddy_guard): after control stops, and the guard. Some(verb @ ("caddy-revert" | "caddy-guard")) => match args .iter() .position(|a| a == "--config") .and_then(|i| args.get(i + 1)) { Some(p) => match Config::load(&PathBuf::from(p)) { Ok(cfg) if verb == "caddy-guard" => { rt.block_on(ianitor_control::caddy_guard::run(cfg)) } Ok(cfg) => rt .block_on(ianitor_control::caddy_guard::revert_after_stop(&cfg)) .map(|done| { if done { eprintln!("Caddy is back on the last good config."); } }), Err(e) => Err(e.to_string()), }, None => return usage(), }, Some("--dev") => rt.block_on(dev::run(&args[1..])), Some("--config") => match args.get(1) { Some(p) => match Config::load(&PathBuf::from(p)) { Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())), Err(e) => Err(e.to_string()), }, None => return usage(), }, Some("--help" | "-h") | None => return usage(), Some(_) => return usage(), }; match result { Ok(()) => ExitCode::SUCCESS, Err(e) => { log::error!(target: "ianitor::control", "{e}"); eprintln!("ianitor-control: {e}"); ExitCode::FAILURE } } }