diff --git a/SECURITY.md b/SECURITY.md index c852ef204..9032f44d4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -69,7 +69,7 @@ chmod 600 ~/.nanobot/config.json The `exec` tool can execute shell commands. While dangerous command patterns are blocked, you should: -- ✅ **Enable the bwrap sandbox** (`"tools.exec.sandbox": "bwrap"`) for kernel-level isolation (Linux only) +- ✅ **Enable the exec sandbox** (`"tools.exec.sandbox": "bwrap"` on Linux, `"seatbelt"` on macOS) for kernel-level isolation - ✅ Review all tool usage in agent logs - ✅ Understand what commands the agent is running - ✅ Use a dedicated user account with limited privileges @@ -77,16 +77,26 @@ The `exec` tool can execute shell commands. While dangerous command patterns are - ❌ Don't disable security checks - ❌ Don't run on systems with sensitive data without careful review -**Exec sandbox (bwrap):** +**Exec sandbox (bwrap on Linux, seatbelt on macOS):** -On Linux, set `"tools.exec.sandbox": "bwrap"` to wrap every shell command in a [bubblewrap](https://github.com/containers/bubblewrap) sandbox. This uses Linux kernel namespaces to restrict what the process can see: +Set `"tools.exec.sandbox"` to wrap every shell command in an OS sandbox. Both backends enforce the same policy: - Workspace directory → **read-write** (agent works normally) - Media directory → **read-only** (can read uploaded attachments) - System directories (`/usr`, `/bin`, `/lib`) → **read-only** (commands still work) -- Config files and API keys (`~/.nanobot/config.json`) → **hidden** (masked by tmpfs) +- Config files and API keys (`~/.nanobot/config.json`) → **hidden** +- Everything else, including `~/.ssh` → **denied** -Requires `bwrap` installed (`apt install bubblewrap`). Pre-installed in the official Docker image. **Not available on macOS or Windows** — bubblewrap depends on Linux kernel namespaces. +| Backend | Value | Platform | Requires | +|---------|-------|----------|----------| +| [bubblewrap](https://github.com/containers/bubblewrap) | `"bwrap"` | Linux | `bwrap` (`apt install bubblewrap`). Pre-installed in the official Docker image. | +| Seatbelt | `"seatbelt"` | macOS | `sandbox-exec(1)`, shipped with macOS. | + +**Windows has no backend**: nanobot logs a warning and runs the command unsandboxed. + +The backends hide the config directory differently. `bwrap` masks the workspace's parent with a tmpfs, so it disappears from directory listings. Seatbelt has no mount namespace, so it denies the parent instead — the directory still appears in listings, but its contents are unreadable. + +Neither backend restricts network access. Enabling the sandbox also automatically activates `restrictToWorkspace` for file tools. diff --git a/docs/configuration.md b/docs/configuration.md index af66a4035..4ca5d0b02 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2092,7 +2092,7 @@ MCP tools are automatically discovered and registered on startup. The LLM can us ## Security > [!TIP] -> For production deployments, set both `"restrictToWorkspace": true` and `"tools.exec.sandbox": "bwrap"` in your config. `restrictToWorkspace` enables nanobot's application-level workspace guards; `tools.exec.sandbox` provides process-level isolation for shell commands. +> For production deployments, set both `"restrictToWorkspace": true` and `"tools.exec.sandbox"` (`"bwrap"` on Linux, `"seatbelt"` on macOS) in your config. `restrictToWorkspace` enables nanobot's application-level workspace guards; `tools.exec.sandbox` provides process-level isolation for shell commands. For API keys, tokens, and other secrets, see [Environment Variables for Secrets](#environment-variables-for-secrets) — avoid storing them directly in `config.json`. @@ -2110,13 +2110,13 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets] |--------|---------|-------------| | `tools.restrictToWorkspace` | `false` | When `true`, enables nanobot's application-level workspace guards for workspace-aware tools. File tools resolve paths under the active workspace; selected internal roots can be added as read-only or explicitly write-enabled roots, and media uploads are read-only by default. Shell execution rejects workspace-external `working_dir` values and applies best-effort command path checks, but this is not an OS sandbox. | | `tools.maxSessionMessagesPerMinute` | `6` | Maximum messages one source session may send during any rolling 60-second window. Additional sends are rejected to stop runaway agent loops. | -| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. Set to `"bwrap"` to wrap exec calls in a [bubblewrap](https://github.com/containers/bubblewrap) sandbox — the process can only see the workspace (read-write) and media directory (read-only); config files and API keys are hidden. Automatically enables workspace restriction for file tools. **Linux only** — requires `bwrap` installed (`apt install bubblewrap`; pre-installed in the Docker image). Not available on macOS or Windows (bwrap depends on Linux kernel namespaces). | +| `tools.exec.sandbox` | `""` | Sandbox backend for shell commands. Set to `"bwrap"` (Linux) or `"seatbelt"` (macOS) to wrap exec calls in an OS sandbox — the process can only see the workspace (read-write) and media directory (read-only); config files and API keys are hidden. Automatically enables workspace restriction for file tools. `"bwrap"` requires `bwrap` installed (`apt install bubblewrap`; pre-installed in the Docker image) and depends on Linux kernel namespaces. `"seatbelt"` uses the `sandbox-exec(1)` binary shipped with macOS. Neither backend is available on Windows, where nanobot logs a warning and runs commands unsandboxed. | | `tools.exec.enable` | `true` | When `false`, the shell `exec` tool is not registered at all. Use this to completely disable shell command execution. | | `tools.exec.timeout` | `60` | Default hard timeout in seconds for shell commands. Config values may exceed the per-call tool cap; set `0` to disable the hard timeout for trusted long-running commands. | | `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. | | `tools.exec.pathAppend` | `""` | Extra directories to append to `PATH` when running shell commands (e.g. `/usr/sbin` for `ufw`). | -| `tools.exec.sandboxRoBinds` | `[]` | Extra absolute paths to read-only bind into the `"bwrap"` sandbox with `--ro-bind-try`, such as `/home/user/.local/bin` or `/home/user/.cargo/bin` when those paths are also in `pathPrepend`/`pathAppend`. These roots are also accepted by the shell absolute-path guard only while bwrap is active. Bind only directories whose contents are safe for agent commands to read; paths equal to or containing the active workspace are ignored so they cannot uncover its masked parent directory. | -| `tools.exec.sandboxRwBinds` | `[]` | Extra absolute paths to read-write bind into the `"bwrap"` sandbox with `--bind-try`, for trusted tool caches or scratch directories. Use sparingly: paths listed here are intentionally writable by shell commands inside the sandbox. Paths equal to or containing the active workspace are ignored. | +| `tools.exec.sandboxRoBinds` | `[]` | Extra absolute paths to expose read-only inside the exec sandbox (`--ro-bind-try` for `"bwrap"`, an SBPL `file-read*` rule for `"seatbelt"`), such as `/home/user/.local/bin` or `/home/user/.cargo/bin` when those paths are also in `pathPrepend`/`pathAppend`. These roots are also accepted by the shell absolute-path guard only while a sandbox is active. Bind only directories whose contents are safe for agent commands to read; paths equal to or containing the active workspace are ignored so they cannot uncover its masked parent directory. | +| `tools.exec.sandboxRwBinds` | `[]` | Extra absolute paths to expose read-write inside the exec sandbox (`--bind-try` for `"bwrap"`, an SBPL `file-read* file-write*` rule for `"seatbelt"`), for trusted tool caches or scratch directories. Use sparingly: paths listed here are intentionally writable by shell commands inside the sandbox. Paths equal to or containing the active workspace are ignored. | | `tools.webuiAllowRemotePackageInstall` | `false` | When `false`, the WebUI can install missing optional packages only from a browser opened on the same machine as nanobot. Set to `true` only when a trusted remote admin is allowed to install Python packages into this nanobot environment. | | `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. | | `channels.*.allowFrom` | omitted | Access control per channel. Omit to use pairing-only mode; set `["*"]` to allow everyone; or list specific user IDs. See [Pairing](#pairing) for details. | diff --git a/nanobot/agent/tools/sandbox.py b/nanobot/agent/tools/sandbox.py index 4c5cbf853..8aa7bfccd 100644 --- a/nanobot/agent/tools/sandbox.py +++ b/nanobot/agent/tools/sandbox.py @@ -101,7 +101,161 @@ def _bwrap( return shlex.join(args) -_BACKENDS = {"bwrap": _bwrap} +# Directories every command needs to read for the dynamic linker, system +# binaries, certificates and device nodes. Seatbelt evaluates resolved paths, +# so the /private-prefixed form is what actually matches on macOS; the bare +# symlink form is listed too because commands spell paths both ways. +_SEATBELT_SYSTEM_READ_SUBPATHS = ( + "/usr", + "/bin", + "/sbin", + "/etc", + "/dev", + "/System", + "/Library", + "/private/etc", + "/var", + "/private/var", + "/tmp", + "/private/tmp", +) + +# Writable scratch space. /private/var/folders holds $TMPDIR, which build tools +# and test runners rely on; /tmp is its symlink spelling. +_SEATBELT_SCRATCH_SUBPATHS = ("/tmp", "/private/tmp", "/var/folders", "/private/var/folders") + +# Ancestors that must stay searchable but are not covered by any allowed +# subpath. Resolving "/private/var/..." stats "/private", and +# (subpath "/private/var") does not cover its own parent. +_SEATBELT_TRAVERSABLE_LITERALS = ("/private",) + + +def _seatbelt_ancestors(*paths: Path) -> list[str]: + """Collect every ancestor directory of *paths*, closest first. + + Seatbelt checks each path component while resolving, so a sandbox that + allows a deep directory but not its ancestors fails with ENOTDIR on every + command. Only ``file-read-metadata`` is granted for these: the directories + stay searchable, but listing or reading them is still denied. + """ + out: list[str] = [] + seen: set[str] = set() + for path in paths: + for ancestor in path.parents: + name = str(ancestor) + if name in seen: + continue + seen.add(name) + out.append(name) + return out + + +def _sbpl_quote(path: str) -> str: + """Render *path* as an SBPL string literal. + + SBPL uses C-style string escaping, so a backslash or a double quote in a + path would otherwise terminate the literal early and change the meaning of + every rule that follows it. + """ + escaped = path.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +def _seatbelt( + command: str, + workspace: str, + cwd: str, + *, + sandbox_ro_binds: Iterable[str] | None = None, + sandbox_rw_binds: Iterable[str] | None = None, +) -> str: + """Wrap command in a macOS Seatbelt sandbox (requires sandbox-exec(1)). + + Mirrors the ``bwrap`` policy: the workspace is read-write, the media + directory is read-only, and the workspace's parent (which holds + ``config.json``) is unreadable so API keys stay hidden. + + Seatbelt has no mount namespace, so masking the parent is expressed as a + deny rule placed *before* the workspace allow — the last matching rule + wins, which re-exposes the workspace subtree while the rest of the parent + stays denied. Unlike ``bwrap``, a denied parent still appears in directory + listings; only its contents are inaccessible. + + Network access is left unrestricted, matching ``bwrap`` (which does not pass + ``--unshare-net``). + """ + ws = Path(workspace).resolve() + media = get_media_dir().resolve() + + try: + sandbox_cwd = str(ws / Path(cwd).resolve().relative_to(ws)) + except ValueError: + sandbox_cwd = str(ws) + + def subpaths(paths: Iterable[str]) -> str: + return " ".join(f"(subpath {_sbpl_quote(p)})" for p in paths) + + ro_binds = _normalize_bind_paths(sandbox_ro_binds, workspace=ws) + rw_binds = _normalize_bind_paths(sandbox_rw_binds, workspace=ws) + + rules = [ + "(version 1)", + "(deny default)", + "(allow process*)", + "(allow sysctl-read)", + "(allow mach*)", + "(allow ipc*)", + # sh(1) reads the root directory while resolving a path, and + # (subpath "/usr") does not cover "/" itself. Without this rule the + # shell aborts during startup. + '(allow file-read* (literal "/"))', + f"(allow file-read* {subpaths(_SEATBELT_SYSTEM_READ_SUBPATHS)})", + f"(allow file-write* {subpaths(_SEATBELT_SCRATCH_SUBPATHS)})", + ] + + # Mask the config directory. The workspace allow below re-exposes the + # workspace subtree, because the last matching rule wins. + parent = ws.parent + if parent != ws and str(parent) != "/": + rules.append(f"(deny file-read* file-write* (subpath {_sbpl_quote(str(parent))}))") + + # Keep every ancestor of an allowed path searchable, including the masked + # parent: metadata only, so it cannot be listed or read. + traversable = _seatbelt_ancestors( + ws, media, *(Path(p) for p in ro_binds), *(Path(p) for p in rw_binds) + ) + literals = [ + *(p for p in _SEATBELT_TRAVERSABLE_LITERALS if p not in traversable), + *traversable, + ] + rules.append( + "(allow file-read-metadata " + + " ".join(f"(literal {_sbpl_quote(p)})" for p in literals) + + ")" + ) + + rules.append(f"(allow file-read* file-write* (subpath {_sbpl_quote(str(ws))}))") + rules.append(f"(allow file-read* (subpath {_sbpl_quote(str(media))}))") + + for p in ro_binds: + rules.append(f"(allow file-read* (subpath {_sbpl_quote(p)}))") + for p in rw_binds: + rules.append(f"(allow file-read* file-write* (subpath {_sbpl_quote(p)}))") + + # sandbox-exec(1) has no --chdir, so the working directory is entered by + # the wrapped shell. `&&` keeps the command from running if cd is denied. + args = [ + "sandbox-exec", + "-p", + "\n".join(rules), + "sh", + "-c", + f"cd {shlex.quote(sandbox_cwd)} && {command}", + ] + return shlex.join(args) + + +_BACKENDS = {"bwrap": _bwrap, "seatbelt": _seatbelt} def wrap_command( diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py index 061d1458d..cfdbcbdb6 100644 --- a/nanobot/agent/tools/shell.py +++ b/nanobot/agent/tools/shell.py @@ -1156,7 +1156,7 @@ class ExecTool(Tool): self, workspace_root: Path | None = None, ) -> list[Path]: - if self.sandbox != "bwrap" or _IS_WINDOWS: + if self.sandbox not in ("bwrap", "seatbelt") or _IS_WINDOWS: return [] roots = [*self.sandbox_ro_binds, *self.sandbox_rw_binds] if workspace_root is None: diff --git a/nanobot/security/workspace_access.py b/nanobot/security/workspace_access.py index 72d0ae4b6..476723e93 100644 --- a/nanobot/security/workspace_access.py +++ b/nanobot/security/workspace_access.py @@ -19,6 +19,7 @@ _PROVIDER_LABELS = { "unknown": "Unknown system sandbox", "macos_app_sandbox": "macOS App Sandbox", "bwrap": "Bubblewrap", + "seatbelt": "macOS Seatbelt", } _CURRENT_WORKSPACE_SCOPE: ContextVar["WorkspaceScope | None"] = ContextVar( diff --git a/tests/tools/test_sandbox.py b/tests/tools/test_sandbox.py index c83ef4220..1d86387a0 100644 --- a/tests/tools/test_sandbox.py +++ b/tests/tools/test_sandbox.py @@ -223,6 +223,191 @@ class TestBwrapBackend: assert (str(parent), str(parent)) not in bind_try_pairs +class TestSeatbeltBackend: + """macOS Seatbelt policy generation. + + These parse the generated ``sandbox-exec`` command line, so they run on any + platform — the profile is only ever executed on macOS. + """ + + @staticmethod + def _profile(cmd: str) -> str: + """Return the SBPL profile from a wrapped command.""" + tokens = _parse(cmd) + return tokens[tokens.index("-p") + 1] + + @staticmethod + def _metadata_rule(profile: str) -> str: + return next( + line + for line in profile.splitlines() + if line.startswith("(allow file-read-metadata ") + ) + + def test_basic_structure(self, tmp_path): + ws = str(tmp_path / "project") + result = wrap_command("seatbelt", "echo hi", ws, ws) + tokens = _parse(result) + + assert tokens[0] == "sandbox-exec" + assert tokens[1] == "-p" + assert tokens[-3] == "sh" + assert tokens[-2] == "-c" + assert tokens[-1].endswith("echo hi") + + def test_denies_by_default(self, tmp_path): + profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + + assert "(version 1)" in profile + assert "(deny default)" in profile + + def test_root_directory_is_readable(self, tmp_path): + """sh(1) stats `/` at startup; without this rule the shell aborts. + + `(subpath "/usr")` does not cover the root directory itself, so a + profile listing only system subpaths kills every wrapped command + before it runs. + """ + profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + + assert '(allow file-read* (literal "/"))' in profile + + def test_workspace_allowed_read_write(self, tmp_path): + ws = (tmp_path / "project").resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + assert f'(allow file-read* file-write* (subpath "{ws}"))' in profile + + def test_config_dir_denied_before_workspace_allow(self, tmp_path): + """Last matching rule wins, so the parent deny must come first. + + The parent holds `config.json`; the workspace allow that follows + re-exposes only the workspace subtree. + """ + ws = (tmp_path / "project").resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + parent_deny = profile.index(f'(deny file-read* file-write* (subpath "{ws.parent}")') + workspace_allow = profile.index(f'(allow file-read* file-write* (subpath "{ws}")') + assert parent_deny < workspace_allow + + def test_no_parent_deny_when_workspace_is_the_root(self): + """Denying `/` would override the root read rule and break startup.""" + profile = self._profile(wrap_command("seatbelt", "ls", "/", "/")) + + assert "(deny file-read*" not in profile + + def test_workspace_ancestors_stay_searchable(self, tmp_path): + """Masking the config dir must not break resolution into the workspace. + + Seatbelt checks every path component while resolving, so without + metadata on the parent the wrapped command dies with ENOTDIR before it + runs anything. + """ + ws = (tmp_path / "project").resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + assert f'(literal "{ws.parent}")' in self._metadata_rule(profile) + + def test_config_dir_is_searchable_but_not_listable(self, tmp_path): + """Metadata only: `cd workspace` works, `ls ..` and `cat ../config.json` do not.""" + ws = (tmp_path / "project").resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + assert f'(literal "{ws.parent}")' in self._metadata_rule(profile) + assert f'(allow file-read* (subpath "{ws.parent}"))' not in profile + assert f'(allow file-read* file-write* (subpath "{ws.parent}"))' not in profile + + def test_scratch_space_covers_the_tmp_symlink_spelling(self, tmp_path): + """`/tmp` and `/var` are symlinks; commands spell scratch paths both ways.""" + profile = self._profile(wrap_command("seatbelt", "ls", str(tmp_path), str(tmp_path))) + + write_rule = next( + line for line in profile.splitlines() if line.startswith("(allow file-write* ") + ) + for expected in ('(subpath "/tmp")', '(subpath "/private/tmp")'): + assert expected in write_rule + + def test_media_dir_read_only(self, tmp_path, monkeypatch): + fake_media = (tmp_path / "media").resolve() + fake_media.mkdir() + monkeypatch.setattr( + "nanobot.agent.tools.sandbox.get_media_dir", + lambda: fake_media, + ) + ws = (tmp_path / "project").resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + assert f'(allow file-read* (subpath "{fake_media}"))' in profile + assert f'file-write* (subpath "{fake_media}")' not in profile + + def test_cwd_inside_workspace(self, tmp_path): + ws = (tmp_path / "project").resolve() + sub = ws / "src" / "lib" + result = wrap_command("seatbelt", "pwd", str(ws), str(sub)) + + assert _parse(result)[-1] == f"cd {shlex.quote(str(sub))} && pwd" + + def test_cwd_outside_workspace_falls_back(self, tmp_path): + ws = (tmp_path / "project").resolve() + outside = tmp_path / "other" + result = wrap_command("seatbelt", "pwd", str(ws), str(outside)) + + assert _parse(result)[-1] == f"cd {shlex.quote(str(ws))} && pwd" + + def test_custom_read_only_binds(self, tmp_path): + ws = (tmp_path / "project").resolve() + tool_bin = (tmp_path / "home" / ".local" / "bin").resolve(strict=False) + + profile = self._profile( + wrap_command( + "seatbelt", "uv --version", str(ws), str(ws), + sandbox_ro_binds=[str(tool_bin)], + ) + ) + + assert f'(allow file-read* (subpath "{tool_bin}"))' in profile + assert f'file-write* (subpath "{tool_bin}")' not in profile + + def test_custom_read_write_binds(self, tmp_path): + ws = (tmp_path / "project").resolve() + cache_dir = (tmp_path / "cache").resolve(strict=False) + + profile = self._profile( + wrap_command( + "seatbelt", "touch cache/file", str(ws), str(ws), + sandbox_rw_binds=[str(cache_dir)], + ) + ) + + assert f'(allow file-read* file-write* (subpath "{cache_dir}"))' in profile + + def test_custom_workspace_parent_binds_are_ignored(self, tmp_path): + """A bind must not uncover the masked config directory.""" + ws = tmp_path / "private" / "project" + parent = ws.parent.resolve(strict=False) + + profile = self._profile( + wrap_command( + "seatbelt", "cat ../config.json", str(ws), str(ws), + sandbox_ro_binds=[str(parent)], + sandbox_rw_binds=[str(parent)], + ) + ) + + assert f'(allow file-read* (subpath "{parent}"))' not in profile + assert f'(allow file-read* file-write* (subpath "{parent}"))' not in profile + + def test_paths_with_quotes_are_escaped(self, tmp_path): + """An unescaped quote would terminate the literal early and silently + widen every rule that follows it.""" + ws = (tmp_path / 'pro"ject').resolve() + profile = self._profile(wrap_command("seatbelt", "ls", str(ws), str(ws))) + + escaped = str(ws).replace('"', '\\"') + assert f'(allow file-read* file-write* (subpath "{escaped}"))' in profile + + class TestUnknownBackend: def test_raises_value_error(self, tmp_path): ws = str(tmp_path / "project")