fix(exec): confine selected shells behind the sandbox launcher
Co-authored-by: Tenable Research <152317477+tenbbughunters@users.noreply.github.com>
This commit is contained in:
1 parent
c8dba74fc5
commit
4dd3fbecb6
5 files changed
+212
-21
No files matched your search
@@ -2375,6 +2375,8 @@ The tool result distinguishes a hard-runtime termination from inactivity. With `
|
||||
Silence is not proof that a command is stuck: builds, downloads, and buffered programs can be quiet while working. Only bytes received through stdout or stderr count as activity; output redirected to files is not observed, and reading logs does not refresh the inactivity clock. Inactivity checks do not detect prompts or supply answers. Choose `"terminate"` only when stopping a quiet command is acceptable, and use a finite hard runtime when total execution time must remain bounded. Shell sessions are not durable jobs and should not be used as a replacement for a scheduler or service manager. A command that detaches a background service and exits is not a managed job; these timing checks do not manage that service afterward.
|
||||
|
||||
|
||||
With a Unix sandbox enabled, the selected shell and any requested login profile run inside the sandbox, with its workspace-scoped `HOME`. Custom interpreters outside the exposed system paths require an explicit read-only bind. Tool PATH settings affect commands inside the sandbox, not selection of the host launcher. Install `bwrap` in the operating system's default executable search path (normally `/bin:/usr/bin`); a custom parent or tool `PATH` cannot override that launcher. Seatbelt uses `/usr/bin/sandbox-exec`. A missing or failed launcher never falls back to unsandboxed execution.
|
||||
|
||||
## Pairing
|
||||
|
||||
Pairing lets users get access to the bot through a simple code exchange — no config editing required. This works for both new users and existing users connecting from a new channel (e.g. someone already approved on Telegram now setting up Discord).
|
||||
|
||||
@@ -429,25 +429,6 @@ class ExecTool(Tool):
|
||||
if guard_error:
|
||||
return guard_error
|
||||
|
||||
if self.sandbox:
|
||||
if _IS_WINDOWS:
|
||||
logger.warning(
|
||||
"Sandbox '{}' is not supported on Windows; running unsandboxed",
|
||||
self.sandbox,
|
||||
)
|
||||
else:
|
||||
workspace = workspace_root or cwd
|
||||
wrapped = wrap_command(
|
||||
self.sandbox,
|
||||
shlex.join(command) if isinstance(command, list) else command,
|
||||
workspace,
|
||||
cwd,
|
||||
sandbox_ro_binds=[str(p) for p in self.sandbox_ro_binds],
|
||||
sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds],
|
||||
)
|
||||
command = shlex.split(wrapped) if isinstance(command, list) else wrapped
|
||||
cwd = str(Path(workspace).resolve())
|
||||
|
||||
effective_timeout = self._resolve_timeout(timeout)
|
||||
env = self._build_env()
|
||||
|
||||
@@ -464,6 +445,39 @@ class ExecTool(Tool):
|
||||
if shell_error:
|
||||
return shell_error
|
||||
|
||||
if self.sandbox:
|
||||
if _IS_WINDOWS:
|
||||
logger.warning(
|
||||
"Sandbox '{}' is not supported on Windows; running unsandboxed",
|
||||
self.sandbox,
|
||||
)
|
||||
else:
|
||||
# The host launches the sandbox, not a caller-selected shell.
|
||||
# Shell selection, profiles and PATH setup run after confinement.
|
||||
if isinstance(command, list):
|
||||
payload = shlex.join(command)
|
||||
else:
|
||||
interpreter = shell_program or shutil.which("bash") or "/bin/bash"
|
||||
args = [interpreter]
|
||||
if login and Path(interpreter).name in {"bash", "zsh"}:
|
||||
args.append("-l")
|
||||
payload = shlex.join([*args, "-c", command])
|
||||
workspace = workspace_root or cwd
|
||||
command = shlex.split(wrap_command(
|
||||
self.sandbox,
|
||||
payload,
|
||||
workspace,
|
||||
cwd,
|
||||
sandbox_ro_binds=[str(p) for p in self.sandbox_ro_binds],
|
||||
sandbox_rw_binds=[str(p) for p in self.sandbox_rw_binds],
|
||||
))
|
||||
# Project/tool and inherited PATH can contain writable programs.
|
||||
launcher = shutil.which(command[0], path=os.defpath)
|
||||
if launcher is None:
|
||||
return ToolResult.error(f"Error: sandbox launcher not found: {command[0]}")
|
||||
command[0] = str(Path(launcher).absolute())
|
||||
cwd = str(Path(workspace).resolve())
|
||||
|
||||
return _PreparedCommand(
|
||||
command=command,
|
||||
cwd=cwd,
|
||||
|
||||
@@ -529,6 +529,7 @@ class TestSandboxPlatform:
|
||||
|
||||
with (
|
||||
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
|
||||
patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: f"/usr/bin/{name}"),
|
||||
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap,
|
||||
patch.object(ExecTool, "_spawn", return_value=mock_proc) as mock_spawn,
|
||||
patch.object(ExecTool, "_guard_command", return_value=None),
|
||||
@@ -538,7 +539,8 @@ class TestSandboxPlatform:
|
||||
|
||||
mock_wrap.assert_called_once()
|
||||
spawned_cmd = mock_spawn.call_args[0][0]
|
||||
assert backend in spawned_cmd
|
||||
assert isinstance(spawned_cmd, list)
|
||||
assert spawned_cmd[0] == f"/usr/bin/{backend}"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
|
||||
@@ -549,6 +551,7 @@ class TestSandboxPlatform:
|
||||
|
||||
with (
|
||||
patch("nanobot.agent.tools.shell._IS_WINDOWS", False),
|
||||
patch("nanobot.agent.tools.shell.shutil.which", side_effect=lambda name, **_kwargs: f"/usr/bin/{name}"),
|
||||
patch("nanobot.agent.tools.shell.wrap_command", return_value=f"{backend} -- sh -c ls") as mock_wrap,
|
||||
patch.object(ExecTool, "_spawn", return_value=mock_proc),
|
||||
patch.object(ExecTool, "_guard_command", return_value=None),
|
||||
|
||||
@@ -224,11 +224,12 @@ async def test_direct_search_uses_configured_path(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
|
||||
def test_direct_search_preserves_sandbox_and_arguments(tmp_path, monkeypatch, backend):
|
||||
monkeypatch.setattr("nanobot.agent.tools.shell._IS_WINDOWS", False)
|
||||
monkeypatch.setattr("nanobot.agent.tools.shell.shutil.which", lambda name, **_kwargs: f"/usr/bin/{name}" if "/" not in name else name)
|
||||
args = ["rg", "-F", "hello | $HOME; 'world'", "."]
|
||||
prepared = RgTool(working_dir=str(tmp_path), sandbox=backend)._prepare_command(args)
|
||||
assert isinstance(prepared, _PreparedCommand)
|
||||
assert isinstance(prepared.command, list)
|
||||
assert prepared.command[0] == ("bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec")
|
||||
assert prepared.command[0] == ("/usr/bin/bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec")
|
||||
assert prepared.command[-2] == "-c"
|
||||
inner_command = prepared.command[-1].split("\n")[-1]
|
||||
assert shlex.split(inner_command) == args
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Native isolation at the public exec boundary, using synthetic canaries only."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.exec_session import ExecSessionManager, ExecSessionTool
|
||||
from nanobot.agent.tools.shell import ExecTool
|
||||
|
||||
BACKEND = "seatbelt" if sys.platform == "darwin" else "bwrap"
|
||||
pytestmark = pytest.mark.skipif(
|
||||
sys.platform not in {"darwin", "linux"}
|
||||
or shutil.which("sandbox-exec" if BACKEND == "seatbelt" else "bwrap") is None,
|
||||
reason="requires a native Unix sandbox",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("session", [False, True])
|
||||
@pytest.mark.parametrize("symlink", [False, True])
|
||||
@pytest.mark.parametrize("shell_name", ["bash", "sh", "zsh"])
|
||||
async def test_selected_shell_runs_inside_sandbox(tmp_path, monkeypatch, session, symlink, shell_name):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside-canary"
|
||||
outside.write_text("unchanged")
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
script = workspace / ("interpreter" if symlink else shell_name)
|
||||
script.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f"cat {shlex.quote(str(outside))}\n"
|
||||
f"printf escaped > {shlex.quote(str(outside))}\n"
|
||||
"printf contained > inside-canary\n"
|
||||
"printf shell-ran\n"
|
||||
)
|
||||
script.chmod(0o700)
|
||||
shell = workspace / shell_name
|
||||
if symlink:
|
||||
shell.symlink_to(script)
|
||||
manager = ExecSessionManager()
|
||||
tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND, session_manager=manager)
|
||||
try:
|
||||
result = await tool.execute(
|
||||
command="printf legitimate", shell=str(shell), timeout=5,
|
||||
yield_time_ms=0 if session else None,
|
||||
)
|
||||
match = re.search(r"session_id:\s*([0-9a-f]+)", result)
|
||||
if match:
|
||||
final = await ExecSessionTool(manager=manager).execute(
|
||||
session_id=match.group(1), until_exit=True, timeout_ms=5000,
|
||||
)
|
||||
result = f"{result}\n{final}"
|
||||
finally:
|
||||
await manager.close_all()
|
||||
assert "Exit code: 0" in result, result
|
||||
assert "shell-ran" in result, result
|
||||
assert "unchanged" not in result
|
||||
assert outside.read_text() == "unchanged"
|
||||
assert (workspace / "inside-canary").read_text() == "contained"
|
||||
|
||||
|
||||
async def test_sandboxed_shell_preserves_ordinary_bash_commands(tmp_path, monkeypatch):
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND)
|
||||
result = await tool.execute(command="items=(hello world); printf '%s' \"${items[1]}\"", shell="bash")
|
||||
assert result.startswith("world\nExit code: 0\n"), result
|
||||
|
||||
|
||||
async def test_configured_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch):
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
impostor = tmp_path / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap")
|
||||
impostor.write_text("#!/bin/sh\nprintf shadowed-launcher")
|
||||
impostor.chmod(0o700)
|
||||
tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND, path_prepend=str(tmp_path))
|
||||
result = await tool.execute(command="printf contained")
|
||||
assert result.startswith("contained\nExit code: 0\n"), result
|
||||
|
||||
|
||||
async def test_login_profile_runs_inside_sandbox(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside-canary"
|
||||
outside.write_text("unchanged")
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
(workspace / ".bash_profile").write_text(
|
||||
f"printf escaped > {shlex.quote(str(outside))}\n"
|
||||
"export SANDBOX_PROFILE_LOADED=yes\n"
|
||||
)
|
||||
tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND)
|
||||
result = await tool.execute(command='printf "%s" "$SANDBOX_PROFILE_LOADED"', shell="bash", login=True)
|
||||
assert "yes" in result, result
|
||||
assert outside.read_text() == "unchanged"
|
||||
|
||||
|
||||
async def test_parent_path_cannot_replace_sandbox_launcher(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
outside = tmp_path / "outside-canary"
|
||||
outside.write_text("unchanged")
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
impostor = workspace / ("sandbox-exec" if BACKEND == "seatbelt" else "bwrap")
|
||||
impostor.write_text(
|
||||
"#!/bin/sh\n"
|
||||
f"printf escaped > {shlex.quote(str(outside))}\n"
|
||||
"printf shadowed-launcher\n"
|
||||
)
|
||||
impostor.chmod(0o700)
|
||||
monkeypatch.setenv("PATH", f"{workspace}{os.pathsep}{os.defpath}")
|
||||
tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND)
|
||||
|
||||
result = await tool.execute(command="printf contained")
|
||||
|
||||
assert result.startswith("contained\nExit code: 0\n"), result
|
||||
assert outside.read_text() == "unchanged"
|
||||
|
||||
|
||||
async def test_missing_launcher_does_not_run_command_unsandboxed(tmp_path, monkeypatch):
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
original_which = shutil.which
|
||||
launcher = "/usr/bin/sandbox-exec" if BACKEND == "seatbelt" else "bwrap"
|
||||
monkeypatch.setattr(
|
||||
"nanobot.agent.tools.shell.shutil.which",
|
||||
lambda name, **kwargs: None if name == launcher else original_which(name, **kwargs),
|
||||
)
|
||||
tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND)
|
||||
|
||||
result = await tool.execute(command="printf ran > must-not-exist")
|
||||
|
||||
assert "sandbox launcher not found" in result
|
||||
assert not (tmp_path / "must-not-exist").exists()
|
||||
|
||||
|
||||
async def test_trusted_shell_completion_preserves_sandbox(tmp_path, monkeypatch):
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
tool = ExecTool(working_dir=str(workspace), sandbox=BACKEND)
|
||||
|
||||
result = await tool.execute_to_completion("printf complete > result", str(workspace))
|
||||
|
||||
assert "Exit code: 0" in result, result
|
||||
assert (workspace / "result").read_text() == "complete"
|
||||
|
||||
|
||||
async def test_sandbox_preserves_literal_argument_vector(tmp_path, monkeypatch):
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
monkeypatch.setattr("nanobot.agent.tools.sandbox.get_media_dir", lambda: media)
|
||||
tool = ExecTool(working_dir=str(tmp_path), sandbox=BACKEND)
|
||||
literal = "hello | $HOME; 'world'"
|
||||
|
||||
result = await tool.execute(command=["printf", "%s", literal])
|
||||
|
||||
assert result.startswith(f"{literal}\nExit code: 0\n"), result
|
||||
Reference in new issue
Block a user