← Knowledge Notes
AI Engineering / Knowledge note · English

Claude Code Security Sandbox: Bubblewrap, Permissions, and Context Boundaries

Explains Claude Code's Linux Bubblewrap sandbox, file and network boundaries; provides verified minimal examples and in-product checking steps, while retaining historical security analysis and competitor comparisons.

Source collection:Cross-source topic compilation · Published here:2026-09-26 · Note updated:2026-05-31

AI SecurityPrivacy ProtectionTool Security

Reading guide: First distinguish sandbox, permissions, and context

Claude Code's Bubblewrap sandbox on Linux mainly limits which files and network resources commands can access; it does not automatically decide for you which information should be sent to the model. In actual use, you need to simultaneously check the execution boundary of commands, the permissions of file tools and MCP, and the content sent to the model.

If you want to get hands-on first, see the minimal Linux example below; if you want to configure Claude Code, read “How to check within the product” first; if you care about data exposure and the historical competitor roadmap, continue reading the original analysis later.

This supplement was verified on 2026-10-25. The main text attached below retains the third-party source-code analysis and inferences from the 2026-03-31 version; it is not today's configuration guide. In particular, the old article's statement that MCP writes are restricted by the sandbox cannot be treated as a current product guarantee: according to the current official sandbox documentation, the Bash sandbox covers shell commands and their subprocesses, while file tools, MCP servers, and Hooks are outside this boundary and require their own access controls.

Minimal Linux example: expose only one working directory

The following demonstrates Bubblewrap's mount and namespace mechanisms. It does not start a model and is not equivalent to fully reproducing Claude Code's network proxy or permission system. Before running it, you need Linux,bwrap and an environment that allows creating user namespaces. macOS and native Windows cannot directly copy this example.

First prepare this example's own temporary working directory, then mount the tools directory into the sandbox as read-only. The example does not mount the host home directory or the entire root filesystem.

demo_dir=$(mktemp -d)
mkdir -p "$demo_dir/work"

bwrap --unshare-all --die-with-parent --new-session \
  --ro-bind /usr /usr \
  --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 \
  --proc /proc --dev /dev --tmpfs /tmp \
  --bind "$demo_dir/work" /work --chdir /work \
  --clearenv --setenv PATH /usr/bin:/bin \
  -- /bin/sh -eu -c '
    printf "sandbox example\n" > /work/result.txt
    test ! -d /home
    if touch /usr/probe-denied 2>/dev/null; then exit 1; fi
    printf "PASS: workspace writable, home absent, tools read-only\n"
  '

cat "$demo_dir/work/result.txt"

The pass criteria for this code are: it can write to /work/result.txt, cannot see /home, and writing to /usr fails.--unshare-all also creates an isolated network namespace; this example provides no network access. Allowing network access by domain name requires additional mechanisms such as a proxy; Bubblewrap itself cannot be treated as a domain-name allowlist.

This time, the above read/write boundaries were verified on Ubuntu 22.04 and Bubblewrap 0.6.1; in addition, an external test file generated on the host and the network namespace identifier were used to confirm “unmounted files are not visible” and network isolation. This verifies only one minimal environment and does not represent completed security acceptance for all Linux distributions, containers, or attack methods. The temporary directory stores only the results of this example and can be cleaned up yourself after inspection.

How to check within the product

Run /sandbox in a Claude Code session to first check dependencies and the restrictions actually in effect. Linux/WSL2 usually requires Bubblewrap and socat; user namespace restrictions on Ubuntu 24.04 and later should be handled according to the official troubleshooting instructions, rather than replacing the fix by disabling the whole machine's security policy or switching to unsandboxed execution.

The checking actions should be delegated to Claude to execute; they cannot merely be tried once in your own ordinary terminal. Have it attempt to create a test file containing no sensitive content in a test directory that is not within the allowed write scope, then inspect the result; at the same time, verify whether the command's network access is subject to the expected restrictions. If a prompt saying “change to outside the sandbox and retry” appears, first clarify the dependencies, paths, and network rules before deciding whether to expand the scope. No actual Claude Code session was executed this time; the in-product steps were cross-checked against official materials and are not passed off as actual integration testing.

