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::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};
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 yet), 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";
pub struct Confined {
command: Command,
report: Report,
plan: Plan,
}
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 exists = |path: &str| Path::new(path).exists();
let generated = crate::sandbox::write_token_plan(policy, ctx, grants, &exists)?;
refuse_state(&generated.plan, &path_string(state))?;
apply(&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: generated.report,
plan: generated.plan,
})
}
fn refuse_state(plan: &Plan, state: &str) -> Result<()> {
let state = state.to_lowercase();
for (root, _) in &plan.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<()> {
win32::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",
"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, 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>,
) -> Vec<Restriction> {
vec![
Restriction::planned(Mechanism::RestrictedToken, true, true),
Restriction::planned(Mechanism::JobObject, true, true),
Restriction::planned(Mechanism::WfpNetwork, false, false),
Restriction::planned(Mechanism::WindowsReadDeny, false, false),
]
}
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
}
#[expect(
clippy::unused_self,
reason = "the method every platform's `Confined` has; Linux's reads itself"
)]
pub fn warning(&self) -> Option<&str> {
Some(WARNING)
}
#[expect(
clippy::unused_self,
reason = "the method every platform's `Confined` has; Linux's reads itself"
)]
pub fn project_notice(&self) -> Option<&str> {
None
}
#[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 status(
self,
on_launch: impl FnOnce(Option<LaunchCheck>) -> Result<()>,
) -> Result<ExitStatus> {
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 token = win32::restricted_token(&self.plan.sids()).context("making the token")?;
let job = win32::Job::new().context("making the job object")?;
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()
};
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 units(text: &std::ffi::OsStr) -> Vec<u16> {
text.encode_wide().collect()
}