Back to all notes
AI & Agents

Locking Claude Code in a Sandbox Without Losing a Day's Work

≈ 14 min read

Claude Code can run every shell command it starts inside an operating-system sandbox (Seatbelt on macOS). With the sandbox on, a confused or manipulated agent can't read your secrets, write to your other projects or send data to arbitrary servers. However, a careless setup also breaks many of your scripts. This article shows the setup I ended up with on macOS, the changes that keep real work going, the paths around the sandbox that need closing separately, and what the setup costs.

1. Turn on Claude Code's sandbox, and remove its escape hatch

Add this to ~/.claude/settings.json, your user settings, which apply to every project:

{
  "sandbox": {
    "enabled": true,
    "allowUnsandboxedCommands": false
  }
}

enabled: true runs every shell command Claude starts inside the sandbox.

allowUnsandboxedCommands: false removes the escape hatch. Without it, when the sandbox blocks a command, Claude can ask you to run that command again outside the sandbox. Approving a single one of those requests gives that command your full rights, so one tired "yes" undoes the whole setup.

What changes once the sandbox is on:

  • Shell commands can write only to the project folder, a temp folder and folders you list.
  • Network traffic goes through a proxy that allows only the hosts you list.
  • macOS automation is off: open, osascript and anything else that drives apps through Apple Events fails.

2. Make your secrets unreadable

By default, a sandboxed command can still read every file in your home folder. Deny the ones that hold secrets.

Read rules in permissions.deny apply to Claude's file tools (Read, Grep, Glob) and to sandboxed shell commands. The sandbox's own denyRead list applies to shell commands only:

{
  "permissions": {
    "deny": [
      "Read(**/.env)",
      "Read(**/.env.local)",
      "Read(**/.env.*.local)",
      "Read(**/.env.production)",
      "Read(~/.ssh/**)"
    ]
  },
  "sandbox": {
    "filesystem": {
      "denyRead": ["~/.ssh"],
      "allowRead": ["~/.ssh/test-machines", "~/.ssh/test-machines.known_hosts"]
    }
  }
}

Name the .env files one by one instead of writing .env*, so .env.example stays readable and editable. The narrower allowRead entry reopens one dedicated key for test machines, while every personal key stays out of reach.

Also check that sandboxed commands can't use your ssh-agent. With access to the agent's socket, a command can sign in with your keys without ever reading them. Run ssh-add -l from a Claude session: it should fail.

SSH keys are only the start. Many command-line tools save sign-in tokens in your home folder. Deny every one you have, both as a Read() rule and in denyRead:

  • ~/.config/gh (GitHub CLI)
  • ~/.aws, ~/.config/gcloud, ~/.kube (cloud and cluster tools)
  • ~/.docker/config.json, ~/.npmrc, ~/.netrc, ~/.git-credentials
  • other AI agents' homes, such as ~/.codex
  • ~/.zsh_history and ~/.bash_history, because tokens pasted into commands end up there
  • ~/Library/Keychains, ~/Library/Cookies and your browser profile, such as ~/Library/Application Support/Google/Chrome

Denying reads has two side effects:

  • A Read() rule also blocks the sandbox. If you deny a tool's own login file, that tool can't sign in when Claude runs it, not just when Claude reads the file directly.
  • Denying ~/Library/Keychains can break TLS. Some command-line tools, Rust ones in particular, look up root certificates through the keychain. When that lookup fails, every HTTPS connection fails with a vague "error sending request". Point those tools at the system's certificate file instead by setting SSL_CERT_FILE=/etc/ssl/cert.pem.

3. Let normal work through the sandbox

Most breakage comes from five places: network hosts, folders outside the project, temp files, local servers and dev servers.

Network hosts. Add every host a command needs to allowedDomains, including IP addresses on your local network. The proxy refuses requests to any other host:

{
  "sandbox": {
    "network": {
      "allowedDomains": ["registry.npmjs.org", "test-mac.example.com", "192.168.64.3"]
    }
  }
}

SSH. Plain ssh can't connect to anything, because all network traffic must pass the proxy and ssh doesn't use a proxy on its own. The sandbox puts a tunnel command in the environment variable SRT_SSH_PROXY_COMMAND. Scripts that write their own SSH config file (here $ssh_config) can add it as a ProxyCommand when the variable is set:

