|
| 1 | +//! sandboy — wrap-the-child confinement for one untrusted command. |
| 2 | +//! |
| 3 | +//! The Sandboy MVP (Layer 2 of docs/notes/sandboy-isolation-adr.md): fork is |
| 4 | +//! implicit — we confine THIS process, then `execve` the target, and both |
| 5 | +//! Landlock and seccomp survive the exec. So |
| 6 | +//! |
| 7 | +//! sandboy run --policy step.toml -- bash -lc '<a .007/gate.toml step>' |
| 8 | +//! |
| 9 | +//! runs that step with: |
| 10 | +//! * filesystem access scoped to an allowlist of paths (Landlock); |
| 11 | +//! * TCP connect/bind scoped to an allowlist of ports (Landlock ABI v4); |
| 12 | +//! * a seccomp denylist stripping the clearly-dangerous syscalls |
| 13 | +//! (ptrace, mount, bpf, kexec, …) to shrink host-kernel attack surface, |
| 14 | +//! * while keeping *broad freedom* for everything a normal toolchain needs. |
| 15 | +//! |
| 16 | +//! This is the least-privilege-per-command layer. It shares the host kernel |
| 17 | +//! (no VM), so it is NOT host-escape resistance on its own — that is Layer 1 |
| 18 | +//! (Firecracker), added when an untrusted target repo enters scope. Host-level |
| 19 | +//! egress by address (CIDR/domain) is Layer 3 (netns + proxy); Landlock only |
| 20 | +//! scopes ports, which is called out below and in the README. |
| 21 | +
|
| 22 | +mod policy; |
| 23 | + |
| 24 | +use std::os::unix::process::CommandExt; |
| 25 | +use std::process::Command; |
| 26 | + |
| 27 | +use anyhow::{anyhow, bail, Context, Result}; |
| 28 | +use landlock::{ |
| 29 | + Access, AccessFs, AccessNet, NetPort, PathBeneath, PathFd, Ruleset, RulesetAttr, |
| 30 | + RulesetCreatedAttr, RulesetStatus, ABI, |
| 31 | +}; |
| 32 | + |
| 33 | +use policy::Policy; |
| 34 | + |
| 35 | +fn main() { |
| 36 | + if let Err(e) = run() { |
| 37 | + eprintln!("sandboy: {e:#}"); |
| 38 | + std::process::exit(if e.to_string().contains("policy") { 2 } else { 1 }); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +fn run() -> Result<()> { |
| 43 | + let (policy_path, argv) = parse_args()?; |
| 44 | + let policy = Policy::load(&policy_path) |
| 45 | + .with_context(|| format!("loading policy {policy_path}"))?; |
| 46 | + let (prog, prog_args) = argv |
| 47 | + .split_first() |
| 48 | + .ok_or_else(|| anyhow!("no command after `--`"))?; |
| 49 | + |
| 50 | + // 1. no_new_privs — required to install a seccomp filter unprivileged. |
| 51 | + set_no_new_privs()?; |
| 52 | + |
| 53 | + // 2. Landlock: filesystem + TCP-port scope. Best-effort so an older kernel |
| 54 | + // degrades (and reports) instead of hard-failing. |
| 55 | + apply_landlock(&policy)?; |
| 56 | + |
| 57 | + // 3. seccomp denylist: strip dangerous syscalls, allow the rest. |
| 58 | + apply_seccomp(&policy)?; |
| 59 | + |
| 60 | + // 4. Hand off. execve replaces us; the two confinements persist into it. |
| 61 | + // `exec()` only returns on failure. |
| 62 | + let err = Command::new(prog).args(prog_args).exec(); |
| 63 | + Err(err).with_context(|| format!("exec {prog}")) |
| 64 | +} |
| 65 | + |
| 66 | +fn parse_args() -> Result<(String, Vec<String>)> { |
| 67 | + let mut it = std::env::args().skip(1); |
| 68 | + match it.next().as_deref() { |
| 69 | + Some("run") => {} |
| 70 | + _ => bail!("usage: sandboy run --policy <file.toml> -- <cmd> [args...]"), |
| 71 | + } |
| 72 | + let mut policy_path = None; |
| 73 | + let mut argv = Vec::new(); |
| 74 | + while let Some(a) = it.next() { |
| 75 | + match a.as_str() { |
| 76 | + "--policy" => policy_path = Some(it.next().ok_or_else(|| anyhow!("--policy needs a value"))?), |
| 77 | + "--" => { |
| 78 | + argv.extend(it.by_ref()); |
| 79 | + break; |
| 80 | + } |
| 81 | + other => bail!("unexpected arg {other:?} (did you forget `--` before the command?)"), |
| 82 | + } |
| 83 | + } |
| 84 | + Ok(( |
| 85 | + policy_path.ok_or_else(|| anyhow!("--policy is required"))?, |
| 86 | + argv, |
| 87 | + )) |
| 88 | +} |
| 89 | + |
| 90 | +fn apply_landlock(policy: &Policy) -> Result<()> { |
| 91 | + // ABI::V4 adds TCP bind/connect scoping (kernel 6.7+). Best-effort compat |
| 92 | + // means: on an older kernel, unsupported bits are dropped, not fatal. |
| 93 | + let abi = ABI::V4; |
| 94 | + let mut ruleset = Ruleset::default() |
| 95 | + .handle_access(AccessFs::from_all(abi))? |
| 96 | + .handle_access(AccessNet::BindTcp | AccessNet::ConnectTcp)? |
| 97 | + .create()?; |
| 98 | + |
| 99 | + // Read+execute paths (binaries, libs, source to analyze). |
| 100 | + for p in &policy.fs_ro { |
| 101 | + ruleset = add_fs(ruleset, p, AccessFs::from_read(abi)) |
| 102 | + .with_context(|| format!("fs_ro {}", p.display()))?; |
| 103 | + } |
| 104 | + // Read+write+execute paths (the worktree, tmp, output dirs). |
| 105 | + for p in &policy.fs_rw { |
| 106 | + ruleset = add_fs(ruleset, p, AccessFs::from_all(abi)) |
| 107 | + .with_context(|| format!("fs_rw {}", p.display()))?; |
| 108 | + } |
| 109 | + // TCP port allowlists. Landlock scopes *ports*, not addresses — host-level |
| 110 | + // egress by CIDR/domain is Layer 3 (see README). |
| 111 | + for &port in &policy.tcp_connect { |
| 112 | + ruleset = ruleset.add_rule(NetPort::new(port, AccessNet::ConnectTcp))?; |
| 113 | + } |
| 114 | + for &port in &policy.tcp_bind { |
| 115 | + ruleset = ruleset.add_rule(NetPort::new(port, AccessNet::BindTcp))?; |
| 116 | + } |
| 117 | + |
| 118 | + let status = ruleset.restrict_self().context("landlock restrict_self")?; |
| 119 | + match status.ruleset { |
| 120 | + RulesetStatus::FullyEnforced => {} |
| 121 | + RulesetStatus::PartiallyEnforced => { |
| 122 | + eprintln!("sandboy: warning: Landlock only PARTIALLY enforced (kernel too old for some access rights)"); |
| 123 | + } |
| 124 | + RulesetStatus::NotEnforced => { |
| 125 | + bail!("Landlock NOT enforced — kernel lacks Landlock (need >=5.13, >=6.7 for TCP). Refusing to run unconfined."); |
| 126 | + } |
| 127 | + } |
| 128 | + Ok(()) |
| 129 | +} |
| 130 | + |
| 131 | +/// A path that doesn't exist would make the whole ruleset fail; skip-with-warn |
| 132 | +/// keeps a policy portable across hosts that lack e.g. /opt. |
| 133 | +fn add_fs( |
| 134 | + ruleset: landlock::RulesetCreated, |
| 135 | + path: &std::path::Path, |
| 136 | + access: landlock::BitFlags<AccessFs>, |
| 137 | +) -> Result<landlock::RulesetCreated> { |
| 138 | + match PathFd::new(path) { |
| 139 | + Ok(fd) => Ok(ruleset.add_rule(PathBeneath::new(fd, access))?), |
| 140 | + Err(e) => { |
| 141 | + eprintln!("sandboy: warning: skipping missing path {}: {e}", path.display()); |
| 142 | + Ok(ruleset) |
| 143 | + } |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +fn apply_seccomp(policy: &Policy) -> Result<()> { |
| 148 | + use seccompiler::{apply_filter, BpfProgram, SeccompAction, SeccompFilter}; |
| 149 | + use std::collections::BTreeMap; |
| 150 | + |
| 151 | + // Denylist model: default = Allow (broad freedom), listed syscalls = EPERM. |
| 152 | + // An empty rule vec means "match unconditionally". |
| 153 | + let mut rules: BTreeMap<i64, Vec<seccompiler::SeccompRule>> = BTreeMap::new(); |
| 154 | + for &nr in &policy.seccomp_deny_numbers() { |
| 155 | + rules.insert(nr, vec![]); |
| 156 | + } |
| 157 | + |
| 158 | + let filter = SeccompFilter::new( |
| 159 | + rules, |
| 160 | + SeccompAction::Allow, // mismatch: everything not listed |
| 161 | + SeccompAction::Errno(libc::EPERM as u32), // match: the dangerous ones |
| 162 | + std::env::consts::ARCH |
| 163 | + .try_into() |
| 164 | + .map_err(|e| anyhow!("seccomp target arch: {e:?}"))?, |
| 165 | + ) |
| 166 | + .context("building seccomp filter")?; |
| 167 | + |
| 168 | + let program: BpfProgram = filter.try_into().context("compiling seccomp bpf")?; |
| 169 | + apply_filter(&program).context("installing seccomp filter")?; |
| 170 | + Ok(()) |
| 171 | +} |
| 172 | + |
| 173 | +/// The one audited `unsafe`: a single prctl to set no_new_privs, without which |
| 174 | +/// an unprivileged seccomp install is rejected. Sandboy is the syscall-boundary |
| 175 | +/// crate, so — unlike the analyzer core (`unsafe_code = forbid`) — it permits |
| 176 | +/// narrowly-scoped, audited unsafe at exactly this seam. Nothing user-derived |
| 177 | +/// touches this call. |
| 178 | +fn set_no_new_privs() -> Result<()> { |
| 179 | + // SAFETY: PR_SET_NO_NEW_PRIVS takes fixed constant args, has no memory |
| 180 | + // effects, and only ever tightens privileges. Return value checked below. |
| 181 | + let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) }; |
| 182 | + if rc != 0 { |
| 183 | + bail!("prctl(PR_SET_NO_NEW_PRIVS) failed: {}", std::io::Error::last_os_error()); |
| 184 | + } |
| 185 | + Ok(()) |
| 186 | +} |
0 commit comments