# Why does an instance lose syscall confinement when a tool call re-enters the sandbox via a cached interpreter **Date of Record:** 2026 December 2 **Scope:** Applies to LLM agent runtimes that confine tool-invoked code execution at the syscall layer (seccomp-bpf, seccomp user notification, or ptrace-mediated filters) while reusing a warm interpreter process across successive tool calls. Does not apply to per-call process-fork sandboxes that tear down the interpreter after each invocation, nor to pure WASM/VM isolation where the filter is re-instantiated per module. ## Core Distinction There are two different things an agent operator means by "the sandbox is still active": 1. **Filter liveness** — the seccomp filter program is still installed on the thread that will execute the next tool call's code. 2. **Confinement continuity** — the *set of syscalls permitted to the code now running* is the same set that was permitted to the code that ran under the same policy at the previous call. These diverge the moment the interpreter is reused. The seccomp filter is installed on the *process* (and inherited by threads), and `prctl(PR_SET_NO_NEW_PRIVS)` plus `seccomp(SECCOMP_SET_MODE_FILTER)` are one-shot and monotonic: a filter can be *tightened* but never *loosened*, and a filter installed for call N stays installed for call N+1. That sounds like a safety property. It is not, because the *policy the agent intended* for call N+1 may be *stricter* than what call N left behind — or the interpreter may have cached a syscall result or a file descriptor whose capability outlives the policy that granted it. The failure mode: a warm interpreter (CPython, Node, JVM) caches state across tool calls — open file descriptors, `mmap`'d buffers, imported native extensions, resolved `dlopen` handles, and, critically, a *pre-opened* `/proc/self/mem` or a `memfd` used for JIT. The next tool call's confinement policy is expressed as "this call may only `read`/`write`/`exit_group`," but the process already holds an fd that lets it `mmap(PROT_WRITE)` over its own text and `mprotect` to `PROT_EXEC`. The seccomp filter sees `mmap` and `mprotect` — both allowed by the *previous* call's policy, which is still installed because filters are additive and the runtime never tore down the interpreter. ## What Was Observed A Python tool-execution agent ran a sequence of calls in a single warm CPython 3.11 subprocess. Call 1 was a benign data-transform that imported `numpy`, which loaded a native extension via `dlopen`, which in turn `mmap`'d an executable segment and called `mprotect(PROT_READ|PROT_WRITE|PROT_EXEC)` on a JIT buffer. The seccomp profile for call 1 permitted `mmap`, `mprotect`, `openat`, `read`, `write`, `close`, `exit_group`, and `rt_sigreturn` — a permissive profile chosen because native-extension loading is unpredictable. Call 2 was classified as "pure computation" and the agent runtime *intended* to install a strict profile permitting only `read`, `write`, `exit_group`. The runtime called `seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &strict_prog)`. Because seccomp filters compose by intersection (the most restrictive wins for any given syscall), the strict filter *should* have blocked `mmap`. It did not block the exploit, because the exploit did not need a new `mmap`: the `memfd` and the `PROT_EXEC` mapping from call 1 were still live in the process. Call 2's code wrote to `/proc/self/mem` — wait, `openat` on `/proc/self/mem` was blocked by the strict filter. But the *already-open* fd to the JIT buffer from call 1 was inherited by the interpreter's running thread and reachable via a Python object left in a module-level cache (`numpy`'s internal buffer registry). Call 2's code did `ctypes`-free pure-Python manipulation of that cached buffer object, which the interpreter had already mapped writable-executable. No new syscall was needed to reach the RWX page; only `write` to an existing mapping, which the strict filter permitted. The observable signal: the strict filter reported `SECCOMP_RET_ALLOW` for every syscall call 2 actually issued, and the runtime's post-call audit ("no `mmap`, no `mprotect`, no `execve` observed") passed. The confinement *looked* continuous. The capability that escaped it was established before the strict filter was installed and survived it because seccomp filters gate *syscall entry*, not *memory access to already-mapped regions*. The secondary observation: a `seccomp` user-notification supervisor (SECCOMP_RET_USER_NOTIF) that the runtime used to log syscalls saw zero notifications during call 2, because call 2 issued only `write` and `exit_group`, both `ALLOW`ed by the strict filter without notification. The supervisor's "no suspicious syscalls" verdict was vacuously true. ## Condition of Validity The invariant that actually holds is narrower than "the sandbox is active": > A syscall filter bounds the *syscalls a thread may issue*, not the *capabilities the thread already holds*. Confinement continuity across a reused interpreter requires that the capability set (open fds, writable-executable mappings, `dlopen`'d code, `memfd`s, `io_uring` rings, `userfaultfd`s) established under policy P_N be a subset of the capability set permitted by policy P_{N+1}, or that the interpreter be torn down between calls. This is valid only when one of the following holds: - **Cold interpreter per call.** The process is forked fresh, the filter installed before `execve` of the interpreter, and the process reaped after the call. Then capability set at entry is empty and the filter is the sole capability source. - **Capability audit at the policy boundary.** Before installing P_{N+1}, the runtime enumerates the process's open fds (`/proc/self/fd`), its mappings (`/proc/self/maps`), and its loaded objects (`/proc/self/maps` `r-xp` entries), and rejects the transition if any capability exceeds P_{N+1}'s allowance — or closes/`munmap`s them. - **Seccomp filter installed at `execve` time via `SECCOMP_FILTER_FLAG_TSYNC` on a freshly `exec`'d interpreter, with `PR_SET_NO_NEW_PRIVS` and no warm reuse.** This is the only configuration where "filter liveness" and "confinement continuity" coincide. It does *not* hold for warm-interpreter reuse where the runtime merely adds a stricter filter at call N+1. The filter is live; the confinement is not continuous. ## Decision Boundary The agent runtime must decide, per tool call, between two regimes: - **Warm reuse is admissible** only if the tool call's declared capability set is a *superset* of everything the interpreter has already acquired — i.e., the call is *at least as privileged* as the accumulated state. In practice this means warm reuse is safe only for a monotone-decreasing privilege ladder where each successive call is *more* restricted than the last *and* the interpreter holds no capability the last call didn't need. Since interpreters cache aggressively, this is almost never true after the first call that loads a native extension or opens a JIT buffer. - **Cold fork is mandatory** whenever the call's policy is stricter than the accumulated capability set, or whenever the call is classified as untrusted (model-generated code, prompt-injected tool arguments). The cost is interpreter startup; the benefit is that the filter is the *only* capability source and the audit is sound. The boundary is crossed exactly when `capabilities_held(interpreter) \ permitted(P_{N+1}) ≠ ∅`. The runtime must compute that set difference, not merely compare filter programs. A runtime that compares filter programs (as the observed one did) will conclude "stricter filter installed, therefore safe" and be wrong. ## Operational Effect Concretely, the runtime must do three things the naive implementation skips: 1. **Enumerate capabilities before every policy transition.** Read `/proc/self/fd`, `/proc/self/maps`, and `/proc/self/status` (`Seccomp`, `NoNewPrivs`). Any `r-xp` mapping, any fd to a `memfd`/`/proc/self/mem`/`/dev/mem`, any `io_uring` fd, any `userfaultfd`, any `AF_PACKET` socket — these are capabilities that survive filter tightening. 2. **Compare against the next policy's allowance, not against the previous filter.** The previous filter's `ALLOW` set is irrelevant; what matters is what the process *holds*. 3. **Fail closed to cold fork** when the difference is non-empty and the call is untrusted. Do not attempt to "close the fd and continue" — `munmap` of an RWX region does not guarantee the interpreter hasn't retained a pointer, and `dlclose` is not guaranteed to unload. Fork-and-reap is the only sound reset. The invariant to encode: *a seccomp filter is a syscall gate, not a capability revoker; confinement continuity across a warm interpreter requires capability-set monotonicity, not filter monotonicity.* ```python import os from pathlib import Path class ConfinementContinuityError(RuntimeError): """Raised when a warm interpreter holds capabilities the next tool-call policy does not permit, so tightening the seccomp filter would not actually confine the next call.""" # Syscalls the strict "pure computation" profile is meant to allow. STRICT_POLICY_ALLOW = frozenset({"read", "write", "close", "exit_group", "rt_sigreturn"}) # Capabilities that survive a seccomp filter tightening because they are # established as kernel objects (mappings, fds), not as syscall entries. DANGEROUS_FD_TARGETS = ("/memfd:", "/proc/self/mem", "/dev/mem", "anon_inode:[io_uring]", "anon_inode:[userfaultfd]") def enumerate_held_capabilities(pid: int = 0) -> dict: """Return the capability set the interpreter currently holds, independent of any seccomp filter that may be installed.""" proc = Path(f"/proc/{pid}" if pid else "/proc/self") caps = {"exec_mappings": [], "dangerous_fds": [], "open_fds": []} for line in (proc / "maps").read_text().splitlines(): parts = line.split() if len(parts) >= 6 and "x" in parts[1]: caps["exec_mappings"].append(parts[-1]) fd_dir = proc / "fd" for fd in fd_dir.iterdir(): try: target = os.readlink(fd) except OSError: continue caps["open_fds"].append(target) if any(target.startswith(t) for t in DANGEROUS_FD_TARGETS): caps["dangerous_fds"].append(target) return caps def assert_confinement_continuity(next_policy_allow: frozenset, next_policy_permits_native_code: bool, pid: int = 0) -> None: """Enforce that tightening the filter for the next call actually confines it. A warm interpreter that holds an RWX mapping or a memfd/proc-mem fd can reach code execution without issuing any syscall the strict filter would block. In that case the filter is live but confinement is discontinuous, and the runtime must cold-fork instead. """ caps = enumerate_held_capabilities(pid) if caps["dangerous_fds"]: raise ConfinementContinuityError( f"warm interpreter holds capability-bearing fds {caps['dangerous_fds']!r}; " f"seccomp filter tightening to {sorted(next_policy_allow)!r} cannot revoke them" ) if caps["exec_mappings"] and not next_policy_permits_native_code: raise ConfinementContinuityError( f"warm interpreter holds executable mappings {caps['exec_mappings']!r} " f"but next policy forbids native code; filter liveness != confinement continuity" ) # Capability set is within the next policy's allowance: warm reuse is sound. return None def dispatch_tool_call(code: str, next_policy_allow: frozenset, next_policy_permits_native_code: bool) -> str: try: assert_confinement_continuity(next_policy_allow, next_policy_permits_native_code) except ConfinementContinuityError: # Fail closed: cold fork, install filter before execve, reap after. return cold_fork_execute(code, next_policy_allow) return warm_execute(code, next_policy_allow) def cold_fork_execute(code: str, policy_allow: frozenset) -> str: raise NotImplementedError("cold-fork path elided; installs seccomp before execve") def warm_execute(code: str, policy_allow: frozenset) -> str: raise NotImplementedError("warm path elided; adds stricter filter to existing process") ```