use std::fs;
use std::path::Path;
use anyhow::{Context as _, Result, bail};
use openmoat_core::{Action, RuleGroup};
use serde::{Deserialize, Serialize};
use crate::home::write_private;
use crate::time;
mod asked;
pub use asked::{approvable, describe, files};
const GRANTS_VERSION: u32 = 2;
const OVERLAY_VERSION: u32 = 1;
pub const OVERLAY_PREFIX: &str = "approved-";
pub const GRANT_TTL_MS: i64 = 24 * 60 * 60 * 1000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
pub host: String,
pub session_id: String,
pub action: Action,
#[serde(default)]
pub granted_at_ms: i64,
}
#[derive(Deserialize)]
struct GrantV1 {
host: String,
session_id: String,
command: String,
#[serde(default)]
granted_at_ms: i64,
}
#[derive(Deserialize)]
struct GrantsV1 {
entries: Vec<GrantV1>,
}
impl Grant {
#[must_use]
pub fn active(&self, now_ms: i64) -> bool {
(0..GRANT_TTL_MS).contains(&now_ms.saturating_sub(self.granted_at_ms))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grants {
pub version: u32,
pub entries: Vec<Grant>,
}
impl Default for Grants {
fn default() -> Self {
Self {
version: GRANTS_VERSION,
entries: Vec::new(),
}
}
}
impl Grants {
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let text =
fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let parse = || format!("parsing {}", path.display());
let value: serde_json::Value = serde_json::from_str(&text).with_context(parse)?;
match value.get("version").and_then(serde_json::Value::as_u64) {
Some(1) => {
let old: GrantsV1 = serde_json::from_value(value).with_context(parse)?;
let entries = old.entries.into_iter().map(|g| Grant {
host: g.host,
session_id: g.session_id,
action: Action::Shell {
command: g.command.trim().to_owned(),
},
granted_at_ms: g.granted_at_ms,
});
Ok(Self {
version: GRANTS_VERSION,
entries: entries.collect(),
})
}
Some(2) => serde_json::from_value(value).with_context(parse),
version => bail!(
"{} has version {}; this build supports {GRANTS_VERSION}",
path.display(),
version.map_or_else(|| "none".to_owned(), |v| v.to_string())
),
}
}
pub fn save(&mut self, path: &Path, now_ms: i64) -> Result<()> {
self.entries.retain(|g| g.active(now_ms));
write_private(
path,
(serde_json::to_string_pretty(self)? + "\n").as_bytes(),
)
}
pub fn grant(&mut self, host: &str, session_id: &str, action: &Action, now_ms: i64) {
self.entries
.retain(|g| !(g.host == host && g.session_id == session_id && g.action == *action));
self.entries.push(Grant {
host: host.to_owned(),
session_id: session_id.to_owned(),
action: action.clone(),
granted_at_ms: now_ms,
});
}
#[must_use]
pub fn matches(&self, host: &str, session_id: &str, action: &Action, now_ms: i64) -> bool {
self.active(now_ms)
.any(|g| g.host == host && g.session_id == session_id && g.action == *action)
}
pub fn active(&self, now_ms: i64) -> impl Iterator<Item = &Grant> {
self.entries.iter().filter(move |g| g.active(now_ms))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Overlay {
pub version: u32,
#[serde(default)]
pub allow: Vec<RuleGroup>,
}
impl Default for Overlay {
fn default() -> Self {
Self {
version: OVERLAY_VERSION,
allow: Vec::new(),
}
}
}
impl Overlay {
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let text =
fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let overlay: Self = openmoat_core::yaml::from_str(&text)
.with_context(|| format!("parsing {}", path.display()))?;
if overlay.version != OVERLAY_VERSION {
bail!(
"{} has version {}; this build supports {OVERLAY_VERSION}",
path.display(),
overlay.version
);
}
if let Some(bad) = overlay
.allow
.iter()
.find(|g| !g.id.starts_with(OVERLAY_PREFIX))
{
bail!(
"{}: rule `{}` must have an id starting with `{OVERLAY_PREFIX}`",
path.display(),
bad.id
);
}
Ok(overlay)
}
pub fn save(&self, path: &Path) -> Result<()> {
let text = format!(
"# Permanent allow rules added with `moat allow`. Remove one with\n\
# `moat allow --remove <id>`, or edit freely, then run `moat doctor --accept`.\n{}",
openmoat_core::yaml::to_string(self)?
);
write_private(path, text.as_bytes())
}
pub fn allow_command(&mut self, command: &str) -> Result<&RuleGroup> {
let pattern = openmoat_core::literal_shell_pattern(command)
.with_context(|| format!("cannot approve `{command}`"))?;
Ok(self.push("moat allow --always", |g| g.shell = vec![pattern]))
}
pub fn allow_files(&mut self, reads: &[String], writes: &[String]) -> Result<&RuleGroup> {
if let Some(bad) = reads
.iter()
.chain(writes)
.find(|p| p.contains(['*', '?', '[', ']', '{', '}', '\\']))
{
bail!(
"{bad} contains glob characters; write it in the policy with `moat edit` instead"
);
}
Ok(self.push("moat allow --always", |g| {
g.fs_read = reads.to_vec();
g.fs_write = writes.to_vec();
}))
}
#[must_use]
pub fn covers(&self, action: &Action) -> bool {
if let Action::Shell { command } = action {
let pattern = openmoat_core::literal_shell_pattern(command).ok();
return self
.allow
.iter()
.any(|g| pattern.as_ref().is_some_and(|p| g.shell.contains(p)));
}
let (reads, writes) = files(action);
!(reads.is_empty() && writes.is_empty())
&& self.allow.iter().any(|g| {
reads.iter().all(|p| g.fs_read.contains(p))
&& writes.iter().all(|p| g.fs_write.contains(p))
})
}
pub fn allow_site(&mut self, host: &str) -> Result<&RuleGroup> {
let host = host.trim().trim_end_matches('.').to_ascii_lowercase();
let plain = host.split('.').all(|label| {
!label.is_empty() && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
});
if !plain {
bail!(
"`{host}` is not a host name such as docs.rs; wildcards, URLs and ports \
are not accepted here (write those in the policy with `moat edit`)"
);
}
Ok(self.push("moat allow --site", |g| g.net = vec![host]))
}
pub fn allow_dir(&mut self, spellings: &[String]) -> &RuleGroup {
let patterns: Vec<String> = spellings
.iter()
.flat_map(|dir| [dir.clone(), format!("{dir}/**")])
.collect();
let git: Vec<String> = spellings
.iter()
.flat_map(|dir| {
[format!("!{dir}/.git/**"), format!("!{dir}/**/.git/**")]
.into_iter()
.chain(
crate::sandbox::RUNS_LATER
.iter()
.map(move |f| format!("!{dir}/{f}")),
)
})
.collect();
self.push("moat allow --dir", |g| {
g.fs_read.clone_from(&patterns);
g.fs_write = patterns.into_iter().chain(git).collect();
})
}
pub fn remove(&mut self, id: &str) -> Option<RuleGroup> {
let index = self.allow.iter().position(|g| g.id == id)?;
Some(self.allow.remove(index))
}
fn push(&mut self, how: &str, fill: impl FnOnce(&mut RuleGroup)) -> &RuleGroup {
let n = self
.allow
.iter()
.filter_map(|g| g.id.strip_prefix(OVERLAY_PREFIX)?.parse::<u64>().ok())
.max()
.unwrap_or(0)
+ 1;
let mut rule = RuleGroup {
id: format!("{OVERLAY_PREFIX}{n}"),
reason: Some(format!(
"approved with `{how}` on {}",
time::timestamp(time::now_ms())
)),
..RuleGroup::default()
};
fill(&mut rule);
self.allow.push(rule);
&self.allow[self.allow.len() - 1]
}
}
#[cfg(test)]
mod tests;