use anyhow::{Result, bail};
use openmoat_core::ir::{Checker, Effect, Enforcement};
use openmoat_core::{AtomicAction, Kind};
use super::Rules;
use crate::sandbox::Report;
use crate::sandbox::bwrap::{Mount, without_runs_later};
use crate::sandbox::patterns::{Spot, folders_above, has_glob, is_below, push_unique, split, spot};
pub const ENTRIES_LOSS: &str = "landlock.project-entries";
const PROBE: &str = "__moat_probe__";
const MAX_RULES: usize = 100_000;
pub fn split_project(
ir: &Enforcement,
rules: &mut Rules,
report: &mut Report,
project: &[String],
) -> Result<()> {
let Some(real) = project.first() else {
return Ok(());
};
let spelling = |p: &String| project.contains(p) || resolved(p) == *real;
let writable = rules.write.iter().any(spelling);
let granted = writable || rules.read.iter().any(spelling);
let around = |list: &[String]| -> Vec<(String, String)> {
list.iter()
.map(|g| (g.clone(), resolved(g)))
.filter(|(_, r)| is_below(real, r))
.collect()
};
let (read_above, write_above) = (around(&rules.read), around(&rules.write));
if !granted && read_above.is_empty() && write_above.is_empty() {
return Ok(());
}
let ir = without_runs_later(ir);
let checker = ir.checker()?;
let above = |p: &String, list: &[(String, String)]| list.iter().any(|(g, _)| g == p);
rules
.read
.retain(|p| !spelling(p) && !above(p, &read_above));
rules
.write
.retain(|p| !spelling(p) && !above(p, &write_above));
let mut split = Split {
checker: &checker,
holders: holders(&ir, project),
real,
rules,
count: 0,
};
for (trees, writable) in [(&read_above, false), (&write_above, true)] {
for (_, tree) in trees {
split.around(tree, writable)?;
}
}
split.dir(real, writable || !write_above.is_empty())?;
let message = "Landlock grants a folder with everything in it, so the project is granted \
entry by entry: commands cannot create, rename or remove entries directly in \
it or in the folders that hold an agent's settings, `.env` files there stay \
unreadable and `.git` and `.moat` read-only; create what a command needs \
there before the run, or install bubblewrap for a view that needs none of this";
report.loss(Kind::FsWrite, ENTRIES_LOSS, message.to_owned());
Ok(())
}
fn holders(ir: &Enforcement, project: &[String]) -> Vec<String> {
let mut found = Vec::new();
let accesses = [&ir.fs.read, &ir.fs.write];
for access in accesses {
let denied = access.deny.iter().flat_map(|r| split(&r.patterns).0);
let excepted = access.allow.iter().flat_map(|r| split(&r.patterns).1);
for pattern in denied.chain(excepted) {
let in_project = project
.iter()
.find_map(|p| pattern.strip_prefix(p.as_str())?.strip_prefix('/'));
let rest = in_project.or(match spot(pattern) {
Spot::Anywhere(rest) => Some(rest),
Spot::Project(_) | Spot::Absolute(_) => None,
});
let Some(rest) = rest.map(|r| r.trim_start_matches("**/")) else {
continue;
};
for folder in folders_above(rest) {
if !has_glob(&folder) {
push_unique(&mut found, folder);
}
}
}
}
found
}
struct Split<'a> {
checker: &'a Checker,
holders: Vec<String>,
real: &'a str,
rules: &'a mut Rules,
count: usize,
}
impl Split<'_> {
fn allowed(&self, kind: Kind, path: &str) -> bool {
let atom = match kind {
Kind::FsWrite => AtomicAction::FsWrite {
path: path.to_owned(),
},
_ => AtomicAction::FsRead {
path: path.to_owned(),
},
};
self.checker.check_os(&atom) == Some(Effect::Allow)
}
fn allowed_all(&self, kind: Kind, path: &str, dir: bool) -> bool {
let below = || self.allowed(kind, &format!("{path}/{PROBE}"));
self.allowed(kind, path) && (!dir || below())
}
fn rule(&mut self, list: fn(&mut Rules) -> &mut Vec<String>, path: String) -> Result<()> {
self.count += 1;
if self.count > MAX_RULES {
bail!(
"granting the project entry by entry would need more than {MAX_RULES} Landlock \
rules; install bubblewrap (`apt install bubblewrap`) so `openmoat run` can \
cover what the policy denies with mounts instead"
);
}
push_unique(list(self.rules), path);
Ok(())
}
fn dir(&mut self, dir: &str, writable: bool) -> Result<()> {
self.rule(|r| &mut r.list, dir.to_owned())?;
for (name, is_dir) in entries(dir)? {
let path = join(dir, &name);
if !self.allowed_all(Kind::FsRead, &path, is_dir) {
continue;
}
let rest = &path[self.real.len() + 1..];
if is_dir && self.holders.iter().any(|h| h == rest) {
self.dir(&path, writable)?;
continue;
}
self.rule(|r| &mut r.read, path.clone())?;
if writable && self.allowed_all(Kind::FsWrite, &path, is_dir) {
self.rule(|r| &mut r.write, path)?;
}
}
Ok(())
}
fn around(&mut self, tree: &str, writable: bool) -> Result<()> {
let mut dir = tree.to_owned();
while dir != self.real {
let Some(rest) = self.real.strip_prefix(dir.trim_end_matches('/')) else {
break;
};
let rest = rest.trim_start_matches('/');
let next = join(&dir, rest.split('/').next().unwrap_or(rest));
self.rule(|r| &mut r.list, dir.clone())?;
for (name, _) in entries(&dir)? {
let path = join(&dir, &name);
if path == next {
continue;
}
self.rule(|r| &mut r.read, path.clone())?;
if writable {
self.rule(|r| &mut r.write, path)?;
}
}
dir = next;
}
Ok(())
}
}
pub fn resolved(path: &str) -> String {
std::fs::canonicalize(path).map_or_else(
|_| path.to_owned(),
|real| crate::context::path_string(&real),
)
}
fn join(dir: &str, name: &str) -> String {
format!("{}/{name}", dir.trim_end_matches('/'))
}
fn entries(dir: &str) -> Result<Vec<(String, bool)>> {
let mut found = Vec::new();
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_symlink() {
continue;
}
if let Ok(name) = entry.file_name().into_string() {
found.push((name, kind.is_dir()));
}
}
found.sort();
Ok(found)
}
pub fn open(masks: &[Mount], rules: &Rules) -> Vec<String> {
let resolve = |list: &[String]| list.iter().map(|g| resolved(g)).collect::<Vec<_>>();
let (read, write) = (resolve(&rules.read), resolve(&rules.write));
let covers = |list: &[String], path: &str| list.iter().any(|g| g == path || is_below(path, g));
let readable = |p: &str| covers(&read, p) || covers(&write, p);
let mut found = Vec::new();
for mask in masks {
let open = match mask {
Mount::Hide { path, .. } => readable(path).then_some(path),
Mount::ReadOnly(path) => covers(&write, path).then_some(path),
Mount::ReadWrite(path) => {
let parent = path.rsplit_once('/').map_or("/", |(p, _)| p);
covers(&write, parent).then_some(path)
}
Mount::Tmpfs(_) => None,
};
if let Some(path) = open {
push_unique(&mut found, path.clone());
}
}
found
}
#[cfg(test)]
mod tests;