feat(settings): check sandbox launchers and configure protected paths
This commit is contained in:
1 parent
f158779c60
commit
5b84b78cac
33 files changed
+1179
-20
No files matched your search
@@ -0,0 +1,115 @@
|
||||
"""Bounded, explicit checks of saved shell sandbox settings, without a model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import signal
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from nanobot.agent.tools.sandbox import wrap_command
|
||||
from nanobot.agent.tools.sandbox_launcher import (
|
||||
SandboxLauncherError,
|
||||
resolve_sandbox_launcher,
|
||||
sandbox_platform,
|
||||
)
|
||||
from nanobot.agent.tools.shell_config import ExecToolConfig
|
||||
|
||||
_PROBE_TIMEOUT_S = 5
|
||||
|
||||
|
||||
class SandboxCheck(TypedDict):
|
||||
state: str
|
||||
reason: str
|
||||
launcher: str | None
|
||||
revision: str
|
||||
supported_backend: str | None
|
||||
|
||||
|
||||
def sandbox_settings_status(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
|
||||
import sys
|
||||
|
||||
backend = "bwrap" if sys.platform.startswith("linux") else "seatbelt" if sys.platform == "darwin" else None
|
||||
revision = hashlib.sha256(json.dumps(
|
||||
{"config": config.model_dump(), "workspace": str(workspace)}, sort_keys=True,
|
||||
).encode()).hexdigest()
|
||||
result: SandboxCheck = {
|
||||
"state": "unchecked", "reason": "", "launcher": None,
|
||||
"revision": revision, "supported_backend": backend,
|
||||
}
|
||||
if not config.enable:
|
||||
result["state"] = "disabled"
|
||||
elif not config.sandbox:
|
||||
result["state"] = "off"
|
||||
elif sandbox_platform(config.sandbox) == "unsupported":
|
||||
result.update(state="unsupported", reason="platform_unsupported")
|
||||
else:
|
||||
try:
|
||||
result["launcher"] = resolve_sandbox_launcher(
|
||||
config.sandbox, config.sandbox_launcher,
|
||||
writable_roots=(workspace, *map(Path, config.sandbox_rw_binds)),
|
||||
)
|
||||
except SandboxLauncherError as exc:
|
||||
result.update(state="unavailable", reason=exc.reason)
|
||||
return result
|
||||
|
||||
|
||||
async def check_sandbox(config: ExecToolConfig, workspace: Path) -> SandboxCheck:
|
||||
result = await asyncio.to_thread(sandbox_settings_status, config, workspace)
|
||||
if result["state"] != "unchecked":
|
||||
return result
|
||||
# Use synthetic files only. Never run startup/login profiles or an arbitrary
|
||||
# user-provided test command. This is a basic probe, not a full security audit.
|
||||
with tempfile.TemporaryDirectory(prefix="nanobot-sandbox-check-") as directory:
|
||||
root = Path(directory).resolve()
|
||||
project = root / "workspace"
|
||||
project.mkdir()
|
||||
canary = root / "outside"
|
||||
canary.write_text("unchanged")
|
||||
script = (
|
||||
"printf checked > inside && "
|
||||
f"! test -r {shlex.quote(str(canary))} && "
|
||||
f"! (printf changed > {shlex.quote(str(canary))})"
|
||||
)
|
||||
argv = shlex.split(wrap_command(
|
||||
config.sandbox, script, str(project), str(project),
|
||||
sandbox_ro_binds=config.sandbox_ro_binds,
|
||||
sandbox_rw_binds=config.sandbox_rw_binds,
|
||||
))
|
||||
# Same resolver and wrapper as ExecTool. Recheck against the probe root.
|
||||
try:
|
||||
argv[0] = resolve_sandbox_launcher(
|
||||
config.sandbox, config.sandbox_launcher,
|
||||
writable_roots=(project, *map(Path, config.sandbox_rw_binds)),
|
||||
)
|
||||
result["launcher"] = argv[0]
|
||||
except SandboxLauncherError as exc:
|
||||
result.update(state="unavailable", reason=exc.reason)
|
||||
return result
|
||||
process: asyncio.subprocess.Process | None = None
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*argv, cwd=str(project), env={"PATH": os.defpath, "HOME": str(project)},
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL, start_new_session=True,
|
||||
)
|
||||
await asyncio.wait_for(process.wait(), timeout=_PROBE_TIMEOUT_S)
|
||||
success = process.returncode == 0 and (project / "inside").read_text() == "checked" and canary.read_text() == "unchanged"
|
||||
result.update(state="passed" if success else "unavailable", reason="" if success else "probe_failed")
|
||||
except TimeoutError:
|
||||
result.update(state="unavailable", reason="probe_timeout")
|
||||
except OSError:
|
||||
result.update(state="unavailable", reason="probe_failed")
|
||||
finally:
|
||||
if process is not None and process.returncode is None:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
await process.wait()
|
||||
return result
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Resolve sandbox launchers without trusting the agent's command search path."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
|
||||
class SandboxLauncherError(ValueError):
|
||||
def __init__(self, reason: str):
|
||||
self.reason = reason
|
||||
super().__init__(reason)
|
||||
|
||||
|
||||
def sandbox_platform(backend: str) -> Literal["supported", "unsupported"]:
|
||||
import sys
|
||||
|
||||
return "supported" if (backend == "bwrap" and sys.platform.startswith("linux")) or (
|
||||
backend == "seatbelt" and sys.platform == "darwin"
|
||||
) else "unsupported"
|
||||
|
||||
|
||||
def resolve_sandbox_launcher(
|
||||
backend: str, custom_path: str = "", *, writable_roots: tuple[Path, ...] = (),
|
||||
) -> str:
|
||||
"""Keep default lookup unchanged; explicit overrides require a protected install.
|
||||
|
||||
A configured filename is not proof of provenance. The administrator must
|
||||
trust its publisher. Root ownership and non-writable ancestors prevent
|
||||
ordinary agent processes from replacing an override before confinement.
|
||||
"""
|
||||
name = "bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec"
|
||||
if not custom_path:
|
||||
launcher = shutil.which(name, path=os.defpath)
|
||||
if launcher is None:
|
||||
raise SandboxLauncherError("launcher_missing")
|
||||
return str(Path(launcher).absolute())
|
||||
if os.name != "posix":
|
||||
raise SandboxLauncherError("platform_unsupported")
|
||||
candidate = Path(custom_path)
|
||||
if not candidate.is_absolute():
|
||||
raise SandboxLauncherError("path_not_absolute")
|
||||
try:
|
||||
resolved = candidate.resolve(strict=True)
|
||||
metadata = resolved.stat()
|
||||
if not stat.S_ISREG(metadata.st_mode) or not os.access(resolved, os.X_OK):
|
||||
raise SandboxLauncherError("not_executable")
|
||||
for root in writable_roots:
|
||||
root = Path(os.path.expandvars(str(root))).expanduser()
|
||||
if root.is_absolute() and resolved.is_relative_to(root.resolve()):
|
||||
raise SandboxLauncherError("agent_writable")
|
||||
for item in (resolved, *resolved.parents):
|
||||
info = item.stat()
|
||||
if (info.st_uid != 0 or info.st_mode & (stat.S_IWGRP | stat.S_IWOTH)
|
||||
or (os.geteuid() != 0 and os.access(item, os.W_OK))):
|
||||
raise SandboxLauncherError("unprotected_installation")
|
||||
except (OSError, RuntimeError):
|
||||
raise SandboxLauncherError("path_unavailable") from None
|
||||
return str(resolved)
|
||||
@@ -29,6 +29,7 @@ from nanobot.agent.tools.exec_session import (
|
||||
format_session_poll,
|
||||
)
|
||||
from nanobot.agent.tools.sandbox import wrap_command
|
||||
from nanobot.agent.tools.sandbox_launcher import SandboxLauncherError, resolve_sandbox_launcher
|
||||
from nanobot.agent.tools.schema import (
|
||||
BooleanSchema,
|
||||
IntegerSchema,
|
||||
@@ -178,6 +179,7 @@ class ExecTool(Tool):
|
||||
restrict_to_workspace=ctx.config.restrict_to_workspace,
|
||||
webui_allow_local_service_access=ctx.config.webui_allow_local_service_access,
|
||||
sandbox=cfg.sandbox,
|
||||
sandbox_launcher=cfg.sandbox_launcher,
|
||||
path_prepend=cfg.path_prepend,
|
||||
path_append=cfg.path_append,
|
||||
sandbox_ro_binds=cfg.sandbox_ro_binds,
|
||||
@@ -209,6 +211,7 @@ class ExecTool(Tool):
|
||||
max_runtime_limit: int | None = None,
|
||||
idle_timeout: int = 300,
|
||||
idle_action: Literal["report", "terminate"] = "report",
|
||||
sandbox_launcher: str = "",
|
||||
):
|
||||
if timeout is not None and max_runtime is not None:
|
||||
raise ValueError("timeout and max_runtime are mutually exclusive")
|
||||
@@ -220,6 +223,7 @@ class ExecTool(Tool):
|
||||
self._exec_config = ExecToolConfig.model_validate(values)
|
||||
self.working_dir = working_dir
|
||||
self.sandbox = sandbox
|
||||
self.sandbox_launcher = sandbox_launcher
|
||||
self.deny_patterns = (deny_patterns or []) + [
|
||||
r"\brm\s+-[rf]{1,2}\b",
|
||||
r"\bdel\s+/[fq]\b",
|
||||
@@ -472,10 +476,15 @@ class ExecTool(Tool):
|
||||
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())
|
||||
try:
|
||||
command[0] = resolve_sandbox_launcher(
|
||||
self.sandbox, self.sandbox_launcher,
|
||||
writable_roots=(Path(workspace), *self.sandbox_rw_binds),
|
||||
)
|
||||
except SandboxLauncherError as exc:
|
||||
if exc.reason == "launcher_missing":
|
||||
return ToolResult.error(f"Error: sandbox launcher not found: {command[0]}")
|
||||
return ToolResult.error(f"Error: sandbox launcher rejected: {exc.reason}")
|
||||
cwd = str(Path(workspace).resolve())
|
||||
|
||||
return _PreparedCommand(
|
||||
|
||||
@@ -19,6 +19,7 @@ class ExecToolConfig(Base):
|
||||
path_prepend: str = ""
|
||||
path_append: str = ""
|
||||
sandbox: str = ""
|
||||
sandbox_launcher: str = ""
|
||||
sandbox_ro_binds: list[str] = Field(default_factory=list)
|
||||
sandbox_rw_binds: list[str] = Field(default_factory=list)
|
||||
allowed_env_keys: list[str] = Field(default_factory=list)
|
||||
|
||||
Reference in new issue
Block a user