pub mod backend;
#[cfg(any(target_os = "linux", all(test, unix)))]
pub mod bwrap;
pub mod claude;
pub mod codex;
pub mod cursor;
#[cfg(test)]
mod differential;
pub mod exposure;
pub mod git_env;
#[cfg(test)]
mod hook_only;
pub mod install;
pub mod kerberos;
pub mod landlock;
mod links;
pub mod linux_needs;
pub mod own_login;
mod patterns;
pub(crate) use patterns::RUNS_LATER;
mod plan;
pub use plan::Plan;
pub mod seatbelt;
#[cfg(any(target_os = "linux", test))]
pub mod seccomp;
pub mod shared_temp;
#[cfg(any(windows, test))]
pub mod write_token;
pub fn backend_of(format: openmoat_hosts::SandboxFormat) -> &'static dyn backend::SandboxBackend {
use openmoat_hosts::SandboxFormat;
match format {
SandboxFormat::ClaudeSettings => &claude::backend::BACKEND,
SandboxFormat::CodexProfile => &codex::backend::BACKEND,
SandboxFormat::CursorSandbox => &cursor::backend::BACKEND,
}
}
use openmoat_core::ir::{Access, Allowance, Effect, Enforcement, Loss};
use openmoat_core::rule_id::DEFAULT_NET;
use openmoat_core::{EvalContext, Policy, PolicyError};
use serde::Serialize;
pub const PROJECT: &str = "/__moat_project__";
pub fn proxy_port(policy: &Policy) -> Option<u16> {
policy
.sandbox
.as_ref()
.and_then(|s| s.proxy_port)
.map(std::num::NonZeroU16::get)
}
pub fn lower_for_hosts(
policy: &Policy,
home: &str,
real_home: Option<String>,
moved_dirs: Vec<(String, String)>,
case_insensitive_paths: bool,
) -> Result<Enforcement, PolicyError> {
openmoat_core::ir::lower(
policy,
&EvalContext {
home: home.to_owned(),
project: Some(PROJECT.to_owned()),
real_home,
real_project: None,
moved_dirs,
cwd: PROJECT.to_owned(),
case_insensitive_paths,
},
)
}
fn with_read_roots(policy: &Policy) -> anyhow::Result<(Policy, bool)> {
let mut policy = policy.clone();
let filled = policy.sandbox.is_none();
if filled {
policy.sandbox = Policy::parse(openmoat_core::DEFAULT_POLICY)?.sandbox;
}
Ok((policy, filled))
}
#[derive(Debug, Clone, Default)]
pub struct Grants {
pub proxy_port: Option<u16>,
pub tmpdir: Option<String>,
pub program: Option<String>,
pub writes: Vec<String>,
pub terminals: Vec<String>,
#[cfg_attr(
not(target_os = "linux"),
expect(dead_code, reason = "only the Linux `--isolate` tier binds it in")
)]
pub trust: Option<String>,
pub tool_shell: Option<ToolShellGrant>,
#[cfg_attr(
not(target_os = "linux"),
expect(dead_code, reason = "only the Linux `--isolate` tier binds it in")
)]
pub helpers: Option<String>,
pub listen: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct ToolShellGrant {
pub dir: String,
pub moat: String,
}
fn lower_for_session(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
) -> anyhow::Result<(Enforcement, Grants)> {
let (policy, _) = with_read_roots(policy)?;
let tmpdir = grants.tmpdir.clone().or_else(session_tmpdir);
Ok((
openmoat_core::ir::lower(&policy, ctx)?,
Grants { tmpdir, ..grants },
))
}
pub fn session_tmpdir() -> Option<String> {
std::fs::canonicalize(std::env::temp_dir())
.ok()
.map(|dir| crate::context::path_string(&dir))
}
pub fn seatbelt_profile(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
) -> anyhow::Result<seatbelt::Generated> {
let (ir, grants) = lower_for_session(policy, ctx, grants)?;
Ok(seatbelt::generate(&ir, &grants))
}
#[cfg(windows)]
pub fn write_token_plan(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
exists: &dyn Fn(&str) -> bool,
) -> anyhow::Result<write_token::Generated> {
let (ir, grants) = lower_for_session(policy, ctx, grants)?;
write_token::generate(&ir, &grants, exists)
}
pub fn landlock_rules(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
) -> anyhow::Result<landlock::Generated> {
let (ir, grants) = lower_for_session(policy, ctx, grants)?;
landlock::generate(&ir, &grants)
}
#[cfg(target_os = "linux")]
pub fn landlock_entries(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
) -> anyhow::Result<(landlock::Generated, Result<Vec<String>, String>)> {
let (ir, grants) = lower_for_session(policy, ctx, grants)?;
let mut generated = landlock::generate(&ir, &grants)?;
let project = project_spellings(ctx);
let landlock::Generated { rules, report } = &mut generated;
landlock::entries::split_project(&ir, rules, report, &project)?;
let open = match project.first() {
Some(real) => bwrap::project_masks(&ir, std::slice::from_ref(real))
.map(|masks| landlock::entries::open(&masks.mounts, &generated.rules))
.map_err(|error| format!("{error:#}")),
None => Ok(Vec::new()),
};
Ok((generated, open))
}
#[cfg(target_os = "linux")]
pub fn bwrap_mounts(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
) -> anyhow::Result<bwrap::Generated> {
let (ir, grants) = lower_for_session(policy, ctx, grants)?;
bwrap::generate(&ir, &grants, &project_spellings(ctx))
}
#[cfg(target_os = "linux")]
pub fn netns_masks(
policy: &Policy,
ctx: &EvalContext,
rules: &landlock::Rules,
) -> anyhow::Result<Vec<bwrap::Mount>> {
let (ir, _) = lower_for_session(policy, ctx, Grants::default())?;
bwrap::grant_masks(&ir, rules, &project_spellings(ctx))
}
#[cfg(target_os = "linux")]
pub fn netns_project_masks(
policy: &Policy,
ctx: &EvalContext,
) -> anyhow::Result<bwrap::ProjectMasks> {
let (ir, _) = lower_for_session(policy, ctx, Grants::default())?;
bwrap::project_masks(&ir, &project_spellings(ctx))
}
#[cfg(target_os = "linux")]
pub fn netns_project_masks_near_top(
policy: &Policy,
ctx: &EvalContext,
) -> anyhow::Result<bwrap::ProjectMasks> {
let (ir, _) = lower_for_session(policy, ctx, Grants::default())?;
bwrap::project_masks_near_top(&ir, &project_spellings(ctx))
}
#[cfg(target_os = "linux")]
pub fn missing_hook_settings(policy: &Policy, ctx: &EvalContext) -> anyhow::Result<Vec<String>> {
let (ir, _) = lower_for_session(policy, ctx, Grants::default())?;
Ok(bwrap::missing_hook_settings(&ir, &project_spellings(ctx)))
}
#[cfg(any(target_os = "linux", all(test, unix)))]
pub fn kernel_self_in_writes(
policy: &Policy,
ctx: &EvalContext,
writes: &[String],
) -> anyhow::Result<Vec<(String, String)>> {
let (ir, _) = lower_for_session(policy, ctx, Grants::default())?;
let ci = crate::context::CASE_INSENSITIVE_PATHS;
let projects: Vec<&String> = ctx.project.iter().chain(&ctx.real_project).collect();
let in_project = |w: &str| projects.iter().any(|p| exposure::within(w, p, ci));
let mut held: Vec<(String, String)> = Vec::new();
let mut record = |holder: &str, path: String| {
if !held.iter().any(|(_, p)| *p == path) {
held.push((holder.to_owned(), path));
}
};
let rules = ir.fs.write.deny.iter().chain(&ir.fs.read.deny);
for rule in rules.filter(|r| r.id == openmoat_core::rule_id::KERNEL_SELF) {
for pattern in patterns::split(&rule.patterns).0 {
if let Some(rest) = pattern.strip_prefix("**/") {
for write in writes.iter().filter(|w| !in_project(w)) {
record(write, format!("{}/**/{rest}", write.trim_end_matches('/')));
}
continue;
}
let base = pattern
.split(['*', '?', '[', '{'])
.next()
.unwrap_or(pattern);
let base = base.trim_end_matches('/');
if !base.starts_with('/') {
continue;
}
let tree = pattern.strip_suffix("/**") == Some(base);
#[cfg(target_os = "linux")]
let base = links::real_path(base);
#[cfg(not(target_os = "linux"))]
let base = base.to_owned();
let base = base.as_str();
let holder = writes
.iter()
.find(|w| exposure::within(base, w, ci) || (tree && exposure::within(w, base, ci)));
if let Some(holder) = holder {
record(holder, pattern.to_owned());
}
}
}
Ok(held)
}
#[cfg(target_os = "linux")]
fn project_spellings(ctx: &EvalContext) -> Vec<String> {
ctx.real_project
.iter()
.chain(&ctx.project)
.cloned()
.collect()
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct Report {
pub losses: Vec<Loss>,
pub allowances: Vec<Allowance>,
}
impl Report {
fn loss(&mut self, kind: openmoat_core::Kind, rule: &str, message: String) {
let loss = Loss {
kind,
rule: rule.to_owned(),
message,
};
if !self.losses.contains(&loss) {
self.losses.push(loss);
}
}
fn allowance(
&mut self,
kind: openmoat_core::Kind,
rule: &str,
patterns: Vec<String>,
message: &str,
) {
if self.allowances.iter().any(|a| {
a.kind == kind && a.rule == rule && a.patterns == patterns && a.message == message
}) {
return;
}
self.allowances.push(Allowance {
kind,
rule: rule.to_owned(),
patterns,
message: message.to_owned(),
});
}
fn proxy_only(&mut self, net: &Access) {
if net.default == Effect::Allow {
let message = "every host is reachable only through OpenMoat's proxy";
self.loss(openmoat_core::Kind::Net, DEFAULT_NET, message.into());
}
for rule in &net.allow {
let message = "these hosts are reachable only through OpenMoat's proxy: a program that \
ignores HTTP(S)_PROXY cannot reach them";
self.loss(openmoat_core::Kind::Net, &rule.id, message.into());
}
}
}
#[cfg(test)]
pub fn assert_golden(name: &str, actual: &str) {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/sandbox")
.join(name);
if std::env::var_os("OPENMOAT_TEST_UPDATE_GOLDEN").is_some() {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, actual).unwrap();
}
let expected = std::fs::read_to_string(&path).unwrap_or_default();
assert_eq!(
actual,
expected,
"OPENMOAT_TEST_UPDATE_GOLDEN=1 updates {}",
path.display()
);
}