Finally, ask one more question: do file tools, MCP, or environment variables still contain content that should not be given to the model? Even if the Bash sandbox is working properly, that cannot be used to infer that these entry points are isolated.

References:Claude Code sandbox documentation,Anthropic sandbox design introduction,Bubblewrap upstream repository,Anthropic sandbox-runtime.

Historical analysis: retain original materials and judgments at the time

What this is:liuup/claude-code-analysis(2.8k⭐) performed on the same batch of CC v2.1.88 source code leaked on 2026-03-31 security analysis + competitor comparison. These are the two parts of this set of notes that do not overlap with other parts: what exactly CC collects from you, where it can be attacked, what defenses it has built itself, how to minimize the exposure surface, and how it compares with Codex/Cursor/Aider/Gemini CLI.

Reminder: third-party analysis based on leaked source code, unofficial, containing inferences. For the architecture (loop/tools/subagents), see Claude Code Internal Architecture (Decompiled Source-Code Level); for inside information such as model codenames/remote switches, see Claude Code Insider Discoveries (Telemetry/Codenames/Undercover/Remote Switches/Roadmap). Complete source code on this machine:~/projects/开源项目/claude-code-analysis.


I. Data exposure surface: the most dangerous thing is not telemetry, but the “context that enters the model”

Most people worried about privacy only focus on “whether telemetry is being uploaded,” but for a coding agent,the truly largest leak point is the lump of “working context” packaged up and sent to the model API in every conversation. CC comes into contact with your data in 6 layers:

Layer What is collected Sensitivity Where it goes
① Model context (most hidden) Conversations + history +tool execution results + file contents + code snippets+ git diff + CLAUDE.md + attachments + MCP responses Extremely high Anthropic model API
② Local persistence transcript JSONL (individual conversation entries) + session metadata + OAuth credential cache + memory files High Local disk, retained long-term by default
③ Long-term memory accumulation Your preferences/identity/project facts automatically distilled from history, injected every time a conversation starts High Local machine, persists across sessions
④ Telemetry Device/session ID, platform, account/organization UUID, subscription level, repository URL hash, tool usage statistics,hashes of file paths/content(not original text) Medium Datadog + 1P
⑤ Team Memory sync Team memory directory (may contain intranet knowledge/ops paths/team rules) High Only when enabled, pushed back to the server
⑥ Active upload transcript sharing + Grove (“help improve Claude,” enters model training) High Only when enabled

Analogy: you may think the risk is “the assistant secretly keeping a ledger and handing it in” (telemetry), but the real risk is “every time the assistant works, it reads aloud to the backend the entire package of all files spread out on your desk, the code on the screen, and the command output just run” (context). The ledger has also been desensitized and hashed, whereas context is original text.

Core conclusion: the risk lies not in a single telemetry point, but the information diffusion boundary. This boundary cannot be eliminated even by turning off telemetry — it is a structural characteristic of this type of product.

One engineering detail is worth noting: there is a deliberate type in the source code AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS; for any string to be reported in telemetry, developers must manually convert this type = equivalent to “signing and fingerprinting in code: I confirm this entry contains no raw code/path text.” This shows the team consciously prevents source code from entering telemetry — but this only guards the telemetry layer, not the ① context layer.


II. Attack surface: 4 types of attacks + CC's source-code defenses

CC can read files/webpages/MCP responses and run commands; these capabilities themselves are attack entry points:

▸ 1. Prompt injection (including Unicode steganography) — an attacker hides instructions in open-source repository comments, webpages, or MCP responses, and when you ask CC to read them, it is induced to perform malicious operations.An even sneakier variant: use invisible zero-width Unicode characters (​, etc.) to hide instructions within normal text.

