Skip to content

Commit b966280

Browse files
committed
spike(sandboy): Layer-2 wrap-the-child confinement MVP
The Sandboy MVP from the ADR §4: confine one untrusted command (a gate step, an agent tool call) with unprivileged Linux primitives — no root, no namespaces, no daemon. sandboy run --policy step.toml -- bash -lc '<a .007/gate.toml step>' Applies confinement to itself, then execve's the target; Landlock and seccomp both survive the exec, so the wrapped command and its children inherit the cage. - Landlock: FS read/exec + read/write path allowlists; TCP connect/bind scoped to allowlisted ports (ABI v4). Best-effort compat — warns on old kernels, refuses only if Landlock is entirely absent. - seccomp-bpf: denylist model (default Allow, dangerous syscalls -> EPERM: ptrace, mount, bpf, kexec, ...) to keep broad freedom while shrinking host-kernel attack surface. - Per-step TOML policy (policy.example.toml); tests/demo.sh shows 1 allowed + 3 denied probes (write outside allowlist, ptrace, off-allowlist port). Honest scope (ADR §4/§5): shares the host kernel, so NOT host-escape resistance on its own (that's Layer 1 / Firecracker); Landlock scopes ports not addresses, so CIDR/domain egress is Layer 3. One audited unsafe (prctl NO_NEW_PRIVS) at the syscall seam, justified in README; all other unsafe lives in the landlock/seccompiler crates. Authored in a network-restricted sandbox (crate downloads egress-blocked), so NOT compiled here — README flags the two version-sensitive apply_* spots. Wires into 007 by wrapping each gate step with a per-step policy. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LMA4JwvgPBCZuEbAiG5LJL
1 parent 3901817 commit b966280

7 files changed

Lines changed: 506 additions & 0 deletions

File tree

‎docs/notes/sandboy-isolation-adr.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,12 @@ worktree — это cleanup-convenience, а не sandbox. «Слот под пе
137137
законченный самостоятельный проект. Слой 1 (VM-граница) добавляется, когда в скоуп
138138
попадёт недоверенный target-репо (триггер из `security-layers.md`).
139139

140+
> **Спайк построен:** `sandboy/` — `sandboy run --policy step.toml -- <cmd>`:
141+
> wrap-the-child через Landlock (FS-scope + TCP-port-scope) + seccomp-denylist,
142+
> unprivileged (без root/namespaces). Per-step TOML-политика, интеграция в gate =
143+
> обернуть каждый шаг. Egress по адресам (CIDR/domain) — по-прежнему Слой 3
144+
> (Landlock скоупит только порты). Authored, собирать локально.
145+
140146
### 4.1 Egress — единственная универсально слабая ось
141147

142148
Ни один механизм не даёт default-deny egress «бесплатно». Даже лучшие доменные

‎sandboy/Cargo.toml‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
[package]
2+
name = "sandboy"
3+
version = "0.1.0"
4+
edition = "2021"
5+
description = "wrap-the-child confinement for untrusted gate steps: Landlock (FS + TCP-port scope) + seccomp denylist, unprivileged. Sandboy MVP, Layer 2 of docs/notes/sandboy-isolation-adr.md."
6+
7+
[[bin]]
8+
name = "sandboy"
9+
path = "src/main.rs"
10+
11+
[dependencies]
12+
# "Берём готовое" (ADR §2 non-goal: не свой LSM). All the unsafe lives in these
13+
# crates, not in ours — see README on the one audited prctl exception.
14+
landlock = "0.4" # FS access-scope + (ABI v4) TCP bind/connect port scope
15+
seccompiler = "0.5" # BPF syscall filter (firecracker's crate)
16+
libc = "0.2" # syscall numbers for the denylist + the NNP prctl
17+
anyhow = "1"
18+
serde = { version = "1", features = ["derive"] }
19+
toml = "0.8"

