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)
|
||||
|
||||
@@ -28,6 +28,7 @@ UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
|
||||
UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
|
||||
CONTEXT_GRAPH_REFERENCES_CAPABILITY = "webui.context-graph.references.v1"
|
||||
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
|
||||
SANDBOX_SETTINGS_CAPABILITY = "webui.sandbox-settings.v1"
|
||||
|
||||
|
||||
class Compatibility(TypedDict):
|
||||
@@ -48,6 +49,7 @@ def webui_contract() -> dict[str, object]:
|
||||
UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
|
||||
UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
|
||||
PROMPT_NAVIGATION_CAPABILITY, CONTEXT_GRAPH_REFERENCES_CAPABILITY,
|
||||
SANDBOX_SETTINGS_CAPABILITY,
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -131,6 +131,7 @@ _CAPABILITY_ROUTES = {
|
||||
}
|
||||
|
||||
_SYSTEM_ROUTES = {
|
||||
"/api/settings/sandbox/check": "sandbox-check",
|
||||
"/api/settings/runtime-config/update": "runtime-config-update",
|
||||
"/api/settings/cli-apps": "cli-list",
|
||||
"/api/settings/cli-apps/install": "cli-install",
|
||||
@@ -162,6 +163,7 @@ _SYSTEM_ROUTES = {
|
||||
}
|
||||
|
||||
_SETTINGS_MUTATION_PATHS = frozenset({
|
||||
"/api/settings/sandbox/check",
|
||||
"/api/settings/nanobot-update/channel",
|
||||
"/api/settings/nanobot-update/plan/create",
|
||||
"/api/settings/nanobot-update/job/prepare",
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import ipaddress
|
||||
import math
|
||||
import re
|
||||
from pathlib import PurePosixPath, PureWindowsPath
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from typing import Any, cast
|
||||
|
||||
from pydantic import BaseModel, TypeAdapter, ValidationError
|
||||
@@ -33,6 +33,7 @@ RUNTIME_CONFIG_PATHS = (
|
||||
"tools.exec.path_prepend",
|
||||
"tools.exec.path_append",
|
||||
"tools.exec.sandbox",
|
||||
"tools.exec.sandbox_launcher",
|
||||
"tools.exec.sandbox_ro_binds",
|
||||
"tools.exec.sandbox_rw_binds",
|
||||
"tools.exec.allowed_env_keys",
|
||||
@@ -152,6 +153,19 @@ def update_runtime_config(
|
||||
raise WebUISettingsError("Set an API key in System before using a network bind address.")
|
||||
if "tools.exec.sandbox" in values and validated.tools.exec.sandbox not in {"", "bwrap", "seatbelt"}:
|
||||
raise WebUISettingsError("tools.exec.sandbox: choose no sandbox, bwrap, or seatbelt")
|
||||
if {"tools.exec.sandbox_launcher", "tools.exec.sandbox_rw_binds"} & values.keys() and validated.tools.exec.sandbox_launcher:
|
||||
from nanobot.agent.tools.sandbox_launcher import (
|
||||
SandboxLauncherError,
|
||||
resolve_sandbox_launcher,
|
||||
)
|
||||
|
||||
try:
|
||||
resolve_sandbox_launcher(
|
||||
validated.tools.exec.sandbox, validated.tools.exec.sandbox_launcher,
|
||||
writable_roots=(validated.workspace_path, *map(Path, validated.tools.exec.sandbox_rw_binds)),
|
||||
)
|
||||
except SandboxLauncherError as exc:
|
||||
raise WebUISettingsError(f"sandbox_launcher_{exc.reason}") from None
|
||||
if "tools.ssrf_whitelist" in values:
|
||||
for cidr in validated.tools.ssrf_whitelist:
|
||||
try:
|
||||
|
||||
@@ -17,6 +17,7 @@ import httpx
|
||||
from pydantic import ValidationError
|
||||
from pydantic.alias_generators import to_snake
|
||||
|
||||
from nanobot.agent.tools.sandbox_check import check_sandbox, sandbox_settings_status
|
||||
from nanobot.build_info import COMMIT
|
||||
from nanobot.channels._setup import channel_setup_spec
|
||||
from nanobot.channels.connect import ChannelConnectError, ChannelConnector, ManagedChannelConnector
|
||||
@@ -167,6 +168,7 @@ def system_settings_payload(
|
||||
"exec_enabled": exec_config.enable,
|
||||
"exec_max_runtime_limit": exec_config.max_runtime_limit,
|
||||
"exec_sandbox": exec_config.sandbox or None,
|
||||
"exec_sandbox_status": sandbox_settings_status(exec_config, config.workspace_path),
|
||||
"exec_path_prepend_set": bool(exec_config.path_prepend),
|
||||
"exec_path_append_set": bool(exec_config.path_append),
|
||||
},
|
||||
@@ -457,6 +459,7 @@ class SystemSettingsHandler:
|
||||
self._closing_connectors = False
|
||||
self._update_jobs = UpdateJobService()
|
||||
self._remove_update_work: Callable[[], None] | None = None
|
||||
self._sandbox_check_running = False
|
||||
|
||||
def _has_pending_connectors(self) -> bool:
|
||||
return self._closing_connectors or any(
|
||||
@@ -503,6 +506,17 @@ class SystemSettingsHandler:
|
||||
channel_name: str | None = None,
|
||||
connect_action: str | None = None,
|
||||
) -> SettingsRouteResult:
|
||||
if action == "sandbox-check":
|
||||
if self._sandbox_check_running:
|
||||
return SettingsRouteResult.failure(409, "sandbox_check_busy")
|
||||
self._sandbox_check_running = True
|
||||
try:
|
||||
config = await asyncio.to_thread(self.settings.config.load)
|
||||
return SettingsRouteResult.success({
|
||||
"sandbox": await check_sandbox(config.tools.exec, config.workspace_path),
|
||||
})
|
||||
finally:
|
||||
self._sandbox_check_running = False
|
||||
if action == "runtime-config-update":
|
||||
values = (request.payload or {}).get("values")
|
||||
if not isinstance(values, dict):
|
||||
|
||||
@@ -217,6 +217,7 @@ _WEBUI_MUTATION_PATHS = {
|
||||
"settings.image_generation.update": "/api/settings/image-generation/update",
|
||||
"settings.transcription.update": "/api/settings/transcription/update",
|
||||
"settings.runtime_config.update": "/api/settings/runtime-config/update",
|
||||
"settings.sandbox.check": "/api/settings/sandbox/check",
|
||||
"settings.network_safety.update": "/api/settings/network-safety/update",
|
||||
"settings.cli_app.install": "/api/settings/cli-apps/install",
|
||||
"settings.cli_app.update": "/api/settings/cli-apps/update",
|
||||
|
||||
Reference in new issue
Block a user