43. Code execution
Why this layer exists
Three earlier chapters stopped at the same wall. Chapter 27’s terminal runs a shell as the reader, and its text says what that costs: “everything the user can read, a private key file included, is readable by any command the reader approves”, and “Chapter 43 narrows the filesystem”. Chapter 36’s skills are inert because nothing could run them safely; ErrInert is the sentence “executable content is not readable until chapter 43’s sandbox exists”. Chapter 37’s registry refuses terminal, and its golden set has no code-execution task, because running model-written code needs a place to run it. Chapter 40 left a Sandbox key in aecd.json and a Runner the terminal can sit behind. This chapter builds what those four promised.
The agent now writes programs and runs them. A mistake in one, or an instruction smuggled into text the model read, then acts with whatever the process can reach. The sandbox is a bound on that damage, and the bound has parts that fail separately: the files the code can read and write, the network it can open, the processes it can leave behind, the memory and CPU it can take, the time it can hold, and the environment of the daemon that started it. A backend says in one Isolation struct which of these it holds, and a test attacks each claim on the hosts the chapter names. The chapter’s table of results is a measurement on two machines and carries no guarantee for a third.
Two limits come first. A sandbox that shares the host’s kernel is not a boundary against a kernel exploit: Chen et al. ran HumanEval completions under gVisor because “a malicious container could potentially compromise a host” and “gVisor protects the host” (arXiv 2107.03374, p. 4), and gVisor’s own documentation describes itself as “an application kernel” that “is written in a memory-safe language (Go) and runs in userspace”. The next steps past a shared kernel are a userspace kernel such as gVisor, a microVM, or another host; this chapter builds the last as an ssh backend and names the microVM (ward, the sibling book’s) as absent. And a boundary is only as good as its test: the chapter spends as much of its length on how the claims were checked, and on what the checks found wrong, as on the mechanisms.
Hermes layers the same way, and its source shows two choices this book makes the other way (everything below is at commit cca83848ec79a4a6a2ecc10285725559bf72c97c). Its environments are local.py, docker.py, ssh.py and cloud backends under tools/environments/. docker.py drops every capability and re-adds three (--cap-drop ALL, then DAC_OVERRIDE, CHOWN and FOWNER, docker.py:307–311); this book’s podman backend re-adds none. The CPU, memory and pid limits are added only when a probe of the host says the cgroup controllers are there (_cgroup_limits_available, docker.py:431–437, used at :789–794): on a host without them the container starts without the limits. And a comment in tools/terminal_tool.py records the failure the book’s nil backend refuses by construction: processes that skip the launch paths “would otherwise fall back to the local backend even when config selects docker — running on the host the user meant to sandbox” (terminal_tool.py:625–627). Here the probes run when the daemon opens, and a daemon whose configured lever is present and does not work does not start.
Mechanism
A backend and what it claims
A command is a program, an environment and a directory, and the interface is deliberately thin so that a backend can be a process group, a namespace, a container or another host.
// Runner runs one command somewhere other than the agent's own process
// group: chapter 43's sandbox backends implement it (sandbox.Backend has
// this method), and Terminal routes its shell through one when Runner is
// set. It is declared here so that tool does not import sandbox.
type Runner interface {
Run(ctx context.Context, c Command) (Output, error)
}
// Command is what a backend runs. Argv is the program and its arguments;
// paths in it are relative to Dir, because a backend may mount Dir
// somewhere else (podman: /work). Dir is the workspace on this host. Env is
// the whole environment the command gets: a backend never adds the daemon's
// own. Wall bounds the run; 0 is the backend's default.
type Command struct {
Argv []string
Dir string
Stdin []byte
Env map[string]string
Wall time.Duration
}
// Output is what came back. Status is the exit status, or -1 when the
// command was ended by a signal, named in Signal ("KILL" for the wall
// limit). Truncated says a stream was cut at the backend's cap. Wall is the
// measured run time.
type Output struct {
Stdout []byte
Stderr []byte
Status int
Signal string
Truncated bool
Wall time.Duration
}
Runner is declared in package tool so that tool does not import sandbox; chapter 27’s Terminal routes its shell through one when it is set. The environment is the whole environment: a backend never adds the daemon’s own, and the tools build it (below). Paths in Argv are relative to Dir, because podman mounts the workspace at /work and a host path would not exist there. A command that fails, is killed or times out is an Output; an error means the backend could not run it at all.
// Limits is what a run may use. Wall is the deadline; CPU is the CPU time
// of each process (RLIMIT_CPU inside every backend; a process count
// multiplies it); MemoryBytes is address space per process (RLIMIT_AS)
// under plain local and bwrap, a cgroup limit for the whole run under
// systemd-run and podman, and the size of each of bwrap's writable tmpfs
// mounts (/tmp, /var/tmp, /dev/shm), which RLIMIT_AS does not count: three
// mounts, so under bwrap alone the code can hold up to three times
// MemoryBytes in tmpfs pages; Pids
// bounds the process count where a cgroup exists (TasksMax,
// --pids-limit) and nowhere else; OutputBytes caps each stream; Network
// false means no network namespace reachable where the backend has one;
// ReadOnly leaves the host read-only with the workspace the one writable
// mount (bwrap and podman; plain local cannot).
//
// Under a scope without bwrap the cgroup limits are cooperative: the
// scope's memory.max, pids.max, cpu.max and cgroup.procs belong to the
// daemon's uid, so code of that uid inside the scope can write them (or
// move itself out of the scope), and the limits hold only against code that
// does not attack them. bwrap inside a scope closes this (its /sys is
// read-only and its cgroup namespace is the scope); podman's cgroup is
// the container runtime's.
type Limits struct {
Wall time.Duration `json:"wall"` // default 60 s
CPU time.Duration `json:"cpu"` // default 30 s
MemoryBytes int64 `json:"memory_bytes"` // default 512 MiB
Pids int `json:"pids"` // default 256
OutputBytes int `json:"output_bytes"` // default 64 KiB each stream
Network bool `json:"network"` // false: no network
ReadOnly bool `json:"read_only"` // root read-only; the workspace is the one writable mount
}
// UnmarshalJSON decodes onto DefaultLimits and refuses a key it does not know: a field the object omits keeps its
// default (ReadOnly true among them) and a field it gives wins, false and zero
// included for the bools and durations it names. A configuration that sets
// only {"memory_bytes": N} therefore keeps the read-only root. Marshalling is
// unchanged, so a full object round-trips; a pointer field that is absent or
// null never reaches this method and stays nil (Configure reads Limits{} as
// DefaultLimits).
func (l *Limits) UnmarshalJSON(b []byte) error {
type plain Limits
p := plain(DefaultLimits())
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
if err := dec.Decode(&p); err != nil {
return err
}
*l = Limits(p)
return nil
}
// DefaultLimits is Limits with every zero field filled.
func DefaultLimits() Limits {
return Limits{Wall: 60 * time.Second, CPU: 30 * time.Second, MemoryBytes: 512 << 20, Pids: 256, OutputBytes: 64 << 10, ReadOnly: true}
}
// withDefaults fills the zero fields of l from DefaultLimits (the bools are
// left as given: false is a value).
func (l Limits) withDefaults() Limits {
d := DefaultLimits()
if l.Wall <= 0 {
l.Wall = d.Wall
}
if l.CPU <= 0 {
l.CPU = d.CPU
}
if l.MemoryBytes <= 0 {
l.MemoryBytes = d.MemoryBytes
}
if l.Pids <= 0 {
l.Pids = d.Pids
}
if l.OutputBytes <= 0 {
l.OutputBytes = d.OutputBytes
}
return l
}
// Isolation is a backend's own account of itself, which the chapter's
// table prints and the escape suite tests. Each field is a claim about
// one property.
type Isolation struct {
Filesystem bool // the host's user trees (home, /root, /run, /tmp) are not visible; the system directories are, read-only
Network bool // no network namespace reachable
Pids bool // a setsid child does not survive the kill (a pid namespace, or a cgroup); under a scope without bwrap it holds against code that does not write cgroupfs
Memory bool // a memory limit is applied (cgroup or rlimit); an rlimit is per process, and a scope's cgroup is cooperative without bwrap
CPU bool // an RLIMIT_CPU per process is applied
Users bool // runs as an unprivileged uid distinct from the daemon's, or in a user namespace
Env bool // the code cannot read the daemon's environment: not through its own environment, and not through /proc (its own pid namespace, or another host)
Host bool // a separate kernel (ssh to another host; ward)
}
// Backend runs commands. Run returns an error only when the backend could
// not run the command at all (the binary is missing, the workspace does
// not exist, the context ended before it started); a command that fails,
// is killed or times out is an Output.
type Backend interface {
Name() string
Run(ctx context.Context, c tool.Command) (tool.Output, error)
Isolates() Isolation
}
// ErrUnavailable is a backend whose host tool is absent.
var ErrUnavailable = errors.New("sandbox: this backend is not available on this host")
// Local runs on this host. With Bwrap and SystemdRun empty it is chapter
// 27's shape plus a ulimit wrapper; with Bwrap set the command runs in
// bubblewrap's namespaces; with SystemdRun set it runs in a transient user
// scope with cgroup limits; with both, the scope wraps bwrap. Shell is the
// shell for the wrapper (default /bin/sh).
//
// Every program the backend itself starts is an absolute path, resolved once
// by Detect (Bwrap, SystemdRun, Env, Systemctl, and true for the probes):
// systemd-run would otherwise look "env" up in the daemon's PATH from the
// workspace, outside bwrap, and a PATH element the model can write would run
// the file it planted there. Env and Systemctl may be left empty by a caller
// that builds a Local by hand; Run then resolves them the same way and
// refuses (ErrUnavailable) when it cannot.
type Local struct {
Bwrap string // path or ""
SystemdRun string // path or ""
Shell string
Env string // env(1), absolute: the scope resets the code's environment with it
Systemctl string // systemctl, absolute: the scope's kill, stop and reset
Limits Limits
scopeProbe
}
// Podman runs rootless containers from Image through Binary.
type Podman struct {
Binary string
Image string
Limits Limits
}
// SSH runs on Host as User through Binary with Key (D3: tested against a
// fake binary; chapter 51 names a real host).
type SSH struct {
Binary string
Host string
User string
Key string
Limits Limits
}
// Ward is the sibling book's microVM supervisor, which does not exist
// today: every method says so.
type Ward struct{}
func (Ward) Name() string { return "ward" }
func (Ward) Run(context.Context, tool.Command) (tool.Output, error) {
return tool.Output{}, ErrUnavailable
}
func (Ward) Isolates() Isolation { return Isolation{Host: true} }
// Detect finds bwrap and systemd-run on PATH and returns a Local that uses
// what it found, plus the names it found, starting nothing. With systemd-run
// it also resolves env, systemctl and true to absolute paths. It does not
// check that a user manager answers systemd-run or that bwrap starts
// (Configure does). A lever that is absent is left out; a lookup that fails
// otherwise (a hit in a relative PATH element, exec.ErrDot) or a program the
// scope needs that is missing is not "absent": the Local keeps the error and
// every Run returns it (Configure returns it at once), so a daemon never runs
// with less isolation than it was asked for.
func Detect() (*Local, []string) {
l, found, _ := detect()
return l, found
}
func detect() (*Local, []string, error) {
l := &Local{Limits: DefaultLimits()}
var found []string
var errs []error
optional := func(name string) string {
p, err := lookAbs(name)
switch {
case err == nil:
found = append(found, name)
return p
case errors.Is(err, exec.ErrNotFound):
default:
errs = append(errs, fmt.Errorf("%w: %s: %w", ErrUnavailable, name, err))
}
return ""
}
l.Bwrap = optional("bwrap")
l.SystemdRun = optional("systemd-run")
if l.SystemdRun != "" {
l.Env, l.Systemctl, l.trueBin, _ = scopePrograms(l.Env, l.Systemctl, l.trueBin, lookAbs, &errs)
}
l.setupErr = errors.Join(errs...)
return l, found, l.setupErr
}
// scopePrograms resolves env, systemctl and true to absolute paths where
// they are empty, appending to errs for each that cannot be.
func scopePrograms(envBin, systemctl, trueBin string, look func(string) (string, error), errs *[]error) (string, string, string, bool) {
ok := true
for _, w := range []struct {
p *string
name string
}{{&envBin, "env"}, {&systemctl, "systemctl"}, {&trueBin, "true"}} {
if *w.p != "" {
continue
}
p, err := look(w.name)
if err != nil {
*errs = append(*errs, fmt.Errorf("%w: %s, which the systemd-run scope needs: %w", ErrUnavailable, w.name, err))
ok = false
continue
}
*w.p = p
}
return envBin, systemctl, trueBin, ok
}
Limits is what a run may use, and its comment records what each number bounds, because each is bounded by a different mechanism in each backend. The defaults are 60 seconds of wall time, 30 of CPU time, 512 MiB, 256 processes, 64 KiB per output stream and a read-only root. Isolation is the backend’s account of itself, one claim per property, and the discipline of the chapter is that a claim is either attacked by a test that could refute it or listed as not attacked; Users is in the second list. Four of the claims are narrower than their names. Filesystem says the user’s trees are hidden and the system directories are visible read-only; it does not say that no host file is visible. Pids says a setsid child does not survive the kill; it does not say the process count is bounded, which only a cgroup bounds. Memory is per process under an rlimit and cooperative under a scope. And Env says the code cannot read the daemon’s environment, which is a stronger sentence than “does not inherit it”, and which is false for two of the four local modes. The sections below derive each.
Local composes up to three levers around the command: a ulimit wrapper always, bubblewrap when Bwrap is set, a systemd user scope when SystemdRun is set, and the scope outside bubblewrap when both are. Detect finds the levers the host has, so the same code is four backends on four hosts.
The ulimit wrapper
The innermost lever is a shell that sets two resource limits and replaces itself with the command.
// ulimitArgv wraps argv in a shell that sets RLIMIT_AS (KiB) and
// RLIMIT_CPU (seconds) and execs argv with its arguments: "$0" is argv[0].
// RLIMIT_NPROC is not set: it counts every process of the uid, not the
// sandbox's. An argv[0] that starts with "-" would be read by exec as an
// option, so it is given as "./-...".
func ulimitArgv(shell string, l Limits, argv []string) []string {
kb := l.MemoryBytes / 1024
sec := int64(l.CPU / time.Second)
if sec < 1 {
sec = 1
}
script := fmt.Sprintf(`ulimit -v %d && ulimit -t %d && exec "$0" "$@"`, kb, sec)
out := append([]string{shell, "-c", script}, argv...)
if len(argv) > 0 && strings.HasPrefix(argv[0], "-") {
out[3] = "./" + argv[0]
}
return out
}
Limits has one custom decoder, UnmarshalJSON, which decodes an object onto DefaultLimits: a field it omits keeps its default, ReadOnly true among them, so a configuration that sets only memory_bytes cannot drop the read-only root by silence; it has no custom encoder, so durations are nanoseconds in the JSON and a full object round-trips. It refuses a key it does not know, as every reader of configuration in this book does, so a misspelt memory_bytes is an error and not a silent default. A pointer field that is absent or null stays nil; the caller then passes Limits{}, which Configure reads as DefaultLimits.
ulimit -v takes kibibytes and sets RLIMIT_AS, the size of the process’s address space; ulimit -t takes seconds and sets RLIMIT_CPU. Without -S or -H the shell sets both the soft and the hard limit, so the code cannot raise either. For the default 512 MiB the arithmetic is
and the CPU limit is the 30 seconds of DefaultLimits (TestPodmanArgv pins ulimit -v 524288 && ulimit -t 30 in the container’s argv). exec "$0" "$@" keeps the command’s own argv[0].
Both limits are per process, and a test shows each. RLIMIT_AS bounds one process’s address space. It counts reserved mappings that are never touched, so a large reservation fails early, and it does not count tmpfs pages, page cache or kernel memory; N children have N budgets, which the escape table’s anonymous-memory row shows under bubblewrap alone, where four 40 MiB pipelines finish under a 64 MiB limit. RLIMIT_CPU is likewise per process, and TestCPULimitKillsASpinInEveryMode runs a spin into it under CPU: 1s and Wall: 20s on every local mode the host has and sees the spin end well before the wall. getrlimit(2) states why RLIMIT_NPROC is not used for a process bound: it is a limit on “the number of extant process (or, more precisely on Linux, threads) for the real user ID of the calling process”. The count is the uid’s, so the daemon’s own processes and every other process of Kyle’s count against it, and the first fork inside the sandbox would fail on a busy host. A per-sandbox count needs a cgroup (pids.max) or a container’s --pids-limit, and the escape table below shows which backends have one.
Namespaces: bubblewrap
Running as the same uid, a process reads every file the uid can read. Permissions cannot hide the reader’s home from code that runs as the reader, so the sandbox hides it by not mounting it: a mount namespace gives the code its own tree. An unprivileged user can make one only together with a user namespace (“Since Linux 3.8, unprivileged processes can create user namespaces”, user_namespaces(7)). Inside the new user namespace the process has capabilities over the resources its namespaces govern and none over the host, and file access is still checked as the invoking uid mapped back, so the namespace changes what is mounted and nothing about what the uid may open. bubblewrap’s README says of itself that it “is not a complete, ready-made sandbox with a specific security policy” and that “the level of protection between the sandboxed processes and the host system is entirely determined by the arguments passed to bubblewrap”. The argument list is the backend.
// smallTmpfs is the size of the tmpfs mounts that replace /home, /root
// and /run: nothing is meant to live there, and one mebibyte stops the
// code from using them as scratch space.
const smallTmpfs = 1 << 20
// bwrapArgv wraps inner in bubblewrap: every namespace unshared, and no
// further user namespace creatable inside (--disable-userns); the network
// shared back only when lim.Network (with the resolver's directory, which
// /etc/resolv.conf points into on a systemd-resolved host); the sandbox
// dies with this process and gets a new session; the host read-only (the
// system directories stay visible), with the reader's home, root's, /run
// (the agent socket, keyrings), /tmp and /var/tmp replaced by empty tmpfs
// and a fresh /proc and /dev. Every tmpfs has a size: RLIMIT_AS does not
// count tmpfs pages, and an unsized one is half of RAM. /home, /root and
// /run get a mebibyte; /tmp, /var/tmp and /dev/shm get lim.MemoryBytes
// each (three mounts: up to three times lim.MemoryBytes in all). The
// workspace is the one writable bind (after the tmpfs mounts, which would
// hide it); the environment is cleared and set to exactly env.
func bwrapArgv(bwrap string, c tool.Command, lim Limits, env []string, inner []string) []string {
argv := []string{bwrap, "--unshare-all", "--unshare-user", "--disable-userns"}
if lim.Network {
argv = append(argv, "--share-net")
}
argv = append(argv, "--die-with-parent", "--new-session", "--ro-bind", "/", "/")
size := func(n int64) string { return strconv.FormatInt(n, 10) }
for _, hidden := range []string{"/home", "/root", "/run"} {
argv = append(argv, "--size", size(smallTmpfs), "--tmpfs", hidden)
}
if lim.Network {
argv = append(argv, "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve")
}
for _, scratch := range []string{"/tmp", "/var/tmp"} {
argv = append(argv, "--size", size(lim.MemoryBytes), "--tmpfs", scratch)
}
argv = append(argv, "--proc", "/proc", "--dev", "/dev", "--size", size(lim.MemoryBytes), "--tmpfs", "/dev/shm",
"--bind", c.Dir, c.Dir, "--chdir", c.Dir, "--clearenv")
for _, kv := range env {
k, v, _ := strings.Cut(kv, "=")
argv = append(argv, "--setenv", k, v)
}
argv = append(argv, "--")
return append(argv, inner...)
}
The list is built in an order that matters, so it is derived in that order.
The root. --ro-bind / / makes the host’s tree visible read-only, recursively, so every host mount comes with it. That is the compromise Isolation.Filesystem words honestly: the programs the code needs are there (on a host whose programs live outside /usr, an allow-list of directories would have to know where), and so is everything world-readable under the system directories. Its alternative is an allow-list of /usr, /etc and a few symlinks, which hides more and must be right for each distribution.
The user trees. The root bind exposes /home, /root and /run. The first two hold the reader’s files; /run holds /run/user/<uid>, the session bus and the agent sockets, and the bubblewrap README’s warning applies to each of them: “Everything mounted into the sandbox can potentially be used to escalate privileges”. Each is covered by an empty tmpfs, as are /tmp and /var/tmp, where other programs leave sockets and files. This relies on mount stacking: a mount made later at a path hides what was there (mount_namespaces(7): “it is possible to stack (and unstack) a mount on top of one of the inherited locked mounts in a less privileged mount namespace”). That is also why the workspace bind comes after every tmpfs. A workspace under /tmp (where Go’s t.TempDir puts the tests’ when TMPDIR is unset) shows why: a --tmpfs /tmp that came after --bind WS WS would hide the workspace and --chdir would fail. The order in the list is the one that works, and TestLocalArgv pins it.
Sizes. An unsized tmpfs has the kernel’s default size, half of RAM, and RLIMIT_AS does not count tmpfs pages. So each tmpfs has a size: a mebibyte for /home, /root and /run, where nothing should live, and MemoryBytes each for /tmp, /var/tmp and /dev/shm. That is three mounts of the budget, not one. Under bubblewrap alone a run can hold up to
of tmpfs pages at the defaults, and MiB under the 64 MiB the escape suite uses; only a scope bounds the whole tree. TestBwrapTmpfsIsSized checks each mount on its own: 8 MiB written to each of /tmp, /var/tmp and /dev/shm succeeds, 100 MiB fails, and 4 MiB into /home or /run fails.
The namespaces. --unshare-all unshares user (as -try), ipc, pid, net, uts and cgroup (also as -try). --unshare-user --disable-userns follows it, because --disable-userns needs an explicit --unshare-user and stops the code from creating a nested user namespace, in which it would hold CAP_SYS_ADMIN and reach more of the kernel (TestBwrapNoNestedUserNamespace runs unshare -U inside). With Network true the argv adds --share-net, which bwrap(1) says overrides an earlier --unshare-all, and binds the resolver’s directory read-only so /etc/resolv.conf is readable on a systemd-resolved host (readable, not “resolves”).
Process death. --die-with-parent --new-session do two jobs. Under --unshare-pid bubblewrap runs a minimal pid 1 in the namespace, and pid_namespaces(7) is the rule that makes the kill work: “If the ‘init’ process of a PID namespace terminates, the kernel terminates all of the processes in the namespace via a SIGKILL signal”. --die-with-parent makes pid 1 die when the daemon’s child (the outer bwrap) dies, and the kernel then kills the namespace, setsid child included. --new-session calls setsid so the code cannot inject keystrokes into the daemon’s terminal (TIOCSTI, CVE-2017-5226). Its cost is that the daemon’s process-group kill reaches only the outer bwrap, so the Pids claim rests on --die-with-parent and the pid namespace alone.
The environment. --clearenv unsets everything and each --setenv sets exactly one entry of Command.Env. This is the subject of its own section below, because it is where the first version of this backend was wrong.
A cgroup: the systemd user scope
A pid namespace kills a tree; it counts nothing. The kernel’s counting and limiting is the cgroup, and an unprivileged user gets one from the systemd user manager: systemd-run --user --scope starts the command inside a transient scope with resource-control properties.
// scopeArgv wraps inner in a transient user scope with cgroup limits.
// MemorySwapMax=0 keeps swap from absorbing what MemoryMax refuses; the
// CPU share is one CPU, a constant, since Limits.CPU is a total that the
// ulimit wrapper inside already enforces. systemd-run expands $ and ${...}
// on its command line by default from systemd 258 on (and not at all
// before 254), so --expand-environment=no (systemd 254 and later) is
// given and the wrapped command reaches the code unchanged on every
// version that accepts it; probeScope refuses a systemd-run that does
// not.
func scopeArgv(systemdRun, unit string, lim Limits, inner []string) []string {
argv := []string{systemdRun, "--user", "--scope", "--quiet", "--collect", "--unit", unit,
"-p", "MemoryMax=" + strconv.FormatInt(lim.MemoryBytes, 10),
"-p", "MemorySwapMax=0",
"-p", "TasksMax=" + strconv.Itoa(lim.Pids),
"-p", "CPUQuota=100%",
"--expand-environment=no",
"--"}
return append(argv, inner...)
}
// argv is the whole command line for c: the ulimit wrapper, then the
// levers from the inside out. bwrap sets the code's environment with
// --clearenv/--setenv; a scope resets the environment of what it starts
// with env -i, bwrap or the shell (the scope inherits the daemon's
// environment, and bwrap's own pid 1 keeps the environment it was
// started with, which the code reads at /proc/1/environ); the scope wraps
// the outermost. env is Local.Env when set, and the bare name for a Local
// built by hand (Run never uses the bare name: see wrappers).
func (l *Local) argv(c tool.Command, lim Limits, env []string, unit string) []string {
envBin := l.Env
if envBin == "" {
envBin = "env"
}
return l.argvWith(c, lim, env, unit, envBin)
}
func (l *Local) argvWith(c tool.Command, lim Limits, env []string, unit, envBin string) []string {
inner := ulimitArgv(l.shell(), lim, c.Argv)
if l.Bwrap != "" {
inner = bwrapArgv(l.Bwrap, c, lim, env, inner)
}
if l.SystemdRun != "" {
inner = scopeArgv(l.SystemdRun, unit, lim, envReset(envBin, env, inner))
}
return inner
}
MemoryMax is memory.max and the kernel’s out-of-memory killer is “invoked inside the unit” when it cannot be contained (systemd.resource-control(5)); MemorySwapMax=0 is memory.swap.max, so swap does not absorb what the limit refuses; TasksMax is pids.max, “the maximum number of tasks that may be created in the unit”, threads included. CPUQuota=100% is a rate, one CPU, not a total; the total is the RLIMIT_CPU inside. --collect unloads the unit even when it ended failed, and the unit name carries a token drawn once per process (UnitPrefix), so a leftover check lists this run’s units and nobody else’s. A scope has no main process and stays active while any process is in it, and cgroup membership is inherited by fork and unchanged by setsid, so killing the cgroup reaches the process a process-group kill misses.
That is why Run ends every scoped run with collectScope: systemctl --user kill --signal=KILL, then stop, then reset-failed, whatever the command did. A stop alone sends a gentler signal first and waits for the unit’s stop timeout; the kill comes first so that the wall limit means the wall limit. A cleanup that cannot be started, or that outlasts its ten seconds, is an error Run returns with the command’s output.
// Run runs c. With a scope, the unit is killed, stopped and reset after
// Wait whatever happened: the kill is what reaches a setsid child, the
// reset what clears a scope the OOM killer left failed. Plain local and
// bwrap alone run with the code's own environment (bwrap needs none: its
// directory and paths are explicit, and its pid 1 keeps the environment
// it started with, which the code can read). A scope runs with the
// daemon's own environment so systemd-run reaches the user bus, and
// resets it with env -i in front of what it starts.
//
// A command that exits 128+n (129 to 159) reads as a death by signal n under
// bwrap and podman, where the wrapper reports a signal that way (under ssh the
// remote shell exits with the killed command's 128+n, which reads the same
// way; chapter 51's table measured it): an
// "exit 137" the code chose is indistinguishable from SIGKILL there (plain
// local and a scope alone report the signal itself). A kill by the CPU limit
// is SIGKILL like the wall kill; only Output.Wall tells them apart.
func (l *Local) Run(ctx context.Context, c tool.Command) (tool.Output, error) {
if len(c.Argv) == 0 {
return tool.Output{}, errEmptyArgv
}
if l.setupErr != nil {
return tool.Output{}, l.setupErr
}
lim := l.Limits.withDefaults()
if c.Wall > 0 {
lim.Wall = c.Wall
}
var envBin, systemctl string
if l.SystemdRun != "" {
if err := ctx.Err(); err != nil {
return tool.Output{}, err
}
var err error
var trueBin string
if envBin, systemctl, trueBin, err = l.wrappers(c.Dir); err != nil {
return tool.Output{}, err
}
if err := l.probeScopeWith(trueBin); err != nil {
return tool.Output{}, err
}
}
env := envList(c.Env)
procEnv := env
if l.SystemdRun != "" {
procEnv = os.Environ()
}
unit := UnitPrefix() + newID()
spec := runSpec{argv: l.argvWith(c, lim, env, unit, envBin), dir: c.Dir, procEnv: procEnv, stdin: c.Stdin, wall: lim.Wall, cap: lim.OutputBytes}
if l.SystemdRun != "" {
spec.after = func() error { return collectScope(systemctl, unit) }
}
out, err := run(ctx, spec)
if l.Bwrap != "" {
out = signalled(out)
}
return out, err
}
// collectScope kills, stops and resets the unit. A command that exits
// non-zero is the usual case (the scope is already gone) and is ignored; one
// that cannot be started, or runs past its 10 seconds, is returned, because
// then the scope may not have been killed.
func collectScope(systemctl, unit string) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
var first error
for _, args := range [][]string{
{"--user", "kill", "--signal=KILL", unit + ".scope"},
{"--user", "stop", unit + ".scope"},
{"--user", "reset-failed", unit + ".scope"},
} {
err := exec.CommandContext(ctx, systemctl, args...).Run()
var ee *exec.ExitError
if err != nil && (ctx.Err() != nil || !errors.As(err, &ee)) && first == nil {
first = fmt.Errorf("systemctl %s %s: %w", args[1], unit, err)
}
}
return first
}
Expansion. systemd-run expands ${VAR} in a scope’s command line itself. The sentence in its manual is “Expand environment variables in command arguments. If enabled (the default) …”, and for --scope the expansion is done by systemd-run itself. The NEWS files give the history: 254 added --expand-environment= and left it off for --scope, and 258 turned it on. The first design doubled every $ so that expansion would collapse them. That is right on 258 and later, and wrong on every version before 258, where nothing collapses {% math %} and the shell receives it literally. The backend therefore passes --expand-environment=no, which the model’s own Argv also needs (text with a $ in it would otherwise be read from systemd-run’s environment), and the probe below refuses a systemd-run older than 254. TestShellTextReachesTheCodeUnchanged sends ${HOME}-$X-{% endmath %}-$(id)-%h, quotes and a backtick through every mode the host has, as an argument and as an environment value, and compares bytes.
The limits are cooperative. The user manager runs as the daemon’s uid, and it creates the scope’s directory and files with that owner. cgroups(7) describes delegation as the delegater making “certain directories and files writable by the delegatee, typically by changing the ownership of the objects to be the user ID of the delegatee”. Code in the scope runs as that uid. It can write max into its own memory.max, pids.max and cpu.max, and by the same permission write its own pid into another cgroup’s cgroup.procs and leave the kill’s reach; the suite attacks only the memory.max write. So under a scope alone, Pids and Memory hold against code that does not attack them. The cgroup row of the escape table measures it: the code writes max to its own memory.max, and the outcome is tampered under a scope alone on both hosts, refused under bubblewrap inside a scope, and refused under podman. What closes it under bubblewrap is derived, and the row confirms the outcome and not the reason: the root is bound read-only, so the cgroup files are visible and cannot be written, and --unshare-cgroup-try roots the code’s cgroup namespace at the scope. A read-only mount refuses a write only while the code cannot remount it or mount a fresh cgroup filesystem, and the code holds no capability to do either: bubblewrap drops them all, and --disable-userns stops the nested namespace that would hand them back. That part is derived from bwrap(1) and not measured, since a write to a cgroup file is an attack. The word invisible in the table’s detail column would mean “no memory.max of this unit was found where the script looked” and not a refused write; no row shows it.
What each mode claims
// Name says which levers are set: local, local+bwrap, local+systemd-run,
// local+bwrap+systemd-run.
func (l *Local) Name() string {
name := "local"
if l.Bwrap != "" {
name += "+bwrap"
}
if l.SystemdRun != "" {
name += "+systemd-run"
}
return name
}
// Isolates states what the levers give. bwrap gives the user trees (home,
// /root, /run, /tmp are replaced; the system directories stay visible
// read-only), the network and the user namespace; bwrap or a scope gives
// Pids (the kill reaches a setsid child: pid 1's death kills the
// namespace, or the cgroup kill); the ulimit wrapper gives Memory
// (RLIMIT_AS, address space, per process) and CPU (RLIMIT_CPU, per
// process) everywhere, and a scope adds the cgroup's tree-wide limits.
//
// Under a scope without bwrap, Pids and Memory are cooperative: the scope's
// cgroup files are writable by the daemon's uid, which the code runs as,
// so the limits hold only against code that does not attack them (the
// escape suite's TestEscapeCgroup measures it). Env is the claim that
// the code cannot read the daemon's environment. Command.Env is all it is
// given everywhere, but plain local and a scope alone leave the daemon
// its parent and in the same pid namespace, where same-uid code reads
// /proc/<daemon>/environ, so Env is true only with bwrap, whose pid
// namespace and /proc hide the daemon and whose own environment is
// Command.Env. Nothing here is a separate kernel.
func (l *Local) Isolates() Isolation {
b, s := l.Bwrap != "", l.SystemdRun != ""
return Isolation{
Filesystem: b,
Network: b && !l.Limits.Network,
Pids: b || s,
Memory: true,
CPU: true,
Users: b,
Env: b,
}
}
The figure draws the same claims as boxes. The dashed border is the cooperative limit, and the lines about the daemon’s environment say which boxes hide it. Read the claims against the levers. Bubblewrap gives Filesystem, Network (unless Network is set), Users and Env. Bubblewrap or a scope gives Pids, by the namespace’s init or by the cgroup’s kill. The ulimit wrapper gives Memory and CPU everywhere, per process, and a scope adds the cgroup’s tree-wide limits. Plain local claims only Memory and CPU: no filesystem, network, process, user or environment claim, and no escape row, because an attack on it would be an attack on the host.
The environment: the first lesson in testing a sandbox
The first design started bubblewrap with the daemon’s environment and relied on --clearenv to clear it for the command. Its test ran env inside the sandbox and passed: the code’s environment was exactly what it was given. The daemon’s whole environment was nonetheless readable at /proc/1/environ, because bubblewrap’s pid 1 inside the namespace is bubblewrap itself, still holding the environment it was started with; --clearenv is applied in the final child just before the command executes. Two independent readers found it, one by deriving the argv from the man pages before reading the code, one by reading the code. The test had checked the property that was easy to check, and the leak was the property that mattered.
The rule as built is that bubblewrap starts with no more than the code’s own environment: in plain and bubblewrap-alone runs the process is started with Command.Env as its environment, and under a scope env -i K=V … stands in front of bubblewrap exactly as it stands in front of the shell. A scope’s own systemd-run process does need the daemon’s environment, to find the user bus, and it passes none of it on.
// DefaultPath is the PATH ExecuteCode, SkillRun and the exec grader give
// the code unless they are told another: the FHS one, which is what a
// container image or a remote host has.
const DefaultPath = tool.DefaultSandboxPath
// HostPath is the PATH to give code that b runs on this host: the
// process's own PATH when b is a *Local (the code sees this host's
// filesystem, and a host whose programs live elsewhere, a Nix one, has
// nothing under DefaultPath), reduced to its absolute elements, and ""
// (DefaultPath) for any other backend, whose filesystem is an image's or
// another host's. The empty element, "." and every relative one are dropped:
// each names the command's working directory, the workspace, where the model
// can write a program without approval and have the next call run it in place
// of python3, cat or the command a human approved. (Elements inside the
// workspace are dropped where the workspace is known: see baseEnv.)
func HostPath(b Backend) string {
if _, ok := b.(*Local); ok {
return tool.PathOutside(os.Getenv("PATH"), "")
}
return ""
}
// baseEnv is what ExecuteCode and SkillRun give the code: a PATH (path, or
// DefaultPath when empty), a HOME that is the workspace, a locale, a
// temporary directory and a dumb terminal. Nothing of the daemon's. Any
// element of path that is the workspace or lies inside it is dropped: the
// model writes there without approval, so a file it plants in such a
// directory would run in place of the program the PATH was meant to find.
func baseEnv(home, path string) map[string]string {
path = tool.PathOutside(path, home)
if path == "" {
path = DefaultPath
}
return map[string]string{"PATH": path, "HOME": home, "LANG": "C.UTF-8", "TMPDIR": "/tmp", "TERM": "dumb"}
}
// lookAbs resolves a program the backend itself starts to an absolute path,
// through the daemon's PATH. A hit in a relative element (exec.ErrDot) is an
// error, not "absent": a backend that looked past it would run less
// isolation than the configuration asked for, silently.
func lookAbs(name string) (string, error) {
p, err := exec.LookPath(name)
if err != nil {
return "", err
}
if !filepath.IsAbs(p) {
return "", fmt.Errorf("%s resolved to the relative path %q: %w", name, p, exec.ErrDot)
}
return p, nil
}
// envReset prefixes `env -i K=V …` so the command runs with exactly env and
// nothing it inherited: used where the wrapping process must keep the
// daemon's own environment (systemd-run needs XDG_RUNTIME_DIR and the user
// bus) but the code inside must not see it. envBin is env(1)'s absolute
// path, resolved once: systemd-run would otherwise look "env" up in the
// daemon's PATH, from the workspace, before env -i runs.
func envReset(envBin string, env []string, argv []string) []string {
out := append([]string{envBin, "-i"}, env...)
return append(out, argv...)
}
// ulimitArgv wraps argv in a shell that sets RLIMIT_AS (KiB) and
// RLIMIT_CPU (seconds) and execs argv with its arguments: "$0" is argv[0].
// RLIMIT_NPROC is not set: it counts every process of the uid, not the
// sandbox's. An argv[0] that starts with "-" would be read by exec as an
// option, so it is given as "./-...".
func ulimitArgv(shell string, l Limits, argv []string) []string {
kb := l.MemoryBytes / 1024
sec := int64(l.CPU / time.Second)
if sec < 1 {
sec = 1
}
script := fmt.Sprintf(`ulimit -v %d && ulimit -t %d && exec "$0" "$@"`, kb, sec)
out := append([]string{shell, "-c", script}, argv...)
if len(argv) > 0 && strings.HasPrefix(argv[0], "-") {
out[3] = "./" + argv[0]
}
return out
}
The test that catches the failure is built to be unable to pass for the wrong reason. A sentinel variable is planted in the environment of a re-executed copy of the test binary, which plays the daemon; the sentinel must be in its exec-time environment, which is what /proc/<pid>/environ shows, and t.Setenv changes only Go’s copy of the environment and never reaches that file. The re-executed process builds each mode the host has and runs code that tests three places for the sentinel: its own environment (self), pid 1’s (pid1: the sandbox’s init under bubblewrap, the host’s otherwise) and its parent’s (ppid: the daemon, outside bubblewrap). A positive control, a child started with the sentinel in its exec-time environment reading its own, must see it, or the cells mean nothing. Only presence is reported, never a value. TestProcEnvironNotReadable compares each mode’s reading with Isolates().Env and fails when they differ, and with the original defect put back, the test fails. Its log on wntrmute (bubblewrap 0.12.0, systemd 261.2):
local: self=clean pid1=clean ppid=LEAK control=1
local+bwrap: self=clean pid1=clean ppid=clean control=1
local+systemd-run: self=clean pid1=clean ppid=LEAK control=1
local+bwrap+systemd-run: self=clean pid1=clean ppid=clean control=1
Under bubblewrap the daemon is not the code’s parent (the sandbox’s init is), and neither it nor pid 1 holds the sentinel; in the other two modes ppid is the daemon, and its environment is readable. The escape suite repeats the attack from inside a real run of every backend (TestEscapeDaemonEnviron): the daemon is the go test process, started by escape.sh with the sentinel in its environment.
So Isolation.Env means the code cannot read the daemon’s environment, and it is true where a pid namespace of its own and a fresh /proc hide the daemon (both bubblewrap modes, and podman’s container) or the daemon is on another host (ssh). It is false for plain local and a scope alone. There the code does not inherit the daemon’s variables, and it reads them anyway: the daemon is its parent in the same pid namespace, running as the same uid, and /proc/<daemon>/environ is readable. The table’s env: the code reads the daemon's environment from /proc row is escaped (recorded) for exactly those rows on both hosts. The hardening that closes the daemon’s own is prctl(PR_SET_DUMPABLE, 0) at daemon start: prctl(2) says a process that is not dumpable produces no core dump, “can not be attached via ptrace(2) PTRACE_ATTACH”, and has the ownership of the files in its /proc/<pid> directory affected. This chapter did not build it, because it is a behaviour change to aecd (no core dumps of the daemon) beyond what the chapter measured; chapter 48 builds it. aecd serve and aecd mcp make the process non-dumpable at start unless given -dumpable, and chapter 48 derives from the access-mode algorithm why that refuses the read, and measures it. The table’s rows above are the measurements as taken, before the hardening existed. The hardening closes the read of the daemon’s environment and not that of the reader’s other processes, which the same-uid code can also read, so a secret in the environment of any other process of the reader’s uid is still one the code can read.
A last point belongs here because it is the same lesson in another place. The values of Command.Env travel on command lines in every wrapping mode (env -i K=V, --setenv K V, podman’s -e K=V, the ssh remote line), where any local user reads them from /proc/<pid>/cmdline. For the five values the tools pass this is harmless. A secret does not belong in Command.Env. Hermes’s ssh.py makes the other choice: it sends names with SendEnv and carries the values on the ssh client’s own environment, “never the remote command text” (ssh.py:121–122).
Which programs the backend starts, and the code’s PATH
The code under a local backend gets the daemon’s PATH, reduced to its absolute elements, with none inside the workspace. Both halves have a reason, and the second was found by measurement.
The first: a host whose programs are not under the FHS directories has nothing under /usr/local/bin:/usr/bin:/bin. straylight is such a host, a Nix machine, and a constant PATH there finds no python3 or cat; the sandbox runs on the host’s filesystem, so the host’s PATH is the right one. Podman and ssh keep the constant, because their filesystem is an image’s or another host’s.
The second: the model writes into the workspace without asking, so a workspace directory on PATH would let one write_file replace python3, the oracle’s cat, or the program a human approved by reading its command line. An empty element, ., and every relative element name the command’s working directory, which is the workspace, so HostPath keeps only absolute elements, and baseEnv, the exec grader and terminal also drop any element that is the workspace or lies inside it, through a symlink as well.
The same reasoning applies to the programs the backend itself starts. systemd-run runs env -i in front of the command, and if env were looked up by name, systemd-run would find it in the daemon’s PATH, outside bubblewrap and with the daemon’s environment. Measured before the fix: a PATH element the code could write held a planted env, which ran unconfined. So every program a backend starts on this host (bwrap, systemd-run, env, systemctl, the probes’ true, podman, ssh) is an absolute path resolved once, and a hit in a relative element is an error. This is the rule that keeps a hijackable program, or a missing env, systemctl or true, from becoming a silent downgrade. It does not cover a missing lever: on a host with neither bwrap nor systemd-run on PATH, "sandbox": "local" is the plain backend, which opens without complaint and isolates nothing; the approval reason says so each time, and Open writes one warning line through Config.Warn naming the backend. A daemon whose PATH has only relative elements gets the FHS default for the code and a refusal for any wrapper it cannot find. TestPlantedWrapperDoesNotRun plants env, sh, bash, bwrap, systemd-run, systemctl, true, python3, cat and ulimit in an absolute element and checks that none runs; TestRelativePathHitIsRefused plants ./bwrap and ./env.
Probed at start, failing closed
// Configure builds the backend a configuration names: "local" (Detect),
// "podman" (the binary on PATH; the image from AEC_PODMAN_IMAGE or
// DefaultImage), "ssh" (the binary; AEC_SSH_HOST, AEC_SSH_USER and
// AEC_SSH_KEY, a path, never printed), "ward" (ErrUnavailable), "" (nil:
// no sandbox, and every tool that needs one refuses). The zero Limits is
// DefaultLimits (a read-only root among them), not an unset set of
// numbers; "local" probes bwrap (the real flags, running true) and the user
// manager (when systemd-run is present) and
// returns ErrUnavailable when either does not answer, or when a program
// the chosen levers need is missing or found only in a relative PATH element
// (never a silent downgrade to less isolation). The daemon
// (Config.Sandbox) and aec-eval (Suite.Sandbox) call it.
func Configure(name string, l Limits) (Backend, error) {
switch name {
case "":
return nil, nil
case "local":
b, _, err := detect()
if err != nil {
// A lever found only through a relative PATH element, or a
// program the scope needs that is missing: not "absent".
return nil, err
}
b.Limits = defaulted(l)
// The levers are checked here, not at the first tool call: a bwrap
// that cannot start with the sandbox's flags (user namespaces off, a
// bwrap too old for an option), a user manager that does not answer,
// or a systemd-run too old for --expand-environment refuses the
// daemon's Open.
if b.Bwrap != "" {
if err := b.probeBwrap(); err != nil {
return nil, err
}
}
if b.SystemdRun != "" {
if err := b.probeScope(); err != nil {
return nil, err
}
}
return b, nil
case "podman":
p, err := lookAbs("podman")
if err != nil {
return nil, fmt.Errorf("%w: podman: %v", ErrUnavailable, err)
}
img := os.Getenv("AEC_PODMAN_IMAGE")
if img == "" {
img = DefaultImage
}
return &Podman{Binary: p, Image: img, Limits: defaulted(l)}, nil
case "ssh":
p, err := lookAbs("ssh")
if err != nil {
return nil, fmt.Errorf("%w: ssh: %v", ErrUnavailable, err)
}
host := os.Getenv("AEC_SSH_HOST")
if host == "" {
return nil, errors.New("sandbox: the ssh backend needs AEC_SSH_HOST (and AEC_SSH_USER, AEC_SSH_KEY)")
}
if strings.HasPrefix(host, "-") {
return nil, fmt.Errorf("sandbox: AEC_SSH_HOST %q begins with '-'", host)
}
return &SSH{Binary: p, Host: host, User: os.Getenv("AEC_SSH_USER"), Key: os.Getenv("AEC_SSH_KEY"), Limits: defaulted(l)}, nil
case "ward":
return nil, fmt.Errorf("%w: ward", ErrUnavailable)
}
return nil, fmt.Errorf("sandbox: unknown backend %q (local, podman, ssh, ward)", name)
}
Configure is what the daemon and aec-eval call. For "local" it runs the levers instead of trusting that a binary exists: bubblewrap with the real flags and a true command, and systemd-run --user --scope --quiet --expand-environment=no -- true. A bubblewrap that cannot start (user namespaces off, a version too old for an option in the argv), a user manager that does not answer, or a systemd-run older than 254 makes Configure return ErrUnavailable with the tool’s own message, and the daemon’s Open fails with it. A program the chosen levers need that is missing or found only through a relative PATH element is the same refusal. Each probe has a 15-second context of its own, never a caller’s, so a caller that gives up cannot make the answer wrong, and a probe that timed out is reported and not remembered. "podman" resolves the binary; "ssh" needs AEC_SSH_HOST; "ward" is ErrUnavailable; "" is no backend at all, and every tool that needs one refuses.
For a lever that is present this is the opposite of the fallback Hermes’s source warns of, and it has a price: a daemon on a host with systemd-run but no answering user manager cannot open with "local". The alternative is a daemon that silently runs terminal unsandboxed, and the price is an error message a reader can act on. A reader who wants to start without a sandbox sets "sandbox": "". A host with neither lever is the exception: there is nothing to probe, "sandbox": "local" is the plain backend, and the warning line is what tells the principal so. Whether such a daemon should refuse to start instead is a design question this chapter leaves open.
Podman, ssh and ward
Podman’s isolation is a container runtime’s, and the argv names each lever.
func (p *Podman) Name() string { return "podman" }
// Isolates: a rootless container shares the kernel and nothing else the
// flags below can withhold.
func (p *Podman) Isolates() Isolation {
return Isolation{Filesystem: true, Network: !p.Limits.Network, Pids: true, Memory: true, CPU: true, Users: true, Env: true}
}
// argv is podman run with every lever: --rm, stdin, a name the cleanup
// can kill, no network, a read-only root, every capability dropped, no
// new privileges, the pids and memory cgroups (--memory-swap equal to
// --memory, as the scope has MemorySwapMax=0: podman-run(1) defaults the swap
// limit to double the memory limit, so swap would otherwise absorb what the
// limit refuses), one CPU, a timeout as the
// backstop, the caller's uid kept, the workspace at /work, the
// environment exactly env (--env-host=false keeps the host's variables out,
// and --http-proxy=false the proxy variables podman otherwise copies from its
// own environment into the container: podman-run(1), "--http-proxy", default
// true; a value equal to the host's workspace path, the HOME the tools set,
// is given as /work, where the container sees it), then the image and the
// ulimit wrapper.
func (p *Podman) argv(c tool.Command, lim Limits, env []string, name string) []string {
argv := []string{p.Binary, "run", "--rm", "-i", "--name", name}
if !lim.Network {
argv = append(argv, "--network", "none")
}
if lim.ReadOnly {
argv = append(argv, "--read-only")
}
argv = append(argv, "--cap-drop", "all", "--security-opt", "no-new-privileges",
"--pids-limit", strconv.Itoa(lim.Pids),
"--memory", strconv.FormatInt(lim.MemoryBytes, 10),
"--memory-swap", strconv.FormatInt(lim.MemoryBytes, 10),
"--cpus", "1",
"--timeout", strconv.Itoa(int(lim.Wall/time.Second)+5),
"--userns", "keep-id",
"-v", c.Dir+":/work", "-w", "/work", "--env-host=false", "--http-proxy=false")
for _, kv := range env {
if k, v, ok := strings.Cut(kv, "="); ok && v == c.Dir {
kv = k + "=/work"
}
argv = append(argv, "-e", kv)
}
argv = append(argv, p.Image)
return append(argv, ulimitArgv("sh", lim, c.Argv)...)
}
// Run runs c in a fresh container. The Go deadline kills the client, which
// does not stop the container, so the cleanup kills and removes it by
// name; --timeout is the backstop for a daemon that died.
func (p *Podman) Run(ctx context.Context, c tool.Command) (tool.Output, error) {
if p.Binary == "" {
return tool.Output{}, ErrUnavailable
}
if len(c.Argv) == 0 {
return tool.Output{}, errEmptyArgv
}
lim := p.Limits.withDefaults()
if c.Wall > 0 {
lim.Wall = c.Wall
}
env := envList(c.Env)
name := UnitPrefix() + newID()
// podman itself runs with the daemon's environment (its socket, config
// and policy live there); the container's environment is --env-host=false
// plus the -e values in argv.
out, err := run(ctx, runSpec{argv: p.argv(c, lim, env, name), dir: c.Dir, procEnv: os.Environ(), stdin: c.Stdin, wall: lim.Wall, cap: lim.OutputBytes,
after: func() error { p.remove(name); return nil }})
return signalled(out), err
}
// remove kills and removes the named container, ignoring errors: in the
// usual case --rm already removed it.
func (p *Podman) remove(name string) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
_ = exec.CommandContext(ctx, p.Binary, "kill", "--signal", "KILL", name).Run()
_ = exec.CommandContext(ctx, p.Binary, "rm", "-f", name).Run()
}
--network none unless Network; --read-only when the limits ask for it (the defaults do; the two configuration paths that set limits, aecd.json’s sandbox_limits and an eval suite’s, decode onto DefaultLimits, so an object that omits read_only keeps it and only an explicit "read_only": false drops it); every capability dropped; no-new-privileges; --pids-limit and --memory as cgroup limits the code cannot rewrite (the cgroup row says the memory.max write is refused on straylight; pids.max was not attacked), with --memory-swap equal to --memory, because podman defaults the swap limit to double the memory limit and swap would absorb what the limit refuses, as the scope’s MemorySwapMax=0 prevents; --cpus 1; --timeout as the backstop, the wall plus five seconds, 65 for the defaults; --userns keep-id, so files the container writes in the workspace are the reader’s; the workspace at /work. The image is alpine pinned by digest, docker.io/library/alpine@sha256:294b683c…, so a run never resolves a moved tag.
The environment needed a second look. --env-host=false keeps the host’s variables out, and it was not enough: podman’s own option file for --http-proxy at v5.8.6 says “By default proxy environment variables are passed into the container if set for the Podman process. This can be disabled by setting the value to false”, with “Defaults to true”. A daemon started behind a proxy would have handed the code the proxy’s address and any credentials in its URL. --http-proxy=false is in the argv, and TestEscapeDaemonEnviron plants http_proxy and HTTPS_PROXY in the daemon (sentinel values with an invalid host name, never a real proxy) and counts proxy-named variables in the code’s environment, with a positive control (http_proxy=x env) that must see one. On straylight it also runs the negative control: the same container with --http-proxy=true, through a wrapper script that changes that one argument, and the code’s environment holds both planted variables (proxy=2 in the evidence file). So the flag is what keeps them out.
The Go deadline kills the podman client, and the client’s death is not the container’s. So Run kills and removes the container by name after every run, and --timeout covers a daemon that died. TestZZNothingLeft lists containers and scopes carrying this process’s prefix at the end of the suite, and the escape script prints the same listings; both were empty on straylight after every run.
func (s *SSH) Name() string { return "ssh" }
// Isolates: another kernel, another user, the command's own environment,
// and ulimits there; what that host's filesystem, network and process
// table allow is that host's, so those are not claimed.
func (s *SSH) Isolates() Isolation {
return Isolation{Memory: true, CPU: true, Users: true, Env: true, Host: true}
}
// remote is the command line the remote shell runs: into the directory,
// an empty environment plus env, timeout(1) as the wall, the ulimit
// wrapper, the argv, each word quoted, then the shell's own exit with the
// command's status. The remote shell does not exec into env: timeout -s
// KILL signals its own process group when the wall fires, and a shell that
// had exec'd would die with it, which ssh reports as status 255 with
// nothing on stderr (Part IX's two "not measured" rows). A shell that
// stays the parent sees the child's 137 and exits with it, and signalled
// reads 137 as SIGKILL.
func (s *SSH) remote(c tool.Command, lim Limits, env []string) string {
var b strings.Builder
b.WriteString("cd " + shellQuote(c.Dir) + " && env -i")
for _, kv := range env {
b.WriteString(" " + shellQuote(kv))
}
b.WriteString(" timeout -s KILL " + strconv.Itoa(int(lim.Wall/time.Second)))
for _, w := range ulimitArgv("sh", lim, c.Argv) {
b.WriteString(" " + shellQuote(w))
}
b.WriteString("; exit $?")
return b.String()
}
// argv is the ssh command line: batch mode (no prompt), known hosts only
// (a daemon runs unattended), a connect timeout, the key and user when
// given, "--" (so a host is never an option), then the host and the remote
// line as one argument.
func (s *SSH) argv(c tool.Command, lim Limits, env []string) []string {
argv := []string{s.Binary}
if s.Key != "" {
argv = append(argv, "-i", s.Key)
}
argv = append(argv, "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "ConnectTimeout=10")
if s.User != "" {
argv = append(argv, "-l", s.User)
}
return append(argv, "--", s.Host, s.remote(c, lim, env))
}
// Run runs c on Host. The remote timeout is the wall; the Go deadline is
// ten seconds longer, for the connection. A run the caller cancels ends the
// local ssh at once and leaves the remote command to the remote timeout.
func (s *SSH) Run(ctx context.Context, c tool.Command) (tool.Output, error) {
if s.Binary == "" || s.Host == "" {
return tool.Output{}, ErrUnavailable
}
if strings.HasPrefix(s.Host, "-") {
return tool.Output{}, fmt.Errorf("sandbox: ssh host %q begins with '-'", s.Host)
}
if len(c.Argv) == 0 {
return tool.Output{}, errEmptyArgv
}
lim := s.Limits.withDefaults()
if c.Wall > 0 {
lim.Wall = c.Wall
}
env := envList(c.Env)
// ssh runs with the daemon's environment (known_hosts under HOME, the
// agent socket); the remote command resets to env with env -i in argv.
out, err := run(ctx, runSpec{argv: s.argv(c, lim, env), dir: c.Dir, procEnv: os.Environ(), stdin: c.Stdin, wall: lim.Wall + 10*time.Second, cap: lim.OutputBytes})
return signalled(out), err
}
ssh is another kernel. BatchMode=yes because a daemon has no one to ask, StrictHostKeyChecking=yes because an unattended connection must not learn a host key on first sight (Hermes’s ssh.py:120 uses accept-new), ConnectTimeout=10, and -- so a host is never an option. The remote line cds into the workspace path, resets the environment with env -i, applies timeout -s KILL as the wall and the same ulimit wrapper, and ends with ; exit $? so the shell stays the parent of timeout instead of exec’ing into it. The remote login shell must be a POSIX one for $? (orion’s is zsh 5.9.1, which handles ; exit $? as a POSIX shell does); a fish or tcsh login shell would reject it. It claims Memory, CPU, Users, Env and Host, and does not claim Filesystem or Network: what that host’s files and network allow is that host’s, and Caveat says so in the approval reason. A cancelled run ends the local ssh at once and leaves the remote command until its own timeout. This backend is tested here against a fake ssh binary that runs the remote line locally. A live table against a real host is chapter 51’s, and so is the matter of where the workspace lives there. Ward answers ErrUnavailable and claims Host; the microVM is the sibling book’s and does not exist.
The tools that run code
execute_code is execute_code(language, code[, stdin]).
// ExecuteCode is execute_code(language, code[, stdin]): the code is written
// to a file under Workspace/.execute_code/ and the language's argv runs it
// through Backend with a workspace-relative path (podman mounts the
// workspace elsewhere). Languages is the argv table (D13: configuration,
// DefaultLanguages by default). Path is the PATH the code gets
// (DefaultPath when empty; HostPath(Backend) for a backend on this host).
// Marked, never idempotent; a nil Backend refuses, so nothing model-written
// ever runs on the host unsandboxed.
type ExecuteCode struct {
Backend Backend
Workspace string
Limits Limits
Languages map[string][]string
Path string
// Approval is chapter 36's policy for the marking: Always (the zero
// value, this chapter's behaviour: every call is marked), or Policy,
// under which NeedsApproval answers false and chapter 47's gate decides
// per call; the daemon refuses Never for it.
Approval skill.ApprovalPolicy
n atomic.Int64
}
// DefaultLanguages is sh and python3 in isolated mode (-I: no site, no
// user site, no PYTHON* environment).
func DefaultLanguages() map[string][]string {
return map[string][]string{"sh": {"sh"}, "python3": {"python3", "-I"}}
}
// extensions names the file a language's code is written to.
var extensions = map[string]string{"sh": "sh", "python3": "py"}
var (
_ agent.Tool = (*ExecuteCode)(nil)
_ agent.Marked = (*ExecuteCode)(nil)
_ agent.Timeouter = (*ExecuteCode)(nil)
)
func (e *ExecuteCode) languages() map[string][]string {
if e.Languages != nil {
return e.Languages
}
return DefaultLanguages()
}
func (e *ExecuteCode) names() []string {
var out []string
for k := range e.languages() {
out = append(out, k)
}
sort.Strings(out)
return out
}
func (e *ExecuteCode) Spec() llm.Tool {
return llm.Tool{Name: "execute_code", Description: "Run a program you write (" + strings.Join(e.names(), ", ") + ") in the sandbox, in the workspace, and see its output. Needs approval.",
Parameters: schema([]string{"language", "code"}, map[string]any{
"language": map[string]any{"type": "string", "enum": e.names(), "description": "The interpreter."},
"code": map[string]any{"type": "string", "minLength": 1, "maxLength": MaxCode, "description": "The program's source."},
"stdin": map[string]any{"type": "string", "maxLength": MaxCode, "description": "Text fed to the program's standard input."},
})}
}
func (e *ExecuteCode) NeedsApproval(call toolcall.Call) (bool, string) {
if e.Approval == skill.Policy {
return false, ""
}
return true, "execute_code runs model-written code in the " + e.backendName() + " sandbox" + Caveat(e.Backend)
}
func (e *ExecuteCode) backendName() string {
if e.Backend == nil {
return "unconfigured"
}
return e.Backend.Name()
}
// Timeout is the wall limit plus ten seconds for the backend's own start
// and cleanup.
func (e *ExecuteCode) Timeout() time.Duration {
return e.Limits.withDefaults().Wall + 10*time.Second
}
func (e *ExecuteCode) Call(ctx context.Context, call toolcall.Call) agent.Result {
if res, ok := validate(e.Spec().Parameters, call); !ok {
return res
}
if e.Backend == nil {
return agent.ErrorResult("execute_code: no sandbox configured; code is not run on the host")
}
if len(stringArg(call.Arguments, "code")) > MaxCode || len(stringArg(call.Arguments, "stdin")) > MaxCode {
return agent.ErrorResult("execute_code: the code and the stdin are each capped at %d bytes", MaxCode)
}
lang := stringArg(call.Arguments, "language")
argv, ok := e.languages()[lang]
if !ok || len(argv) == 0 {
return agent.ErrorResult("execute_code: no interpreter for %q (known: %s)", lang, strings.Join(e.names(), ", "))
}
ext := extensions[lang]
if ext == "" {
ext = lang
}
rel, err := e.writeCode(ext, stringArg(call.Arguments, "code"))
if err != nil {
return agent.ErrorResult("execute_code: %v", err)
}
lim := e.Limits.withDefaults()
cmd := tool.Command{Argv: append(append([]string(nil), argv...), "./"+rel), Dir: e.Workspace,
Stdin: []byte(stringArg(call.Arguments, "stdin")), Env: baseEnv(e.Workspace, e.Path), Wall: lim.Wall}
out, err := e.Backend.Run(ctx, cmd)
if err != nil {
if ctx.Err() != nil {
return agent.ErrorResult("execute_code: interrupted\n%s", string(out.Stdout))
}
return agent.ErrorResult("execute_code: %v", err)
}
return observation("execute_code", out, lim)
}
// writeCode writes code to Workspace/.execute_code/<n>.<ext> through
// os.Root, 0600 and O_EXCL, and returns the workspace-relative path. n is
// the first number after this value's counter for which <n>.<ext> does not
// exist: a workspace outlives the tool value (the daemon builds its tools
// per turn over a session's workspace), so the counter is only a starting
// point and an earlier program is never overwritten or re-used.
func (e *ExecuteCode) writeCode(ext, code string) (string, error) {
root, err := os.OpenRoot(e.Workspace)
if err != nil {
return "", err
}
defer root.Close()
const dir = ".execute_code"
if err := root.Mkdir(dir, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
return "", err
}
for {
n := e.n.Add(1)
if n > MaxCodeFiles {
break
}
rel := fmt.Sprintf("%s/%d.%s", dir, n, ext)
f, err := root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if errors.Is(err, os.ErrExist) {
continue
}
if err != nil {
return "", err
}
if _, err := f.WriteString(code); err != nil {
f.Close()
return "", err
}
return rel, f.Close()
}
return "", fmt.Errorf("%s holds %d programs already", dir, MaxCodeFiles)
}
// observation turns an Output into what the model sees: the status line,
// stdout, stderr under its own heading when any, a note when a stream
// was cut, and an error observation for a non-zero status or a signal.
func observation(name string, out tool.Output, lim Limits) agent.Result {
var b strings.Builder
if out.Signal != "" {
fmt.Fprintf(&b, "%s: killed by SIG%s after %s (wall limit %s)\n", name, out.Signal, out.Wall.Round(time.Millisecond), lim.Wall)
} else {
fmt.Fprintf(&b, "exit %d\n", out.Status)
}
b.Write(out.Stdout)
if len(out.Stderr) > 0 {
if !strings.HasSuffix(b.String(), "\n") {
b.WriteByte('\n')
}
b.WriteString("[stderr]\n")
b.Write(out.Stderr)
}
if out.Truncated {
if !strings.HasSuffix(b.String(), "\n") {
b.WriteByte('\n')
}
fmt.Fprintf(&b, "[truncated: each stream is capped at %d bytes]\n", lim.OutputBytes)
}
text := b.String()
switch {
case out.Signal != "":
return agent.ErrorResult("%s", text)
case out.Status != 0:
return agent.ErrorResult("%s: exit %d\n%s", name, out.Status, strings.TrimPrefix(text, fmt.Sprintf("exit %d\n", out.Status)))
case len(out.Stdout) == 0 && len(out.Stderr) == 0:
return agent.TextResult("exit 0 (no output)")
}
return agent.TextResult(text)
}
The languages are a table: sh and python3 -I (isolated mode: no site directories, no PYTHON* variables). The code is written to .execute_code/<n>.<ext> in the workspace through os.Root, mode 0600 and O_EXCL, and the command is the interpreter and ./.execute_code/<n>.<ext>, a path relative to Dir. The daemon builds its tools per turn over a workspace that outlives them, so the counter is only a starting point: writeCode takes the first number whose file does not exist and never overwrites or re-uses an earlier program. Code and stdin are each capped at 64 KiB. The call is marked (unless Approval is skill.Policy, which the daemon sets only under chapter 47’s gate with a model tier), never idempotent, and a nil backend refuses (“code is not run on the host”). Its Timeout is the wall plus ten seconds for the backend’s own start and cleanup, 70 seconds at the defaults; without it the loop’s default would end a 60-second wall early. The observation is exit N and the streams (stderr under its own heading), an error result for a nonzero status or a signal, and a note when a stream was cut.
skill_run is chapter 36’s one lift of ErrInert.
// SkillRun is skill_run(name, script[, args]): chapter 36's one lift of
// ErrInert. Only a regular, executable, non-symlink file under the skill's
// scripts/ directory runs, and it runs through Backend over Workspace
// after the skill's scripts/ tree is copied into Workspace/.skills/<name>/
// (regular files only), so a skill on a path the sandbox hides still runs
// and an ssh backend needs no mount. Skills is called per request, as
// skill.View's. Approval is skill.Write's policy (Always by default).
// Marked and never idempotent: a script's second run is a second side
// effect, so the loop never answers a repeated call from its cache.
type SkillRun struct {
Skills func() []skill.Skill
Dir string // the skills directory the daemon loaded from; skill_run reads each skill's own Dir and does not use it
Workspace string
Backend Backend
Limits Limits
Approval skill.ApprovalPolicy
MaxArgs int // default 16
Path string // the PATH the script gets (DefaultPath when empty; HostPath(Backend) on this host)
}
// ErrNotScript is the refusal for anything but a regular executable file
// under scripts/.
var ErrNotScript = errors.New("skill_run: only a regular executable file under the skill's scripts/ directory runs")
// Copy caps: a skill's scripts/ tree over either is refused.
const (
maxScriptFiles = 64
maxScriptBytes = 1 << 20
)
var (
_ agent.Tool = (*SkillRun)(nil)
_ agent.Marked = (*SkillRun)(nil)
_ agent.Timeouter = (*SkillRun)(nil)
)
// Timeout is the wall limit plus ten seconds for the backend's own start
// and cleanup, as ExecuteCode's: without it the loop's 30-second default
// would end a 60-second wall early.
func (r *SkillRun) Timeout() time.Duration {
return r.Limits.withDefaults().Wall + 10*time.Second
}
func (r *SkillRun) maxArgs() int {
if r.MaxArgs > 0 {
return r.MaxArgs
}
return 16
}
func (r *SkillRun) Spec() llm.Tool {
return llm.Tool{Name: "skill_run", Description: "Run one of a skill's scripts (a file under its scripts/ directory) in the sandbox, in the workspace. Needs approval.",
Parameters: schema([]string{"name", "script"}, map[string]any{
"name": map[string]any{"type": "string", "pattern": "^[a-z0-9-]{1,64}$", "description": "The skill, as listed in the skills index."},
"script": map[string]any{"type": "string", "minLength": 1, "maxLength": 1024, "description": "The script's path inside the skill, under scripts/."},
"args": map[string]any{"type": "array", "maxItems": r.maxArgs(), "items": map[string]any{"type": "string", "maxLength": 1024}, "description": "Arguments for the script."},
})}
}
func (r *SkillRun) NeedsApproval(call toolcall.Call) (bool, string) {
switch r.Approval {
case skill.Never, skill.Policy:
return false, ""
}
return true, "skill_run runs a skill's script in the " + r.backendName() + " sandbox" + Caveat(r.Backend)
}
func (r *SkillRun) backendName() string {
if r.Backend == nil {
return "unconfigured"
}
return r.Backend.Name()
}
func (r *SkillRun) Call(ctx context.Context, call toolcall.Call) agent.Result {
if res, ok := validate(r.Spec().Parameters, call); !ok {
return res
}
if r.Backend == nil {
return agent.ErrorResult("skill_run: no sandbox configured; scripts are not run on the host")
}
name, script := stringArg(call.Arguments, "name"), stringArg(call.Arguments, "script")
var args []string
if raw, ok := call.Arguments["args"].([]any); ok {
for _, a := range raw {
s, _ := a.(string)
args = append(args, s)
}
}
var sk *skill.Skill
for _, s := range r.Skills() {
if s.Name == name {
s := s
sk = &s
break
}
}
if sk == nil {
return agent.ErrorResult("skill_run: no skill named %q", name)
}
rel := path.Clean(script)
if !strings.HasPrefix(rel, "scripts/") || strings.Contains(rel, "..") {
return agent.ErrorResult("skill_run: %s/%s: %v", name, script, ErrNotScript)
}
root, err := os.OpenRoot(sk.Dir)
if err != nil {
return agent.ErrorResult("skill_run: %v", err)
}
defer root.Close()
listed := make(map[string]bool, len(sk.Files))
for _, f := range sk.Files {
listed[f.Path] = true
}
st, err := root.Lstat(rel)
switch {
case err != nil, !listed[rel]:
return agent.ErrorResult("skill_run: %s/%s: %v", name, rel, ErrNotScript)
case st.Mode()&os.ModeSymlink != 0, !st.Mode().IsRegular(), st.Mode()&0o111 == 0:
return agent.ErrorResult("skill_run: %s/%s: %v", name, rel, ErrNotScript)
}
dest := ".skills/" + name
if err := copyScripts(root, r.Workspace, dest, listed); err != nil {
return agent.ErrorResult("skill_run: %s: %v", name, err)
}
lim := r.Limits.withDefaults()
cmd := tool.Command{Argv: append([]string{"./" + dest + "/" + rel}, args...), Dir: r.Workspace, Env: baseEnv(r.Workspace, r.Path), Wall: lim.Wall}
out, err := r.Backend.Run(ctx, cmd)
if err != nil {
if ctx.Err() != nil {
return agent.ErrorResult("skill_run: interrupted\n%s", string(out.Stdout))
}
return agent.ErrorResult("skill_run: %v", err)
}
return observation("skill_run", out, lim)
}
// copyScripts replaces workspace/dest/scripts with a copy of the skill's
// scripts/ tree: the regular files the loader listed for the skill (listed,
// by path; any other file is left out), at most maxScriptFiles and
// maxScriptBytes; a symlink, a special file or a file with more than one
// link refuses the whole copy; directories 0700, files 0700 when
// executable and 0600 otherwise.
func copyScripts(skillRoot *os.Root, workspace, dest string, listed map[string]bool) error {
ws, err := os.OpenRoot(workspace)
if err != nil {
return err
}
defer ws.Close()
if err := ws.RemoveAll(dest); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := ws.MkdirAll(dest+"/scripts", 0o700); err != nil {
return err
}
files, total := 0, int64(0)
return fs.WalkDir(skillRoot.FS(), "scripts", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
info, err := skillRoot.Lstat(p)
if err != nil {
return err
}
switch {
case info.Mode()&os.ModeSymlink != 0:
return fmt.Errorf("%s is a symlink; scripts/ holds regular files only", p)
case info.IsDir():
return ws.MkdirAll(dest+"/"+p, 0o700)
case !info.Mode().IsRegular():
return fmt.Errorf("%s is not a regular file", p)
case linkCount(info) > 1:
return fmt.Errorf("%s has more than one link; scripts/ holds files with a single name", p)
case !listed[p]:
return nil
}
files++
total += info.Size()
if files > maxScriptFiles || total > maxScriptBytes {
return fmt.Errorf("scripts/ is over the copy cap (%d files, %d bytes)", maxScriptFiles, maxScriptBytes)
}
mode := os.FileMode(0o600)
if info.Mode()&0o111 != 0 {
mode = 0o700
}
src, err := skillRoot.Open(p)
if err != nil {
return err
}
defer src.Close()
dst, err := ws.OpenFile(dest+"/"+p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return err
}
if _, err := io.Copy(dst, io.LimitReader(src, maxScriptBytes+1)); err != nil {
dst.Close()
return err
}
return dst.Close()
})
}
Only a regular, executable, non-symlink file the loader listed under the skill’s scripts/ runs. The skill’s scripts/ tree is copied into .skills/<name>/ in the workspace first, so a skill on a path the sandbox hides still runs and an ssh backend needs no mount. The copy takes only the regular files the loader listed, at most 64 files and 1 MiB; a symlink anywhere in scripts/, a special file, or a file with more than one link refuses the whole copy (a second name for a file is a way to reach something the loader did not list). Directories are 0700, files 0700 when executable and 0600 otherwise.
skill_view lifts ErrInert under scripts/ and nowhere else.
allowExec := v.Sandboxed && underScripts(p)
if file.Executable && !allowExec {
return agent.ErrorResult("skill_view: %s/%s: %v", name, p, ErrInert)
}
Sandboxed is set when the daemon has a backend. With it, a file under scripts/ is returned as data, inside chapter 36’s fence like any other file; an executable file anywhere else still answers ErrInert. The level-1 file list marks a regular executable under scripts/ “executable script”, which says what skill_run would be offered; it does not promise skill_run will accept it, because one symlink in the tree refuses the copy. Chapter 36’s output, with Sandboxed false, is unchanged.
terminal moves behind the backend through Terminal.Runner.
// sandboxEnv is the environment a command gets under a backend, built as
// execute_code builds its own: PATH (path, without the elements the model
// can write; DefaultSandboxPath when nothing is left), HOME the workspace,
// TMPDIR /tmp and TERM dumb, and of chapter 27's allowlist only the names
// that carry no host path, LANG and the POSIX LC_ names, from environ. PATH,
// HOME, TMPDIR and USER of the daemon are never passed, and its PATH only to
// a backend on this host, reduced as above: under a container or another host
// those values name directories that are not there.
func sandboxEnv(environ []string, path, workspace string) map[string]string {
path = PathOutside(path, workspace)
if path == "" {
path = DefaultSandboxPath
}
env := map[string]string{"PATH": path, "HOME": workspace, "TMPDIR": "/tmp", "TERM": "dumb"}
for _, kv := range environ {
if k, v, ok := strings.Cut(kv, "="); ok && (k == "LANG" || strings.HasPrefix(k, "LC_")) && allowedEnv[k] {
env[k] = v
}
}
return env
}
With a Runner, the command’s environment is built as execute_code’s is: PATH by the rule above, HOME the workspace, TMPDIR /tmp, TERM dumb, and of chapter 27’s allowlist only the locale names. The daemon’s HOME, TMPDIR and USER are never passed, and its PATH only to a backend on this host, reduced as above, because under a container or another host those values name directories that are not there. With no Runner, chapter 27’s behaviour is byte for byte what it was. The approval reason names the sandbox and what it does not isolate: execute_code runs model-written code in the local+bwrap+systemd-run sandbox when the backend isolates the filesystem and the network, and a parenthesis such as “it isolates neither the host’s files nor the network” when it does not, because a reader asked to approve code “in the sandbox” should be told where it matters that the sandbox leaves the host’s files reachable.
Code in an eval
Chapter 37’s registry refused terminal and had no oracle that runs a project’s own tests. It now has execute_code behind the runner’s backend and an exec grader, the shape SWE-bench uses: Jimenez et al. give the property that makes such tasks attractive as “generated solutions can be easily verified by running unit tests” (arXiv 2310.06770, p. 2).
// Exec is the exec grader: the side-effect oracle chapter 37 could not
// have (its Files oracle compares bytes; this one runs the project's own
// tests). Command runs with sh -c in the sandbox over the trajectory's
// workspace after the run, and the task passes when the status is
// ExpectStatus (0 by default): the SWE-bench shape, "run the tests". The
// backend comes from the context (WithSandbox, which Runner.Trial sets);
// without one the grade is an error, never a run on the host. Regrade has
// no workspace, so an exec trial cannot be regraded and says so; its
// verdict is in the stored detail.
type Exec struct {
Command string
ExpectStatus int
}
// ExecWall bounds the oracle's command.
const ExecWall = 60 * time.Second
type sandboxKey struct{}
// WithSandbox carries the backend a grader may run commands through.
func WithSandbox(ctx context.Context, b sandbox.Backend) context.Context {
if b == nil {
return ctx
}
return context.WithValue(ctx, sandboxKey{}, b)
}
type sandboxPathKey struct{}
// WithSandboxPath carries the PATH the exec grader gives its command ("" is
// sandbox.DefaultPath).
func WithSandboxPath(ctx context.Context, path string) context.Context {
return context.WithValue(ctx, sandboxPathKey{}, path)
}
func sandboxFrom(ctx context.Context) sandbox.Backend {
b, _ := ctx.Value(sandboxKey{}).(sandbox.Backend)
return b
}
func (g *Exec) Grade(ctx context.Context, t *Trajectory) (Score, error) {
b := sandboxFrom(ctx)
if b == nil {
return Score{}, fmt.Errorf("exec: no sandbox in the context; the oracle's command is not run on the host")
}
if t.Workspace == "" {
return Score{}, fmt.Errorf("exec: the trajectory has no workspace (a regrade cannot re-run a side-effect oracle; the record's detail holds its verdict)")
}
path, _ := ctx.Value(sandboxPathKey{}).(string)
if path == "" {
path = sandbox.DefaultPath
}
// The model can write files in the workspace without approval: a PATH
// element that is the workspace, or inside it, would run what it planted
// there in place of the oracle's cat or grep.
if path = tool.PathOutside(path, t.Workspace); path == "" {
path = sandbox.DefaultPath
}
out, err := b.Run(ctx, tool.Command{Argv: []string{"sh", "-c", g.Command}, Dir: t.Workspace,
Env: map[string]string{"PATH": path, "HOME": t.Workspace, "LANG": "C.UTF-8", "TMPDIR": "/tmp", "TERM": "dumb"}, Wall: ExecWall})
if err != nil {
return Score{}, fmt.Errorf("exec: %w", err)
}
detail := fmt.Sprintf("status %d", out.Status)
if out.Signal != "" {
detail = "killed by SIG" + out.Signal
}
if line := firstLine(out.Stderr); line != "" {
detail += ": " + line
}
if out.Signal == "" && out.Status == g.ExpectStatus {
return Score{Value: 1, Pass: true, Detail: "exec pass: " + detail}, nil
}
return Score{Value: 0, Pass: false, Detail: fmt.Sprintf("exec fail: %s, want %d", detail, g.ExpectStatus)}, nil
}
// isolated reports whether a backend withholds the host's filesystem and
// network from the code: the condition under which the runner approves
// execute_code on its own. A plain local backend (Detect on a host without
// bwrap) reports neither and gets no automatic approval.
func isolated(b sandbox.Backend) bool {
iso := b.Isolates()
return iso.Filesystem && iso.Network
}
// approver: a sandbox that isolates the filesystem and the network is the
// approval for execute_code and for nothing else (or any configured
// backend, under AllowUnisolated; the same rule gates every task that
// carries an exec grader, in Trial). The golden set runs without approval
// (chapter 37: terminal is not in the registry), and that stays true; a
// suite that names a sandbox has asked for code to run in it.
func (r *Runner) approver() agent.Approver {
if r.Sandbox == nil {
return nil
}
allow := isolated(r.Sandbox) || r.AllowUnisolated
return agent.ApproverFunc(func(ctx context.Context, req agent.ApprovalRequest) (agent.Approval, error) {
decision := agent.Deny
if allow && req.Call.Name == "execute_code" {
decision = agent.Allow
}
return agent.Approval{Request: req.ID, CallHash: req.Call.Hash, Decision: decision, By: "eval: the suite's sandbox", At: r.now()}, nil
})
}
// namesExecuteCode reports whether a task offers execute_code.
func namesExecuteCode(task *Task) bool {
for _, name := range task.Tools {
if ref, err := parseTool(name); err == nil && ref.base == "execute_code" {
return true
}
}
return false
}
// needsSandbox reports whether a task names execute_code or carries an
// exec grader anywhere in its grader tree.
func needsSandbox(task *Task) bool {
return namesExecuteCode(task) || graderNeedsSandbox(task.Grader)
}
func graderNeedsSandbox(g Grader) bool {
switch g := g.(type) {
case *Exec:
return true
case All:
for _, sub := range g {
if graderNeedsSandbox(sub) {
return true
}
}
}
return false
}
// firstLine is the first non-empty line of b, at most 120 bytes.
func firstLine(b []byte) string {
for _, line := range strings.Split(string(b), "\n") {
if line = strings.TrimSpace(line); line != "" {
if len(line) > 120 {
line = line[:120]
}
return line
}
}
return ""
}
The grader runs sh -c COMMAND through the backend over the trial’s workspace after the run, and the task passes when the status is the expected one. With no backend in the context the grade is an error, never a run on the host. A regrade has no workspace, so an exec trial cannot be regraded: its verdict is in the stored detail, where chapter 37’s oracle verdicts already live, and a text grader’s verdict can be recomputed from the transcript.
if needsSandbox(task) && r.Sandbox == nil {
return fail(Skipped, "task %s needs a sandbox (execute_code or an exec grader) and the runner has none; nothing sent", task.ID)
}
if r.Sandbox != nil && needsSandbox(task) && !isolated(r.Sandbox) && !r.AllowUnisolated {
return fail(Skipped, "task %s runs model-written or model-rewritable code (execute_code, or an exec grader over files the task's tools can write) but sandbox %s does not isolate both filesystem and network; nothing sent (aec-eval -allow-unisolated-code overrides)", task.ID, r.Sandbox.Name())
}
The gate is the part a first design got wrong. It ran an exec grader on the host over a workspace that the task’s own tools could write: a model that rewrote check.sh decided its own grade, and the rewritten file ran with no isolation at all. A task with an exec grader is now treated like one that names execute_code: it runs only under a backend whose Isolates() has both Filesystem and Network, and is skipped with the reason otherwise, unless the operator passes aec-eval -allow-unisolated-code (a flag and never a suite field, because the suite is data). A skipped code task is a reported gap, the rule of chapter 38’s decide: a rule run on fewer inputs than it was registered for is not that rule. The rule an oracle’s files obey, for the author of a task, is that they must not be writable by the tools the task offers; the gate bounds what a violation costs, and the verdict of a task that breaks the rule is still the model’s to forge. The suite shipped with the chapter has a second task of that shape (write_file over a workspace holding check.sh); it exists to exercise the gate and the oracle, and the rule says its verdict means little.
In the daemon
if cfg.Sandbox != "" {
// Chapter 43: the backend the configuration names, built before the
// scheduler reads the tools' names. A backend this host lacks fails
// Open, as an embedder that is not loaded does: nothing runs on the
// host in place of the sandbox the reader asked for.
lim := sandbox.Limits{}
if cfg.SandboxLimits != nil {
lim = *cfg.SandboxLimits
}
if d.sandbox, err = sandbox.Configure(cfg.Sandbox, lim); err != nil {
return nil, fmt.Errorf("daemon: sandbox %q: %w", cfg.Sandbox, err)
}
d.warnUnisolated()
}
The backend is built at Open, after the skills load and before the scheduler reads the tools’ names, so a job can name execute_code and skill_run. Its limits come from the configuration’s sandbox_limits when that is set (chapter 53 sets it, for a daemon whose model runs the Go toolchain, which does not start under the defaults’ 512 MiB of address space) and are sandbox.Limits{}, this chapter’s defaults, when it is not. terminal passes its own deadline per call (60 s unless the tool sets one), and this chapter’s exec grader its ExecWall, so the configured wall bounds neither; it bounds the daemon’s execute_code (the one mcp_serve exposes included) and skill_run. A named backend whose binary is missing, or a lever that is present and does not start, fails Open, as an embedder that is not loaded does. A host with neither lever is the case that does not fail, and Open says so:
// warnUnisolated is ruling 7d-E12: "local" on a host with neither bwrap nor
// systemd-run is the plain backend, which Configure builds without complaint
// (a lever that is absent is not an error). When the configured backend's
// Isolates() reports no isolation of the host's files, the network or the
// daemon's environment, the principal gets one line through Config.Warn,
// whatever -v says, naming the backend and what it does not isolate.
func (d *Daemon) warnUnisolated() {
if d.sandbox == nil {
return
}
iso := d.sandbox.Isolates()
if iso.Filesystem || iso.Network || iso.Env || iso.Host {
return
}
d.warnf("daemon: sandbox %q is the %s backend, which isolates neither the host's files, nor the network, nor the daemon's environment: model-written code runs with the daemon's own reach", d.cfg.Sandbox, d.sandbox.Name())
}
TestDaemonWarnsOfAnUnisolatedBackend opens a daemon with a PATH that holds no lever and expects exactly one such line, and with a stub bwrap that answers its probe and expects none.
// tools is Tools' body, in the one assembly order Part VII uses: the file
// tools, the terminal (through the sandbox backend when Config.Sandbox names
// one, chapter 43; unsandboxed otherwise), the scratchpad, the memory tools
// when the service exists, the skills tools when skills are configured (the
// view returns an executable file as data once a backend exists), then
// chapter 43's execute_code and, with skills, skill_run, both only with a
// backend, then chapter 44's mounted MCP tools (daemon-wide, each named
// prefix__name, so none can take another tool's name); ToolHook may then
// replace the set. delegate (chapter 45) is not here: runTurn appends it per
// turn, after this set and before the turn's ToolFilter, because its workers
// take the turn's loop, filtered tool set, system message, privacy and role,
// and the turn's compactor. Nothing here creates, opens or writes workspace:
// checkJobTools calls this at Open with a path that does not exist.
func (d *Daemon) tools(workspace string) []agent.Tool {
ts := tool.FileTools(workspace)
ts = append(ts, &tool.Terminal{Workspace: workspace, Runner: d.Runner(), Path: sandbox.HostPath(d.sandbox)})
ts = append(ts, (&compact.Scratchpad{Path: filepath.Join(workspace, "SCRATCH.md")}).Tools()...)
if d.mem != nil {
ts = append(ts, d.mem.Tools(d.auxClient, d.auxModel)...)
}
skills := func() []skill.Skill { return d.skills }
// Chapter 47: with a gate that has a model tier, the three agent-authored-
// text tools leave their marking to the policy hook (skill.Policy); a
// rules-only block (no weights) keeps chapter 36's and 43's marking of
// every call (ruling X8-2), and so does a daemon without the block.
approval := skill.Always
if d.gate != nil && d.gate.Model != nil {
approval = skill.Policy
}
if d.cfg.Skills != "" {
ts = append(ts, &skill.View{Skills: skills, Sandboxed: d.sandbox != nil}, &skill.Write{Dir: d.cfg.Skills, Approval: approval})
}
if d.sandbox != nil {
ts = append(ts, &sandbox.ExecuteCode{Backend: d.sandbox, Workspace: workspace, Limits: d.sandboxLimits(), Languages: sandbox.DefaultLanguages(), Path: sandbox.HostPath(d.sandbox), Approval: approval})
if d.cfg.Skills != "" {
ts = append(ts, &sandbox.SkillRun{Skills: skills, Dir: d.cfg.Skills, Workspace: workspace, Backend: d.sandbox, Limits: d.sandboxLimits(), Approval: approval, Path: sandbox.HostPath(d.sandbox)})
}
}
ts = append(ts, d.mounted...) // chapter 44: the mounted servers' tools, daemon-wide
if d.cfg.ToolHook != nil {
ts = d.cfg.ToolHook(workspace, ts)
}
if d.audit != nil { // chapter 48: an outward call is recorded after the hook, so a hook's tool is recorded too
wrapped := make([]agent.Tool, len(ts))
for i, t := range ts {
wrapped[i] = d.auditWrap(t, workspace)
}
ts = wrapped
}
return ts
}
The tool set keeps chapter 40’s order: the file tools, terminal (behind the backend), the scratchpad, the memory tools, skill_view and skill_write, then execute_code and, with skills, skill_run, both only with a backend, then the tools of the MCP servers aecd.json mounts (chapter 44, named prefix__name), and ToolHook last. ToolHook is called once at Open with a workspace path that does not exist, to check the jobs’ tool names; the constructors here hold the path and open nothing until Call, and TestToolsWithSandbox checks the path is never created.
Jobs. A job with no tools key gets exactly six tools by name (read_file, search_files, scratch_read, scratch_write, memory_recall, skill_view), so a default job never has terminal, execute_code or skill_run; a named list is exactly that list. A job that names execute_code has it, and its turn runs under chapter 42’s Unattended, which answers every marked call timeout at once. execute_code and skill_run are marked, so in this chapter no job runs code: the batch is refused, the run ends approval_timeout, and the reader is told “a tool call needed your approval and nobody was there to give it”. Chapter 47’s gate is what can let a marked call run unattended. TestToolsWithSandbox pins that nothing is written under the job’s workspace.
The ledger. Neither execute_code nor skill_run declares itself idempotent (their tests assert it), so a call in flight at a crash is chapter 40’s rule and nothing is added. Under Abort, the default, the turn is completed from the ledger with denied: unknown outcome: the daemon stopped while this call was in flight, and the call is not run again. Under Confirm the principal is asked whether it ran. Under Replay the turn is re-run and the code may run twice, which is the daemon’s own reason string: “policy replay: the turn re-runs and the call may run twice”. A call that ended before the crash is lost, because its result was in memory only. The program file written before the crash stays where it is, and a re-run turn writes the next free number. aecd resolve -session ID prints the table without opening the session. The chapter claims no more than that: it does not make code idempotent, and it does not undo what a program did to the workspace.
Approval. A marked call is approved in one of two families. A control client names the approver in session/send: allow approves every marked call (By: "control"), deny is the default, and client has the daemon send approval/ask on the connection that sent the request, carrying the call’s name, its arguments, the reason, the loop’s nonce and the call hash, and the client answers; aecd send -approve tty is client with the question printed to a terminal, approve execute_code {…}? ("execute_code runs model-written code in the local+bwrap+systemd-run sandbox") [y/N]. A gateway peer answers through chapter 41’s approve: channel, in the turn’s own thread. The capture below uses -approve allow, because a script cannot answer a terminal, so its approval is the control client’s flag and not a person reading the code.
Warnings and the terminal. A backend that cannot run a command is an error observation to the model and, under -v, a line through the ledger’s end event; the chapter adds no warning of its own. A program’s bytes reach the reader’s terminal only through the model’s final text, and aecd send prints that line by line through the terminal filter when its standard output is a terminal, and byte for byte otherwise; the tty question’s name and arguments are filtered whatever the output is, because a prompt has no other reader. status, jobs, queue, resolve and the error lines are filtered the same way (chapter 42 has the filter).
What the code can still do
Take the strongest local mode, a scope around bubblewrap, and list from the argv and the namespaces what is left. The code can read the system directories that the root bind exposes read-only (/usr, /etc, /opt, /var/log, /srv, /sys) and the kernel-wide files of its /proc; its /proc/self/mountinfo names the workspace’s host path. It can write the workspace, its own /tmp, /var/tmp and /dev/shm, with no disk quota on a workspace that lives on a real filesystem. It can use one CPU’s share for the wall, Pids tasks and MemoryBytes of RAM with no swap. It cannot create a nested user namespace (--disable-userns). It does not see /home, /root, /run or the host’s /tmp (the filesystem rows for /tmp and /home; /root and /run by the same argv), the daemon’s environment (the /proc row) or a process outside its pid namespace (the pid 1 row), and it cannot rewrite the cgroup’s memory limit (the cgroup row). With Network true, which the daemon’s default limits do not set, it has the host’s network, loopback services included, and the host’s abstract Unix sockets. It shares the kernel: a kernel bug ends the boundary, and nothing in this chapter tests a kernel.
For contrast, plain local and a scope alone can additionally read the reader’s home, the repository and every other uid-1000 process’s environment, signal Kyle’s processes, connect to every local socket, and, under the scope, rewrite or leave their own cgroup.
On a Nix host two things were untested when this chapter’s tables were captured. straylight had no bubblewrap then, so its table has no bubblewrap rows. The flake’s dev shell now carries bubblewrap, and chapters 52 to 54 run the local backend under it on straylight, but the escape suite has not been run there under bubblewrap. Also, --tmpfs /run hides /run/current-system, where a NixOS host’s programs live, so a daemon on such a host needs a PATH of store directories (chapter 51 met this and states the rule). The chapter claims no escape result for bubblewrap on such a host.
Walkthrough
One captured turn
The turn below was captured on wntrmute with the daemon’s own router: ornith-1.5-35b-a3b on 127.0.0.1:8080, loaded (/v1/models was read first and the 9b was unloaded throughout). aecd.json named "sandbox": "local", "embedder": "" and a 32768-token window; aecd serve -deterministic -v ran in the background and aecd send -session ch43 -approve allow sent one message. It took one attempt and two completions. The daemon’s local is whatever Detect finds, and the two hosts differ. go run ./labs/ch43/detect prints the lever names and the backend Configure("local") builds from them, and nothing else. On wntrmute (go/labs/ch43/testdata/detect-wntrmute.txt):
levers found on PATH: bwrap, systemd-run
Detect: local+bwrap+systemd-run
Configure("local") opens: local+bwrap+systemd-run
On straylight, run through tools/remote/straylight.sh (detect-straylight.txt):
levers found on PATH: systemd-run
Detect: local+systemd-run
Configure("local") opens: local+systemd-run
So the name in the approval reason below is what Detect found on wntrmute, the strongest mode, a scope around bubblewrap. On straylight, which has no bubblewrap, the same "sandbox": "local" is local+systemd-run, and its approval reason ends “(it isolates neither the host’s files nor the network)”.
The daemon’s log (serve.log):
listening /home/kyle/Work/aec-runs/part7-ch43-execute/state/aecd.sock
ledger: begin "W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1" "execute_code"
ledger: end "W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1" ok
ledger: append "ch43/1" at=368 len=518
turn ch43/1: final
The ledger’s begin and end bracket the call that chapter 40’s rule reads after a crash; the append is the turn’s write to the session file. The session file holds the transcript, and its third and fourth lines are the call and the observation:
{"role":"assistant","content":null,"reasoning_content":"The user wants me to compute 17*23 and say the number.\n","tool_calls":[{"id":"W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1","name":"execute_code","arguments":"{\"code\":\"print(17*23)\",\"language\":\"python3\"}"}]}
{"role":"tool","content":[{"type":"text","text":"exit 0\n391\n"}],"tool_call_id":"W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1","name":"execute_code"}
The model chose python3 and wrote print(17*23). The tool reply is exit 0 and the program’s stdout. The model’s final text is 391. The trace shows the approval and the call as spans of the turn:
{"trace":"ch43/1","id":"d8","parent":"d2","seq":7,"kind":"approval","name":"execute_code",…,"status":"ok","attrs":{"by":"control","call_hash":"3ca9eaac…","call_id":"W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1","decision":"allow","nonce":"d7","reason":"execute_code runs model-written code in the local+bwrap+systemd-run sandbox","timeout_s":"60"}}
{"trace":"ch43/1","id":"d6","parent":"d2","seq":6,"kind":"tool_call","name":"execute_code",…,"status":"ok","attrs":{"approval":"allow","call_hash":"3ca9eaac…","call_id":"W00NOlOq5aA8YJ7NtM0ve7NCXV3CJHm1","result_kind":"ok","tool":"execute_code"}}
What the backend ran for that call is the command line TestLocalArgv pins for a call of this shape (limits at the defaults, a workspace /ws and a PATH of /bin standing in for the real ones; the arguments are joined with spaces here, so the quoting is the test’s and not a shell’s; this is the test’s expected string and not the captured run’s):
/usr/bin/systemd-run --user --scope --quiet --collect --unit aec-sb-x -p MemoryMax=536870912 -p MemorySwapMax=0 -p TasksMax=256 -p CPUQuota=100% --expand-environment=no -- /usr/bin/env -i HOME=/ws PATH=/bin /usr/bin/bwrap --unshare-all --unshare-user --disable-userns --die-with-parent --new-session --ro-bind / / --size 1048576 --tmpfs /home --size 1048576 --tmpfs /root --size 1048576 --tmpfs /run --size 536870912 --tmpfs /tmp --size 536870912 --tmpfs /var/tmp --proc /proc --dev /dev --size 536870912 --tmpfs /dev/shm --bind /ws /ws --chdir /ws --clearenv --setenv HOME /ws --setenv PATH /bin -- /bin/sh -c ulimit -v 524288 && ulimit -t 30 && exec "$0" "$@" python3 -I ./.execute_code/1.py
The scope’s limits come first, env -i clears the environment in front of bubblewrap, bubblewrap builds the namespaces and the tmpfs mounts, and the ulimit wrapper is the innermost shell.
The approval’s by is control: the control client’s flag allowed the call, and no person read the code. The reason is the sentence NeedsApproval returns, and it has no parenthesis because the backend isolates both the filesystem and the network. The clock is the deterministic 2026-10-01T00:00:00Z, so every span has the same start and end and the trace carries no timing. Its token counts are the two completions’: 1143 prompt and 67 completion tokens for the call, 1214 and 26 for the answer (1139 of the second prompt cached), and the run’s total of 2357 and 93 is their sum. The files are go/labs/ch43/testdata/execute-session.jsonl, execute-serve.log and execute-trace-1.jsonl; the capture shows what the model did on one attempt and says nothing about how often it does it.
The escape tables
The escape suite runs under AEC_ESCAPE=1 through escape.sh, never in make check: every TestEscape* skips without it, so a reader’s go test ./... runs no attack on their host. The script plants the daemon’s sentinel in the environment of go test, runs the suite, and prints the containers and scopes named aec-sb- (expected none) and the table the suite wrote. The suite runs with -v, and the script prints the table and a second file, the evidence. Each host’s table and evidence file were produced twice, and the two runs are byte-identical on each host. The table records outcomes only: no pid, no time, no path. The evidence file (go/labs/ch43/testdata/escape-wntrmute-evidence.md and escape-straylight-evidence.md) records what the rows were decided on: the statuses the attacks logged, as a class (all 0, killed, error exit) where a kill makes the exact statuses differ from run to run, counts as a decade (20-29) where the uid’s other processes move them, and times rounded to a second. Two rows are decided by what the test sees on the host, which the file does not hold: the /tmp write (the in-sandbox write succeeds everywhere, into the sandbox’s own /tmp under bubblewrap) and pid 1’s name (cat succeeds everywhere). One thing varies between runs and is in the test log only: the signal a run reports when a cgroup kills it, which was none, TERM or KILL in different runs. The tables are per host, and they are measurements of two machines at one time, not guarantees. Under AEC_SANDBOX=ssh (with AEC_SSH_HOST and AEC_ESCAPE_REMOTE_PATH) the suite drives the ssh backend against a real host, refuses to write a row of any other backend under that host’s header, and checks that the remote workspace is gone after each test; under AEC_ESCAPE_MERGE=1 a run rewrites only the rows it recorded in an existing table and keeps the rest, which is how chapter 51’s orion table holds rows from two runs.
wntrmute (kernel 7.2.5-3-omarchy, bubblewrap 0.12.0, systemd 261.2; three local modes, no podman):
| Property | Backend | Outcome | Detail |
|---|---|---|---|
| cgroup: the code writes its own memory.max | local+bwrap+systemd-run | contained | refused |
| cgroup: the code writes its own memory.max | local+systemd-run | escaped (recorded) | tampered |
| env: a proxy variable of the daemon’s reaches the code | local+bwrap | contained | |
| env: a proxy variable of the daemon’s reaches the code | local+bwrap+systemd-run | contained | |
| env: a proxy variable of the daemon’s reaches the code | local+systemd-run | contained | |
| env: the code reads the daemon’s environment from /proc | local+bwrap | contained | |
| env: the code reads the daemon’s environment from /proc | local+bwrap+systemd-run | contained | |
| env: the code reads the daemon’s environment from /proc | local+systemd-run | escaped (recorded) | |
| filesystem: read a planted home file | local+bwrap | contained | |
| filesystem: read a planted home file | local+bwrap+systemd-run | contained | |
| filesystem: read a planted home file | local+systemd-run | escaped (recorded) | |
| filesystem: the repository is visible or a planted file writable | local+bwrap | contained | |
| filesystem: the repository is visible or a planted file writable | local+bwrap+systemd-run | contained | |
| filesystem: the repository is visible or a planted file writable | local+systemd-run | escaped (recorded) | |
| filesystem: write under the host’s /tmp | local+bwrap | contained | |
| filesystem: write under the host’s /tmp | local+bwrap+systemd-run | contained | |
| filesystem: write under the host’s /tmp | local+systemd-run | escaped (recorded) | |
| memory: 200 MiB buffered under a 64 MiB limit | local+bwrap | contained | head=141 tail=1 |
| memory: 200 MiB buffered under a 64 MiB limit | local+bwrap+systemd-run | contained | head=141 tail=1 |
| memory: 200 MiB buffered under a 64 MiB limit | local+systemd-run | contained | head=141 tail=1 |
| memory: four 40 MiB pipelines at once under a 64 MiB limit | local+bwrap | escaped (recorded) | all 4 finished |
| memory: four 40 MiB pipelines at once under a 64 MiB limit | local+bwrap+systemd-run | contained | fewer than 4 finished |
| memory: four 40 MiB pipelines at once under a 64 MiB limit | local+systemd-run | contained | fewer than 4 finished |
| memory: four 40 MiB writers into /dev/shm under a 64 MiB limit | local+bwrap | contained | 0 of 4 writers finished |
| memory: four 40 MiB writers into /dev/shm under a 64 MiB limit | local+bwrap+systemd-run | contained | 0 of 4 writers finished |
| memory: four 40 MiB writers into /dev/shm under a 64 MiB limit | local+systemd-run | contained | 0 of 4 writers finished |
| network: connect to a listener on the host | local+bwrap | contained | |
| network: connect to a listener on the host | local+bwrap+systemd-run | contained | |
| network: connect to a listener on the host | local+systemd-run | escaped (recorded) | |
| pids: a setsid child outlives the run | local+bwrap | contained | |
| pids: a setsid child outlives the run | local+bwrap+systemd-run | contained | |
| pids: a setsid child outlives the run | local+systemd-run | contained | |
| pids: process count | local+bwrap | escaped (recorded) | no bound; not attacked |
| pids: process count | local+bwrap+systemd-run | contained | bounded; stopped short of 500 attempts, at most 24 children |
| pids: process count | local+systemd-run | contained | bounded; stopped short of 500 attempts, at most 24 children |
| pids: the host’s pid 1 is visible | local+bwrap | contained | |
| pids: the host’s pid 1 is visible | local+bwrap+systemd-run | contained | |
| pids: the host’s pid 1 is visible | local+systemd-run | escaped (recorded) | |
| wall: a sleep past the limit | local+bwrap | contained | SIGKILL |
| wall: a sleep past the limit | local+bwrap+systemd-run | contained | SIGKILL |
| wall: a sleep past the limit | local+systemd-run | contained | SIGKILL |
| wall: a spin past the limit | local+bwrap | contained | SIGKILL |
| wall: a spin past the limit | local+bwrap+systemd-run | contained | SIGKILL |
| wall: a spin past the limit | local+systemd-run | contained | SIGKILL |
straylight (kernel 6.18.51, systemd 260.2, podman 5.8.6; no bubblewrap when this table was captured, so a scope and podman):
| Property | Backend | Outcome | Detail |
|---|---|---|---|
| cgroup: the code writes its own memory.max | local+systemd-run | escaped (recorded) | tampered |
| cgroup: the code writes its own memory.max | podman | contained | refused |
| env: a proxy variable of the daemon’s reaches the code | local+systemd-run | contained | |
| env: a proxy variable of the daemon’s reaches the code | podman | contained | |
| env: the code reads the daemon’s environment from /proc | local+systemd-run | escaped (recorded) | |
| env: the code reads the daemon’s environment from /proc | podman | contained | |
| filesystem: read a planted home file | local+systemd-run | escaped (recorded) | |
| filesystem: read a planted home file | podman | contained | |
| filesystem: the repository is visible or a planted file writable | local+systemd-run | escaped (recorded) | |
| filesystem: the repository is visible or a planted file writable | podman | contained | |
| filesystem: write under the host’s /tmp | local+systemd-run | escaped (recorded) | |
| filesystem: write under the host’s /tmp | podman | contained | |
| memory: 200 MiB buffered under a 64 MiB limit | local+systemd-run | contained | head=141 tail=1 |
| memory: 200 MiB buffered under a 64 MiB limit | podman | contained | head=141 tail=1 |
| memory: four 40 MiB pipelines at once under a 64 MiB limit | local+systemd-run | contained | fewer than 4 finished |
| memory: four 40 MiB pipelines at once under a 64 MiB limit | podman | contained | fewer than 4 finished |
| memory: four 40 MiB writers into /dev/shm under a 64 MiB limit | local+systemd-run | contained | 0 of 4 writers finished |
| memory: four 40 MiB writers into /dev/shm under a 64 MiB limit | podman | contained | 0 of 4 writers finished |
| network: connect to a listener on the host | local+systemd-run | escaped (recorded) | |
| network: connect to a listener on the host | podman | contained | |
| pids: a setsid child outlives the run | local+systemd-run | contained | |
| pids: a setsid child outlives the run | podman | contained | |
| pids: process count | local+systemd-run | contained | bounded; stopped short of 500 attempts, at most 24 children |
| pids: process count | podman | contained | bounded; stopped short of 500 attempts, at most 24 children |
| pids: the host’s pid 1 is visible | local+systemd-run | escaped (recorded) | |
| pids: the host’s pid 1 is visible | podman | contained | |
| terminal: an external command runs with the constant PATH | podman | ran | uname -s printed Linux |
| wall: a sleep past the limit | local+systemd-run | contained | SIGKILL |
| wall: a sleep past the limit | podman | contained | SIGKILL |
| wall: a spin past the limit | local+systemd-run | contained | SIGKILL |
| wall: a spin past the limit | podman | contained | SIGKILL |
Reading a row. The Outcome column says what the attack did against that backend. contained is the attack failing. escaped (recorded) is the attack succeeding against a backend that does not claim the property, and the suite asserts it in that direction too: for every row the test compares what it measured with what Isolates() (or the harness’s expected value) says, and fails on a difference either way. A table whose only possible outcome is contained is a table of tests that cannot fail. An attack that did not work against a backend that claims nothing would mean the attack is broken, or the claim understates, and either is a finding; and the claim that the scope alone does not isolate the filesystem is as much a claim as the one that bubblewrap does. The row that reads a planted “home” file plants it in a fakehome directory under the test’s temporary root, not under /home, so under bubblewrap it shows the /tmp tmpfs; the repository row shows /home on wntrmute.
Each row has evidence that the attack ran, and where contained could be a missing tool it has a control. Every attack script starts by writing ./started in the workspace, and the test fails when the marker is absent; a script that logs a status of 127 (command not found) fails the test. The network row first runs the same attack with the network allowed, which must connect and be accepted by the listener, and only then without it: for podman the target is host.containers.internal with a listener on every address, because inside a container 127.0.0.1 is the container’s own loopback whether or not the network is isolated. The buffering row’s control pipes 8 MiB through tail under the same limit and must finish with both halves at status 0. The anonymous-memory row’s control runs one of its four 40 MiB pipelines alone, which must finish, so that fewer than four finishing is the sum and not the pipeline. The /dev/shm row’s control writes 8 MiB once. The environment row’s control reads a child’s own environment with the same tr and grep. The setsid row polls /proc for the sentinel for two seconds after the run, and for a container first checks that the scan can see a container process at all. The cgroup row fails if memory.max reads max before the attack, because then the limit was never applied, and it calls a write refused only when the value read before it was a number: an unreadable file reads as empty and is its own word, unreadable, which fails the test. The wall row’s sleep 30 and its spin (while :; do :; done, which never blocks, so only a kill ends it) must return within six seconds of a one-second limit (the lab’s own bound) with a signal. The process-count row is probed first with a bounded set of forks, Pids plus ten (34 against the suite’s 24), and the fork bomb of 500 runs only where that probe started fewer than 34 children; under bubblewrap alone the count is not bounded, the bomb is not run, and the row says no bound; not attacked, because running it would harm the host.
Scope-only rows are escaped (recorded) for the filesystem, network, /proc pid 1 and environment rows on both hosts, and tampered for the cgroup row: the limits are cooperative. The three memory rows are three mechanisms. head=141 tail=1 in the buffering row is tail failing to allocate (status 1) and head dying of SIGPIPE (141), on every backend: it is RLIMIT_AS, per process, and says nothing about a cgroup. The anonymous-memory row is the one only a cgroup can pass: four 40 MiB pipelines at once, each inside the per-process limit, 160 MiB in all against 64 MiB. Under bubblewrap alone all four finish, and the row is escaped (recorded): N children have N budgets. Under a scope, and under bubblewrap inside a scope, none finished on wntrmute; on straylight none finished under a scope and one under podman (1; killed in the evidence file). The pipelines that did not finish were killed, with the status 137 of a killed tail and the 141 of the head left writing to it, or with nothing logged because the subshell went with them. Which pipelines die, and the signal the run itself reports, differ from run to run; the table says fewer than 4 finished and the file the class. This row is what shows a cgroup stopping memory under each backend that has one, --memory and --memory-swap under podman included. The /dev/shm row bounds a tmpfs instead: four 40 MiB writers against 64 MiB. Under bubblewrap alone the writers fail with ENOSPC (status 1, error exit) from the 64 MiB tmpfs that bubblewrap sizes at the limit. Under a scope, under bubblewrap inside a scope and under podman, whose /dev/shm is also 64 MiB by its default --shm-size, the writers were killed (killed) and not refused, so the cgroup’s limit came first. 0 of 4 writers finished is therefore the same on every backend, by the tmpfs where there is no cgroup and by the cgroup where there is, and the 8 MiB control finished everywhere. Under bubblewrap alone, one memory number is not a tree bound: the 200 MiB buffer is stopped by RLIMIT_AS, only the three sized tmpfs mounts stand between a run and 192 MiB of pages, and four processes hold 160 MiB of anonymous memory. The wall rows are SIGKILL everywhere, which is the backend reporting that its own deadline fired; the suite asserts a return within six seconds of the one-second limit, and the evidence file records the time, 1 on every backend. Under bubblewrap, podman and ssh a wrapper reports a signal death as exit 128 plus the signal, and signalled maps 129 to 159 back, which has a cost the next paragraph states. The process-count rows say bounded; stopped short of 500 attempts, at most 24 children, which is the suite’s wording for a spawner whose shell stopped before its 500th attempt with at most 24 distinct children; the shell’s own fork error is not captured, and the shell ends at the first fork that fails, so the attempts equal the children. The evidence file has the counts by decade: 20-29 on every backend that bounds the count, and 30-39 for the 34-fork probe under bubblewrap alone, where nothing does. Four properties have no row where the attack succeeds: the wall, the 200 MiB buffer, the /dev/shm writers and setsid (the proxy row has its succeeding case in the negative control, in the evidence file), so each is checked in one direction, with a control to show that the attack could have worked. The straylight table has a row the others do not: terminal: an external command runs with the constant PATH, ran under podman, one benign terminal call that ran uname -s and printed Linux. Its outcome is ran, not contained, because it is not an attack.
What exit 137 can mean. A command that exits with a status from 129 to 159 reads as a death by signal under bubblewrap and podman (under ssh the remote shell stays the parent of timeout and exits with the command’s 128+n, so a wall kill reads the same way; chapter 51’s table against orion measured it), so a deliberate exit 137 reads as “killed by SIGKILL after … (wall limit …)”. A kill by the CPU limit is SIGKILL, like the wall kill; only the measured Output.Wall tells them apart.
What was not attacked. The kernel: a shared-kernel sandbox is not a boundary against a kernel exploit, and gVisor, a microVM or another host are the next steps; no row tests it. The plain backend has no row; its claims are Memory and CPU per process and everything else false. The ssh backend has no row here; its live table is chapter 51’s, and here it is tested against a fake binary. ward is unavailable. The system directories the root bind exposes are visible by design and are not attacked. A fork bomb under bubblewrap alone, as said, was not run. No row tests Users. CPU has no escape row: its limit is in the argv of every backend and, on the local modes, a default test runs a spin into it (TestCPULimitKillsASpinInEveryMode), but under podman and ssh no test runs a process into it. Under podman, --cap-drop, no-new-privileges, the read-only root and --timeout are in the argv and unattacked, and --pids-limit is shown only by the process-count row. Under a scope, only the memory.max write was attacked, not pids.max, cpu.max or a move through cgroup.procs. The network row is one TCP connect. Bubblewrap was not run on a Nix host in this chapter; chapter 51 runs it under a NixOS unit in its VM test.
Exercises
(a) A reader sets RLIMIT_NPROC to 256 in the ulimit wrapper to “bound the sandbox’s processes”. Say what it counts, what the daemon and the reader’s other processes do to it, and what the right mechanism is for a scope, a container and bubblewrap.
Answer
It counts every process (on Linux, thread) of the real uid, so it bounds the uid and not the run: the daemon, the reader’s shell and browser all count against the same 256, and on a busy host the sandbox’s first fork returns EAGAIN, and on a quiet one the run gets what is left of the 256 after the uid’s other processes, a number that changes with what else the reader has open. The right bound is a counter that belongs to the run: pids.max (TasksMax) on a systemd scope, --pids-limit on a container. A pid namespace alone, as bubblewrap gives, kills a tree and counts nothing, which is why the table’s process-count row for bubblewrap alone says no bound; not attacked.
(b) Under plain local, a setsid child survives the end of the run. Write the command that proves it, and say which mechanism stops it under bubblewrap alone, and which under a scope alone.
Answer
setsid sh -c 'echo $$ > child.pid; exec sleep 300' &, then sleep 1, then ask whether /proc/$(cat child.pid) still exists after the run returns. The child leaves the process group, so the daemon’s kill(-pgid) does not reach it. Under bubblewrap the pid namespace’s init dies with its parent (--die-with-parent), and the kernel kills every process in the namespace (pid_namespaces(7)). Under a scope the manager kills the whole cgroup, and setsid does not change cgroup membership. Both make Isolates().Pids true. Neither kill bounds the count; the scope bounds it separately, with TasksMax, and the pid namespace does not.
(c) A task’s oracle is pytest -q. Give its exec grader, say when it runs and when it is skipped, and say why Regrade cannot recompute its verdict while it can recompute a regexp grader’s.
Answer
{"kind": "exec", "command": "pytest -q"}, with expect_status left at 0 (pytest exits non-zero on a failure). It runs through the runner’s backend, over the trial’s workspace after the run, and only when that backend’s Isolates() has both Filesystem and Network (or -allow-unisolated-code is given); under a backend without them, or with none, the task is skipped with the reason and nothing is sent. A regexp grader reads the stored transcript, which is all Regrade has; the exec grader needs the workspace, which was deleted when the trial ended, so its verdict is the one written into the record’s detail at grading time and is kept, not recomputed.
(d) The bubblewrap argv covers /home, /root, /run, /tmp and /var/tmp with tmpfs mounts over a read-only root. Name a case where a sixth is needed and say how to tell from inside a sandbox.
Answer
A host that keeps a credential store or a service’s state in a directory outside those five: a password manager’s data under /var/lib, a database socket under /srv. They are visible read-only through the root bind, and the argv does not hide them. To find them, run ls / and a readable-file search (find /var /srv /opt -readable -type f | head) through the terminal tool under the backend, and look for anything the reader would not hand to a stranger. The fix is another --tmpfs before the workspace bind, or an allow-list root (/usr, /etc and the compatibility symlinks) that hides by default; the cost of the allow-list is that it must be right for each distribution.
(e) The same daemon moves from plain Local plus a scope to local+bwrap. Which of the two reads of its environment is closed, by what, and what does a terminal command still see of the reader’s other processes?
Answer
Both reads are closed, by the pid namespace and the fresh /proc. /proc/$PPID/environ is no longer the daemon’s: the code’s parent is bubblewrap’s init inside the namespace, which was started with no more than Command.Env. The other processes of the uid are not in the namespace, so their /proc/<pid>/environ files are not there to read. What a terminal command sees of the other processes is nothing: /proc lists the sandbox’s own two or three, bubblewrap’s init, the shell and whatever the shell started. Its own environment is the five values the tool gives it.
Lab
go/labs/ch43 declares Impl{NewLocal, ExecuteCode}; you write them in mine/sandbox.go (its doc comments are the specification) and run
make lab CH=43
make lab CH=43 IMPL=mine
The first runs the reference, the second yours. You write the Local backend: the ulimit wrapper, bubblewrap’s and the scope’s command lines, the process control, the output cap and the wall, the environment given exactly, and kept out of bubblewrap’s pid 1, and an Isolates() that tells the truth; and execute_code. The backend interface, the Command and Output types, Podman, SSH, skill_run, the eval registry and the exec grader are provided.
TestModesruns the shape, environment, output cap, wall limit and signal checks on every mode the host has, through yourNewLocal; the command lines for bubblewrap and the scope are yours too.TestRunShape,TestEnvAndCap,TestWallLimitandTestGroupKillrun the plain backend alone: the shape of anOutput, the exact environment and the output cap, the wall limit, and that a backgrounded child dies with its process group.TestExecuteCodeToolandTestExecuteCodeTurnrun yourexecute_codedirectly and in one scripted turn through the loop: the model calls it, the approver allows it, the observation carries the program’s output, and the trace shows the approval and the call.TestDaemonEnvironmentIsNotReadablere-executes the test binary as a daemon with a sentinel variable in its exec-time environment, runs a benign probe through yourNewLocalon every mode the host has (it reads threeenvironfiles for the variable’s presence and prints presence only), and compares what the code can read with yourIsolates().Env. It is the check the chapter’s first defect would have failed.TestExecuteCodeKeepsEarlierProgramscalls yourexecute_codetwice over one workspace through two tool values and expects two program files, each with its own code.- The escape suite attacks the properties of your
Isolates()that have rows, on the same modes, built through yourNewLocal. It is gated byAEC_ESCAPE=1and run throughgo/labs/ch43/escape.sh, and it skips otherwise.TestNoSecretsInTestdatascans the committed capture.
The default tests check the shape of a run on every mode the host has and one isolation claim, Env. Your other claims (Filesystem, Network, Pids, Memory) are attacked only by sh go/labs/ch43/escape.sh, which runs attacks on your host. With the starter, the first test to reach a stub reports chapter 43 lab: not implemented. What the lab cannot do: it cannot test a kernel, it runs no attack on the plain backend, and its default ssh tests are against a fake binary (the remote mode above is opt-in). On a host without bubblewrap or a user manager, the rows for that lever are not run; a missing row is a gap in the table, not a pass.
Further reading
- bubblewrap,
README.mdat v0.12.0: “not a complete, ready-made sandbox”, the user-namespace mechanism and the removed setuid mode. - pid_namespaces(7), mount_namespaces(7), user_namespaces(7), cgroups(7) (the delegation section), getrlimit(2) (
RLIMIT_AS,RLIMIT_CPU,RLIMIT_NPROC;setrlimit(2)is its alias) and PR_SET_DUMPABLE(2const), the Linux man-pages project, from the kernel.org git mirror at the tagman-pages-6.16. - systemd-run(1) (
--scope,--expand-environment=), systemd.scope(5) (a scope’s lifecycle is “not bound to the lifetime of one specific process, but to the existence of at least one process in the scope”) and systemd.resource-control(5) (MemoryMax=,MemorySwapMax=,TasksMax=,CPUQuota=), and systemd’s NEWS at v254 (the option added, off for--scope) and v258 (on for--scope). --http-proxy, podman’s option file at v5.8.6, included bypodman run.- gVisor documentation: the application kernel, written in a memory-safe language and running in userspace.
- Mark Chen et al., Evaluating Large Language Models Trained on Code, arXiv 2107.03374, 2021: the HumanEval sandboxing paragraph on p. 4.
- Carlos E. Jimenez et al., SWE-bench: Can Language Models Resolve Real-World GitHub Issues?, arXiv 2310.06770, 2023 (revised 2024): unit tests as the oracle, p. 2.
- Nous Research, Hermes Agent at commit
cca83848ec79a4a6a2ecc10285725559bf72c97c:tools/environments/docker.py,tools/environments/ssh.pyandtools/terminal_tool.py, as cited by file and line.