use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use anyhow::{Result, bail};
use openmoat_core::rule_id::KERNEL_INTEGRITY;
use openmoat_core::{Decision, Verdict};
use openmoat_hosts::{InstallSpec, RelaxedCheck, RelaxedKey};
use serde_json::{Map, Value};
use super::keys::{differing, object_digests};
use super::spec_keys;
use super::{Drift, Kept, Lock, deny_for};
use crate::home::Home;
use crate::install::Recorded;
#[derive(Debug, Default)]
pub struct Checked {
pub deny: Option<Decision>,
pub relaxed: Vec<Drift>,
}
#[derive(Debug)]
pub struct Verified {
pub lock: Lock,
pub home: Home,
pub checked: Checked,
}
pub fn check(home: &Home) -> Result<Verified> {
let lock_path = home.lock_path();
if !lock_path.is_file() {
bail!(
"no policy lock at {}; run `openmoat init`",
lock_path.display()
);
}
let lock = Lock::load(&lock_path)?;
let (drift, home) = super::verify_state(home, &lock);
let mut checked = split(&home, &lock, drift);
if checked.deny.is_none()
&& let Some(reason) = super::binary::check(&home, &lock).deny_reason()
{
checked.deny = Some(Decision::single(Verdict::Deny, KERNEL_INTEGRITY, reason));
}
Ok(Verified {
lock,
home,
checked,
})
}
pub fn split(home: &Home, lock: &Lock, drift: Vec<Drift>) -> Checked {
if drift.is_empty() {
return Checked::default();
}
let kept = home.kept();
let relaxed =
Recorded::load(home).is_ok_and(|r| drift.iter().all(|d| is_relaxed(lock, d, &r, kept)));
if relaxed {
Checked {
deny: None,
relaxed: drift,
}
} else {
Checked {
deny: deny_for(&drift),
relaxed: Vec::new(),
}
}
}
pub(super) fn parent_digests(
path: &Path,
install: &InstallSpec,
) -> Option<BTreeMap<String, String>> {
if install.relaxed_check != RelaxedCheck::ByKey
|| !fs::symlink_metadata(path).ok()?.file_type().is_file()
{
return None;
}
let root = object(&fs::read(path).ok()?)?;
let parent = RelaxedCheck::parent(install.relaxed_keys)?;
object_digests(root.get(parent)?.as_object()?, &[])
}
fn is_relaxed(lock: &Lock, drift: &Drift, recorded: &Recorded, kept: &Kept) -> bool {
let Drift::KeysChanged(path, _) = drift else {
return false;
};
let stored = path.to_string_lossy();
let (Some(host), Some(bytes)) = (lock.hook_owner(&stored), kept.drifted(path)) else {
return false;
};
let Some(install) = lock.relaxing(&stored) else {
return false;
};
let owned = recorded.written_rules(host);
match install.relaxed_check {
RelaxedCheck::Rest => lock
.relaxed_rest
.get(stored.as_ref())
.is_some_and(|pinned| spec_keys::only_relaxed(bytes, install, pinned)),
RelaxedCheck::ByKey => by_key(lock, &stored, bytes, install, owned),
_ => false,
}
}
fn by_key(
lock: &Lock,
stored: &str,
bytes: &[u8],
install: &InstallSpec,
owned: &[String],
) -> bool {
let Some(pinned) = lock.keys.get(stored) else {
return false;
};
let Some(root) = object(bytes) else {
return false;
};
let Some(now) = object_digests(&root, install.unpinned_keys) else {
return false;
};
let keys = install.relaxed_keys;
let parent = RelaxedCheck::parent(keys);
differing(pinned, &now).all(|key| {
if parent == Some(key.as_str()) {
let pinned_inner = lock.permission_keys.get(stored);
inner_relaxed(
pinned_inner,
pinned.contains_key(key),
key,
&root,
keys,
owned,
)
} else {
relaxed_value(keys, None, key, root.get(key), owned)
}
})
}
fn relaxed_value(
keys: &[RelaxedKey],
parent: Option<&str>,
name: &str,
value: Option<&Value>,
owned: &[String],
) -> bool {
keys.iter().any(|k| {
let at = match k.path.split_once('.') {
Some((outer, inner)) => parent == Some(outer) && inner == name,
None => parent.is_none() && k.path == name,
};
at && match value {
Some(value) => k.shape.holds(value, owned),
None => k.shape.may_be_removed(),
}
})
}
fn object(bytes: &[u8]) -> Option<Map<String, Value>> {
match serde_json::from_slice(bytes).ok()? {
Value::Object(root) => Some(root),
_ => None,
}
}
fn inner_relaxed(
pinned: Option<&BTreeMap<String, String>>,
had_parent: bool,
parent: &str,
root: &Map<String, Value>,
keys: &[RelaxedKey],
owned: &[String],
) -> bool {
let empty = Map::new();
let now = match root.get(parent) {
None => &empty,
Some(Value::Object(inner)) => inner,
Some(_) => return false,
};
let none = BTreeMap::new();
let pinned = match pinned {
Some(pinned) => pinned,
None if !had_parent => &none,
None => return false,
};
let Some(digests) = object_digests(now, &[]) else {
return false;
};
differing(pinned, &digests)
.all(|key| relaxed_value(keys, Some(parent), key, now.get(key), owned))
}
#[cfg(test)]
mod tests;