Skip to content

Commit 3fdefdf

Browse files
committed
fix(sandbox): harden supervisor egress edges from adversarial review
Three findings from an adversarial review of the network-split + supervisor: - _maybe_start_egress only caught EgressBrokerError, so a socket bind/listen OSError inside start_egress_broker (fd exhaustion, permissions) escaped and leaked the temp socket dir. Now catches OSError too and fails closed (clean up + refuse the run). - The agent subprocess trusted the protect_paths it received; it now re-confirms cwd-containment at the boundary (defense in depth — the engine already filters them, and the Rust launcher validates, but a stray path should be dropped). - On hardened, `tool_network = "allowed"` ran tool states with no warning even though per-tool `allow_network=false` isolation can't be honored there (no per-child netns). It now warns loudly that every tool command shares the host network on hardened. (We warn rather than refuse: "allowed" is the operator's explicitly permissive choice, and refusing would block all tool machines on a hardened-only host, where blocked/carveouts are already refused.) Adds regression tests for the egress fail-closed cleanup and the subprocess protect-path re-validation.
1 parent 77e9afd commit 3fdefdf

4 files changed

Lines changed: 118 additions & 3 deletions

File tree

‎src/agent6/cli/egress.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@ def _maybe_start_egress(
151151
try:
152152
broker = start_egress_broker(endpoints, sock_dir=sock_dir)
153153
enter_network_isolation()
154-
except EgressBrokerError as exc:
154+
except (EgressBrokerError, OSError) as exc:
155+
# OSError covers a socket bind/listen failure inside start_egress_broker
156+
# (resource exhaustion, permissions). Fail closed: clean up the socket
157+
# dir and refuse the run rather than leak it or run unconfined.
155158
shutil.rmtree(sock_dir, ignore_errors=True)
156159
return None, None, f"could not establish agent-network confinement: {exc}"
157160
for ep in endpoints:

‎src/agent6/cli/machine_agent.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,14 @@ def _run_one(req: dict[str, Any]) -> dict[str, Any]:
9898
provider = _build_role_provider(
9999
cfg, "worker", transcript_sink=TranscriptSink(transcript_dir), budget=budget
100100
)
101+
# Re-confirm the cwd-containment invariant at the subprocess boundary
102+
# (defense in depth — the engine already filtered these).
103+
root_r = root.resolve()
104+
protect = tuple(
105+
rp
106+
for p in req.get("protect_paths", [])
107+
if (rp := Path(p).resolve()).is_relative_to(root_r)
108+
)
101109
dispatcher = ToolDispatcher(
102110
root=root,
103111
config=cfg,
@@ -107,7 +115,7 @@ def _run_one(req: dict[str, Any]) -> dict[str, Any]:
107115
graph_client=None,
108116
run_root_node_id=None,
109117
mcp_manager=None,
110-
extra_protect_paths=tuple(Path(p) for p in req.get("protect_paths", [])),
118+
extra_protect_paths=protect,
111119
)
112120
wf = Workflow(
113121
root=root,

‎src/agent6/cli/machine_cmds.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ def _machine_network_refusal(
353353
return None
354354

355355

356-
def _cmd_machine_run(path: Path, *, exit_on_wait: bool = False) -> int: # noqa: PLR0911
356+
def _cmd_machine_run(path: Path, *, exit_on_wait: bool = False) -> int: # noqa: PLR0911, PLR0912
357357
try:
358358
spec = load_machine(path)
359359
except MachineError as exc:
@@ -391,6 +391,16 @@ def _cmd_machine_run(path: Path, *, exit_on_wait: bool = False) -> int: # noqa:
391391
if refusal is not None:
392392
print(f"REFUSING: {refusal}", file=sys.stderr)
393393
return 2
394+
if tool_states and profile == "hardened" and cfg.sandbox.tool_network == "allowed":
395+
# hardened has no per-child netns, so a tool's allow_network = false
396+
# cannot be honored — every tool command shares the host network.
397+
# The operator opted into "allowed" (broad), so we warn, not refuse.
398+
print(
399+
"[agent6] note: on the hardened profile tool states are not"
400+
" network-isolated per-tool — every tool command shares the host"
401+
" network (per-tool allow_network needs the strict profile).",
402+
file=sys.stderr,
403+
)
394404
if has_agent_state:
395405
missing = _check_provider_keys(cfg)
396406
if missing is not None:

‎tests/unit/test_sandbox_network.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from __future__ import annotations
77

88
from pathlib import Path
9+
from typing import Any
910

1011
import pytest
1112

@@ -172,3 +173,96 @@ def _fake(*_a: object, **_k: object) -> object:
172173
out = machine_agent._run_one(req) # pyright: ignore[reportPrivateUsage]
173174
assert out["reason"] == "finish_run"
174175
assert out["payload"] == {"label": "ok"}
176+
177+
178+
def _stub_loop(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
179+
"""Stub the agent loop in machine_agent; return a dict capturing dispatcher kwargs."""
180+
from agent6.workflows.loop import RunResult
181+
182+
class _FakeWf:
183+
def __init__(self, **_kw: object) -> None:
184+
pass
185+
186+
def run(self, _prompt: str) -> RunResult:
187+
return RunResult(
188+
reason="finish_run",
189+
completed=True,
190+
summary="d",
191+
iterations=1,
192+
tool_calls=0,
193+
finish_payload={},
194+
)
195+
196+
captured: dict[str, Any] = {}
197+
198+
def _disp(**kw: object) -> object:
199+
captured.update(kw)
200+
return object()
201+
202+
def _prov(*_a: object, **_k: object) -> object:
203+
return object()
204+
205+
monkeypatch.setattr(machine_agent, "Workflow", _FakeWf)
206+
monkeypatch.setattr(machine_agent, "_build_role_provider", _prov)
207+
monkeypatch.setattr(machine_agent, "ToolDispatcher", _disp)
208+
return captured
209+
210+
211+
def test_run_one_drops_out_of_cwd_protect_paths(
212+
iso: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
213+
) -> None:
214+
captured = _stub_loop(monkeypatch)
215+
inside = iso / "m.asm.toml"
216+
inside.write_text("x", encoding="utf-8")
217+
outside = tmp_path.parent / "evil.asm.toml"
218+
outside.write_text("x", encoding="utf-8")
219+
req = {
220+
"cwd": str(iso),
221+
"root": str(iso),
222+
"overlay": {},
223+
"profile": "none",
224+
"transcript_dir": str(tmp_path / "t"),
225+
"protect_paths": [str(inside), str(outside)],
226+
"request": {
227+
"model": "claude-x",
228+
"prompt": "go",
229+
"timeout_s": 5.0,
230+
"provider": "anthropic",
231+
"thinking": None,
232+
"temperature": None,
233+
"max_usd": None,
234+
"max_input_tokens": None,
235+
"max_output_tokens": None,
236+
},
237+
}
238+
machine_agent._run_one(req) # pyright: ignore[reportPrivateUsage]
239+
# Only the in-cwd path survives the subprocess-boundary re-validation.
240+
assert captured["extra_protect_paths"] == (inside.resolve(),)
241+
242+
243+
def test_egress_fails_closed_and_cleans_up_on_socket_error(
244+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
245+
) -> None:
246+
import agent6.cli.egress as eg
247+
248+
sock = tmp_path / "egress-sock"
249+
250+
def _fake_mkdtemp(**_k: object) -> str:
251+
sock.mkdir()
252+
return str(sock)
253+
254+
def _boom(*_a: object, **_k: object) -> object:
255+
raise OSError("too many open files")
256+
257+
monkeypatch.setattr(eg.tempfile, "mkdtemp", _fake_mkdtemp)
258+
monkeypatch.setattr(eg, "start_egress_broker", _boom)
259+
cfg = validate_config(
260+
{
261+
"providers": {"anthropic": {"kind": "anthropic"}},
262+
"sandbox": {"agent_network": "providers"},
263+
}
264+
)
265+
broker, sock_dir, err = _maybe_start_egress(cfg, "strict")
266+
assert broker is None and sock_dir is None
267+
assert err is not None and "too many open files" in err
268+
assert not sock.exists() # the socket dir was cleaned up, not leaked

0 commit comments

Comments
 (0)