use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail};
use openmoat_audit::{Cached, Event, EventId, Store};
use openmoat_core::rule_id::SESSION_TAINT;
use openmoat_core::{Action, CompiledPolicy, Decision, Staging, Taint, Verdict};
use openmoat_hosts::{HookEvent, Host};
use serde::{Deserialize, Serialize};
use crate::approvals::{self, Grants};
use crate::context;
use crate::home::Home;
use crate::integrity::sha256_hex;
use crate::realpath::FsPathResolver;
pub mod injected;
pub mod issued;
pub mod provenance;
pub mod run;
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionTaint {
pub taint: Taint,
pub untrusted_last_ms: Option<i64>,
pub untrusted_last_row: Option<i64>,
#[serde(default)]
pub staging: Staging,
#[serde(default)]
pub cwdless: bool,
}
pub fn is_dir(path: &str) -> bool {
Path::new(path).is_dir()
}
pub fn of_session(
store: &Store,
host: Host,
session: &str,
policy: &CompiledPolicy<'_>,
cwd: &str,
progress: &mut Progress<'_>,
) -> Result<(SessionTaint, Option<CacheWrite>)> {
fold_session(store, host, session, policy, cwd, progress, Mode::Decide)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Decide,
Exact,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Exact,
Carried,
}
fn fold_session(
store: &Store,
host: Host,
session: &str,
policy: &CompiledPolicy<'_>,
cwd: &str,
progress: &mut Progress<'_>,
mode: Mode,
) -> Result<(SessionTaint, Option<CacheWrite>)> {
let rows = Rows::of(host, policy, cwd)?;
let (mut out, start, kind) = rows.read(store, session, host, mode);
let mut upto = start;
let mut pass = Pass {
deadline: Some(progress.deadline),
..Pass::default()
};
let mut saved = Instant::now();
let write = |out: &SessionTaint, upto: EventId| -> Result<CacheWrite> {
Ok(CacheWrite {
session: session.to_owned(),
host,
cached: Cached {
digest: rows.of_fold(out, kind).to_owned(),
upto,
state: serde_json::to_string(out)?,
},
wait: false,
})
};
loop {
let events = store
.session_page(session, upto, PAGE_LEN)
.context("reading this session from the audit log")?;
let folded = fold(&mut out, &events, host, policy, cwd, &mut pass)?;
progress.folded = pass.folded;
if let Some(last) = events.get(..folded).and_then(<[Event]>::last) {
upto = last.id;
}
if folded < events.len() {
if upto != start {
let mut reached = write(&out, upto)?;
reached.wait = true;
(progress.save)(&reached);
}
bail!("{}", behind(pass.folded));
}
if events.len() < PAGE_LEN {
break;
}
if saved.elapsed() >= progress.every {
(progress.save)(&write(&out, upto)?);
saved = Instant::now();
}
}
let write = if upto == start {
None
} else {
Some(write(&out, upto)?)
};
if openmoat_core::TaintSettings::provenance_on(policy.policy().taint.as_ref())
&& let Some(exposure) = store
.exposure(session, host.id())
.context("reading this session's file provenance from the audit log")?
{
out.taint.untrusted.get_or_insert(exposure.source);
out.untrusted_last_ms = out.untrusted_last_ms.max(Some(exposure.last_ts_ms));
out.untrusted_last_row = out.untrusted_last_row.max(Some(exposure.last_event.0));
}
Ok((out, write))
}
pub fn behind(folded: usize) -> String {
format!(
"OpenMoat was still reading this session's earlier calls from its audit log (it read \
{folded} more for this call) and ran out of time to decide it, so this call was \
stopped, not judged; what was read is kept and the next call reads on from there, so \
run it again"
)
}
pub fn catch_up(
store: &Store,
host: Host,
session: &str,
policy: &CompiledPolicy<'_>,
cwd: &str,
deadline: Instant,
) {
let mut save = |write: &CacheWrite| write.write(store);
let mut progress = Progress {
deadline,
save: &mut save,
every: CHECKPOINT_EVERY,
folded: 0,
};
if let Ok((_, Some(write))) = fold_session(
store,
host,
session,
policy,
cwd,
&mut progress,
Mode::Exact,
) {
write.write(store);
}
}
const PAGE_LEN: usize = 512;
pub const CHECKPOINT_EVERY: Duration = Duration::from_secs(2);
pub struct Progress<'a> {
pub deadline: Instant,
pub save: &'a mut dyn FnMut(&CacheWrite),
pub every: Duration,
pub folded: usize,
}
#[cfg(debug_assertions)]
const CHECKPOINT_ENV: &str = "MOAT_TEST_TAINT_CHECKPOINT_MS";
#[cfg(debug_assertions)]
pub fn checkpoint_every() -> Duration {
std::env::var(CHECKPOINT_ENV)
.ok()
.and_then(|ms| ms.parse().ok())
.map_or(CHECKPOINT_EVERY, Duration::from_millis)
}
#[cfg(not(debug_assertions))]
pub fn checkpoint_every() -> Duration {
CHECKPOINT_EVERY
}
pub struct CacheWrite {
session: String,
host: Host,
cached: Cached,
wait: bool,
}
impl CacheWrite {
pub fn write(&self, store: &Store) {
let _ = if self.wait {
store.set_session_cache(&self.session, self.host.id(), &self.cached)
} else {
store
.try_set_session_cache(&self.session, self.host.id(), &self.cached)
.map(drop)
};
}
pub fn save_in(&self, home: &Home) {
if let Ok(writable) = crate::audit_key::open_existing(home) {
self.write(&writable);
}
}
}
struct Rows {
shared: String,
here: String,
carried_shared: String,
carried_here: String,
}
type Row = (SessionTaint, EventId);
impl Rows {
fn of(host: Host, policy: &CompiledPolicy<'_>, cwd: &str) -> Result<Self> {
let shared = digest(host, policy)?;
let here = sha256_hex(&parts(&[&shared, cwd]));
let carried_shared = sha256_hex(&parts(&[CARRIED, &shared]));
let carried_here = sha256_hex(&parts(&[CARRIED, &here]));
Ok(Self {
shared,
here,
carried_shared,
carried_here,
})
}
fn read(
&self,
store: &Store,
session: &str,
host: Host,
mode: Mode,
) -> (SessionTaint, EventId, Kind) {
let row = |digest: &str| -> Option<Row> {
let cached = store.session_cache(session, host.id(), digest).ok()??;
let state: SessionTaint = serde_json::from_str(&cached.state).ok()?;
Some((state, cached.upto))
};
let exact = Self::best(row(&self.shared), row(&self.here));
let reached = exact.as_ref().map_or(0, |(_, upto)| upto.0);
if mode == Mode::Decide {
let carried = Self::best(row(&self.carried_shared), row(&self.carried_here))
.or_else(|| self.seed(store, session, host));
if let Some((state, upto)) = carried
&& upto.0 > reached
{
return (state, upto, Kind::Carried);
}
}
let (state, upto) = exact.unwrap_or_else(|| (SessionTaint::default(), EventId(0)));
(state, upto, Kind::Exact)
}
fn best(shared: Option<Row>, here: Option<Row>) -> Option<Row> {
let shared = shared.filter(|(state, _)| !state.cwdless);
match (shared, here) {
(Some(shared), Some(here)) => Some(if here.1.0 >= shared.1.0 { here } else { shared }),
(row @ Some(_), None) | (None, row) => row,
}
}
fn seed(&self, store: &Store, session: &str, host: Host) -> Option<Row> {
let ours = [
&self.shared,
&self.here,
&self.carried_shared,
&self.carried_here,
];
store
.session_caches(session, host.id())
.ok()?
.into_iter()
.filter(|cached| !ours.contains(&&cached.digest))
.find_map(|cached| {
let state: SessionTaint = serde_json::from_str(&cached.state).ok()?;
(!state.cwdless).then_some((state, cached.upto))
})
}
fn of_fold(&self, fold: &SessionTaint, kind: Kind) -> &str {
match (kind, fold.cwdless) {
(Kind::Exact, false) => &self.shared,
(Kind::Exact, true) => &self.here,
(Kind::Carried, false) => &self.carried_shared,
(Kind::Carried, true) => &self.carried_here,
}
}
}
const CARRIED: &str = "carried";
fn digest(host: Host, policy: &CompiledPolicy<'_>) -> Result<String> {
let context = openmoat_core::EvalContext {
cwd: String::new(),
..policy.context().clone()
};
Ok(sha256_hex(&parts(&[
FOLD_FORMAT,
crate::VERSION,
host.id(),
&serde_json::to_string(policy.policy())?,
&format!("{context:?}"),
])))
}
const FOLD_FORMAT: &str = "fold-3";
fn parts(parts: &[&str]) -> Vec<u8> {
let mut bytes = Vec::new();
for part in parts {
bytes.extend_from_slice(&part.len().to_le_bytes());
bytes.extend_from_slice(part.as_bytes());
}
bytes
}
#[derive(Default)]
struct Pass {
seen: HashMap<(String, String), (Taint, Staging)>,
deadline: Option<Instant>,
folded: usize,
}
fn fold(
out: &mut SessionTaint,
events: &[Event],
host: Host,
policy: &CompiledPolicy<'_>,
cwd: &str,
pass: &mut Pass,
) -> Result<usize> {
for (taken, event) in events.iter().enumerate() {
if pass.deadline.is_some_and(|d| Instant::now() >= d) {
return Ok(taken);
}
if event.host != host.id() || !ran(host, event.verdict) {
continue;
}
pass.folded += 1;
if event.action_unreadable {
bail!("audit event {} of this session cannot be decoded", event.id);
}
let Some(action) = &event.action else {
continue;
};
out.cwdless |= event.cwd.is_none();
let cwd = event
.cwd
.as_deref()
.map_or_else(|| cwd.to_owned(), |c| context::path_string(Path::new(c)));
let key = (serde_json::to_string(action)?, cwd);
let (exposure, collection) = match pass.seen.entry(key) {
Entry::Occupied(known) => known.get().clone(),
Entry::Vacant(slot) => {
let cwd = &slot.key().1;
let parts = policy.exposure_and_collection(action, cwd, &FsPathResolver, &is_dir);
slot.insert(parts).clone()
}
};
if exposure.untrusted.is_some() {
out.untrusted_last_ms = out.untrusted_last_ms.max(Some(event.ts_ms));
out.untrusted_last_row = out.untrusted_last_row.max(Some(event.id.0));
}
out.taint.absorb(exposure);
out.staging.absorb(collection);
}
Ok(events.len())
}
pub struct Call<'a> {
pub home: &'a Home,
pub store: &'a Store,
pub host: Host,
pub session: &'a str,
pub action: &'a Action,
pub cwd: &'a str,
pub user_home: &'a str,
}
pub fn answered(
call: &Call<'_>,
policy: &CompiledPolicy<'_>,
session: &SessionTaint,
untainted: Decision,
tainted: Decision,
now_ms: i64,
) -> Result<Decision> {
let Some(last_read) = session.untrusted_last_ms else {
return Ok(tainted);
};
if tainted.verdict != Verdict::Review || !tainted.rules.iter().any(|r| r == SESSION_TAINT) {
return Ok(tainted);
}
let secrets_only = Taint {
secrets: session.taint.secrets.clone(),
..Taint::default()
};
let with_secrets = policy.with_taint(
untainted.clone(),
call.action,
&FsPathResolver,
&secrets_only,
);
if with_secrets.rules.iter().any(|r| r == SESSION_TAINT) {
return Ok(tainted);
}
let grants = Grants::load_in(call.home)?;
let read_row = session.untrusted_last_row;
let fresh =
|g: &&approvals::Grant| after_read(g.granted_at_ms, g.audit_row, last_read, read_row);
let project = approvals::project_of(Path::new(call.cwd), Path::new(call.user_home));
let scope = approvals::Scope {
host: call.host.id(),
session_id: call.session,
project: &project,
};
let exact = approvals::approvable(call.action, Some(call.cwd), call.user_home)
.and_then(|reviewed| grants.newest(scope, &reviewed, now_ms).cloned());
if exact.as_ref().is_some_and(|g| fresh(&g)) {
let mut decision = untainted;
decision.reasons.push(
"approved with `openmoat allow` after the session last read untrusted content"
.to_owned(),
);
return Ok(decision);
}
if grants
.covering_taint(scope, now_ms)
.is_some_and(|g| fresh(&g))
{
let mut decision = untainted;
decision.reasons.push(
"the session's protected writes were approved with `openmoat allow` after it last read \
untrusted content"
.to_owned(),
);
return Ok(decision);
}
if let Some(reason) = earlier_write_ran(call, policy, session)? {
let mut decision = untainted;
decision.reasons.push(reason);
return Ok(decision);
}
let mut decision = tainted;
if call.host.spec().reviews.allow_last_hint {
decision.reasons.push(
"to stop these reviews in this session, run `openmoat allow --last` in a terminal"
.to_owned(),
);
}
Ok(decision)
}
fn earlier_write_ran(
call: &Call<'_>,
policy: &CompiledPolicy<'_>,
session: &SessionTaint,
) -> Result<Option<String>> {
let files = provenance::Files::of(policy, call.action);
if files.writes.is_empty() {
return Ok(None);
}
let ci = policy.context().case_insensitive_paths;
let keys: Vec<String> = files
.writes
.iter()
.map(|path| provenance::key(path, ci))
.collect();
let written = call
.store
.session_wrote(call.host.id(), call.session, &keys)
.context("reading the files this session wrote from the audit log")?;
for (path, key) in files.writes.iter().zip(&keys) {
let Some(write) = written.iter().find(|w| &w.path == key) else {
return Ok(None);
};
let after = match (session.untrusted_last_row, session.untrusted_last_ms) {
(Some(read_row), _) => write.event_id.0 > read_row,
(None, Some(read_ms)) => write.ts_ms > read_ms,
(None, None) => false,
};
let (Some(sha256), Some(before)) = (&write.sha256, &write.before) else {
return Ok(None);
};
if !after || sha256 == before || !provenance::holds(path, Some(sha256)) {
return Ok(None);
}
}
let files: Vec<&str> = files.writes.iter().map(String::as_str).collect();
Ok(Some(format!(
"an earlier write of {} in this session was approved after the session last read \
untrusted content",
files.join(", ")
)))
}
fn after_read(granted_ms: i64, seen_row: Option<i64>, read_ms: i64, read_row: Option<i64>) -> bool {
match (seen_row, read_row) {
(Some(seen), Some(read)) => seen >= read,
_ => granted_ms > read_ms,
}
}
pub(crate) fn ran(host: Host, verdict: Verdict) -> bool {
host.answer(&HookEvent::PreToolUse, &Decision::new(verdict))
.verdict
!= Verdict::Deny
}
#[cfg(test)]
mod tests;