[ -z "${SRT_SSH_PROXY_COMMAND:-}" ] || \
  printf '  ProxyCommand /bin/sh -c "$SRT_SSH_PROXY_COMMAND" srt %%h %%p\n' >>"$ssh_config"

Folders outside the project. Every folder outside the project that Claude should write to needs listing twice: in sandbox.filesystem.allowWrite for shell commands, and in permissions.additionalDirectories for Claude's file tools:

{
  "sandbox": { "filesystem": { "allowWrite": ["~/test-clones", "~/test-logs"] } },
  "permissions": { "additionalDirectories": ["~/test-clones", "~/test-logs"] }
}

Create each folder yourself first. A sandboxed command can't create a new folder in your home folder, even one that's on the list.

Temp files. On macOS, mktemp -d -t name ignores $TMPDIR and creates the folder in a place the sandbox blocks. Give the full path inside $TMPDIR instead:

work=$(mktemp -d "${TMPDIR:-/tmp}/name.XXXXXX")

Local servers. By default, the sandbox refuses to let a command listen on a port. Tests that start a server on 127.0.0.1 fail with listen EPERM: operation not permitted. This setting allows it:

{ "sandbox": { "network": { "allowLocalBinding": true } } }

Outbound traffic still goes only to the listed hosts. But while such a server runs, any program on your machine can connect to it, your browser included.

Dev servers. The Claude desktop app can start your dev server for you, from .claude/launch.json, and show it in its browser pane. That server runs outside the sandbox, and it runs project code that Claude edits all the time: the framework config, the scripts, the app itself. So the app asks you before every start. A prompt you approve without reading adds clicks, not safety. Let Claude start the server inside the sandbox instead, as a background shell command, and open only its URL in the browser pane. That needs no prompt, and Claude's code stays inside the sandbox.

File watchers need one more change. Inside the sandbox, macOS's file-change notifications are blocked, so a dev server's watcher fails (for Next.js: EMFILE: too many open files, watch, then every route returns 404). Make the watcher poll instead. For Next.js, Turbopack still served stale CSS after that, while webpack with polling picked up every edit:

WATCHPACK_POLLING=true next dev --webpack --port 3005

Secrets in .env.local stay unreadable, so features that need them fail in these previews. Leave them failing rather than moving your real secrets into a file the sandbox may read.

Testing features that need secrets. When you do want to test such a feature, there are two clean ways. Which one fits depends on whether the test needs your real secrets or just working ones.

Option 1: throwaway dev secrets the sandbox may read (for routine testing)

Create separate credentials that only reach a dev setup, such as a second database with test data only and a different API secret. Put them in a file whose name none of your deny rules match, such as .env.sandbox, and add that file to .gitignore.

Next.js only loads .env, .env.local, .env.development and .env.development.local by itself, and your deny rules block all of them. So load the file explicitly before starting the server:

set -a; . ./.env.sandbox; set +a
WATCHPACK_POLLING=true next dev --webpack --port 3005

Add the dev database's host to the sandbox's host allowlist too.

The trade-off: Claude can read these secrets. That's acceptable only because they're throwaway. If one leaked, it would open a database with nothing worth stealing, and you could replace it in a minute.

Option 2: test on your hosting provider, not on your machine (for real secrets or real data)

Never start a server with your real secrets because Claude asks you to, whether through the app's start prompt or by running a command it suggests. Claude may have changed the code so that the server reads out those secrets: it could print them to a log Claude reads, write them to a file, or show them on a page Claude opens.

Test features that need real secrets where your app already runs with them: a preview or production deployment on your hosting provider, such as Vercel. The secrets live there, not on your machine, and Claude only sees the pages. That holds only as long as Claude has no access to that provider: no connector, no CLI with your token, no MCP server that can read environment variables. Check what each session has before you rely on it.

If you really have to run it locally, start the server yourself in your own terminal, with your normal .env.local, and only after reading every change since your last review. Claude then only opens localhost in its browser pane. Keep this rare.

What to avoid: unblocking .env.local for the sandbox, or putting real secrets into a file the sandbox may read. That turns every session in the project into one that can read your production credentials.

4. What the sandbox always blocks, and how to work around it

Claude Code's sandbox has built-in blocks that no setting opens. They protect things that run code or hold other apps' data:

