use std::{
ffi::OsString,
fmt,
path::{Path, PathBuf},
};
use nachalnik::{Capability, Verdict};
use crate::tools::{Careful, Subject};
pub const EXEC_FLAG: &str = "--confine-and-run";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sandbox {
pub workdir: PathBuf,
pub extra: Vec<PathBuf>,
pub writable: bool,
pub network: bool,
}
impl Sandbox {
pub fn of(policy: &Careful, workdir: PathBuf, extra: Vec<PathBuf>, granted: bool) -> Self {
Self {
workdir,
extra,
writable: policy.stance(&Subject::Capability(Capability::Write)) != Verdict::Deny,
network: granted
|| policy.stance(&Subject::Capability(Capability::Network)) == Verdict::Allow,
}
}
pub fn argv(&self, cmd: &str) -> Vec<OsString> {
let mut argv = vec![
OsString::from(EXEC_FLAG),
self.workdir.clone().into(),
OsString::from(match self.writable {
true => "rw",
false => "ro",
}),
OsString::from(match self.network {
true => "net",
false => "nonet",
}),
OsString::from(self.extra.len().to_string()),
];
argv.extend(self.extra.iter().map(|path| path.clone().into()));
argv.push(cmd.into());
argv
}
pub fn from_argv(argv: &[OsString]) -> Option<(Self, OsString)> {
let mut argv = argv.iter();
if argv.next()? != EXEC_FLAG {
return None;
}
let workdir = PathBuf::from(argv.next()?);
let writable = argv.next()? == "rw";
let network = argv.next()? == "net";
let count: usize = argv.next()?.to_str()?.parse().ok()?;
let extra: Vec<PathBuf> = argv.by_ref().take(count).map(PathBuf::from).collect();
let cmd = argv.next()?.clone();
Some((
Self {
workdir,
extra,
writable,
network,
},
cmd,
))
}
}
impl fmt::Display for Sandbox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {}",
self.workdir.display(),
match self.writable {
true => "read-write",
false => "read-only",
}
)?;
for path in &self.extra {
write!(f, ", {} read-write", path.display())?;
}
write!(
f,
", the system directories read-only, {}",
match self.network {
true => "the network reachable",
false => "no network",
}
)
}
}
#[derive(Debug, Clone)]
pub struct Reach {
pub workdir: PathBuf,
pub extra: Vec<PathBuf>,
pub confined: bool,
}
impl Reach {
pub fn allows(&self, path: &str) -> Result<PathBuf, String> {
let path = PathBuf::from(path);
if !self.confined {
return Ok(path);
}
let absolute = match path.is_absolute() {
true => path.clone(),
false => self.workdir.join(&path),
};
let mut existing = absolute.as_path();
let mut rest = PathBuf::new();
let resolved = loop {
match existing.canonicalize() {
Ok(resolved) if rest.as_os_str().is_empty() => break resolved,
Ok(resolved) => break resolved.join(&rest),
Err(_) => match (existing.file_name(), existing.parent()) {
(Some(name), Some(parent)) => {
rest = match rest.as_os_str().is_empty() {
true => PathBuf::from(name),
false => Path::new(name).join(&rest),
};
existing = parent;
}
_ => break absolute.clone(),
},
}
};
match std::iter::once(&self.workdir)
.chain(self.extra.iter())
.any(|allowed| {
allowed
.canonicalize()
.is_ok_and(|allowed| resolved.starts_with(allowed))
}) {
true => Ok(resolved),
false => Err(format!(
"{}: outside {}, which is as far as this agent reaches. Start it there, or pass \
--sandbox-allow",
path.display(),
self.workdir.display()
)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Confinement {
Full,
Partial,
Unavailable,
Unsupported,
}
impl Confinement {
pub fn is_confined(self) -> bool {
matches!(self, Self::Full | Self::Partial)
}
pub fn complaint(self) -> Option<&'static str> {
match self {
Self::Full => None,
Self::Partial => Some("the kernel enforced only part of the sandbox"),
Self::Unavailable => {
Some("this kernel has no Landlock, so the shell is not confined at all")
}
Self::Unsupported => {
Some("this platform has no Landlock, so the shell is not confined at all")
}
}
}
}
impl fmt::Display for Confinement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Full => "confined",
Self::Partial => "partly confined",
Self::Unavailable => "not confined (no Landlock in this kernel)",
Self::Unsupported => "not confined (no Landlock on this platform)",
})
}
}
#[cfg(target_os = "linux")]
const SYSTEM: &[&str] = &[
"/usr", "/etc", "/bin", "/sbin", "/lib", "/lib64", "/opt", "/proc", "/sys", "/run",
];
#[cfg(target_os = "linux")]
pub fn confine(sandbox: &Sandbox, scratch: &Path) -> Confinement {
use landlock::{
ABI, Access, AccessFs, AccessNet, Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetStatus,
path_beneath_rules,
};
let abi = ABI::V1;
let Ok(mut ruleset) = Ruleset::default().handle_access(AccessFs::from_all(abi)) else {
return Confinement::Unavailable;
};
if !sandbox.network {
match ruleset.handle_access(AccessNet::ConnectTcp | AccessNet::BindTcp) {
Ok(with_net) => ruleset = with_net,
Err(_) => return Confinement::Unavailable,
}
}
let writable: Vec<PathBuf> = std::iter::once(sandbox.workdir.clone())
.filter(|_| sandbox.writable)
.chain(std::iter::once(scratch.to_path_buf()))
.chain(sandbox.extra.iter().cloned())
.collect();
let readable: Vec<PathBuf> = SYSTEM
.iter()
.map(PathBuf::from)
.chain(std::iter::once(sandbox.workdir.clone()))
.collect();
let restricted = ruleset
.create()
.and_then(|created| {
created.add_rules(path_beneath_rules(&readable, AccessFs::from_read(abi)))
})
.and_then(|created| {
created.add_rules(path_beneath_rules(
&["/dev"],
AccessFs::ReadFile | AccessFs::WriteFile,
))
})
.and_then(|created| {
created.add_rules(path_beneath_rules(&writable, AccessFs::from_all(abi)))
})
.and_then(|created| created.restrict_self());
match restricted {
Ok(status) => match status.ruleset {
RulesetStatus::FullyEnforced => Confinement::Full,
RulesetStatus::PartiallyEnforced => Confinement::Partial,
RulesetStatus::NotEnforced => Confinement::Unavailable,
},
Err(_) => Confinement::Unavailable,
}
}
#[cfg(not(target_os = "linux"))]
pub fn confine(_sandbox: &Sandbox, _scratch: &Path) -> Confinement {
Confinement::Unsupported
}
pub fn scratch_for(pid: u32) -> PathBuf {
std::env::temp_dir().join(format!("kamchatka-{pid}"))
}
pub fn available(program: &Path) -> Confinement {
let sandbox = Sandbox {
workdir: std::env::temp_dir(),
extra: Vec::new(),
writable: true,
network: false,
};
let output = std::process::Command::new(program)
.args(sandbox.argv("exit 0"))
.env(REPORT_VAR, "1")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()
.and_then(|child| {
let scratch = scratch_for(child.id());
let output = child.wait_with_output();
let _ = std::fs::remove_dir_all(&scratch);
output
});
match output {
Ok(output) => match String::from_utf8_lossy(&output.stderr)
.lines()
.find_map(|line| line.strip_prefix(REPORT))
{
Some("full") => Confinement::Full,
Some("partial") => Confinement::Partial,
Some("unsupported") => Confinement::Unsupported,
_ => Confinement::Unavailable,
},
Err(_) => Confinement::Unavailable,
}
}
const REPORT: &str = "kamchatka-confinement:";
const REPORT_VAR: &str = "KAMCHATKA_REPORT_CONFINEMENT";
pub fn run_if_asked() -> Option<i32> {
let argv: Vec<OsString> = std::env::args_os().skip(1).collect();
let (sandbox, cmd) = Sandbox::from_argv(&argv)?;
let scratch = scratch_for(std::process::id());
let _ = std::fs::create_dir_all(&scratch);
let confinement = confine(&sandbox, &scratch);
if std::env::var_os(REPORT_VAR).is_some() {
eprintln!(
"{REPORT}{}",
match confinement {
Confinement::Full => "full",
Confinement::Partial => "partial",
Confinement::Unavailable => "unavailable",
Confinement::Unsupported => "unsupported",
}
);
}
let mut command = std::process::Command::new("sh");
command
.arg("-c")
.arg(&cmd)
.current_dir(&sandbox.workdir)
.env("TMPDIR", &scratch);
#[cfg(unix)]
let code = {
use std::os::unix::process::CommandExt as _;
let failure = command.exec();
eprintln!("could not run the command: {failure}");
127
};
#[cfg(not(unix))]
let code = match command.status() {
Ok(status) => status.code().unwrap_or(1),
Err(e) => {
eprintln!("could not run the command: {e}");
127
}
};
Some(code)
}