diff --git a/SECURITY.md b/SECURITY.md index 513bc668f..f2a87a076 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -96,7 +96,7 @@ Set `"tools.exec.sandbox"` to wrap every shell command in an OS sandbox. Both ba The backends protect the workspace's parent differently. `bwrap` masks it with a tmpfs and re-exposes the workspace and allowed binds. Seatbelt has no mount namespace: it denies the parent, re-allows traversal metadata, and exposes the workspace and allowed roots. Keep configuration and credentials outside the workspace and extra binds; choosing an overly broad workspace or explicitly exposing secret-bearing paths defeats that separation. -Seatbelt does **not** expose the host's shared `/tmp`, `/var/folders`, `/Library`, or `/etc` trees. It allows system code, device reads and selected system configuration/certificate paths. `HOME` and `TMPDIR` point to the workspace. Tools must use that scratch location; on macOS use an explicit template such as `mktemp "$TMPDIR/job.XXXXXX"`, since bare `mktemp` may prefer the host's system temp directory. Tools that require other installations or caches need narrow `sandboxRoBinds` / `sandboxRwBinds`. Read-only binds revoke workspace writes beneath them; explicit read-write binds are applied last, matching bwrap's operator-controlled precedence. This is filesystem containment, not a VM or separate user identity. +Seatbelt does **not** expose the host's shared `/tmp`, `/var/folders`, `/Library`, or `/etc` trees. It allows system code, device reads and selected system configuration/certificate paths. `HOME` and `TMPDIR` point to the workspace. Tools must use that scratch location; on macOS use an explicit template such as `mktemp "$TMPDIR/job.XXXXXX"`, since bare `mktemp` may prefer the host's system temp directory. Tools that require other installations or caches need narrow `sandboxRoBinds` / `sandboxRwBinds`. Read-only binds revoke workspace writes beneath them; explicit read-write binds take precedence, matching bwrap's operator-controlled policy. Seatbelt also prevents renaming or removing ancestor directories of media and read-only roots, so moving a writable parent cannot bypass a read-only rule; unrelated children of those ancestors remain writable where otherwise allowed. An explicit read-write bind covering an entire read-only root overrides that root's protection, but a writable descendant does not unlock its ancestors. This is filesystem containment, not a VM or separate user identity. Neither backend restricts network access. diff --git a/nanobot/agent/tools/sandbox.py b/nanobot/agent/tools/sandbox.py index 6cba5dd1b..e3fa90451 100644 --- a/nanobot/agent/tools/sandbox.py +++ b/nanobot/agent/tools/sandbox.py @@ -156,6 +156,20 @@ def _seatbelt_ancestors(*paths: Path) -> list[str]: return out +def _seatbelt_is_within(path: Path, root: Path) -> bool: + """Match existing path aliases without lowercasing case-sensitive volumes.""" + if path.is_relative_to(root): + return True + for ancestor in (path, *path.parents): + try: + if ancestor.samefile(root): + return True + except OSError: + # Missing/inaccessible paths retain conservative lexical matching. + continue + return False + + def _sbpl_quote(path: str) -> str: """Render *path* as an SBPL string literal. @@ -258,8 +272,25 @@ def _seatbelt( 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. + # Path-based read-only rules do not follow a renamed ancestor. Keep those + # directory entries fixed without denying writes to their other children. + # A RW bind covering the entire RO root intentionally overrides protection; + # a writable descendant must not unlock the rest of the read-only tree. + writable_roots = [Path(p) for p in rw_binds] + protected_roots = [ + root for root in (media, *(Path(p) for p in ro_binds)) + if not any(_seatbelt_is_within(root, writable) for writable in writable_roots) + ] + ancestors = _seatbelt_ancestors(*protected_roots) + if ancestors: + rules.append( + "(deny file-write-unlink " + + " ".join(f"(literal {_sbpl_quote(p)})" for p in ancestors) + + ")" + ) + + # sandbox-exec(1) has no --chdir. Exit on failure before evaluating any of + # the submitted shell list; `cd ... && a; b` would still execute b on failure. args = [ # Resolve the security boundary before consulting operator tool PATHs. "/usr/bin/sandbox-exec", @@ -270,7 +301,7 @@ def _seatbelt( f"TMPDIR={ws}", "sh", "-c", - f"cd {shlex.quote(sandbox_cwd)} && {command}", + f"cd {shlex.quote(sandbox_cwd)} || exit\n{command}", ] return shlex.join(args) diff --git a/tests/tools/test_sandbox.py b/tests/tools/test_sandbox.py index b6682ddaa..3865b1701 100644 --- a/tests/tools/test_sandbox.py +++ b/tests/tools/test_sandbox.py @@ -1,10 +1,11 @@ """Tests for nanobot.agent.tools.sandbox.""" import shlex +from pathlib import Path import pytest -from nanobot.agent.tools.sandbox import _sbpl_quote, wrap_command +from nanobot.agent.tools.sandbox import _sbpl_quote, _seatbelt_is_within, wrap_command def _parse(cmd: str) -> list[str]: @@ -357,14 +358,14 @@ class TestSeatbeltBackend: sub = ws / "src" / "lib" result = wrap_command("seatbelt", "pwd", str(ws), str(sub)) - assert _parse(result)[-1] == f"cd {shlex.quote(str(sub))} && pwd" + assert _parse(result)[-1] == f"cd {shlex.quote(str(sub))} || exit\npwd" 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" + assert _parse(result)[-1] == f"cd {shlex.quote(str(ws))} || exit\npwd" def test_custom_read_only_binds(self, tmp_path): ws = (tmp_path / "project").resolve() @@ -390,6 +391,55 @@ class TestSeatbeltBackend: profile.index(f"(deny file-write* (subpath {self._quote(ro)}))") ) + @pytest.mark.parametrize("source", ["bind", "media"]) + def test_readonly_ancestors_cannot_be_unlinked(self, tmp_path, monkeypatch, source): + ws = (tmp_path / "workspace").resolve() + ro = ws / 'tree with "quotes' / "branch" / "readonly" + media = ro if source == "media" else tmp_path / "media" + monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media) + profile = self._profile(wrap_command( + "seatbelt", "ls", str(ws), str(ws), + sandbox_ro_binds=[str(ro)] if source == "bind" else [], + )) + + rule = profile.splitlines()[-1] + assert rule.startswith("(deny file-write-unlink ") + for parent in ro.parents: + assert f"(literal {self._quote(parent)})" in rule + assert "subpath" not in rule + + @pytest.mark.parametrize("override", ["root", "parent", "child"]) + def test_rw_override_only_unlocks_fully_covered_roots(self, tmp_path, monkeypatch, override): + ws = (tmp_path / "workspace").resolve() + ro = ws / "tree" / "readonly" + rw = {"root": ro, "parent": ro.parent, "child": ro / "cache"}[override] + monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: ro) + profile = self._profile(wrap_command( + "seatbelt", "ls", str(ws), str(ws), + sandbox_ro_binds=[str(ro)], sandbox_rw_binds=[str(rw)], + )) + + if override == "child": + assert profile.splitlines()[-1].startswith("(deny file-write-unlink ") + assert f"(literal {self._quote(ro.parent)})" in profile.splitlines()[-1] + else: + assert "(deny file-write-unlink " not in profile + + @pytest.mark.parametrize("same_directory", [True, False]) + def test_rw_coverage_uses_filesystem_identity(self, tmp_path, monkeypatch, same_directory): + ro = tmp_path / "Tree" / "ReadOnly" + rw = tmp_path / "tree" + monkeypatch.setattr( + Path, "samefile", + lambda path, other: same_directory and path == ro.parent and other == rw, + ) + assert _seatbelt_is_within(ro, rw) is same_directory + + def test_missing_rw_alias_does_not_unlock_readonly_root(self, tmp_path): + ro = tmp_path / "missing" / "readonly" + assert not _seatbelt_is_within(ro, tmp_path / "MISSING") + assert _seatbelt_is_within(ro, ro.parent) + def test_custom_read_write_binds(self, tmp_path): ws = (tmp_path / "project").resolve() cache_dir = (tmp_path / "cache").resolve(strict=False) diff --git a/tests/tools/test_seatbelt_native.py b/tests/tools/test_seatbelt_native.py index 39760fa32..889b92863 100644 --- a/tests/tools/test_seatbelt_native.py +++ b/tests/tools/test_seatbelt_native.py @@ -140,3 +140,127 @@ async def test_native_network_remains_available(layout): finally: server.shutdown() thread.join(timeout=3) + + +@pytest.mark.parametrize("target", ["ro", "media"]) +@pytest.mark.parametrize("ancestor", ["tree", "tree/branch"]) +async def test_native_readonly_ancestor_cannot_be_renamed(layout, target, ancestor): + workspace = layout["workspace"] + protected = workspace / "tree" / "branch" / "readonly" + protected.mkdir(parents=True) + sentinel = protected / "sentinel" + sentinel.write_text("synthetic-readonly") + layout[target] = protected + moved_sentinel = Path("shifted") / protected.relative_to(workspace / ancestor) / "sentinel" + + result = await run_script( + layout, + f"mv {ancestor} shifted && printf changed > {shlex.quote(str(moved_sentinel))}", + ) + + assert "Operation not permitted" in result + assert sentinel.read_text() == "synthetic-readonly" + assert not (workspace / "shifted").exists() + + +async def test_native_readonly_ancestor_keeps_other_children_writable(layout): + workspace = layout["workspace"] + protected = workspace / "tree" / "readonly" + protected.mkdir(parents=True) + layout["ro"] = protected + + result = await run_script( + layout, + "mkdir tree/sibling && printf writable > tree/sibling/file && " + "mv tree/sibling tree/renamed && rm tree/renamed/file && rmdir tree/renamed", + ) + + assert result == "\nExit code: 0" + assert protected.is_dir() + assert not (workspace / "tree" / "renamed").exists() + + +@pytest.mark.parametrize("override", ["root", "parent", "child"]) +async def test_native_rw_override_preserves_readonly_ancestor_policy(layout, override): + workspace = layout["workspace"] + protected = workspace / "tree" / "readonly" + writable = protected / "cache" + writable.mkdir(parents=True) + layout["ro"] = protected + layout["rw"] = {"root": protected, "parent": protected.parent, "child": writable}[override] + + result = await run_script(layout, "printf writable > tree/readonly/cache/file") + assert result == "\nExit code: 0" + assert (writable / "file").read_text() == "writable" + + result = await run_script(layout, "mv tree shifted") + if override == "child": + assert "Operation not permitted" in result + assert protected.is_dir() + else: + assert result == "\nExit code: 0" + assert (workspace / "shifted" / "readonly" / "cache" / "file").read_text() == "writable" + + +@pytest.mark.parametrize("cwd_kind", ["missing", "file"]) +@pytest.mark.parametrize("separator", ["; ", "\n", " || "]) +async def test_native_failed_cwd_does_not_execute_shell_list(layout, cwd_kind, separator): + workspace = layout["workspace"] + cwd = workspace / "unusable" + if cwd_kind == "file": + cwd.write_text("not-a-directory") + tool = ExecTool(working_dir=str(workspace), sandbox="seatbelt") + + result = str(await tool.execute( + command=f"printf first > first{separator}printf second > second", + working_dir=str(cwd), timeout=5, + )) + + assert "cd:" in result + assert not result.endswith("Exit code: 0") + assert not (workspace / "first").exists() + assert not (workspace / "second").exists() + + +async def test_native_nested_cwd_runs_complete_shell_list(layout): + workspace = layout["workspace"] + cwd = workspace / "nested 'directory" + cwd.mkdir() + tool = ExecTool(working_dir=str(workspace), sandbox="seatbelt") + + result = str(await tool.execute( + command="printf first > first; printf second > second", + working_dir=str(cwd), timeout=5, + )) + + assert result == "\nExit code: 0" + assert (cwd / "first").read_text() == "first" + assert (cwd / "second").read_text() == "second" + assert not (workspace / "second").exists() + + +@pytest.mark.parametrize("override", ["root", "parent"]) +async def test_native_rw_override_respects_volume_case_sensitivity(layout, override): + workspace = layout["workspace"] + protected = workspace / "Tree" / "ReadOnly" + protected.mkdir(parents=True) + sentinel = protected / "sentinel" + sentinel.write_text("synthetic-readonly") + alias = workspace / "tree" / "readonly" + alias.mkdir(parents=True, exist_ok=True) + same_directory = alias.samefile(protected) + layout["ro"] = protected + layout["rw"] = alias if override == "root" else alias.parent + + result = await run_script(layout, "printf writable > tree/readonly/other") + assert result == "\nExit code: 0" + result = await run_script(layout, "mv Tree shifted") + + if same_directory: + assert result == "\nExit code: 0" + assert (workspace / "shifted" / "ReadOnly" / "other").read_text() == "writable" + else: + # On a case-sensitive volume the distinct RW directory must not remove + # protection from Tree/ReadOnly, even though its spelling differs only by case. + assert "Operation not permitted" in result + assert sentinel.read_text() == "synthetic-readonly"