Always blockedHow to work around it
git worktree add and git worktree remove, and commits in a worktree another session createdStart each session in its own worktree, created by the Claude app; otherwise make the commit yourself
Writing to ~/Library/Application Support, where every app keeps its data, sign-ins includedReading still works; you make the changes
open, osascript and apps driven by Apple EventsExclude one specific tool from the sandbox (below), or run the command yourself
Seeing or stopping processes the session didn't start (lsof, kill)Claude gives you the command to run

When a tool has to drive another app, such as a virtual-machine manager, exclude exactly that tool's binary from the sandbox:

{
  "sandbox": {
    "excludedCommands": ["/Applications/UTM.app/Contents/MacOS/utmctl"]
  }
}

Always give the full path. A bare name like utmctl matches whatever program of that name comes first in PATH, and a command can put its own folder first in PATH. Check every settings file for bare names, because exclusions from all settings files add up.

The exclusion only applies when the excluded command is typed on its own. Called from inside a script, the same tool runs inside the sandbox again. So write scripts to take the tool's result as a parameter (an IP address, a port) and skip calling the tool when the parameter is given.

5. Stop Claude from changing its own sandbox settings

The sandbox only covers shell commands. Claude's own Edit and Write tools aren't sandboxed, so they could rewrite the settings files that switch the sandbox on, add a hook or register an MCP server. Hooks and MCP servers run outside the sandbox, with your full rights.

Deny those edits. Deny rules beat every allow rule and every permission mode:

{
  "permissions": {
    "deny": [
      "Edit(~/.claude/settings.json)",
      "Edit(**/.claude/settings.json)",
      "Edit(**/.claude/settings.local.json)",
      "Edit(~/.claude.json)",
      "Edit(**/.mcp.json)",
      "Edit(~/.claude/plugins/**)",
      "Edit(~/.claude/hooks/**)"
    ],
    "blockWritesOutsideWorkingDirectories": true
  }
}

These rules protect your user settings from Claude, and they also hold when Claude tries to write through a symlink. But they live in a file in your home folder. For protection that doesn't depend on any file Claude can reach, copy the same rules into the managed settings file, /Library/Application Support/ClaudeCode/managed-settings.json. That file is owned by root, so changing it needs sudo, and its rules override every other settings file:

{
  "parentSettingsBehavior": "merge",
  "permissions": {
    "deny": ["…the rules above…"],
    "disableBypassPermissionsMode": "disable",
    "blockWritesOutsideWorkingDirectories": true
  },
  "sandbox": {
    "enabled": true,
    "allowUnsandboxedCommands": false,
    "filesystem": {
      "allowManagedReadPathsOnly": true,
      "allowWrite": ["~/test-clones"],
      "denyWrite": [
        "~/test-clones/**/.git/hooks",
        "~/test-clones/**/.git/config*",
        "~/test-clones/**/.claude",
        "~/test-clones/**/.mcp.json"
      ]
    },
    "network": {
      "allowManagedDomainsOnly": true,
      "allowedDomains": ["registry.npmjs.org"]
    }
  }
}

Install it with:

sudo install -m 644 -o root -g wheel managed-settings.json \
  "/Library/Application Support/ClaudeCode/managed-settings.json"

Three details in this file matter:

  • Lists from all settings files merge. Without the locks allowManagedReadPathsOnly and allowManagedDomainsOnly, any user or project settings file could still add hosts or reopen read paths. Exclusions and write folders have no such lock, which is why the settings files themselves need the deny rules above.
  • Other repositories are open doors. The sandbox protects .git and .claude only in the current project. In any other repository Claude may write to, a planted git hook or core.fsmonitor setting runs with your full rights the next time you run git status there. A planted .claude/settings.json loosens the next Claude session started in that folder. The denyWrite entries block those files in the folders Claude may write to.
  • parentSettingsBehavior: "merge" keeps the restrictions that an app embedding Claude Code, such as Claude Desktop, adds on top. Without it, the managed file replaces them.

6. Close the paths around the sandbox

The sandbox walls off shell commands. Four paths lead around it: a folder renamed into a protected place, web fetches and MCP servers, plugins, and the commands you run yourself.

A folder renamed into a protected place

denyWrite checks the path each write lands on. Renaming a folder checks only the folder itself, not the files inside it. So Claude could build a clone in $TMPDIR, add a git hook to it there, and then mv the whole clone into a protected folder: the hook arrives intact.

