use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use super::super::events::head;
use super::super::text::say;
use super::policy::{Policy, Rule};
pub const FACILITY: &str = "/usr/bin/sandbox-exec";
const TOUCH: &str = "/usr/bin/touch";
const ERROR_BYTES: usize = 512;
pub fn usable(facility: &Path) -> Result<(), String> {
if super::super::adapter::executable(facility) {
return Ok(());
}
Err(say(
"sandbox_missing",
&[("facility", &facility.display().to_string())],
))
}
fn quiet(command: &mut Command) -> io::Result<Output> {
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.output()
}
fn refused(error: &str) -> String {
say(
"sandbox_refused",
&[("error", head(error.trim(), ERROR_BYTES))],
)
}
pub fn target(policy: &Policy, private: &Path, home: &Path) -> Option<PathBuf> {
let mut name = private.file_name()?.to_os_string();
name.push(".probe");
let beside = private.parent()?.canonicalize().ok()?.join(name);
let named = format!(
".neosian-harness-probe-{}-{}",
std::process::id(),
uuid::Uuid::new_v4().simple()
);
let home = home.canonicalize().ok()?;
[beside, home.join(named)]
.into_iter()
.find(|candidate| !policy.allow.iter().any(|rule| covers(rule, candidate)))
}
pub fn covers(rule: &Rule, path: &Path) -> bool {
match rule {
Rule::Literal(literal) => path == Path::new(literal),
Rule::Subpath(below) => path.starts_with(below),
Rule::Pattern(pattern) => reaches(pattern, path),
}
}
fn reaches(pattern: &str, path: &Path) -> bool {
let Ok(regex) = fancy_regex::Regex::new(pattern) else {
return path.starts_with(literal_dir(pattern));
};
path.ancestors().any(|place| {
place
.to_str()
.is_none_or(|text| regex.is_match(text).unwrap_or(true))
})
}
fn literal_dir(pattern: &str) -> String {
let mut out = String::new();
let mut chars = pattern.trim_start_matches('^').chars();
while let Some(c) = chars.next() {
match c {
'\\' => out.extend(chars.next()),
c if "^$.|?*+()[]{}".contains(c) => break,
c => out.push(c),
}
}
match out.rfind('/') {
Some(at) => out[..at.max(1)].to_string(),
None => "/".to_string(),
}
}
pub fn probe(facility: &Path, profile: &str, target: &Path) -> Result<(), String> {
usable(facility)?;
let ran = quiet(
Command::new(facility)
.arg("-p")
.arg(profile)
.arg("--")
.arg(TOUCH)
.arg(target),
);
if target.symlink_metadata().is_ok() {
let _ = std::fs::remove_file(target);
return Err(say("sandbox_unenforced", &[]));
}
match ran {
Ok(output) if output.status.code() == Some(1) => Ok(()),
Ok(output) => Err(refused(&String::from_utf8_lossy(&output.stderr))),
Err(error) => Err(refused(&error.to_string())),
}
}
pub fn command(facility: &Path, profile: &str, program: &Path) -> Command {
let mut command = Command::new(facility);
command.arg("-p").arg(profile).arg("--").arg(program);
command
}