‎sandboy/README.md‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# sandboy — wrap-the-child confinement (Layer 2 MVP)
2+
3+
**Status: spike.** The Sandboy MVP from
4+
[`docs/notes/sandboy-isolation-adr.md`](../docs/notes/sandboy-isolation-adr.md)
5+
§4 — the least-privilege-per-command layer. It confines one untrusted command
6+
(an `.007/gate.toml` step, an agent tool call) using only **unprivileged Linux
7+
primitives**: Landlock + seccomp. No root, no namespaces, no daemon.
8+
9+
```
10+
sandboy run --policy step.toml -- bash -lc '<a gate step>'
11+
```
12+
13+
The process applies the confinement to itself and then `execve`s the target;
14+
**Landlock and seccomp both survive the exec**, so the wrapped command — and
15+
everything it spawns — inherits the cage.
16+
17+
## What it enforces
18+
19+
| Boundary | Mechanism | Scope |
20+
|---|---|---|
21+
| **Filesystem** | Landlock | read+exec / read+write allowlists of paths; everything else `EACCES` |
22+
| **TCP ports** | Landlock ABI v4 | connect/bind only to allowlisted ports (e.g. 443, 22) |
23+
| **Syscalls** | seccomp-bpf | denylist of dangerous syscalls (ptrace, mount, bpf, kexec, …) → `EPERM`; everything else allowed |
24+
25+
The seccomp model is a **denylist** on purpose: the goal is *broad freedom*
26+
inside a box, so we strip the clearly-dangerous rather than allowlist a minimal
27+
set (which breaks arbitrary toolchains). Landlock is the load-bearing FS/net
28+
boundary; seccomp shrinks host-kernel attack surface behind it.
29+
30+
## What it is NOT (honest scope — ADR §4/§5)
31+
32+
- **Not host-escape resistance.** It shares the host kernel (no VM). A kernel
33+
LPE reachable through an *allowed* syscall still escapes. True escape
34+
resistance is **Layer 1 (Firecracker)**, added when an untrusted target repo
35+
enters scope. Layer 2 is defense-in-depth *inside* that, and the 80/20 MVP.
36+
- **Not host/CIDR/domain egress control.** Landlock scopes *ports*, not
37+
addresses. `tcp_connect = [443]` means "TCP to port 443 anywhere", not "only
38+
to github.com". Address/domain egress is **Layer 3** (netns + filtering
39+
proxy, blanket-UDP-block per ADR §7.3).
40+
- **Not a side-channel defense** (out of the single-tenant threat model).
41+
42+
## Policy
43+
44+
TOML, per step. See [`policy.example.toml`](policy.example.toml):
45+
46+
```toml
47+
fs_ro = ["/usr", "/bin", "/lib", "/lib64", "/etc"]
48+
fs_rw = ["/home/user/work/worktree", "/tmp"]
49+
tcp_connect = [443, 22] # https + ssh; [] = no outbound TCP
50+
tcp_bind = []
51+
# omit seccomp_deny to use the curated default denylist
52+
```
53+
54+
## Build & run
55+
56+
> **Authored, not compiled here.** Written in a network-restricted sandbox
57+
> (no crate downloads: `static.crates.io` egress-blocked), so it has **not**
58+
> been through `cargo`. The `landlock`/`seccompiler` crate API pins may need a
59+
> minor nudge — those two `apply_*` functions are the likely spots.
60+
61+
```bash
62+
cargo build --release # needs Linux; the crates are Linux-only
63+
./tests/demo.sh # four probes: 1 allowed, 3 denied
64+
```
65+
66+
`demo.sh` shows a write inside the worktree succeeding, and a write to `$HOME`,
67+
a `ptrace`, and a connect to a non-allowlisted port all being denied.
68+
69+
### The one `unsafe`
70+
71+
Sandboy is the syscall-boundary crate, so — unlike the analyzer core
72+
(`unsafe_code = forbid`) — it permits **one** narrowly-scoped, audited `unsafe`:
73+
the `prctl(PR_SET_NO_NEW_PRIVS)` needed before an unprivileged seccomp install.
74+
All other unsafe lives inside the `landlock`/`seccompiler` crates ("берём
75+
готовое", ADR §2). Nothing user-derived reaches the prctl.
76+
77+
## Wiring into 007 (the actual use)
78+
79+
The gate runner wraps each step instead of running it bare:
80+
81+
```
82+
# before: bash -lc "<step.cmd>" (under bypassPermissions)
83+
# after: sandboy run --policy <step-policy> -- bash -lc "<step.cmd>"
84+
```
85+
86+
Per-step policies let a `fmt` step run with no network and RO toolchain, while a
87+
`cargo test` step gets 443 + a writable target dir — least privilege per step,
88+
which is exactly what `007/docs/security-layers.md` marks as the missing layer
89+
in the `run`/gate slot.
90+
91+
## Kernel requirements
92+
93+
- Landlock FS scoping: kernel ≥ 5.13.
94+
- Landlock TCP-port scoping: kernel ≥ 6.7 (ABI v4). On older kernels sandboy
95+
runs **best-effort** and prints a `PARTIALLY enforced` warning; it refuses to
96+
run only if Landlock is entirely absent (`NOT enforced`).

‎sandboy/policy.example.toml‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Example confinement policy for one .007/gate.toml step.
2+
# Tune per step: a `cargo test` step needs the toolchain + worktree + 443
3+
# (crates.io); a formatting step may need no network at all.
4+
5+
# Read+execute: toolchain, shared libs, read-only system config.
6+
fs_ro = [
7+
"/usr",
8+
"/bin",
9+
"/lib",
10+
"/lib64",
11+
"/etc",
12+
]
13+
14+
# Read+write+execute: the worktree the agent/gate operates in, scratch, output.
15+
fs_rw = [
16+
"/home/user/work/worktree",
17+
"/tmp",
18+
]
19+
20+
# TCP egress by PORT (Landlock scopes ports, not hosts — host/CIDR/domain
21+
# egress is Layer 3, netns + proxy). 443 = https (git, package registries),
22+
# 22 = ssh (git over ssh). Empty list = no outbound TCP.
23+
tcp_connect = [443, 22]
24+
25+
# No listening sockets by default.
26+
tcp_bind = []
27+
28+
# seccomp: omit `seccomp_deny` to use the curated default denylist
29+
# (ptrace, mount, bpf, kexec, …). Override here only to widen/narrow it, e.g.:
30+
# seccomp_deny = ["ptrace", "mount", "bpf", "kexec_load", "kexec_file_load"]

‎sandboy/src/main.rs‎

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
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

Comments
 (0)