No denyWrite rule can block that rename without also breaking git, which renames files constantly. Instead, a PreToolUse hook in the managed settings checks each shell command before it runs and refuses Claude's move and copy commands into the protected folders:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{ "type": "command", "command": "\"/Library/Application Support/ClaudeCode/guard-moves.sh\"" }]
    }]
  }
}

Claude Code passes the command to the script as JSON on standard input. When the command moves, copies or links files and names a protected folder, or runs inside one, the script prints a reason and exits with code 2. Exit code 2 tells Claude Code to block the command and show Claude the reason:

#!/bin/sh
# Refuse Claude's move, copy and link commands into protected folders.
# Exit 2 blocks the call and shows the message to Claude.
input=$(cat)
cmd=$(printf '%s' "$input" | /opt/homebrew/bin/jq -r '.tool_input.command // empty')
cwd=$(printf '%s' "$input" | /opt/homebrew/bin/jq -r '.cwd // empty')
[ -z "$cmd" ] && exit 0
 
# The protected folders, in every way a command can name them.
roots='(~|\$HOME|\$\{HOME\}|/Users/[^/ ]+)/(test-clones|test-logs)'
# Commands that put existing files at a new path.
verbs='(^|[;&|(`[:space:]])(mv|cp|rsync|ditto|install|ln|rename)[[:space:]]|os\.(rename|replace)|shutil\.(move|copytree)|fs\.(rename|renameSync|cp|cpSync)'
 
