mod trust;
use std::path::PathBuf;
use anyhow::{Context as _, Result, bail};
use openmoat_core::Policy;
use openmoat_proxy::{CA_VALID_DAYS, CaFiles, Roots, Tls};
pub use self::trust::Trust;
use crate::home::Home;
use crate::integrity::Lock;
const EXPIRY_NOTICE_DAYS: i64 = 30;
const MS_PER_DAY: i64 = 86_400_000;
pub fn cert_path(home: &Home) -> PathBuf {
home.root().join("proxy-ca").join("ca.pem")
}
pub fn key_path(home: &Home) -> PathBuf {
home.root().join("proxy-ca").join("key.pem")
}
pub fn files(home: &Home) -> Vec<PathBuf> {
vec![cert_path(home), key_path(home)]
}
pub fn terminated_hosts(policy: &Policy) -> Vec<String> {
let mut hosts: Vec<String> = policy
.secrets
.iter()
.filter(|s| s.terminates())
.map(|s| s.host.clone())
.chain(request_hosts(policy))
.collect();
hosts.sort();
hosts.dedup();
hosts
}
pub fn request_hosts(policy: &Policy) -> Vec<String> {
openmoat_core::RequestRules::for_proxy(&policy.requests)
.map(|rules| rules.hosts())
.unwrap_or_default()
}
pub fn pinned_cert(home: &Home) -> Option<String> {
let lock = Lock::load(&home.lock_path()).ok()?;
if !files(home).iter().all(|f| lock.pins(f) && f.is_file()) {
return None;
}
std::fs::read_to_string(cert_path(home)).ok()
}
pub const EXFIL_PACK: &str = "exfil-endpoints";
pub fn status_lines(home: &Home, policy: &Policy) -> Vec<(bool, String)> {
let Some(cert) = pinned_cert(home) else {
return Vec::new();
};
let mut lines = Vec::new();
let hosts = request_hosts(policy);
if !hosts.is_empty() {
let tls = crate::key_file::read(&key_path(home))
.ok()
.and_then(|key| Tls::new(&cert, &key, &Roots::System, &[]).ok());
let uncovered: Vec<&str> = hosts
.iter()
.filter(|h| !tls.as_ref().is_some_and(|t| t.covers(h)))
.map(String::as_str)
.collect();
if uncovered.is_empty() {
lines.push((
true,
format!("request rules: the proxy CA covers {}", hosts.join(", ")),
));
} else {
lines.push((
false,
format!(
"request rules: the proxy CA does not cover {}, so the proxy refuses their \
connections (`requests_untrusted`); run `openmoat proxy ca init` in a \
terminal",
uncovered.join(", ")
),
));
}
}
let installed = crate::packs::Packs::load(&home.packs_path())
.is_ok_and(|packs| packs.packs.contains_key(EXFIL_PACK));
if !installed && !hosts.is_empty() {
lines.push((
false,
format!(
"request rules: a proxy CA exists, but the `{EXFIL_PACK}` pack is not installed, \
so the proxy holds none of its endpoint rules for {}; install it signed by \
whoever distributes it: `openmoat policy install {EXFIL_PACK}.yaml`",
hosts.join(", ")
),
));
}
lines
}
pub fn load_for_requests(home: &Home, policy: &Policy) -> (Option<Tls>, Option<String>) {
let hosts = request_hosts(policy);
if hosts.is_empty() {
return (None, None);
}
let untrusted = match policy.requests_untrusted() {
openmoat_core::RequestsUntrusted::Refuse => "refused",
openmoat_core::RequestsUntrusted::Relay => "relayed unread",
};
let pinned = Lock::load(&home.lock_path())
.is_ok_and(|lock| files(home).iter().all(|f| lock.pins(f) && f.is_file()));
let loaded = if pinned {
std::fs::read_to_string(cert_path(home))
.map_err(anyhow::Error::from)
.and_then(|cert| Ok((cert, crate::key_file::read(&key_path(home))?)))
.and_then(|(cert, key)| Ok(Tls::new(&cert, &key, &Roots::System, &hosts)?))
} else {
Err(anyhow::Error::msg("there is no pinned proxy CA yet"))
};
match loaded {
Ok(tls) => (
Some(tls),
Some(format!(
"moat proxy: note: {} have request rules: HTTPS there is read for the sessions \
that received the proxy CA (from their agent's session-start hook); the \
connections of other sessions are {untrusted} (`requests_untrusted`)",
hosts.join(", ")
)),
),
Err(why) => (
None,
Some(format!(
"moat proxy: WARNING: {} have request rules, but {why:#}: run `openmoat proxy ca \
init` in a terminal (again, when a host was added since); until then their \
connections are {untrusted} (`requests_untrusted`)",
hosts.join(", ")
)),
),
}
}
fn date(ts_ms: i64) -> String {
crate::time::rfc3339(ts_ms)[..10].to_owned()
}
pub fn cert_text(ca: &CaFiles, hosts: &[String], now_ms: i64) -> String {
format!(
"# OpenMoat proxy CA, made by `openmoat proxy ca init` on {}\n\
# valid until {}, and only for: {}\n\
# trusted only by the commands `openmoat run` starts (ADR-043), and those of a \
session given its per-session trust files (ADR-062)\n{}",
date(now_ms),
date(now_ms + CA_VALID_DAYS * MS_PER_DAY),
hosts.join(", "),
ca.cert_pem
)
}
pub fn valid_until(text: &str) -> Option<&str> {
text.lines()
.find_map(|l| l.strip_prefix("# valid until "))
.and_then(|rest| rest.get(..10))
}
pub struct Loaded {
pub tls: Tls,
pub cert_pem: String,
pub notice: Option<String>,
}
pub fn load(home: &Home, policy: &Policy) -> Result<Option<Loaded>> {
let hosts = terminated_hosts(policy);
if hosts.is_empty() {
return Ok(None);
}
let again = "run `openmoat proxy ca init` in a terminal";
let lock = Lock::load(&home.lock_path())?;
if !files(home).iter().all(|f| lock.pins(f) && f.is_file()) {
bail!(
"TLS to {} is terminated (`tls: terminate`, or `requests:` without `hook_only`), but \
there is no pinned proxy CA yet: {again}",
hosts.join(", ")
);
}
let cert = std::fs::read_to_string(cert_path(home))
.with_context(|| format!("reading {}", cert_path(home).display()))?;
let key = crate::key_file::read(&key_path(home))?;
let tls = Tls::new(&cert, &key, &Roots::System, &hosts).with_context(|| {
format!(
"the proxy CA cannot be used for {} (a host added since it was made needs a new \
one); {again}",
hosts.join(", ")
)
})?;
let now = crate::time::now_ms();
let notice = valid_until(&cert)
.filter(|until| *until <= date(now + EXPIRY_NOTICE_DAYS * MS_PER_DAY).as_str())
.map(|until| {
format!("moat run: the proxy CA expires on {until}; {again} to make a new one")
});
Ok(Some(Loaded {
tls,
cert_pem: cert,
notice,
}))
}
#[cfg(test)]
mod tests;