From 9f140040d6d921994957b82f650eb2b404d79f96 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Thu, 22 Oct 2026 17:22:08 +0300 Subject: [PATCH] fix(sandbox): document stdio data-dir/socket exposure, add doctor warning, make /dev/null writable Under isolation none or sandbox a stdio child runs as the proxy's user: it can read the data directory (mcp_config.json with api_key, config.db with OAuth tokens) and, while enable_socket is on, mint agent tokens over the admin socket without a key. Landlock confines writes only, so hiding the files would not close the gap (#1704, verified by the reporter). - docs: state the limit in the sandbox page (new "What the sandbox does not hide" section with the reporter's verification table), the isolation mode tables and honest limitations, the socket page, and the headless install checklist (enable_socket: false + docker isolation). - doctor: config.StdioSocketExposureFinding names every enabled stdio server resolving to none/sandbox while enable_socket is true, with the fix; wired through the existing DoctorFindings runtime_warnings path. - sandbox: the default spec never granted WRITE_FILE on /dev/null, so a confined `sh -c '... 2>/dev/null'`, Node stdio:"ignore" and Python subprocess.DEVNULL failed with EACCES (confirmed on kernel 6.8, Landlock ABI 4). buildSandboxSpec now grants /dev/null read-write and addPathRule masks directory-only rights for non-directory targets, which Landlock otherwise rejects with EINVAL (and the fail-closed wrapper then aborted the whole confinement). - docs: snap-packaged runtimes cannot run under the sandbox (snap-confine needs privileges no_new_privs forbids). Closes #1704 --- docs/docker-isolation.md | 5 +- docs/features/docker-isolation.md | 5 +- docs/features/sandbox-isolation.md | 67 +++++++++++++- docs/getting-started/installation.md | 3 +- docs/socket-communication.md | 1 + internal/config/doctor_findings.go | 50 +++++++++- internal/config/doctor_findings_test.go | 96 ++++++++++++++++++++ internal/sandbox/sandbox_linux.go | 27 +++++- internal/sandbox/sandbox_linux_test.go | 36 ++++++++ internal/upstream/core/sandbox.go | 8 +- internal/upstream/core/sandbox_linux_test.go | 39 ++++++++ internal/upstream/core/sandbox_test.go | 14 +++ 12 files changed, 338 insertions(+), 13 deletions(-) create mode 100644 internal/config/doctor_findings_test.go diff --git a/docs/docker-isolation.md b/docs/docker-isolation.md index 8c7ca7d46..7a092df1f 100644 --- a/docs/docker-isolation.md +++ b/docs/docker-isolation.md @@ -35,8 +35,8 @@ MCPProxy resolves an **isolation mode** for every stdio server. Set it globally | Mode | What it does | Where it works | uid/gid drop | |------|--------------|----------------|--------------| | `docker` | Wraps the server in a Docker container (process/FS/network isolation, resource limits). The default and most capable mode. | Any host with a working Docker daemon. | Yes (container user) | -| `sandbox` | Runs the server **natively** under a Linux [Landlock](https://docs.kernel.org/userspace-api/landlock.html) filesystem allowlist + `setrlimit` resource caps — **no Docker required**. For hosts where Docker isolation is unavailable or broken (e.g. snap-docker + AppArmor). | Linux 5.13+ only (Landlock). Best-effort downgrade across ABI 1–5. macOS/Windows: documented no-op ⇒ behaves like `none`. | **No** — see [Honest limitations](#honest-limitations) | -| `none` | No confinement; the server runs directly on the host. | Everywhere. | n/a | +| `sandbox` | Runs the server **natively** under a Linux [Landlock](https://docs.kernel.org/userspace-api/landlock.html) filesystem allowlist + `setrlimit` resource caps — **no Docker required**. For hosts where Docker isolation is unavailable or broken (e.g. snap-docker + AppArmor). Confines **writes** only: the server still runs as the proxy's user and can read the data directory and use the admin socket (see [Honest limitations](#honest-limitations)). | Linux 5.13+ only (Landlock). Best-effort downgrade across ABI 1–5. macOS/Windows: documented no-op ⇒ behaves like `none`. | **No** — see [Honest limitations](#honest-limitations) | +| `none` | No confinement; the server runs directly on the host as the proxy's user, with the data directory and the admin socket reachable. | Everywhere. | n/a | ```json { @@ -454,6 +454,7 @@ Your options on such a host: - **No uid/gid drop.** Dropping to an unprivileged uid/gid requires `CAP_SETUID`/`CAP_SETGID` (i.e. running as root). When mcpproxy runs unprivileged, the uid/gid drop is **best-effort and typically a no-op** — the sandboxed process keeps the launching user's identity. Landlock (filesystem) and `setrlimit` (resource caps) still apply. Docker mode does drop to a container user. This is an honest trade-off, not a bug. - **Linux-only.** Landlock is a Linux 5.13+ feature. On older kernels the launcher degrades best-effort (fewer access-right bits enforced on ABI 1). On macOS/Windows `sandbox` is a documented **no-op** and behaves like `none`. - **Filesystem + resources only.** Landlock confines the filesystem write-allowlist; it does not provide network namespacing. Pair with care for network-sensitive servers, or use `docker` mode with `network_mode: none`. +- **`none` and `sandbox` do not hide the data directory or the Unix socket.** A stdio server runs as the proxy's user, so it can read `mcp_config.json` (holds `api_key`) and `config.db` (holds the upstream OAuth tokens), and while `enable_socket` is on it can connect to `/mcpproxy.sock` without a key — a sandboxed child minted an agent token over it ([#1704](https://github.com/smart-mcp-proxy/mcpproxy-go/issues/1704)). Landlock does block `/proc//environ`, so the key is safe in the environment but not on disk or over the socket. Set `enable_socket: false` for headless installs and use `docker` isolation for servers you do not trust; `mcpproxy doctor` warns when an enabled stdio server resolves to `none` or `sandbox` with the socket on. Verification table: [What the sandbox does not hide](features/sandbox-isolation.md#what-the-sandbox-does-not-hide). - **Docker-based scanners do not run under `sandbox`/`none`.** They are skipped and the skip is surfaced via the informational `deep_scan` descriptor — it never downgrades the baseline verdict (Spec 077 FR-008). A native scanner runtime is a future enhancement (D3 option a). ## Platform support matrix diff --git a/docs/features/docker-isolation.md b/docs/features/docker-isolation.md index b25db7f24..3e810ead8 100644 --- a/docs/features/docker-isolation.md +++ b/docs/features/docker-isolation.md @@ -32,8 +32,8 @@ MCPProxy resolves an **isolation mode** for every stdio server. Set it globally | Mode | What it does | Where it works | uid/gid drop | |------|--------------|----------------|--------------| | `docker` | Wraps the server in a Docker container (process/FS/network isolation, resource limits). The default and most capable mode. | Any host with a working Docker daemon. | Yes (container user) | -| `sandbox` | Runs the server **natively** under a Linux [Landlock](https://docs.kernel.org/userspace-api/landlock.html) filesystem allowlist + `setrlimit` resource caps — **no Docker required**. For hosts where Docker isolation is unavailable or broken (e.g. snap-docker + AppArmor). | Linux 5.13+ only. macOS/Windows: documented no-op ⇒ behaves like `none`. | **No** — see [Honest limitations](#honest-limitations) | -| `none` | No confinement; the server runs directly on the host. | Everywhere. | n/a | +| `sandbox` | Runs the server **natively** under a Linux [Landlock](https://docs.kernel.org/userspace-api/landlock.html) filesystem allowlist + `setrlimit` resource caps — **no Docker required**. For hosts where Docker isolation is unavailable or broken (e.g. snap-docker + AppArmor). Confines **writes** only: the server still runs as the proxy's user and can read the data directory and use the admin socket (see [Honest limitations](#honest-limitations)). | Linux 5.13+ only. macOS/Windows: documented no-op ⇒ behaves like `none`. | **No** — see [Honest limitations](#honest-limitations) | +| `none` | No confinement; the server runs directly on the host as the proxy's user, with the data directory and the admin socket reachable. | Everywhere. | n/a | ```json { @@ -424,6 +424,7 @@ See [Shutdown Behavior](/operations/shutdown-behavior) for detailed subprocess l - **No uid/gid drop.** Dropping to an unprivileged uid/gid requires `CAP_SETUID`/`CAP_SETGID` (i.e. running as root). When mcpproxy runs unprivileged, the uid/gid drop is **best-effort and typically a no-op** — the sandboxed process keeps the launching user's identity. Landlock (filesystem) and `setrlimit` (resource caps) still apply. Docker mode does drop to a container user. This is an honest trade-off, not a bug. - **Linux-only.** Landlock is a Linux 5.13+ feature. On older kernels the launcher degrades best-effort (fewer access-right bits enforced). On macOS/Windows `sandbox` is a documented **no-op** and behaves like `none`. - **Filesystem + resources only.** Landlock confines the filesystem write-allowlist; it does not provide network namespacing. For network-sensitive servers, use `docker` mode with `network_mode: none`. +- **`none` and `sandbox` do not hide the data directory or the Unix socket.** A stdio server runs as the proxy's user, so it can read `mcp_config.json` (holds `api_key`) and `config.db` (holds the upstream OAuth tokens), and while `enable_socket` is on it can connect to `/mcpproxy.sock` without a key — a sandboxed child minted an agent token over it ([#1704](https://github.com/smart-mcp-proxy/mcpproxy-go/issues/1704)). Landlock does block `/proc//environ`, so the key is safe in the environment but not on disk or over the socket. Set `enable_socket: false` for headless installs and use `docker` isolation for servers you do not trust; `mcpproxy doctor` warns when an enabled stdio server resolves to `none` or `sandbox` with the socket on. Verification table: [What the sandbox does not hide](/features/sandbox-isolation#what-the-sandbox-does-not-hide). - **Docker-based scanners do not run under `sandbox`/`none`.** They are skipped and the skip is surfaced via the informational `deep_scan` descriptor — it never downgrades the baseline verdict (Spec 077 FR-008). A native scanner runtime is a future enhancement. ## Platform support matrix diff --git a/docs/features/sandbox-isolation.md b/docs/features/sandbox-isolation.md index 04fd35115..904ceaa80 100644 --- a/docs/features/sandbox-isolation.md +++ b/docs/features/sandbox-isolation.md @@ -38,8 +38,11 @@ back-compat; `mode` supersedes it (see MCP-34.2). - **Filesystem write allowlist.** Reads stay broad (the runtime can load interpreters, `node_modules`, and `site-packages` from anywhere), but **writes** are denied outside a small allowlist: the server's `working_dir`, the OS temp - dir, and the common package caches (`~/.npm`, `~/.cache`, `~/.local/share`). - Tightening reads is deferred — a read allowlist breaks tool discovery. + dir, `/dev/null`, and the common package caches (`~/.npm`, `~/.cache`, + `~/.local/share`). Tightening reads is deferred — a read allowlist breaks + tool discovery. (`/dev/null` is on the list because the read-only `/` rule + does not let a confined `sh -c '… 2>/dev/null'`, Node's `stdio: "ignore"` + or Python's `subprocess.DEVNULL` open the device for writing.) - **Resource limits.** Core dumps are disabled (`RLIMIT_CORE=0`, so in-memory secrets can't spill to disk) and the descriptor table is capped (`RLIMIT_NOFILE`). @@ -61,6 +64,66 @@ stdin/stdout pass straight through with no intervening multiplexer. the server still starts but runs **unconfined**, and the host log records a `DEGRADED/unconfined` diagnostic. This favors availability; use `docker` mode when you need a hard guarantee. +- **The data directory and the admin socket stay reachable.** In `none` and + `sandbox` mode a stdio server runs as the proxy's user and can read the data + directory and, if `enable_socket` is on, use the admin socket. Set + `enable_socket: false` for headless installs and use `docker` isolation for + servers you do not trust. Details and the verification table are in + [What the sandbox does not hide](#what-the-sandbox-does-not-hide). +- **Snap-packaged runtimes do not start.** Landlock requires `no_new_privs`, + and `snap-confine` needs privileges that flag forbids, so a `uvx` or `node` + installed from a snap fails with *snap-confine is packaged without necessary + permissions*. Use a non-snap install of the runtime (the official `uv` + installer, a distro package, `nvm`). + +## What the sandbox does not hide + +Landlock confines **writes**. It does not change who the server runs as, and +it does not hide files or sockets the proxy's user can reach. Two things in +the data directory matter here: + +- `mcp_config.json` holds `api_key`; `config.db` holds the upstream OAuth + tokens. The directory is `0700` and the files `0600`, but the child runs as + the same user, so that does not help. +- `mcpproxy.sock` (on by default, `enable_socket: true`) is the local admin + endpoint. Connections to it are trusted **without an API key**, because the + OS already authenticated the peer as the same user — which a stdio child is. + +Verified by a contributor on `main` (Linux, Landlock ABI 8) with +`enable_socket` at its default and the key passed as `MCPPROXY_API_KEY` +([#1704](https://github.com/smart-mcp-proxy/mcpproxy-go/issues/1704)); a stdio +child ran a probe script: + +| | `none` | `sandbox` (Landlock) | `docker` (rootless Podman) | +|---|---|---|---| +| Read `mcp_config.json` (has `api_key`) | read | read | not visible (data dir not mounted) | +| Read `config.db` (OAuth tokens) | read | read | not visible | +| `api_key` in the child's environment | no | no | no | +| Connect to `/mcpproxy.sock` with no key | **yes**, `GET /api/v1/status` returns data | **yes**, same | the socket is not visible | +| Mint a token over the socket (`POST /api/v1/tokens`, read+write+destructive, all servers) | same socket | **201, `mcp_agt_…` returned** | n/a | +| `GET /api/v1/config` over the socket | same socket | returns the config, `api_key` masked | n/a | +| Read the proxy's `/proc//environ` (has `MCPPROXY_API_KEY`) | **yes** | **no**, permission denied (a Landlock domain cannot reach processes outside it) | n/a | + +So in `sandbox` mode the environment is protected, but the unauthenticated +socket gives the child admin on its own, and hiding the files would not help. +With `enable_socket: false` the socket row disappears; the files remain +readable in `none` and `sandbox`. + +What to do: + +- **Headless installs** (no tray): set `enable_socket: false`. The tray is the + only socket client, so a headless service loses nothing. +- **Servers you do not trust**: use `docker` isolation + (`docker_isolation.mode: "docker"`, or per-server `isolation.mode`). The + container does not mount the data directory, so neither the files nor the + socket are visible. +- `mcpproxy doctor` reports every enabled stdio server that resolves to `none` + or `sandbox` while `enable_socket` is on, so a config that drifts into this + state is visible without re-reading this page. + +The same exposure applies to a server-edition container that runs stdio +children next to its `/data` volume unless Docker isolation is turned on +there. ## Platform support diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index c489bbb55..6c7158f3f 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -281,7 +281,7 @@ sudo tee /etc/mcpproxy/mcp_config.json >/dev/null <:8080/api/v1/status - **Always set a non-empty `api_key`.** The REST API enforces it, but a network-reachable instance with an obvious or empty key is one `curl` away from full tool execution. - **Put a firewall in front.** If only one workstation needs access, prefer binding to a single LAN IP (e.g. `"listen": "192.168.1.10:8080"`) or restrict port 8080 in `ufw`/`firewalld` to known source addresses. - **Consider `require_mcp_auth: true`** if you also want the `/mcp` endpoint to require the API key. It's `false` by default for AI-client compatibility. +- **Headless? Set `enable_socket: false` and use `docker` isolation for stdio servers.** The Unix socket in the data directory trusts every same-user connection without a key, and a stdio server under isolation `none` or `sandbox` runs as the service user: it can read `mcp_config.json` and `config.db` and mint agent tokens over the socket. The tray is the only socket client, so a headless service loses nothing by turning it off; `docker` isolation keeps the data directory out of the server's view. `mcpproxy doctor` warns about the combination. See [What the sandbox does not hide](/features/sandbox-isolation#what-the-sandbox-does-not-hide). - **Don't expose to the public internet without TLS in front.** Run nginx/Caddy/Traefik as a reverse proxy with HTTPS, or tunnel via Tailscale/WireGuard/SSH. The built-in HTTP server is not designed to be a public ingress. ::: diff --git a/docs/socket-communication.md b/docs/socket-communication.md index fe59054ac..8a4c30973 100644 --- a/docs/socket-communication.md +++ b/docs/socket-communication.md @@ -33,6 +33,7 @@ MCPProxy uses platform-specific local IPC for secure, low-latency communication - **Socket/Pipe connections**: Trusted by default (skip API key validation) - **TCP connections**: Require API key authentication - **Middleware**: `internal/httpapi/server.go` checks connection source via context +- **Trust boundary**: "trusted by default" means every process running as the same user — including the stdio MCP servers mcpproxy itself spawns under isolation `none` or `sandbox` (Landlock confines writes only). Such a server can mint agent tokens over the socket without a key. On headless installs set `enable_socket: false` (the tray is the only socket client); run stdio servers you do not trust under `docker` isolation, which does not mount the data directory. `mcpproxy doctor` reports the combination. See [What the sandbox does not hide](/features/sandbox-isolation#what-the-sandbox-does-not-hide). ## File Locations diff --git a/internal/config/doctor_findings.go b/internal/config/doctor_findings.go index 8ab396e70..4d3db958a 100644 --- a/internal/config/doctor_findings.go +++ b/internal/config/doctor_findings.go @@ -1,5 +1,11 @@ package config +import ( + "fmt" + "strconv" + "strings" +) + // MsgRequireMCPAuthOverridden is the boot notice and doctor finding text of // contracts/config-keys.md for an explicit require_mcp_auth: false under an // enabled server-edition block (Spec 107 FR-029). @@ -14,5 +20,47 @@ func DoctorFindings(cfg *Config) []string { if cfg == nil { return nil } - return serverEditionDoctorFindings(cfg) + var out []string + if f := StdioSocketExposureFinding(cfg); f != "" { + out = append(out, f) + } + return append(out, serverEditionDoctorFindings(cfg)...) +} + +// StdioSocketExposureFinding is the GH #1704 doctor finding: every enabled +// stdio server whose resolved isolation mode is none or sandbox while +// enable_socket is on, in config order. Such a child runs as the proxy's user, +// so it can read the data directory (mcp_config.json with api_key, config.db +// with OAuth tokens) and connect to the admin socket in that directory, which +// trusts every connection without a key — a sandboxed child minted an agent +// token over it. Landlock confines writes only; neither mode hides either. +// Servers resolved to docker, servers that run docker themselves and servers +// with no child process are not listed. Returns "" when there is nothing to +// report. +func StdioSocketExposureFinding(cfg *Config) string { + if cfg == nil || !cfg.EnableSocket { + return "" + } + var exposed []string + for _, s := range cfg.Servers { + if s == nil || !s.Enabled || s.Command == "" || IsDockerCommand(s.Command) { + // No child process, or the server already runs in a container of its + // own (the structural gate only fires for non-none modes, so check it + // here too). + continue + } + if ResolveIsolation(cfg.DockerIsolation, s).Mode == IsolationModeDocker { + continue + } + exposed = append(exposed, strconv.Quote(s.Name)) + } + if len(exposed) == 0 { + return "" + } + return fmt.Sprintf("%d enabled stdio server(s) run under isolation none or sandbox while enable_socket is true (%s): "+ + "a stdio server runs as the proxy's user, can read the data directory (mcp_config.json holds api_key, config.db holds OAuth tokens) "+ + "and can mint agent tokens over the admin socket in that directory without a key; the sandbox mode confines writes only. "+ + "Set enable_socket: false on headless installs and use docker isolation (docker_isolation.mode: \"docker\", or per-server isolation.mode) for servers you do not trust. "+ + "See https://docs.mcpproxy.app/features/sandbox-isolation/", + len(exposed), strings.Join(exposed, ", ")) } diff --git a/internal/config/doctor_findings_test.go b/internal/config/doctor_findings_test.go new file mode 100644 index 000000000..6e1ab6777 --- /dev/null +++ b/internal/config/doctor_findings_test.go @@ -0,0 +1,96 @@ +package config + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stdioServer is an enabled stdio server with an optional per-server isolation +// mode override (empty = inherit the global mode). +func stdioServer(name string, mode IsolationMode) *ServerConfig { + s := &ServerConfig{Name: name, Command: "npx", Args: []string{"-y", name}, Protocol: "stdio", Enabled: true} + if mode != "" { + m := mode + s.Isolation = &IsolationConfig{Mode: &m} + } + return s +} + +// GH #1704: a stdio child runs as the proxy's user. Under isolation none or +// sandbox it can read the data directory and, while enable_socket is on, use +// the admin socket without a key (a sandboxed child minted an agent token over +// it). The doctor finding must name every such server and the fix. +func TestDoctorFindings_StdioSocketExposure_NamesUnisolatedServers(t *testing.T) { + cfg := &Config{ + Listen: "127.0.0.1:8080", + EnableSocket: true, + Servers: []*ServerConfig{ + stdioServer("inherits-none", ""), + stdioServer("explicit-sandbox", IsolationModeSandbox), + stdioServer("explicit-docker", IsolationModeDocker), + {Name: "remote-http", URL: "https://example.com/mcp", Protocol: "http", Enabled: true}, + {Name: "disabled-stdio", Command: "uvx", Protocol: "stdio", Enabled: false}, + {Name: "runs-docker-itself", Command: "docker", Args: []string{"run", "img"}, Protocol: "stdio", Enabled: true}, + }, + } + findings := DoctorFindings(cfg) + require.Len(t, findings, 1, "%v", findings) + f := findings[0] + assert.Contains(t, f, `"inherits-none"`) + assert.Contains(t, f, `"explicit-sandbox"`) + assert.NotContains(t, f, "explicit-docker", "docker isolation hides the data dir and the socket") + assert.NotContains(t, f, "remote-http", "no child process") + assert.NotContains(t, f, "disabled-stdio", "never spawned") + assert.NotContains(t, f, "runs-docker-itself", "the server itself runs in a container") + assert.Contains(t, f, "enable_socket", "the finding must name the switch") + assert.Contains(t, f, "docker", "the finding must point at docker isolation") + assert.Equal(t, 1, strings.Count(f, "\n")+1, "one line per finding") +} + +func TestDoctorFindings_StdioSocketExposure_SilentWhenSocketOff(t *testing.T) { + cfg := &Config{ + Listen: "127.0.0.1:8080", + EnableSocket: false, + Servers: []*ServerConfig{stdioServer("inherits-none", "")}, + } + assert.Empty(t, DoctorFindings(cfg)) +} + +func TestDoctorFindings_StdioSocketExposure_SilentUnderGlobalDocker(t *testing.T) { + cfg := &Config{ + Listen: "127.0.0.1:8080", + EnableSocket: true, + DockerIsolation: &DockerIsolationConfig{Mode: IsolationModeDocker}, + Servers: []*ServerConfig{stdioServer("inherits-docker", "")}, + } + assert.Empty(t, DoctorFindings(cfg)) +} + +// A per-server legacy enabled:false opt-out downgrades an active global docker +// mode to none for that server, so it must be named. +func TestDoctorFindings_StdioSocketExposure_NamesPerServerOptOut(t *testing.T) { + optOut := stdioServer("opted-out", "") + optOut.Isolation = &IsolationConfig{Enabled: BoolPtr(false)} + cfg := &Config{ + Listen: "127.0.0.1:8080", + EnableSocket: true, + DockerIsolation: &DockerIsolationConfig{Mode: IsolationModeDocker}, + Servers: []*ServerConfig{optOut, stdioServer("inherits-docker", "")}, + } + findings := DoctorFindings(cfg) + require.Len(t, findings, 1, "%v", findings) + assert.Contains(t, findings[0], `"opted-out"`) + assert.NotContains(t, findings[0], "inherits-docker") +} + +func TestDoctorFindings_StdioSocketExposure_NoStdioServers(t *testing.T) { + cfg := &Config{ + Listen: "127.0.0.1:8080", + EnableSocket: true, + Servers: []*ServerConfig{{Name: "remote", URL: "https://example.com/mcp", Protocol: "http", Enabled: true}}, + } + assert.Empty(t, DoctorFindings(cfg)) +} diff --git a/internal/sandbox/sandbox_linux.go b/internal/sandbox/sandbox_linux.go index fec44711a..4b4d03cad 100644 --- a/internal/sandbox/sandbox_linux.go +++ b/internal/sandbox/sandbox_linux.go @@ -35,6 +35,17 @@ const ( unix.LANDLOCK_ACCESS_FS_IOCTL_DEV // ABI 5 accessFSReadWrite = accessFSRead | accessFSWrite + + // accessFSFile is the subset Landlock accepts on a rule whose target is a + // regular file or a device rather than a directory. The directory-only + // rights (READ_DIR, MAKE_*, REMOVE_*, REFER) make landlock_add_rule fail + // with EINVAL on such a target, which is how a /dev/null grant used to + // abort the whole confinement (GH #1704). + accessFSFile = unix.LANDLOCK_ACCESS_FS_EXECUTE | + unix.LANDLOCK_ACCESS_FS_WRITE_FILE | + unix.LANDLOCK_ACCESS_FS_READ_FILE | + unix.LANDLOCK_ACCESS_FS_TRUNCATE | + unix.LANDLOCK_ACCESS_FS_IOCTL_DEV ) // handledAccessFS returns the set of filesystem access rights the ruleset @@ -162,9 +173,11 @@ func Apply(spec Spec) (Report, error) { return rep, nil } -// addPathRule grants access to the subtree beneath path. Returns (false, nil) -// when the path does not exist so the caller can record it as skipped rather -// than fail the whole confinement. +// addPathRule grants access to the subtree beneath path, or to the single +// file when path is not a directory (then only the file-compatible rights are +// requested; see accessFSFile). Returns (false, nil) when the path does not +// exist so the caller can record it as skipped rather than fail the whole +// confinement. func addPathRule(rulesetFD int, path string, access uint64) (bool, error) { fd, err := unix.Open(path, unix.O_PATH|unix.O_CLOEXEC, 0) if err != nil { @@ -175,6 +188,14 @@ func addPathRule(rulesetFD int, path string, access uint64) (bool, error) { } defer unix.Close(fd) + var st unix.Stat_t + if err := unix.Fstat(fd, &st); err != nil { + return false, err + } + if st.Mode&unix.S_IFMT != unix.S_IFDIR { + access &= accessFSFile + } + beneath := unix.LandlockPathBeneathAttr{ Allowed_access: access, Parent_fd: int32(fd), diff --git a/internal/sandbox/sandbox_linux_test.go b/internal/sandbox/sandbox_linux_test.go index 046d3c4de..3dbf38e36 100644 --- a/internal/sandbox/sandbox_linux_test.go +++ b/internal/sandbox/sandbox_linux_test.go @@ -145,3 +145,39 @@ func TestHandledAccessFSMasksByABI(t *testing.T) { t.Errorf("handledAccessFS(5) = %#x, want full set %#x", h5, uint64(accessFSReadWrite)) } } + +// TestAddPathRule_FileTarget pins GH #1704's /dev/null fix at the syscall +// boundary: a ReadWritePaths entry that names a FILE (here a regular temp file +// standing in for the /dev/null device) must be accepted. Landlock rejects a +// rule on a non-directory that carries directory-only rights (READ_DIR, +// MAKE_*, REMOVE_*, REFER) with EINVAL, so the adder has to mask them off. +// Only a ruleset is created; nothing restricts the test process. +func TestAddPathRule_FileTarget(t *testing.T) { + abi, err := landlockABI() + if err != nil || abi < 1 { + t.Skipf("Landlock unavailable (abi=%d, err=%v)", abi, err) + } + target := filepath.Join(t.TempDir(), "devnull-stand-in") + if err := os.WriteFile(target, nil, 0o600); err != nil { + t.Fatal(err) + } + handled := handledAccessFS(abi) + rulesetFD, err := landlockCreateRuleset(&unix.LandlockRulesetAttr{Handled_access_fs: handled}) + if err != nil { + t.Fatalf("landlock_create_ruleset: %v", err) + } + defer unix.Close(rulesetFD) + + ok, err := addPathRule(rulesetFD, target, uint64(accessFSReadWrite)&handled) + if err != nil { + t.Fatalf("addPathRule on a file target failed: %v", err) + } + if !ok { + t.Fatalf("addPathRule reported the existing file %q as missing", target) + } + // A directory target keeps the full set (regression guard for the mask). + ok, err = addPathRule(rulesetFD, t.TempDir(), uint64(accessFSReadWrite)&handled) + if err != nil || !ok { + t.Fatalf("addPathRule on a directory target: ok=%v err=%v", ok, err) + } +} diff --git a/internal/upstream/core/sandbox.go b/internal/upstream/core/sandbox.go index 5402d3ce0..f0b43bf3e 100644 --- a/internal/upstream/core/sandbox.go +++ b/internal/upstream/core/sandbox.go @@ -66,14 +66,18 @@ func (c *Client) wrapWithSandbox(command string, args []string) (wrappedCommand // reads stay broad (read-only "/") so package-manager runtimes can load // interpreters, node_modules, and site-packages from anywhere on the host, while // WRITES are denied outside a small allowlist — the server's working directory, -// the OS temp dir, and the common package caches the runtimes need. Tightening +// the OS temp dir, /dev/null, and the common package caches the runtimes need. Tightening // reads is deliberately deferred: a read allowlist breaks tool discovery and // belongs to a future per-server explicit allowlist. // // BestEffort is set so a kernel without Landlock degrades to unconfined-with- // diagnostic instead of failing the connection outright. func buildSandboxSpec(cfg *config.ServerConfig) sandbox.Spec { - rw := []string{os.TempDir()} + // /dev/null is granted as a single device, not the whole of /dev: the + // read-only "/" rule covers reading it but not WRITE_FILE, so without this + // grant a confined `sh -c '... 2>/dev/null'` fails with "Permission denied" + // and the runtimes' own stdio-to-devnull plumbing breaks (GH #1704). + rw := []string{os.TempDir(), "/dev/null"} if cfg != nil && cfg.WorkingDir != "" { rw = append(rw, cfg.WorkingDir) } diff --git a/internal/upstream/core/sandbox_linux_test.go b/internal/upstream/core/sandbox_linux_test.go index 1e23fd10e..202e8364a 100644 --- a/internal/upstream/core/sandbox_linux_test.go +++ b/internal/upstream/core/sandbox_linux_test.go @@ -12,6 +12,7 @@ import ( "golang.org/x/sys/unix" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/sandbox" ) @@ -160,3 +161,41 @@ func scrubEnv(env []string, key string) []string { } return out } + +// TestSandboxWrapper_DefaultSpecAllowsDevNull reproduces the GH #1704 side +// observation on a real kernel: under the PRODUCTION spec (buildSandboxSpec, +// not a hand-built one) a confined shell must be able to redirect to +// /dev/null, both as `2>/dev/null` and as an explicit write. Before the fix +// the shell reported "Permission denied" because the read-only "/" grant does +// not cover WRITE_FILE on the device. +func TestSandboxWrapper_DefaultSpecAllowsDevNull(t *testing.T) { + if !sandbox.Available() { + t.Skip("Landlock unavailable on this kernel (needs 5.13+ with Landlock LSM enabled)") + } + spec := buildSandboxSpec(&config.ServerConfig{Name: "srv", WorkingDir: t.TempDir()}) + spec.BestEffort = false // this test requires real enforcement + + script := ` +echo to-stderr 1>&2 2>/dev/null || { echo REDIRECT_FAILED; exit 1; } +echo discarded >/dev/null || { echo WRITE_FAILED; exit 1; } +: /dev/null` +// fails with EACCES, which breaks launch scripts and the runtimes' own +// stdio-to-devnull plumbing. The grant must be the device itself, not /dev. +func TestBuildSandboxSpec_DevNullWritable(t *testing.T) { + spec := buildSandboxSpec(&config.ServerConfig{Name: "srv"}) + if !contains(spec.ReadWritePaths, "/dev/null") { + t.Errorf("ReadWritePaths %v missing /dev/null", spec.ReadWritePaths) + } + if contains(spec.ReadWritePaths, "/dev") { + t.Errorf("ReadWritePaths %v grants all of /dev; only /dev/null is needed", spec.ReadWritePaths) + } +}