printf '%s' "$cmd" | grep -Eq "$verbs" || exit 0
if printf '%s' "$cmd" | grep -Eq "$roots"; then hit=1; fi
case "$cwd" in "$HOME"/test-clones|"$HOME"/test-clones/*|"$HOME"/test-logs|"$HOME"/test-logs/*) hit=1 ;; esac
 
if [ "${hit:-0}" = 1 ]; then
  echo "Blocked: moving or copying files into protected folders can plant git hooks. Ask the user to run it." >&2
  exit 2
fi
exit 0

The script calls jq through its Homebrew path on Apple Silicon. Change /opt/homebrew/bin/jq if yours is installed elsewhere.

Install the script owned by root, next to the managed settings file, so Claude can't edit it:

sudo install -m 755 -o root -g wheel guard-moves.sh \
  "/Library/Application Support/ClaudeCode/guard-moves.sh"

A guard that Claude could rewrite would protect nothing. So keep an editable copy in your project, let Claude draft and test changes there, and install them yourself with the same line after reading the diff. Hooks load when a session starts, so start a new session after each install.

To test the script, pipe a sample command into it: echo '{"tool_input":{"command":"mv x ~/test-clones/y"},"cwd":"/tmp"}' | sh guard-moves.sh; echo $? should print the message and 2.

The script is a guardrail, not a wall. It only reads the command text, so a script that renames files indirectly gets past it. It also refuses harmless copies into the protected folders; you run those yourself.

Note the escaped quotes around the path in the command setting. Claude Code runs hook commands through a shell, so a path containing a space (like Application Support) needs quoting. Unquoted, the shell can't find the script and the hook fails with exit code 127. Claude Code doesn't treat that failure as a block, so the guarded command simply runs, and nothing tells you the guard is broken.

Web fetches and MCP servers

The host allowlist only applies to shell commands. Claude's WebFetch tool and every MCP server connect to the internet directly, so they can carry data out in a URL or an upload.

If you keep WebFetch, add a second PreToolUse hook for it. This one never blocks: it lets plain reading URLs through and makes Claude Code ask you before fetching a URL that could carry data. That covers URLs with a query string or fragment, long or encoded-looking parts, an IP address as the host, or a username and password. The prompt appears even in auto mode.

Short, plain URLs can still leak a few bytes each, so this only works together with the unreadable secrets from section 2.

Add the hook to the same PreToolUse list in the managed settings:

{
  "matcher": "WebFetch",
  "hooks": [{ "type": "command", "command": "\"/Library/Application Support/ClaudeCode/guard-webfetch.sh\"" }]
}

To make Claude Code ask, the script prints a JSON answer with permissionDecision: "ask" and the reason, and exits with code 0:

#!/bin/sh
# Let plain reading URLs through; ask the user before any URL that could carry data out.
url=$(/opt/homebrew/bin/jq -r '.tool_input.url // empty')
[ -z "$url" ] && exit 0
 
reason=""
case "$url" in
  http://*|https://*) ;;
  *) reason="not an http(s) URL" ;;
esac
rest=${url#*://}
host=${rest%%[/?#]*}
path=${rest#"$host"}
 
if [ -z "$reason" ]; then
  if [ ${#url} -gt 160 ]; then reason="URL longer than 160 characters"
  elif printf '%s' "$url" | grep -q '[?#]'; then reason="URL has a query string or fragment"
  elif printf '%s' "$host" | grep -q '@'; then reason="URL carries credentials"
  elif printf '%s' "$host" | grep -Eq '^[0-9.]+(:[0-9]+)?$|^\['; then reason="host is an IP address"
  elif printf '%s' "$host" | tr '.' '\n' | grep -Eq '^.{31,}$'; then reason="a host label is longer than 30 characters"
  elif printf '%s' "$path" | tr '/' '\n' | grep -Eq '^.{81,}$'; then reason="a path segment is longer than 80 characters"
  elif printf '%s' "$host$path" | grep -Eq '[A-Za-z0-9+=_]{32,}'; then reason="URL contains a long encoded-looking run"
  fi
fi
 
[ -z "$reason" ] && exit 0
/opt/homebrew/bin/jq -n --arg r "Check before fetching: $reason." \
  '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "ask", permissionDecisionReason: $r}}'
exit 0

Install it the same way as the move guard:

sudo install -m 755 -o root -g wheel guard-webfetch.sh \
  "/Library/Application Support/ClaudeCode/guard-webfetch.sh"

Documentation pages such as https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API are fetched without asking. https://example.com/?d=… and https://<base64>.example.com/ make Claude Code ask you first. Hyphens don't count as encoded, so long readable page names still pass.

Plugins

Plugins can add hooks and MCP servers, and those run outside the sandbox with your full rights. Plugins also update themselves from their repositories, so a compromised repository becomes code running on your machine. Keep only plugins you trust, and limit the sources plugins may come from in the managed settings:

{
  "strictKnownMarketplaces": [
    { "source": "github", "repo": "anthropics/claude-plugins-official" }
  ]
}

Adding a marketplace that isn't on this list is then refused.

The commands you run yourself

Commands you run in your own terminal, or with ! in Claude's prompt box, skip both the sandbox and the hooks. Some commands Claude runs switch off another tool's own sandbox on purpose, because Claude's sandbox surrounds them, for example a second AI agent started with full access. Never copy such a command into your own terminal: there, nothing surrounds it.

7. What the sandbox costs you

  • More hand-offs. Pushing, worktree commands, opening apps and stopping stray processes all become commands Claude prints and you run.
  • Claude can't change its own setup. Every new host, folder or exclusion is an edit you make. Changes to the managed settings need sudo, and a running session keeps the hooks and settings it started with, so start a new session after each change.
  • MCP servers still work, but you add them. Claude can't register them anymore. Like hooks and plugins, they run outside the sandbox.
  • Git worktrees work only when the Claude app creates them. A worktree made with a plain git worktree add is read-only to every other session.
  • No git clone into protected folders. A clone writes exactly the .git/hooks and .git/config files you blocked there.
  • A locked host list is strict. With allowManagedDomainsOnly, you can't allow a host for a single command; every new host is a sudo edit.
  • Scripts need small changes: temp folders inside $TMPDIR, the SSH proxy command, a certificate file for some tools, and parameters instead of calls to GUI tools.
  • A second AI agent needs its own home folder. To run another agent's command-line tool, such as Codex, inside the sandbox, give it a separate home folder, sign in there once from your own terminal, block writes to its config file, and keep your normal home for that agent unreadable.

8. Test that the sandbox holds

Don't trust the configuration; try to break it. From a new Claude session, ask Claude to:

  • write the settings files through the shell, through Edit, and through a symlink;
  • write them from a test started by npm test;
  • write a git hook in another repository;
  • move a clone with a planted hook into a protected folder;
  • read a secret.

Every attempt should fail, while plain file writes and git status keep working.

Test each layer on its own. Permission rules and auto mode often stop a command before the sandbox sees it, which proves nothing about the sandbox underneath. To reach the sandbox, put the same read into a small script and run the script. And test hooks in a new session: a running session may pick up new sandbox paths, but it doesn't load new hooks.

One hole no setting closes: code Claude writes and you run. Tests, scripts and install hooks run with your full rights the moment you start them in your own terminal. The sandbox protects you while Claude works; reading the diff protects you afterwards.