Defense:partiallySanitizeUnicode() — NFKC normalization (unify “looks like A but is actually a composite character”) + remove zero-width/direction-spoofing/private-use-area characters, repeatedly cleaning in a loop until unchanged (up to 10 times). MCP return values are recursively cleaned throughout. (Real vulnerability: HackerOne #3086545 used zero-width characters to hide instructions in an MCP response.)

▸ 2. Shell command injection — inducing the model to generate commands carrying malicious payloads to hijack your machine.

Defense:dangerous-pattern blacklist —— python/node/bash/eval/sudo/ssh, etc. If you have configured broad authorization such as Bash(python:*) (equivalent to “letting AI run arbitrary scripts without restriction” = administrator privileges), it will be temporarily revoked before entering automatic mode and restored after exiting.

▸ 3. Git escape (sophisticated multi-stage) — create a fake bare git repository inside the sandbox (HEAD/objects/refs) and plant a malicious core.fsmonitor hook, which waits to trigger when you run git log on the host machine outside the sandbox.

Defense: after each sandboxed command finishes,scrubBareGitRepoFiles() forcibly sweep away bare git repository files inside the sandbox.

▸ 4. Untrusted input from MCP servers — an untrusted MCP server returns malicious “tool results” to manipulate Claude.

Defense: recursive Unicode cleaning + independent MCP permission authentication + sandbox restricts writes triggered by MCP to allowlisted paths.


III. Defense system: 5 lines of defense (concentric circles)

        Telemetry privacy isolation + secret scanning         ← Data egress defense
      ┌─ Tiered permission mode controls ─┐           ← Policy defense
   ┌──┼ Tool Permission application-layer interception ┼──┐ ← Application defense
   │  │   Sandbox system-level isolation        │  │ ← Underlying defense
   │  │   Unicode cleaning / path validation    │  │
   └──┴────── Host machine (protected) ──────┴──┘
Defense How to do it Points PMs should remember
Dual permission gates Application layer (popup confirmation) + system layer (sandbox); if one layer is breached, the other remains Even if AI obtains permission, the sandbox still limits what it can actually touch
Sandbox Linux/WSL2 use bubblewrap + namespace kernel isolation; macOS uses the native sandbox. Driven by an allowlist: precisely controls which paths can be read/written and which domains can be accessed Programs inside the sandbox "cannot see" the real ~/.claude/settings.json, and changes only affect the isolated view. Configuration hot-reload is synchronized, with no "old-rule time window" escape
Permission tiers default (ask every time) → acceptEdits → plan (read-only planning) → auto (classifier decides) → bypassPermissions (skip everything, dangerous) bypassPermissions can be toggled remotely by the enterprise or set locally to force-disable it, even if you pass --dangerously-skip-permissions it is ignored
Secret scanning Before content leaves the local machine, use regex to scan for 30+ credential types (AWS/GitHub PAT/OpenAI/Stripe/PEM private keys, etc.) Scanning does not return the original matched text(preventing the scan itself from becoming a leakage channel); it can be redacted into [REDACTED] rather than discarded directly
Privacy tiers default / no-telemetry / essential-traffic three levels PII fields are routed to dedicated BigQuery columns with access control, and before being sent to Datadog stripProtoFields are desensitized; MCP tool names are replaced with generic mcp_tool(without exposing your private MCP server names)

Engineering aesthetics highlight: the permission system is fail-closed (conservatively secure) by default — buildTool(), isConcurrencySafe/isReadOnly/isDestructive all default to false (treated by default as "not concurrent / has side effects / potentially destructive"), and restrictions are relaxed only when safety is explicitly declared. This is the correct security posture: default suspicion, not default trust.

Overall assessment: CC is by no means zero-risk (context leakage is structural and cannot be avoided even by turning off telemetry), but its defensive engineering is solid — dual gates/sandbox/secret scanning/Unicode sanitization/dangerous-rule interception all have real source code. The most effective security measure for users is controlling the input boundary(playbook below).


4. Privacy-minimization playbook (actionable)

If you need to handle sensitive code/data in CC, reduce the exposure surface in three steps: "network → disk persistence → behavior."Doing only step 1 without steps 2/3 gives privacy benefits far below expectations.

▸ Step 1: Turn off network and telemetry

  • DISABLE_TELEMETRY —— turn off telemetry/analytics
  • CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC —— more aggressive, turn off all unnecessary outbound network access (even automatic updates/Grove/release notes). Choose this if you want "as little outbound network access as possible."

▸ Step 2: Turn off disk persistence and memory

  • --no-session-persistence or cleanupPeriodDays: 0 —— do not generate recoverable transcripts (which also reduces opportunities for them to be reused for memory/resume/share)
  • CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 or autoMemoryEnabled: false or --bare —— turn off automatic memory and stop accumulating your long-term profile
  • Do not enable Team Memory —— it monitors directories + synchronizes pull/push back to the server
  • Do not enable Remote/Bridge/Transcript Share —— all expand the boundary

▸ Step 3: Control your own input(most critical; turning off telemetry cannot save careless feeding)

  • Do not paste keys/tokens/private keys directly into the prompt
  • Do not stuff an entire .env, production configuration, or customer data into the context
  • Do not let the agent scan large directories containing sensitive materials
  • Do not work on sensitive projects while Grove is enabled

▸ Enterprise governance(personal habits are insufficient to converge risk; unified policies are required): disable auto memory + team memory + cleanupPeriodDays:0 by default + default essential-traffic + prohibit remote/bridge + use isolated repositories/desensitized mirrors/temporary worktrees to run agents.

A realistic judgment: if your real requirement is "code must never leave this machine, must not enter the model, and must leave no trace,"this type of product is naturally unsuitable as the default way of working —— the closest option can only be --bare + everything turned off + strict input control. CC can "reduce the exposure surface," but it is not a "zero-collection-first" architecture.


5. Competitor comparison: CC vs Codex / Gemini CLI / Aider / Cursor

The comparison is based on each company's official public materials as of 2026-03-31. The table below shows "route differences," not "who is better."

Product One-sentence positioning Key differences from CC
Codex(OpenAI) General-purpose coding agent platform covering local + cloud Broader entry points (CLI/IDE/web/app/SDK/Slack), more mature cloud, stronger emphasis on a unified product line and enterprise governance;CC's file-based memory and local auditability are stronger
Gemini CLI(Google) High-standard open-source terminal CLI agent baseline Already includes built-in tools/MCP/checkpoint/sandbox/trusted folders/telemetry, with clearer and more direct product boundaries;CC's memory layering is deeper (not just checkpoint), and the agent runtime is heavier (teammate/swarm/team memory)
Aider Lightweight terminal pair programming Lighter, repo map + git + lint/test closed loop, simple scripting;CC has more complex state management (like a terminal workbench) and stronger platform capabilities (MCP/bridge/swarm/team memory)
Cursor IDE-driven remote agent platform IDE-led, strong background agents, outstanding remote isolated execution;CC is led by a local terminal kernel, with remote as only an extension layer

▸ CC's real differentiation(not "more features," but these three points holding simultaneously, while competitors usually cover only one or two):

  1. Unified execution kernel —— REPL/headless/子 agent/后台/远程Everything goes through the same query() main loop, with no behavioral differences from two implementations
  2. File-based, auditable, layered memory —— memory is Markdown on disk that can be cat (the four Auto/Session/Agent/Team layers each have their own switches), not a black-box database
  3. Local-first but able to scale smoothly to remote/bridge/swarm

In one sentence:CC is not "putting a CLI skin on the Claude API," but a local agent platform with an independent query kernel + file-based memory + trunk-based permissions + multi-agent runtime. When selecting: choose Codex for broad coverage + cloud + enterprise governance; choose Cursor for IDE + background agents; choose Aider for extreme lightness; CC's strength is a local kernel + deep memory + multi-agent collaboration.

Sources and related materials