use std::os::windows::ffi::OsStrExt as _;
use std::os::windows::process::ExitStatusExt as _;
use std::path::Path;
use std::process::{Command, ExitStatus};
use anyhow::{Context as _, Result, bail};
use openmoat_core::boundary::{LaunchCheck, Mechanism, NetworkMode, Restriction};
use openmoat_core::{EvalContext, Policy};
use super::command_line;
use crate::agent_account::RunAs;
use crate::cli::IsolatedArgs;
use crate::context::{path_string, strip_verbatim};
use crate::exit::Code;
use crate::sandbox::write_token::{self, Entry, Plan};
use crate::sandbox::{Grants, Report};
pub mod account;
mod acl;
mod win32;
const NETWORK_GAP: &str = "Windows: `openmoat run` sets HTTP_PROXY and HTTPS_PROXY to its proxy, \
and nothing in the operating system holds the network (no Windows Filtering Platform \
filter: `openmoat agent-account setup`, from an administrator terminal, adds the agent \
account's), so a program that ignores the variables connects directly";
const WARNING: &str = "moat run: Windows preview tier: writes outside the project, the run's \
temp directory and --write paths are refused by a write-restricted token; reads are not \
restricted (the hook decides them) and the network goes through the proxy only for \
programs that honour HTTP_PROXY";
const ACCOUNT_WARNING: &str = "moat run: Windows preview tier, as the agent account (ADR-129): \
writes outside the project, the run's temp directory and --write paths, and the reads the \
policy denies in your profile, are refused by Windows; the network goes through the proxy \
only for programs that honour HTTP_PROXY (no network filters: `openmoat agent-account \
setup` again, from an administrator terminal, adds them)";
const FILTERED_NOTICE: &str = "moat run: Windows preview tier, as the agent account (ADR-129): \
writes outside the project, the run's temp directory and --write paths, and the reads the \
policy denies in your profile, are refused by Windows, and so is every connection and \
listen but the proxy's; name lookups still leave through Windows' DNS Client service";
enum Mode {
Token(Plan),
Account(Box<account::Active>),
}
pub struct Confined {
command: Command,
report: Report,
mode: Mode,
run_as: RunAs,
project: Option<String>,
}
pub fn confine(
policy: &Policy,
ctx: &EvalContext,
grants: Grants,
program: &Path,
state: &Path,
) -> Result<Confined> {
if let Some(why) = command_line::refused(&program.to_string_lossy()) {
bail!("{why}");
}
let tmpdir = grants.tmpdir.clone();
let port = grants.proxy_port;
let exists = |path: &str| Path::new(path).exists();
let active = account::active(state);
let state = path_string(state);
let run_as = match &active {
None => RunAs::Person,
Some(active) => filtered(active, port),
};
let (report, mode) = if let Some(active) = active {
let plan =
crate::sandbox::account_plan(policy, ctx, grants, &exists, &active.record.profile)?;
refuse_state(plan.roots.iter(), &state)?;
active.apply(&plan)?;
(plan.report, Mode::Account(Box::new(active)))
} else {
let generated = crate::sandbox::write_token_plan(policy, ctx, grants, &exists)?;
refuse_state(generated.plan.roots.iter().map(|(root, _)| root), &state)?;
apply(&generated.plan)?;
(generated.report, Mode::Token(generated.plan))
};
let mut command = Command::new(strip_verbatim(&program.to_string_lossy()));
if let Some(temp) = tmpdir {
let native = temp.replace('/', "\\");
command.env("TEMP", &native).env("TMP", &native);
}
Ok(Confined {
command,
report,
mode,
run_as,
project: ctx.project.clone(),
})
}
fn filtered(active: &account::Active, port: Option<u16>) -> RunAs {
let in_range = active
.record
.wfp
.as_ref()
.zip(port)
.is_some_and(|(wfp, port)| wfp.permits(port));
if active.filters && in_range {
RunAs::Filtered
} else {
RunAs::Account
}
}
fn refuse_state<'a>(roots: impl Iterator<Item = &'a String>, state: &str) -> Result<()> {
let state = state.to_lowercase();
for root in roots {
let root = root.to_lowercase();
if root == state || root.starts_with(&format!("{}/", state.trim_end_matches('/'))) {
bail!(
"`openmoat run` refuses a write grant on OpenMoat's state directory ({root}): \
commands must never write it"
);
}
}
Ok(())
}
fn apply(plan: &Plan) -> Result<()> {
for entry in &plan.entries {
let path = Path::new(&entry.path);
let have = crate::state_acl::descriptor(path)
.ok()
.and_then(|d| d.aces)
.unwrap_or_default();
if !write_token::needs_change(&have, entry) {
continue;
}
if entry.allows {
eprintln!(
"moat run: granting this run's own SID write on {} (once per folder; it names no \
account)",
entry.path
);
}
set(entry).with_context(|| format!("setting the access list of {}", entry.path))?;
}
Ok(())
}
fn set(entry: &Entry) -> Result<()> {
acl::add_entry(
&wide(&entry.path.replace('/', "\\"))?,
&entry.sid,
(entry.allows, entry.mask, entry.inherit),
)
}
fn wide(text: &str) -> Result<Vec<u16>> {
let mut units: Vec<u16> = text.encode_utf16().collect();
if units.contains(&0) {
bail!("{text} holds a NUL character");
}
units.push(0);
Ok(units)
}
pub fn isolate(_: &Policy, _: &EvalContext, _: Grants, _: &Path, _: &Path) -> Result<Confined> {
bail!(
"`openmoat run --isolate` runs on Linux only (bubblewrap); Windows has the preview tier \
alone: `openmoat run` without --isolate"
)
}
pub fn inside(_: &IsolatedArgs) -> Result<Code> {
bail!("only `openmoat run --isolate` on Linux starts this")
}
pub const BASE_ENV: &[&str] = &[
"SystemRoot",
"SystemDrive",
"windir",
"ComSpec",
"PATHEXT",
"Path",
"USERPROFILE",
"HOME",
"USERNAME",
"USERDOMAIN",
"HOMEDRIVE",
"HOMEPATH",
"APPDATA",
"LOCALAPPDATA",
"ProgramData",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"CommonProgramFiles",
"CommonProgramFiles(x86)",
"CommonProgramW6432",
"ALLUSERSPROFILE",
"PUBLIC",
"COMPUTERNAME",
"OS",
"NUMBER_OF_PROCESSORS",
"PROCESSOR_ARCHITECTURE",
"PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL",
"PROCESSOR_REVISION",
"PSModulePath",
];
pub fn unavailable() -> Option<String> {
None
}
pub const NETWORK: NetworkMode = NetworkMode::ProxyVariables;
#[expect(
clippy::unnecessary_wraps,
reason = "one signature on every platform: Linux's lets `--listen` through"
)]
pub fn listen_refused_here(port: u16) -> Option<String> {
Some(format!(
"`openmoat run --listen {port}` is refused here: nothing in this system's tier holds \
the network for a listen it permits (the agent account's network filters refuse \
every one), so nothing could keep the port to this machine; start the agent without \
`openmoat run`, under its hook"
))
}
pub const TOOL_SHELL_GAP: Option<&str> =
Some("Windows: `openmoat run` has no tool-shell wrapper there yet");
pub const MCP_SANDBOX_BY_DEFAULT: bool = false;
pub fn restrictions(
_isolated: bool,
_port_only: bool,
_kernel: Option<&crate::sandbox::landlock::abi::Kernel>,
run_as: RunAs,
) -> Vec<Restriction> {
let as_account = run_as.account();
let filtered = run_as == RunAs::Filtered;
let writes = if as_account {
Mechanism::AgentAccount
} else {
Mechanism::RestrictedToken
};
vec![
Restriction::planned(writes, true, true),
Restriction::planned(Mechanism::JobObject, true, true),
Restriction::planned(Mechanism::WfpNetwork, filtered, filtered),
Restriction::planned(Mechanism::WindowsReadDeny, as_account, as_account),
]
}
pub fn agent_account(state: &Path) -> RunAs {
match account::active(state) {
None => RunAs::Person,
Some(active) if active.filters => RunAs::Filtered,
Some(_) => RunAs::Account,
}
}
pub fn proxy_ports(state: &Path) -> Option<[u16; 2]> {
account::proxy_ports(state)
}
pub fn landlock() -> Option<crate::sandbox::landlock::abi::Kernel> {
None
}
pub fn port_only_network() -> Option<String> {
None
}
#[expect(
clippy::unnecessary_wraps,
reason = "Linux decides at run time; every platform file shares the signature"
)]
pub fn no_network_namespace() -> Option<String> {
Some(NETWORK_GAP.to_owned())
}
pub fn isolation() -> super::isolation::Offered {
super::isolation::Offered::Not
}
pub fn bubblewrap() -> Option<bool> {
None
}
pub fn bubblewrap_userns() -> Option<std::result::Result<(), String>> {
None
}
pub fn project_open(_: &Policy, _: &EvalContext) -> Option<String> {
None
}
pub fn link_tool_shell(_: &Path, _: &Path) -> std::io::Result<()> {
Err(std::io::ErrorKind::Unsupported.into())
}
#[expect(
clippy::unnecessary_wraps,
reason = "one signature on every platform: Linux's adds a Landlock layer, which can fail"
)]
pub fn seal_tool_shell() -> Result<()> {
Ok(())
}
pub fn exec_tool_shell(_: &mut Command) -> std::io::Error {
std::io::ErrorKind::Unsupported.into()
}
pub fn terminals() -> Vec<String> {
Vec::new()
}
pub fn in_restricted_token() -> bool {
win32::current_token_restricted()
}
impl Confined {
pub fn command(&mut self) -> &mut Command {
&mut self.command
}
pub fn report(&self) -> &Report {
&self.report
}
pub fn report_mut(&mut self) -> &mut Report {
&mut self.report
}
pub fn warning(&self) -> Option<&str> {
match (&self.mode, self.run_as) {
(Mode::Token(_), _) => Some(WARNING),
(Mode::Account(_), RunAs::Filtered) => None,
(Mode::Account(_), _) => Some(ACCOUNT_WARNING),
}
}
pub fn project_notice(&self) -> Option<&str> {
(self.run_as == RunAs::Filtered).then_some(FILTERED_NOTICE)
}
#[expect(
clippy::unused_self,
reason = "the method every platform's `Confined` has; Linux's reads itself"
)]
pub fn project_top_open(&self) -> bool {
false
}
pub fn agent_account(&self) -> RunAs {
self.run_as
}
pub fn status(
mut self,
on_launch: impl FnOnce(Option<LaunchCheck>) -> Result<()>,
) -> Result<ExitStatus> {
if let (Mode::Account(_), Some(project)) = (&self.mode, &self.project) {
let vars = safe_directory(&self.command, project)?;
self.command.envs(vars);
}
let program: Vec<u16> = self.command.get_program().encode_wide().collect();
let args: Vec<Vec<u16>> = self
.command
.get_args()
.map(|a| a.encode_wide().collect())
.collect();
let line = command_line::command_line(&program, &args)?;
let inherited = std::env::vars_os()
.map(|(name, value)| (units(&name), units(&value)))
.collect();
let changes = self
.command
.get_envs()
.map(|(name, value)| (units(name), value.map(units)))
.collect();
let env = command_line::environment_block(inherited, changes)?;
let mut application = program;
application.push(0);
let job = win32::Job::new().context("making the job object")?;
let (started, check) = match &self.mode {
Mode::Token(plan) => {
let token = win32::restricted_token(&plan.sids()).context("making the token")?;
let started = win32::start(&token, &job, &application, line, &env)?;
let check = LaunchCheck {
restricted_token: Some(true),
agent_token_restricted: Some(started.token_restricted),
job_object: Some(true),
agent_in_job: Some(started.in_job),
..LaunchCheck::default()
};
(started, check)
}
Mode::Account(active) => {
let started = active.start(&job, &application, line, &env)?;
let check = LaunchCheck {
agent_account: Some(true),
agent_token_account: Some(started.user_is_account),
job_object: Some(true),
agent_in_job: Some(started.started.in_job),
read_denies: Some(true),
wfp_filters: (self.run_as == RunAs::Filtered).then_some(true),
..LaunchCheck::default()
};
(started.started, check)
}
};
if let Err(error) = on_launch(Some(check)) {
job.terminate();
return Err(error);
}
started.resume()?;
let code = started.wait();
job.terminate();
Ok(ExitStatus::from_raw(code?))
}
}
fn safe_directory(command: &Command, project: &str) -> Result<Vec<(String, String)>> {
let set: Vec<(String, Option<String>)> = command
.get_envs()
.map(|(name, value)| {
(
name.to_string_lossy().into_owned(),
value.map(|v| v.to_string_lossy().into_owned()),
)
})
.collect();
let lookup = |var: &str| match set.iter().find(|(name, _)| name.eq_ignore_ascii_case(var)) {
Some((_, value)) => value.clone(),
None => std::env::var(var).ok(),
};
crate::sandbox::git_env::append(
&lookup,
vec![("safe.directory".to_owned(), project.to_owned())],
)
}
fn units(text: &std::ffi::OsStr) -> Vec<u16> {
text.encode_wide().collect()
}