概要
Rust port of Anthropic's sandbox-runtime (srt): single-binary macOS/Linux sandboxing, Windows x64 build (runtime unverified)
セキュリティ・プライバシー計測したスター増加
- 24時間
- +2
- 7日間
- 履歴を収集中
- 15日間
- 履歴を収集中
- 1か月
- 履歴を収集中
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナルsandbox-runtime-rs
A Rust single-binary port of Anthropic's sandbox-runtime v0.0.83, released under Apache-2.0. It provides a lightweight way to enforce filesystem and network restrictions on arbitrary processes at the OS level, without requiring a container image.
The srt executable uses macOS Seatbelt through sandbox-exec, Linux bubblewrap with seccomp,
and proxy-based network filtering. It can sandbox agents, local MCP servers, shell commands,
and their child processes.
Port status: macOS and Linux are the implemented runtime targets. Windows x64 builds, but runtime behavior is UNVERIFIED and important integrations are incomplete. This is not a claim of full upstream feature parity; consult Platform Support, Windows (x64), and the Security model before relying on a boundary.
Installation
mise (ubi backend)
Install the release executable with mise:
mise use -g 'ubi:KonghaYao/sandbox-runtime-rs[exe=srt]@latest'
srt --version
Pin a specific release for reproducible deployments:
mise use -g 'ubi:KonghaYao/sandbox-runtime-rs[exe=srt]@v0.0.83-rs.3'
exe=srt is required: the archive contains an executable named srt, whereas the ubi backend
otherwise looks for the repository name.
The ubi backend is deprecated in newer mise versions. These commands apply to versions that still
provide it; if your version no longer does, install a release asset directly or build from source.
Deprecation does not change the executable name or the release assets.
If mise keeps using cached release metadata or an old archive after an upgrade, clear its cache and retry the desired version:
mise cache clear
mise use -g 'ubi:KonghaYao/sandbox-runtime-rs[exe=srt]@v0.0.83-rs.3'
Release assets
Download an asset matching your host from this repository's releases. Archives are named by target triple so that ubi can select the appropriate build:
| Target | Asset |
|---|---|
aarch64-apple-darwin |
srt-aarch64-apple-darwin.tar.gz |
x86_64-unknown-linux-gnu |
srt-x86_64-unknown-linux-gnu.tar.gz |
aarch64-unknown-linux-gnu |
srt-aarch64-unknown-linux-gnu.tar.gz |
x86_64-pc-windows-msvc |
srt-x86_64-pc-windows-msvc.zip |
Every archive is accompanied by a <asset>.sha256 checksum file. Verify the archive against that
file before extracting it and place srt in a trusted directory on PATH. On Windows the executable
is srt.exe; availability of an archive does not establish runtime support.
Keep the executable outside directories that sandboxed commands may write. The single-binary distribution removes the JavaScript runtime dependency, not the platform dependencies listed below.
Build from source
The workspace pins Rust 1.98.1 in rust-toolchain.toml. From the repository root, build with the
checked-in lockfile:
cargo build -p srt --release --locked
./target/release/srt --version
The result is target/release/srt (srt.exe on Windows). The Linux seccomp entry point is built
into this executable; no separate seccomp build is needed for the supported Linux architectures.
The repository also provides equivalent mise tasks:
mise run build
mise run test
mise run lint
Platform Support
| Platform | Port status | Isolation and dependencies |
|---|---|---|
| macOS arm64 (Apple Silicon) | Verified runtime target | Seatbelt via system sandbox-exec |
| Linux x86_64 | Verified runtime target | bubblewrap, socat, ripgrep; built-in seccomp |
| Linux arm64 | Verified runtime target | bubblewrap, socat, ripgrep; built-in seccomp |
| Windows x64 | Builds only; runtime UNVERIFIED | Partial srt-win management and exec routing; see Windows (x64) |
The status labels describe the port's existing platform status, not a new cross-platform verification performed by reading this document. Neither Node nor Bun is required to run the Rust executable.
Platform-Specific Dependencies
macOS: sandbox-exec is supplied by the operating system. The Rust Seatbelt backend generates
its profile directly and does not require the upstream JavaScript tooling or its deny-path scan
dependencies.
Linux: install all three runtime tools:
| Distribution | Install command |
|---|---|
| Ubuntu / Debian | sudo apt-get install bubblewrap socat ripgrep |
| Fedora | sudo dnf install bubblewrap socat ripgrep |
| Arch | sudo pacman -S bubblewrap socat ripgrep |
bubblewrap(bwrap) creates the mount, PID, user, and network namespaces.socatbridges the isolated workload to the host proxies over Unix sockets.ripgrep(rg) finds mandatory deny paths within writable trees.
The dependency check accepts bwrapPath, socatPath, and ripgrep.command overrides. An explicitly
configured bwrapPath or socatPath that is not executable is an error, not a reason to search
PATH instead.
bubblewrap versions: the upstream baseline is 0.4.0 or later. A deny or credential mask over a
non-regular file needs 0.5.0 or later because older versions prepare file-bind destinations
differently. The Rust dependency check warns about versions older than 0.5.0; use a current
distribution build and test the policies you depend on. The --disable-userns fallback described
below requires 0.8.0 or later and a non-setuid executable.
Ubuntu 24.04 and later: AppArmor restrictions on unprivileged user namespaces can let namespace
creation succeed while removing the capabilities bubblewrap and the seccomp layer need. Prefer an
administrator-managed AppArmor profile granting the necessary userns permission to the relevant
executables. A system-wide alternative, with broader security consequences, is disabling that
restriction:
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
Do not change a host-wide security setting without considering other users and workloads on it.
Running as root: kernels enforcing the Linux 5.12 UID-mapping rule (including distribution
backports) require CAP_SETFCAP when mapping UID 0 into a user namespace. The Rust dependency check
diagnoses a missing capability when the bubblewrap probe fails. Tightened container capability sets
or service CapabilityBoundingSet settings can trigger this. Prefer a non-root caller; do not broaden
a service's capabilities merely to suppress an unexplained sandbox error.
Keeping namespace restrictions intact: the built-in seccomp layer blocks user/mount namespace
creation and mount-changing operations by default. Write denies are mounts in a particular namespace;
letting a command control a new namespace can undermine them. Programs that sandbox themselves, such
as Chromium, rootless container tools, nested bubblewrap, or nested srt, may fail with EPERM.
A direct clone3 receives ENOSYS so common runtimes can fall back to clone.
allowNestedUserNamespaces: true opts out of this protection. Treat write denies and mandatory denies
as insufficient against an adversarial command under that setting. When Unix socket blocking is
disabled, the backend uses bubblewrap's --disable-userns if available. Combining
allowAllUnixSockets with enableWeakerNestedSandbox can leave this fallback off too. An externally
supplied seccomp helper must enforce the restrictions you expect; the port cannot make an older
helper equivalent to the built-in one.
Windows: there is no verified runtime dependency/setup recipe for this port. Building the x64 artifact is not evidence that account provisioning, UAC, WFP, ACLs, logon, or execution work on a live machine.
Basic Usage
Start with an explicit settings file so that the examples have a clear policy:
{
"network": {
"allowedDomains": ["anthropic.com"],
"deniedDomains": []
},
"filesystem": {
"denyRead": ["~/.ssh"],
"allowWrite": ["."],
"denyWrite": []
}
}
Save it as ~/.srt-settings.json, or select it with -s.
srt -c 'curl https://anthropic.com'
srt -c 'curl https://example.com'
srt -c 'cat README.md'
srt -c 'ls ~/.ssh'
The first request is permitted by name; the second is blocked by the network allowlist. Reading the current README is allowed, while reading the denied SSH directory fails. Exact client error messages depend on the command and platform. A permitted hostname must also pass the resolved-address policy; being on the allowlist is not a promise that DNS, TLS, or the remote service will succeed.
With no settings file at the default location, reads are unrestricted, network access is denied,
and only the built-in write paths remain writable. The current directory is not automatically a
writable workspace; add it to filesystem.allowWrite when needed.
Overview
The upstream design combines OS-enforced boundaries with host-side network policy. This port exposes that design through a standalone Rust executable, with conservative defaults for network access and writes. Read isolation is opt-in: explicitly deny sensitive locations or broad home-directory regions.
Key capabilities on macOS and Linux:
- Network restrictions: allow or deny host/domain and port combinations for HTTP, HTTPS CONNECT, and SOCKS5 TCP traffic.
- Filesystem restrictions: control readable regions and writable paths using native profiles or mounts.
- Unix socket restrictions: restrict local IPC, with different macOS and Linux enforcement.
- TLS and credentials: optional in-process TLS termination and selected credential protection features, subject to the port limits below.
- Violation reporting: proxy policy denials are collected; OS-level filesystem diagnostics remain platform-specific.
Example Use Case: Sandboxing MCP Servers
A local MCP server often needs only its workspace, not unrestricted writes to the user's home. Wrap the server executable rather than changing its implementation.
Without sandboxing, a host's .mcp.json might contain:
{
"mcpServers": {
"filesystem": {
"command": "/opt/tools/filesystem-mcp-server",
"args": ["/path/to/workspace"]
}
}
}
With sandboxing:
{
"mcpServers": {
"filesystem": {
"command": "srt",
"args": ["/opt/tools/filesystem-mcp-server", "/path/to/workspace"]
}
}
}
The server path is illustrative; use the executable and arguments supplied by your MCP server.
Configure ~/.srt-settings.json for its actual needs:
{
"filesystem": {
"denyRead": [],
"allowWrite": ["."],
"denyWrite": ["~/sensitive-folder"]
},
"network": {
"allowedDomains": [],
"deniedDomains": []
}
}
The server cannot write to the denied path, even if another allowed write root covers it. This
example does not protect secrets from reads: add denyRead entries if the server must not see them.
Relative paths refer to the working directory in which the host starts srt.
How It Works
The sandbox applies restrictions to the command and its descendants using native OS primitives:
- macOS:
srt-platformgenerates a Seatbelt profile and executes throughsandbox-exec. - Linux:
srt-platformconstructs a bubblewrap mount/namespace plan, starts proxy bridges, and invokes the executable's built-in seccomp mode before the workload. - Windows: partial helper management and argument orchestration exist, but the complete runtime integration is not verified or feature-equivalent.
Dual Isolation Model
Both filesystem and network isolation are needed. Network policy alone does not stop a process from reading secrets, and filesystem policy alone does not control where readable data can be sent.
Filesystem isolation uses different precedence for reads and writes:
- Read, deny-then-allow: reads are allowed by default. A broad deny such as
/Userscan be narrowed by re-allowing.. A more-specific deny inside that readable region remains denied. See the platform caveats in Filesystem Configuration. - Write, allow-only: writes are denied except for built-in paths and explicitly allowed roots.
denyWritetakes precedence overallowWrite. An empty allowlist does not remove the built-in write conveniences.
Network isolation is allow-only. An empty allowedDomains list means no proxy-authorized
destinations. Traffic is mediated by host-side proxies:
- On Linux, the workload has a separate network namespace. Unix socket bridges connect its local HTTP/SOCKS endpoints to the proxies on the host.
- On macOS, the profile permits outgoing IP connections only to the selected local proxy ports.
The port's
allowLocalBindingoption does not grant arbitrary localhost outbound access.
HTTP/HTTPS traffic uses the HTTP proxy; other proxy-aware TCP clients can use SOCKS5. These are not transparent interception mechanisms for arbitrary protocols or UDP. Programs that ignore proxy configuration generally fail to connect rather than gaining unrestricted internet access.
For upstream background, see the Claude Code sandboxing documentation and Anthropic's sandboxing design discussion. Those resources describe upstream integration, not additional port features.
Architecture
The runtime ships as one executable, organized internally as Rust crates:
crates/
srt/ CLI parsing, settings, control channel, execution
srt-core/ Configuration validation, paths, domains, environment
srt-platform/ macOS profiles, Linux mounts/seccomp, Windows routing
srt-proxy/ HTTP/SOCKS5, TLS termination, credentials, decider mode
srt-coreowns the JSON schema and shared policy conversions. Accepting a field in the schema is not proof that the CLI implements it; the CLI also checks unsupported capabilities before validation strips unknown keys.srt-platformtranslates configuration into OS restrictions and manages platform execution.srt-proxyowns connection policy, resolved-address checks, HTTP/SOCKS forwarding, TLS, credential substitution, and standalone proxy mode.srtloads settings, starts proxies and bridges, runs the command, and reports its status.
These crate boundaries describe the implementation, not a supported Node embedding interface. See Embedding the library (Rust) for the supported Rust entry points and Implementation Details for the relevant Rust modules.
Usage
As a CLI tool
Run a command directly, or use -c for a shell command string:
srt echo 'hello world'
srt -c 'printf "%s\n" hello'
srt --debug -c 'curl https://example.com'
srt -s /path/to/srt-settings.json -c 'cargo test'
srt --settings /path/to/srt-settings.json -- git status
| Option | Meaning |
|---|---|
-c <command> |
Run a command string as shell input, with no additional escaping |
-s, --settings <path> |
Select a JSON settings file instead of ~/.srt-settings.json |
-d, --debug |
Enable debug diagnostics; SRT_DEBUG also enables debug behavior |
--control-fd <fd> |
Read complete config replacements as JSON lines from an inherited descriptor |
-V, --version |
Print the executable version |
-h, --help |
Display CLI help |
For operands, the Unix CLI quotes the arguments before running its shell; use -c when you intend
shell syntax such as pipelines or redirections. The current Unix backend resolves bash on PATH.
Do not interpolate untrusted input into a shell command string.
A missing default settings file is permitted and selects built-in defaults. A file that exists
but is empty, unreadable, invalid JSON, or invalid configuration is an error. A file named by
--settings must exist. The CLI refuses to replace such a file's requested policy with defaults,
which would discard read denies, carve-outs, and credential rules.
Exit status: ordinary command exits preserve the command's status. The current Unix supervisors
treat a directly signaled child differently: SIGINT or SIGTERM maps to 0, and another terminating
signal maps to 1 (macOS also reports it). The nested Linux seccomp reaper can report 128 + signal
for a signaled workload, so do not assume one universal signal mapping. Settings, dependency,
unsupported-feature, or startup errors normally return 1 before the workload runs. A denied operation
need not terminate the workload: the client receives an error and may handle it itself.
Updating the config while the command runs: --control-fd
On macOS and Linux, --control-fd <fd> reads an already-open descriptor numbered 3 or above.
Supply a dedicated read-only end of a pipe or a suitable stream. The channel uses one JSON object
per line, in the same shape as the settings file:
srt --control-fd 3 -s /path/to/srt-settings.json -c 'cargo test'
Descriptor 3 must have been opened and inherited by the caller; this command does not create it. Standard streams 0 through 2 are not control channels. An unusable descriptor is a startup error, rather than silently running without the requested channel.
Each line is a complete config, not a patch. network and filesystem and their required lists
must be present. Omitted optional keys return to their defaults; do not send a fragment intended to
merge with old settings. Blank lines are ignored. Invalid or unsupported configurations are reported
on stderr and dropped, leaving the previous policy in force.
What changes in this port:
- The local proxy reads accepted network allow/deny lists, denial reasons, and resolved-address rules for subsequent policy checks.
- Accepted request-time flags and SigV4 policy are read from the new config where the running proxy uses them. Credentials and masks are constructed at startup; updates do not discover new secret values or rebuild masks.
- The entire
network.tlsTerminateobject must stay unchanged. A change to its presence or contents, including exclusions and limits, is rejected. credentials.source、credentials.entries、credentials.hosts的存在与全部内容不可变;更新不会重新读取 secret fd。更换秘密必须重启srt。- Filesystem profiles, mount plans, process environment, proxy listeners, and credential masks are fixed at startup. An update does not re-sandbox the process or revoke existing tunnels.
- If both external proxy ports were selected, there is no local proxy policy state to update; accepting a line does not reconfigure that external proxy.
Channel lifecycle differs from some upstream library integrations:
- Reading starts after local proxy initialization. Startup filesystem rules always come from the initial settings, not from a race with control input.
- EOF leaves the command running under the last accepted config, including EOF before the first update. A final non-empty line at EOF is processed.
- A read error closes the update channel and reports that no further updates will be applied; it does not install a default or empty policy.
- The worker stops when the wrapped command finishes; it does not wait for the writer to close.
- Oversized pending input is rejected rather than retained without bound; keep individual updates well below 1 MiB.
- The sandboxed Unix command is not given the control channel. The execution layer marks non-standard descriptors close-on-exec before launching the workload.
Treat the writer as trusted policy authority. Send secrets only through appropriately protected
settings or channels and do not log config payloads. --control-fd is unsupported on Windows.
As a standalone proxy with an external decider: srt proxy
srt proxy runs only the Rust HTTP proxy, without a sandboxed child. It also dispatches when launched
with argv[0]=srt-proxy, such as through a symlink; no second runtime or separate compiled
JavaScript program is needed.
The host supplies a listening socket and a channel to an external decider. Each forwarded request requires an allow verdict. CONNECT traffic is terminated in-process; without a supplied CA, CONNECT is refused rather than turned into an opaque tunnel. The host must isolate the workload and protect the proxy's inherited descriptors and CA material.
See docs/srt-proxy.md for flags, framing, protocol version 1, verdicts, timeouts, limits, and the standalone security model. This mode is distinct from configuring an external forwarding proxy for a sandboxed command.
Embedding the library (Rust)
The srt crate exposes a library target next to the binary. The library does not initialize an
async runtime and never terminates the calling process: embedders own writing the returned output
and choosing the exit status.
[dependencies]
srt = { git = "https://github.com/KonghaYao/sandbox-runtime-rs.git", rev = "<SHA>" }
use std::ffi::OsString;
let out = srt::run_os(std::env::args_os());
// Write out.stdout and out.stderr to inherited stdio, then exit with out.code.
let cli = srt::run_cli(&["--version".to_owned()]);
let helper = srt::apply_seccomp(&[OsString::from("/bin/true")]);
run_osperforms the same dispatch as thesrtbinary: the Windows multicall helper,--srt-apply-seccomp, thesrt-proxyargv0 mode, then the ordinary CLI. Arguments are converted with the binary's existing lossy UTF-8 rule.run_cliruns only the ordinary CLI on the arguments after argv0; it performs no helper or proxy argv0 dispatch.apply_seccompapplies the Linux seccomp filter and returns the workload status. On other platforms it printsapply-seccomp: only supported on Linuxand returns 1.VERSIONandOutput(code,stdout,stderr) are public.
The library does not redirect, close, or capture standard streams or inherited descriptors.
run_os buffers stdout/stderr for the ordinary CLI paths; the seccomp helper and the Windows
multicall write to the inherited descriptors directly, because they run or isolate the workload
before returning. CLIs that need the original descriptor topology, such as the proxy's CA and
decider descriptors, must inherit them exactly as they would from the binary.
peri-sandbox uses this entry point to dispatch internal SRT, Workspace, and a verbatim
--srt-apply-seccomp before initializing Tokio for service mode. Embedders can stay synchronous on
execution-only paths; run_os starts no runtime itself.
This port does not provide a Node library API; use the CLI or srt proxy. Embedding that relies on
the Windows multicall helper is UNVERIFIED, like the rest of the Windows runtime behavior.
Configuration
Settings File Location
The default settings file is ~/.srt-settings.json. Select another file with --settings or -s:
srt -s /path/to/srt-settings.json -c 'git status'
The format follows the upstream v0.0.83 JSON settings model. The tables and notes below retain the upstream policy vocabulary while identifying features not wired into this port. Unknown or unsupported security-relevant options must not be interpreted as effective restrictions.
JSON cannot represent functions such as network.filterRequest. The upstream CLI cannot load
executable callbacks from JSON; this port likewise does not evaluate strings as functions. Its CLI
rejects unsupported fields such as filterRequest before schema normalization. Other unknown nested
fields may be stripped by the schema, not implemented. Use srt proxy and its external decider for
request-level policy instead of trying to encode a callback in JSON.
Complete Configuration Example
This example combines ordinary macOS/Linux settings, not every optional field. The Docker socket entry is deliberately powerful: remove it unless the workload genuinely requires host Docker access.
{
"network": {
"allowedDomains": [
"github.com",
"*.github.com",
"lfs.github.com",
"api.github.com",
"npmjs.org",
"*.npmjs.org"
],
"deniedDomains": ["malicious.com"],
"allowUnixSockets": ["/var/run/docker.sock"],
"allowLocalBinding": false
},
"filesystem": {
"denyRead": ["~/.ssh"],
"allowRead": [],
"allowWrite": [".", "src/", "test/", "/tmp"],
"denyWrite": [".env", "config/production.json"]
},
"ignoreViolations": {
"*": ["/usr/bin", "/System"],
"git push": ["/usr/bin/nc"],
"cargo test": ["/private/tmp"]
},
"enableWeakerNestedSandbox": false,
"allowNestedUserNamespaces": false,
"enableWeakerNetworkIsolation": false,
"allowAppleEvents": false
}
On Linux, allowUnixSockets cannot selectively allow that socket; the seccomp filter is all-or-nothing.
Merely copying the example does not enable Docker access there. None of these configurations
establishes a supported Windows runtime setup.
Configuration Options
Network Configuration
The network policy is allow-only: destinations are denied unless allowed, and an explicit deny wins.
| Field | Meaning |
|---|---|
network.allowedDomains |
Required array of domains or IP literals; supports *.example.com and optional :port |
network.deniedDomains |
Required array checked first; supports the same port syntax and deny-all * or *:22 |
network.deniedDomainReasons |
Optional map from an exact deny entry to a user-facing explanation |
network.deniedResolvedAddresses |
Additional unbracketed IPv4/IPv6 addresses or CIDRs denied for hostname resolutions |
network.strictAllowlist |
Optional upstream-compatible policy flag; not a substitute for explicit destination lists |
network.allowLocalBinding |
Default false; platform-dependent local bind/accept permission, described below |
network.allowUnixSockets |
macOS socket-path allowlist; not a Linux per-path exception |
network.allowAllUnixSockets |
Default false; permits unrestricted Unix socket creation/access as the backend allows |
network.allowMachLookup |
macOS Mach service names, optionally with a trailing * prefix match |
network.httpProxyPort |
Existing host HTTP proxy port; pair with socksProxyPort to select external endpoints |
network.socksProxyPort |
Existing host SOCKS proxy port; external endpoints own their filtering policy |
network.tlsTerminate |
Optional object enabling in-process TLS termination for the local proxy |
network.refuseOpaqueTunnels |
Refuse opaque CONNECT and SOCKS tunnels; HTTPS then needs TLS termination |
network.requireHostMatch |
Require consistent request authority, Host header, and TLS server name |
A domain without :port matches every destination port. For example, github.com permits port 22 as
well as 443; github.com:443 does not. IPv6 literals must be bracketed in domain lists: [::1] or
[2001:db8::1]:443. An unbracketed multi-colon entry is ambiguous and rejected. CIDRs in
deniedResolvedAddresses, in contrast, are unbracketed.
Denial reasons are explanatory text, not policy. Put the sanctioned alternative first and keep them short, especially for SSH clients that truncate disconnect descriptions. The proxy sanitizes text used in violation lines and HTTP status phrases; clients differ in how much they show. A no-auth SOCKS connection to an SSH destination can receive a pre-key-exchange denial explanation. Do not put credentials in reasons.
Local binding: on macOS this port permits bind and inbound operations when allowLocalBinding
is true, but keeps outbound IP access limited to proxy ports. Unlike upstream, it does not open
arbitrary localhost outbound connections. On Linux the separate network namespace has its own
loopback; this option does not expose host loopback services. Windows loopback mode belongs to the
unverified WFP/helper path, not a verified port guarantee.
Resolved-address check: before dialing an allowed hostname, the local proxy resolves it, removes denied addresses, and dials a surviving address without a second DNS lookup. If no address survives, HTTP/CONNECT is refused with 403 and SOCKS reports a policy denial. The recorded reason identifies the address class without exposing a resolved address as normal user-facing output.
The denied set includes:
- Loopback (
127.0.0.0/8,::1) and unspecified (0.0.0.0/8,::). - Link-local (
169.254.0.0/16,fe80::/10), multicast, and broadcast. - Cloud metadata/platform endpoints outside those ranges:
100.100.100.200,168.63.129.16,192.0.0.192,fd00:ec2::/32,fd20:ce::254,fd00:c1::a9fe:a9fe, andfd00:42::42. - Addresses assigned to the host's network interfaces.
- IP literals in
deniedDomains, including their port restrictions, and extra ranges indeniedResolvedAddresses.
Embedded IPv4 forms, including IPv4-mapped/compatible/translated IPv6, well-known NAT64 64:ff9b::/96,
and 6to4, are checked against the embedded IPv4 policy. Local-use or network-specific NAT64 prefixes
cannot be inferred from their address alone; list their relevant translated ranges explicitly.
A host's public NAT address, router port-forward, or VM/container gateway alias may reach the host without being assigned to an interface. Such addresses are not automatically discovered; deny them explicitly if needed.
Allowlisting an IP literal is an explicit exception to automatic address classes, unless an explicit deny still applies. A hostname can use that exception when its resolved address and port are themselves allowlisted. For a local development name, use both entries deliberately:
{
"network": {
"allowedDomains": ["myapp.test", "127.0.0.1:3000"],
"deniedDomains": []
},
"filesystem": {
"denyRead": [],
"allowWrite": [],
"denyWrite": []
}
}
localhost and names below .localhost must resolve to loopback or an explicitly allowed literal.
Private-use address space is not denied by default, since intranet destinations may be legitimate.
To exclude it, add ranges such as these to network.deniedResolvedAddresses:
[
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"100.64.0.0/10",
"fc00::/7"
]
List IPv4 and IPv6 ranges separately. External proxy endpoints are not subject to the local proxy's destination checks: their operator must enforce an equivalent policy.
TLS termination is optional and experimental. It lets the local proxy inspect decrypted HTTP requests and apply built-in credential hooks. There is no JavaScript runtime requirement. The child receives a public trust bundle, while CA private material is protected from sandbox reads.
network.tlsTerminate field |
Meaning |
|---|---|
caCertPath, caKeyPath |
PEM CA certificate and key; supply both or neither for an ephemeral CA |
caKeyDir |
私钥专用绝对目录;0700、当前 euid 所有,不能与 cert/key 路径同时配置;见下方 Supervisor-supplied secrets |
excludeDomains |
Allowed destinations whose CONNECT traffic remains opaque |
extraCaCertPaths |
Additional PEM roots appended to the child's public trust bundle |
maxTunnels |
Concurrent termination limit, integer 1–65536, default 256 |
handshakeTimeoutMs |
CONNECT handshake deadline, integer 100–600000 ms, default 10000 |
Excluded hosts remain subject to domain policy, but their TLS handshake is between the child and
upstream. Credential injection and request inspection do not apply. Use exclusions for mTLS services
and clients pinning the real server certificate. With refuseOpaqueTunnels, an exclusion cannot be
used to obtain an opaque tunnel.
The trust environment variables replace tools' usual CA-file settings, so include site-local roots
needed by excluded services too. Extra files that are missing, unreadable, or contain no PEM
certificate are skipped. Only CERTIFICATE blocks are copied, not private keys from a combined PEM.
{
"network": {
"allowedDomains": ["*.example.com", "internal-mtls.example.net"],
"deniedDomains": [],
"tlsTerminate": {
"excludeDomains": ["internal-mtls.example.net"],
"extraCaCertPaths": ["/etc/internal-mtls-roots.pem"]
}
},
"filesystem": {
"denyRead": [],
"allowWrite": [],
"denyWrite": []
}
}
At the tunnel cap, CONNECT receives 503 with X-Proxy-Error: too-many-tunnels. The slot is reserved
before reading the initial payload, so even a connection that turns out not to carry TLS can encounter
the cap. Excluded tunnels do not consume a termination slot. See TLS Termination
for idle/progress deadlines. All TLS options are fixed at startup in this port; the control channel
rejects changes to the object.
Request filtering and rewriting compatibility: these upstream options are retained as a compatibility reference, not as accepted Rust sandbox CLI settings:
| Upstream field or hook | Port boundary |
|---|---|
network.filterRequest |
Function-valued upstream library hook; rejected by this CLI |
network.allowPlaintextHeaderSet |
Rejected as a settings key; standalone proxy has --plaintext-header-set |
network.stripResponseHeaders |
Rejected as a settings key; standalone proxy has --strip-response-header |
network.ambiguousRequestTarget |
Rejected as a settings key; standalone protocol exposes its request-target policy |
network.parentProxy |
Not supported; a parent-proxy environment is also rejected when starting local proxies |
network.mitmProxy |
External MITM socket routing is not supported |
Upstream request decisions can allow/deny, choose a denial status, remove/set headers, and observe a response. These callbacks are not JSON settings. The standalone decider protocol supports its documented verdicts and header edits; it is not every upstream callback hook.
Preserve these request-policy considerations when writing a decider:
- Plain HTTP header injection can disclose credentials in cleartext. It is disabled unless explicitly enabled; removing headers is different from adding secrets.
- Response-header stripping is case-insensitive and folds
-,_, and.. - An opaque CONNECT or SOCKS tunnel cannot be inspected as HTTP.
- Host, absolute-form authority, and TLS server name can disagree. Use consistency checks rather than trusting only one spelling.
- Raw request-target spelling and normalized paths can identify different resources on different upstreams. The upstream modes are
refuse,asSpelled, andnormalize; normalization can invalidate signatures or change object-store keys. A parsed URL does not preserve spelling. - Fragments are not request targets;
%23is data. Malformed target forms, invalid encodings, and malformed headers are not safe policy inputs. - TRACE/TRACK can echo injected headers. The standalone request path rejects them rather than allowing a credential to be reflected to the client.
See the decider protocol for exact fields, accepted modes, and refusal codes, rather than configuring unsupported options in a sandbox settings file.
Unix socket settings:
| Setting | macOS | Linux |
|---|---|---|
allowUnixSockets: string[] |
Allowlist of socket paths | Ignored as a per-path exception |
allowAllUnixSockets: boolean |
Allow all Unix sockets | Disable Unix socket seccomp blocking |
Unix socket creation/access is restricted by default on supported Unix targets. Linux seccomp cannot distinguish paths. Disabling it is a broad IPC permission, not permission for just one socket. Unsupported architectures and external helpers require separate review; the built-in helper supports Linux x86_64 and arm64.
Filesystem Configuration
| Field | Meaning and precedence |
|---|---|
filesystem.denyRead |
Required list of read-denied paths; empty means unrestricted ordinary reads |
filesystem.allowRead |
Optional readable carve-outs within denied regions |
filesystem.allowWrite |
Required writable roots, in addition to built-in paths |
filesystem.denyWrite |
Required write exceptions; take precedence over writable roots |
filesystem.disabled |
Disable ordinary filesystem policy; does not remove credential/CA protection |
filesystem.allowGitConfig |
Opt out of selected automatic Git-config protections; does not grant writes itself |
Reads use a deny-then-allow pattern; writes use an allow-only pattern. This opposite precedence allows readable workspace islands within a denied home and protected files within a writable workspace. Making a directory writable does not make it readable through a mask.
A few paths are writable without appearing in allowWrite: the child's stdio, /tmp/claude, and the
convenience paths ~/.npm/_logs and ~/.claude/debug. The home-directory conveniences are removed
when a read deny covers them, unless an applicable read carve-out reopens them. List a path explicitly
if the workload requires it under a home read-deny.
Path syntax on macOS: git-style glob patterns are supported.
| Pattern | Meaning | Example |
|---|---|---|
* |
Characters other than / |
*.rs |
** |
Characters including / |
src/**/*.rs |
? |
One character other than / |
file?.txt |
[abc], [0-9] |
A character set or range | file[0-9].txt |
A * or ? inside a character set is a set member. Brackets that do not form a valid set, such as a
backwards range or empty set, remain literal text; the rest of the entry may still be a pattern.
Examples:
"allowWrite": ["src/"]allows writes undersrc/."allowWrite": ["src/**/*.rs"]allows matching Rust files on macOS."denyRead": ["~/.ssh"]denies access to the SSH directory."denyRead": ["/Users"], "allowRead": ["."]reopens the workspace."denyWrite": [".env"]protects that file inside an allowed write root.
Path syntax on Linux: bubblewrap binds concrete paths. The upstream implementation expands some read globs at wrap time; this port does not implement general deny-glob expansion. A deny pattern requiring it is a startup error, including a credential deny glob, rather than a silently unenforced deny. Prefer literal paths for security policy.
- A trailing
/**on an ordinary string is removed before Linux path handling, sosrc/**can designate the concrete directorysrc. - Allow patterns do not grant arbitrary future matching paths. Existing literal readings may be used, while unsupported pattern readings grant nothing.
SRT_DEBUGreports skipped write paths. - Missing
denyReadpaths hide nothing for that invocation. Protect an existing parent if files may appear after startup. - Missing write-denied paths under writable roots may need temporary placeholders; see Filesystem Isolation.
- A read-denied directory is hidden with an empty tmpfs. The empty view can be writable without exposing or modifying the hidden host directory.
- Read carve-outs are restored only when compatible with masks. The backend rejects cases it cannot safely represent, including some symlinked denies, rather than claiming complete upstream parity.
/proc,/dev, and/syshave kernel-specific treatment; a root read deny does not remove every facility needed to start a process.
Examples using concrete Linux paths:
"allowWrite": ["src/"]allows that existing directory."denyRead": ["/home/user/.ssh"]hides the SSH directory."denyRead": ["/home"], "allowRead": ["."]reopens the workspace.- Use
"denyRead": ["build"]for a known directory rather than relying on recursive discovery of every futurebuilddirectory.
Shared path rules and literal names:
- Absolute paths and paths relative to the working directory are accepted.
~expands to home. - A deny glob ending in a separator is rejected: write
/data/*, or use a complete**segment where that platform supports the intended pattern. - Names can contain glob metacharacters. On Unix an existing directory such as
/work/[WIP] projectmay be interpreted as both a name and a pattern. A deny covers each applicable reading; an allow must not assume a pattern is a literal-only permission. - Existence is inspected when constructing the sandbox. A path created afterwards does not retroactively rebuild the profile or mount plan.
- Symlinks and missing/uninspectable entries complicate those readings. The Rust path utilities preserve conservative interpretations where implemented; Linux refuses unsupported deny cases.
- To name a path unambiguously, use
{ "path": "/work/*.env", "literal": true }instead of a string.~and relative-path handling still apply, but glob characters, including trailing/**, belong to the name. - The four filesystem lists accept literal objects;
credentials.filesdoes not. Objects without"literal": trueor with extra keys are rejected. - Windows has additional path restrictions and no general glob expansion in this port. Do not infer Windows behavior from Unix examples.
The upstream's exhaustive read-glob traversal, unreadable-tree handling, pattern-warning API, and
function-valued configuration are not extra CLI features. Rust definitions live in srt-core's
path_entries and config modules, with enforcement in srt-platform.
Other Configuration
| Field | Meaning / port status |
|---|---|
ignoreViolations |
Map command patterns to paths/text to suppress in violation reporting; grants no access |
enableWeakerNestedSandbox |
Default false; weaker Linux setup for constrained nested/container environments |
allowNestedUserNamespaces |
Default false; allow nested user namespaces at the cost of mount-policy strength |
enableWeakerNetworkIsolation |
Default false; macOS access to com.apple.trustd.agent |
allowPty |
Default false; macOS pseudo-terminal access |
allowAppleEvents |
Default false; macOS Apple Events and Launch Services access |
bwrapPath, socatPath |
Linux executable-path overrides |
seccomp.applyPath, seccomp.argv0 |
Linux helper override and optional multicall dispatch |
ripgrep.command, ripgrep.args, ripgrep.argv0 |
Deny-scan executable and invocation customization |
mandatoryDenySearchDepth |
Linux mandatory-deny scan depth, default 3, range 1–10 |
git.safeDirectories |
Upstream Git safe-directory injection; non-empty lists are rejected in this port |
javaAgentJarPath |
Upstream JVM proxy-agent override; rejected by this port |
credentials |
Secret withholding/substitution settings, with the limitations below |
enableWeakerNestedSandbox is not a harmless compatibility flag. It reduces isolation on Linux and
should only be used with an independent boundary appropriate to the workload.
allowNestedUserNamespaces is useful for programs that sandbox themselves, but must come from trusted
policy. Its cost also applies when other settings jointly disable namespace restrictions; review the
dependency notes above.
enableWeakerNetworkIsolation allows a macOS trust service used by some Go TLS clients. It opens an
additional host-service channel and potential data exfiltration route. Do not enable it as a blanket
TLS fix.
allowPty grants pseudo-terminal operations and access to /dev/ptmx and /dev/ttys* on macOS.
It does not apply on Linux or Windows.
allowAppleEvents permits requests used by open, osascript, and URL/app launchers. This removes
code-execution isolation: launched applications can run outside the sandbox. TCC may mediate automation
of existing apps, but does not make arbitrary application launching safe. Source this option only from
trusted user/administrator policy, never from untrusted project settings.
For seccomp overrides, a missing applyPath falls back to the built-in entry point. argv0 requires
applyPath; a custom helper must implement the expected invocation contract and security behavior.
Existing but unusable helpers fail rather than silently turning filtering off.
The upstream JVM agent is not packaged or injected by this port. JAVA_TOOL_OPTIONS is preserved with
the backend's IPv4 preference, not augmented with a proxy-authentication agent. JVM tools that ignore
proxy environment variables need their own compatible configuration and may otherwise fail to connect.
Credentials: credentials.envVars and credentials.files describe values the child must not see
in their real form. mode: "deny" withholds them; mode: "mask" uses sentinels and permits host-restricted
egress substitution by the local proxy. Default injection hosts derive from network.allowedDomains;
set injectHosts deliberately for sensitive data.
Masking requires TLS termination unless credentials.allowPlaintextInject explicitly permits cleartext
disclosure. Environment masking and proxy substitution are implemented. The current platform wiring
denies masked files instead of mounting sentinel file contents, including on Linux; do not assume the
upstream Linux file-mask workflow is available.
Extraction/JWT options include extract, onExtractNoMatch, decode, and maskClaims; file entries
also have maskDuplicates. AWS settings include awsPairs and the sigv4 policies for streaming,
presigned, and SigV4a requests. These specialized features do not guarantee that any secret-bearing
protocol can be rewritten safely. Keep values in protected environment variables/files, not embedded
in examples or committed settings. Windows credential integration is not connected.
Supervisor-supplied secrets
macOS/Linux 的 srt run(默认 CLI 模式)支持独立于静态 envVars/files 的一次性秘密通道。settings 只声明 id、目标和 fd,真实值由可信 supervisor 经专用继承 fd 传入,不从环境变量读取,也不进入子进程环境、argv 或 settings。
| 配置 | 含义 |
|---|---|
credentials.source |
strict 对象:fd 为 ≥3 的整数;timeoutMs 默认 5000,范围 1–600000;不能等于 --control-fd |
credentials.entries |
1–64 个 strict entry:唯一 id、mode: inject|mask、必填 sendAs;mask 必填 envVar,inject 禁止 envVar |
credentials.entries[].sendAs |
strict 对象:合法且非 routing/hop-by-hop 的 header,可选 template(默认 {{value}});只允许可见 ASCII,恰好一个 {{value}},渲染后 ≤8192 字节 |
credentials.hosts |
规范化小写精确 hostname/IP → {entries: [id, ...], responseGuard?: "buffer-or-502"|"stream"};无端口、通配符;每个 host/header 唯一 |
{
"network": {
"allowedDomains": ["api.example.com"], "deniedDomains": [],
"tlsTerminate": {"caKeyDir": "/run/srt-ca"}
},
"filesystem": {"denyRead": [], "allowWrite": [], "denyWrite": []},
"credentials": {
"source": {"fd": 4, "timeoutMs": 5000},
"entries": [{"id": "broker-token", "mode": "mask", "envVar": "UPSTREAM_TOKEN",
"sendAs": {"header": "Authorization", "template": "Bearer {{value}}"}}],
"hosts": {"api.example.com": {"entries": ["broker-token"]}}
}
}
帧 v1:所有整数为大端,u32 L(1..=1 MiB,后续 payload 长度)+ SRTS1\n + u16 count(1..=64),随后每项为 u16 id_len + id ASCII + u32 value_len + value。id 匹配 ^[A-Za-z][A-Za-z0-9._-]{0,63}$;值必须非空、≤65535 字节且全部位于 0x20..=0x7E。所有声明必须恰好出现一次,未知、缺失、重复、空值、非法值、截断、超时或尾随字节均启动失败,错误只含 id/fd/偏移/固定原因,不含值。supervisor 应写完一帧并关闭写端。srt 在创建 CA、临时目录或 socket 前设置 FD_CLOEXEC,读取后直接关闭原 fd(无论成功失败,不 dup);此所有权约定不同于 control fd。
三个 source 配置键必须同时出现;必须开启本地 TLS 终止和文件系统隔离。allowPlaintextInject 不能豁免,外部代理端口、显式 refuseOpaqueTunnels:false、AWS pairs(含隐式 AWS mask pair)、sigv4、Windows 均拒绝。source 隐式拒绝 opaque CONNECT 和 SOCKS tunnel。host 必须被 allowedDomains 覆盖且不被 excludeDomains 覆盖,所有 entry 至少被一个 host 引用。source entry 不接受静态 extraction/JWT 字段;静态 credentials 仍可并存,envVar 名不能冲突。
只在 TLS 终止且上游证书验证成功后注入,目标取 CONNECT authority,而不是客户端 Host。静态替换之后,删除目标 header 的全部客户端值,再写入恰好一个模板值;不会替换任意 header、路径、query 或 body。mask 的 fake 只提供给子进程,不参与静态替换。建议同时启用 requireHostMatch。到 credential host 的明文请求在拨号前返回 403 credential_requires_tls。
默认响应守卫仅对 guarded host 删除请求 Accept-Encoding、Range 和 If-Range(其它无关头保留),先发送请求体,再在 60 秒总预算内缓冲响应;只接受 identity encoding、无 trailer、解码后正文 ≤16 MiB。扫描将转发的头与解码正文中的字面秘密(source + 同 host 静态 masked 值),包括跨 chunk 的子串。上游即使仍返回 206 Partial Content 或任何 Content-Range,也一律视为不可判定;与回显、压缩、超时、超限、101 或无法证明安全的 framing 一样,返回固定 502,X-Proxy-Error: response_guard_blocked,记录脱敏 deny response-guard,不透传部分响应。HEAD/204/304 也拒绝上述部分响应标记,其余只扫描头。守卫只证明单响应内的字面字节;Range 分片被拒绝,非 Range 的跨响应拆分不在证明范围。responseGuard: "stream" 是显式退出响应守卫的开关,工作负载可能收到秘密回显。
caKeyDir 必须是当前 euid 所有的 0700 非符号链接绝对目录(不存在则创建);拒绝 /、TMPDIR、/tmp、/var/tmp、/dev/shm 的重叠路径、cwd/home 的祖先及 allowWrite 重叠根。每次运行在其下创建 0700 srt-ca-run-* 和 0600 ca.key;公开证书和 trust bundle 留在临时目录。也可显式配置 caCertPath+caKeyPath,私钥父目录须通过相同预检,私钥须为 euid 所有、0600/0400。沙箱强制拒绝该目录读写;正常退出删除运行子目录,保留父目录。崩溃残留由 supervisor 清理;磁盘不保证擦除,可选独立挂载、非上述临时根路径的 tmpfs。
安全边界:Secret 无 Debug/Clone,帧与渲染缓冲尽力零化,日志/违规双重脱敏;不承诺清除内核 socket 缓冲、swap、core dump,或抵御宿主同 uid 的 ptrace/进程内存读取。守卫只证明单响应内 identity 字面字节不回显;Range 请求头被删除,206/Content-Range 被拒绝,其它跨响应拆分、JSON 转义、base64、URL 编码或上游主动变换不在证明范围;它不是通用 DLP,stream 为显式退出开关。
Common Configuration Recipes
Allow GitHub access at the upstream recipe's usual endpoints:
{
"network": {
"allowedDomains": [
"github.com",
"*.github.com",
"lfs.github.com",
"api.github.com"
],
"deniedDomains": []
},
"filesystem": {
"denyRead": [],
"allowWrite": ["."],
"denyWrite": []
}
}
This is broad domain permission, not permission only for one repository. Narrow it with ports and destinations when possible.
Restrict to specific directories:
{
"network": {
"allowedDomains": [],
"deniedDomains": []
},
"filesystem": {
"denyRead": ["~/.ssh"],
"allowWrite": [".", "src/", "test/"],
"denyWrite": [".env", "secrets/"]
}
}
secrets/ here is a literal directory write deny, not a read deny. Add it to denyRead if its
contents must not be visible.
Workspace-only home-directory access:
{
"network": {
"allowedDomains": [],
"deniedDomains": []
},
"filesystem": {
"denyRead": ["/Users"],
"allowRead": ["."],
"allowWrite": ["."],
"denyWrite": []
}
}
This denies the macOS /Users tree, then re-allows the working directory. Use /home for a typical
Linux home tree. System locations such as /usr and /lib remain readable; this is not a complete
filesystem allowlist.
Common Issues and Tips
Running Jest: disable Watchman if its external service causes sandbox violations:
srt -c 'jest --no-watchman'
Watchman can access resources outside the intended boundary. Disabling it lets Jest use its built-in watcher; it does not require disabling filesystem or network restrictions.
Exit status and shells: upstream had a historical Linux/zsh cleanup trap issue that could hide
command failures. The Rust CLI uses its own execution/status handling and currently selects bash;
do not assume an upstream binShell library option is a supported CLI setting. Check the command's
status when diagnosing failures.
Configuration validation: upstream's zod-version advice concerned its library dependency tree.
This executable validates JSON in srt-core and has no zod dependency to select. A schema-compatible
field may still be rejected by the CLI's capability guard.
Proxy environment: inherited HTTP_PROXY/HTTPS_PROXY is not a supported parent proxy for the
local-proxy path. Remove it intentionally for that invocation or use a separately managed architecture;
do not assume automatic proxy chaining.
Linux patterns: replace unsupported deny globs with concrete directories or literal objects. Do not remove a failed deny merely to start a command without reconsidering the resulting access.
Windows (x64)
The Windows x64 artifact builds, but runtime behavior is UNVERIFIED. No live guarantee is made for installation, UAC, WFP, ACLs, profile access, logon, cleanup, or execution.
Implemented scaffolding includes windows-install / windows-uninstall command routing, helper
resolution/status checks, and structured exec argument/environment orchestration in srt and
srt-platform. This is not the complete upstream Windows sandbox integration.
Important boundaries:
- Local proxy startup, MITM/TLS termination, and credentials are not connected to the Windows path.
- Session filesystem grant/ranking is incomplete; non-empty
allowReadorallowWritelists are refused rather than represented as effective grants. - Execution requires both externally enforced proxy ports. Passing ports does not prove that the external proxy or WFP boundary is secure.
--control-fd, Unix-specific options, and several session options are unsupported.- The experimental upstream MXC backend is not supported. Selecting it fails rather than falling back to another backend.
The upstream account/WFP/token/ACL design is context, not a supported setup guide for this port. Consult the Windows platform module, Windows execution routing, and the upstream v0.0.83 design for precise contracts. Do not infer runtime support from cross-compilation or argument-dispatch tests.
Development
Use the pinned Rust toolchain from the repository root:
cargo build -p srt --release --locked
cargo test --workspace --locked
cargo fmt --check
cargo clippy --workspace --all-targets --locked -- -D warnings
Or use the repository tasks:
mise run build
mise run test
mise run lint
mise run lint checks formatting then runs Clippy. Linux seccomp filters and the hidden helper entry
point are part of the Rust build; no separate seccomp-binary build workflow is needed.
Golden configuration, CLI, rule, and JSON-boundary inputs are documented in testdata/README.md. They are static test inputs, not runtime logs or proof that every platform was exercised. Reading them and running Rust tests needs no JavaScript runtime. Baseline regeneration is a separate upstream-comparison operation documented there.
Platform integration tests require the actual OS facilities and dependencies. Parsing, golden-vector, and cross-build checks do not establish that Seatbelt, namespaces, seccomp, or Windows security mechanisms worked on another host. The Linux seccomp regression probe also uses Python 3 as documented with the test corpus.
Implementation Details
Network Isolation Architecture
The local srt-proxy implementation filters HTTP/HTTPS and SOCKS5 TCP connections using
network.allowedDomains, deniedDomains, and the resolved-address policy. It is not a general
packet inspector.
- HTTP requests are checked against their destination and forwarded after policy accepts them.
- HTTPS CONNECT is either an opaque permitted tunnel or, with TLS termination, a locally terminated HTTP connection.
- SOCKS5 carries other proxy-aware TCP clients and is refused when opaque tunnels are prohibited.
- macOS Seatbelt or the Linux network namespace prevents ordinary direct internet connections outside those proxy paths.
On Linux, the bridge exposes host proxies through Unix
sockets and socat relays. Workload loopback listeners are inside its network namespace, not general
access to host localhost. On macOS, the profile permits the
chosen proxy ports explicitly.
Proxy environment variables help cooperative tools find these endpoints. They are routing hints,
not the boundary itself. A tool ignoring them can fail even when its destination is allowed. Existing
external HTTP/SOCKS ports select externally managed filtering; local allowlists and credential hooks
cannot enforce traffic handled by somebody else's proxy. parentProxy and mitmProxy forwarding
modes are not implemented here.
Git-over-SSH needs a proxy command because SSH does not read HTTP proxy variables. The shared
environment generation supplies platform-specific proxy-command settings; SSH keys and agent access
remain independent filesystem and Unix-socket permissions. An arbitrary ssh invocation is not made
proxy-aware merely by allowing a domain. Broad SSH or agent access deserves separate review.
The upstream JVM proxy-authentication agent is not included. Upstream Windows-specific application environment advice likewise does not establish complete Windows proxy integration in this port.
TLS Termination
TLS termination lives in srt-proxy's MITM module and
HTTP handling. For an allowed, non-excluded CONNECT, the proxy accepts
the tunnel and examines the initial bytes.
A TLS ClientHello is handled on that same stream. The proxy creates a leaf certificate for the selected name and forwards decrypted HTTP over a separate, certificate-verified upstream TLS connection. Plaintext and real injected credentials remain in the proxy process and leave it only over verified TLS unless plaintext injection was explicitly enabled. There is no per-tunnel listening port or named socket exposing the decrypted stream.
The selected name comes from the ClientHello where usable, falling back to the CONNECT target. With requireHostMatch, the CONNECT target controls the leaf identity and mismatched requests are refused. Conflicting HTTP authorities do not become alternate destinations merely because a client completed a handshake.
A non-TLS initial payload remains opaque unless refuseOpaqueTunnels requires refusal. Excluded hosts are also opaque, without inspection or credential rewriting. Pinning and mTLS can therefore require explicit exclusions or a different trust architecture.
Resource controls include:
maxTunnelsreserves a slot before handshake processing.handshakeTimeoutMsbounds CONNECT-to-handshake time, including clients that send nothing.- The first request after a handshake has an idle deadline of 10 seconds.
- After a response, idle tunnels close after 6 seconds; keep-alive responses advertise 5 seconds.
- Active transfers have progress-based timeouts rather than a fixed total upload duration.
- Streaming/backpressure budgets limit buffering for slow clients and upstreams. Exact standalone limits are specified in the proxy document.
These controls are Rust code, including the watchdog and buffer budgets; historical Node/Bun parser/buffering differences are not runtime requirements. A valid TLS handshake still does not make an allowed endpoint trustworthy.
Filesystem Isolation
macOS uses generated Seatbelt rules; Linux uses read-only/read-write binds, tmpfs masks, and explicit carve-outs. Windows session filesystem integration is incomplete, not an equivalent enforcement path.
Defaults and precedence: reads are allowed unless denied; writes are denied except for built-in and configured roots. Read carve-outs reopen broader denied regions, with specific inner denies protected. Write denies win even if an allowed root is at or below them. filesystem.disabled removes ordinary policy, not credential/CA read protection imposed separately.
Links: a symbolic-link write is judged at its destination. A symlink in a writable tree does not grant writes to an otherwise unwritable location. Existing hard links need more care: a second name can expose the same underlying file inside an allowed tree. Name-based policy is not a universal guarantee for aliased host files. Linux rejects some deny/carve-out cases it cannot safely mount.
Linux read masks: a hidden host directory becomes an empty tmpfs view. Writes there do not modify the hidden directory. Carve-outs must not undo overlapping masks or expose denied targets through a second spelling. Missing literal read denies apply to nothing for that invocation; unsupported deny globs cause an error.
Write denies for missing paths: bubblewrap needs mount destinations. The Rust planner may create empty placeholders for missing protected files or intermediate directories under writable roots. Host tools can see them during execution; paths whose existence is meaningful, such as lockfiles, can therefore affect host behavior.
The mount plan tracks its own empty placeholders for cleanup. A killed/crashed supervisor can leave them behind. Do not blindly remove files after a crash: distinguish legitimate host data and another active sandbox's resources. Ownership, read-only filesystems, immutable paths, and concurrent host changes affect whether a deny is representable. Unsafe cases may fail startup rather than reproduce every upstream fallback, including its WSL-specific behavior.
Large Linux profiles: an unnamed O_TMPFILE argument file carries mounts that are too large inline. The executor tries /tmp and /dev/shm and refuses if neither can supply the unnamed file; it does not use a replaceable named fallback. The supervisor holds the descriptor until completion, and the sandbox's PID namespace prevents access to the supervisor through its /proc.
The planner checks bubblewrap's 9000-argument limit, command length, and NUL-containing paths. Mandatory denies can reach the limit even with short explicit settings. Reducing scan depth reduces protection, not just argument count. See mount planning, profile errors, and execution for actual port behavior.
Mandatory Deny Paths (Auto-Protected Files)
With ordinary filesystem isolation enabled, sensitive startup/project configuration receives automatic write protection even inside allowed roots. This is defense in depth, not a complete list of files that another program might execute or trust.
Protected files include:
- Shell startup files:
.bashrc,.bash_profile,.zshrc,.zprofile,.profile. - Git configuration:
.gitconfig,.gitmodules. - Other tool configuration:
.ripgreprc,.mcp.json.
Protected directory/configuration locations include:
.vscode/,.idea/..claude/commands/,.claude/agents/.- Repository
.git/hooks/and.git/config, with platform-specific treatment of worktree/submodule.gitfiles.
No explicit denyWrite entry is needed for these automatic protections. For example, attempting to
change a protected startup file should fail under the ordinary policy:
srt -c 'touch .bashrc'
macOS generates path rules. Linux scans with ripgrep without allowing ignore files to hide dangerous
paths, then constructs read-only binds or placeholders. The default depth is 3: dangerous files can
be found through a/b/.bashrc, while protected directories or repository hooks/config have different
effective nesting depth. Empty, missing, or deeper directories are not equivalent to discovered files.
Increase the Linux search depth deliberately:
{
"network": {
"allowedDomains": [],
"deniedDomains": []
},
"mandatoryDenySearchDepth": 5,
"filesystem": {
"denyRead": [],
"allowWrite": ["."],
"denyWrite": []
}
}
The range is 1–10; higher depth increases cost and mount-plan size. Working-directory protections
are not removed by a shallow scan. allowGitConfig relaxes selected Git configuration protection;
do not treat it as an unrelated convenience.
Pinned directories on Linux: ancestors of protected paths within writable roots are mounted to
prevent removing/renaming an ancestor from simply moving a deny aside. Such operations can fail with
EBUSY. With a writable root filesystem, top-level covers can also create EXDEV boundaries for
cross-directory rename/hard-link operations. Ordinary file access inside pinned directories is not
meant to become read-only merely because an ancestor is pinned.
Pins and mandatory denies do not solve every path-mutation case. Retain the shared upstream P0 rename warning in Known Limitations; matching an upstream mount plan does not establish that this issue is absent.
Unix Socket Restrictions (Linux)
The built-in implementation lives in the Linux seccomp module.
It uses a hidden mode of the same srt binary on x86_64 and arm64, not a separately packaged helper.
The execution sequence preserves the upstream two-stage model:
- Outer bubblewrap creates filesystem, network, and PID boundaries.
- Proxy bridges start while Unix sockets are still usable.
- The seccomp entry point creates nested user/PID/mount isolation and a fresh workload
/proc. - A non-dumpable init/reaper supervises the command and forwards signals.
- The workload receives syscall filters before it executes.
The Unix filter refuses socket(AF_UNIX, ...) and blocks io_uring_setup, io_uring_enter, and
io_uring_register, since io_uring socket creation could evade a socket()-only rule. A separate
namespace filter restricts namespace/mount operations unless explicitly weakened.
Nested PID isolation keeps unfiltered bridge processes outside the command's visible process set. Failed setup aborts rather than intentionally running without isolation. Filters do not revoke Unix socket descriptors already inherited or received through descriptor passing. Review inherited resources as well as pathname policy.
allowAllUnixSockets: true removes Unix socket blocking. allowUnixSockets cannot selectively punch
holes by path on Linux. No runtime C compiler or libseccomp development package is needed for the
built-in implementation on supported architectures.
Violation Detection and Monitoring
Proxy denials are recorded by srt-proxy policy state, with command
attribution and sanitized reasons. ignoreViolations suppresses matching report entries; it does not
authorize operations or change OS policy.
OS-denied operations commonly return EPERM or EACCES, but not every blocked operation produces a
proxy violation. This CLI does not provide Claude Code's permission-prompt UI or automatically enable
the upstream macOS log-stream monitor.
For macOS diagnostics, inspect system sandbox logs, for example:
log stream --predicate 'process == "sandbox-exec"' --style syslog
Relevant records/process names depend on the OS and workload. Linux bubblewrap has no complete violation event stream; trace the command to debug policy:
strace -f srt -c 'your-command' 2>&1 | grep EPERM
strace -f -e trace=open,openat,stat,access srt -c 'your-command' 2>&1 | grep EPERM
strace -f -e trace=network srt -c 'your-command' 2>&1 | grep EPERM
Tracing may need host permissions. Logs/traces can contain arguments, paths, and application data; protect and redact them before sharing.
Security model
The intended boundary is the OS sandbox around a command and descendants, plus trusted host-side proxies constraining egress. Configuration, the executable, dependencies, the supervisor, and any decider are trusted inputs. This is not a VM boundary or protection against a compromised kernel, malicious administrator, or unrestricted same-user host processes.
Use both filesystem and network policy. Keep sensitive data unreadable, writes limited to the smallest useful roots, destinations narrow, and local IPC/service permissions deliberate. Settings are security policy, not harmless project preferences.
A standalone srt proxy provides request mediation only. Its host supplies workload isolation, protects descriptors and CA keys, and keeps the unauthenticated listener inaccessible to other clients. See its security model for the separate protocol trust boundary.
Security Limitations
Supervisor secret-source 的证明边界。 新通道只在已验证的 TLS authority 上按显式 header 注入;守卫只证明单响应内的 identity 字面字节,不识别编码或主动变换。guarded host 删除
Range/If-Range并拒绝上游 206/Content-Range,其它跨响应拆分不在证明范围。stream为显式退出守卫的开关,会允许回显。fd 关闭和缓冲零化不等于防御宿主同 uid 的进程内存访问、swap 或 core dump。CA 目录依赖 supervisor 所有权、权限预检和沙箱强制读写拒绝,崩溃残留仍需清理。Domain policy is not content policy. An allowed endpoint can receive readable data unless a separate request policy rejects it. Broad domains, shared hosting, and domain fronting can weaken assumptions about the recipient. Prefer narrow destinations and least-privilege credentials.
DNS and local services need explicit policy. Address checks cover the documented classes, not every private/NAT/gateway route. Literal grants are intentional holes; external proxies own their equivalent checks.
TLS termination is not universal inspection. Excluded/opaque tunnels have no HTTP decisions. Pinning, mTLS, non-HTTP protocols, and client trust stores need separate treatment.
Unix sockets can confer host authority. Docker and other powerful service sockets can negate the intended boundary. Allowing them grants service access, not just transport convenience.
Broad writable paths enable later execution. Tool configuration, executable search paths, startup files, and files consumed outside the sandbox can become persistence/escalation surfaces. Automatic denies are only defense in depth.
Protect the installed binary and helpers. Keep
srt, helpers, and parent directories outside writable roots. A later invocation must not execute a binary an earlier command could replace.Weaker Linux modes reduce mount-policy strength. Nested namespaces and weakened setup flags permit operations blocked by the defaults. Independent isolation must justify their use.
macOS host-service permissions are consequential. Trustd opens an extra channel; Apple Events and Launch Services remove code-execution isolation for launched apps. Never take these permissions from attacker-controlled project settings.
Windows is not a verified security boundary here. Build/dispatch checks do not establish account, WFP, token, or ACL enforcement.
credentials.source/entries/hosts和network.tlsTerminate.caKeyDir的拒绝向量仅经 Windows GNU 交叉 check/测试 no-run 编译;Windows 运行仍为 UNVERIFIED。Inherited resources remain capabilities. Policy does not revoke every descriptor or service handle a caller supplies. Pass only what the workload needs.
Known Limitations
- Shared upstream P0 rename bypass: a known path/rename-related policy bypass is shared with the upstream design. Mandatory denies and pinned ancestors do not eliminate every rename-based failure, and this port does not claim it is fixed. Keep high-value data outside writable trees and use a stronger independent boundary for hostile code; no exploitation procedure is provided.
- macOS
allowLocalBindingis stricter than upstream: it permits bind/accept, not arbitrary direct localhost connections. Workflows expecting upstream loopback-outbound permission may fail. - Linux deny-glob parity is incomplete: general upstream deny expansion and some symlink or uninspectable-path behavior are absent. Unsupported deny patterns fail; missing read denies cannot hide files created later.
- Credential file masks are not mounted as sentinel contents: current wiring denies them. Environment masking and proxy substitution do not imply full file-mask parity.
- Runtime updates are partial: only local-proxy policy state updates. Existing OS restrictions, credentials, TLS options, and connections are not rebuilt or universally revoked by control input.
- Proxy discovery is cooperative: programs ignoring HTTP/SOCKS settings may fail to connect. Transparent UDP routing and automatic low-level proxy interception are not implemented promises.
- Upstream hooks are not CLI features: Node library APIs, callback configuration, JVM-agent injection, external MITM/parent-proxy forwarding, and non-empty Git safe-directory injection are unavailable.
- Windows x64 remains build-only and runtime UNVERIFIED: local proxies, MITM, credentials, and full session filesystem grants are incomplete; MXC is unsupported.
License & attribution
Licensed under the Apache License 2.0. This project derives from Anthropic's sandbox-runtime v0.0.83. See NOTICE for upstream attribution and the Rust-port copyright notices.
関連プロジェクトを探す
読み込み中…