mirror of
https://github.com/yashshah9/agentbox.git
synced 2026-11-18 18:03:44 +00:00
fix(v0.8.1): soft egress honesty, fetch hooks, localhost SSRF
Do not claim network_isolated for soft allowlists; patch Node fetch/http; require explicit localhost allowlisting; merge PYTHONPATH/NODE_OPTIONS.
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## [0.8.1] - 2026-09-19
|
||||
|
||||
- Honest soft-allowlist isolation; Node fetch/http hooks; localhost SSRF guard
|
||||
|
||||
|
||||
## [0.8.0] - 2026-09-18
|
||||
|
||||
### Added
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "agentbox-sandbox"
|
||||
version = "0.8.0"
|
||||
version = "0.8.1"
|
||||
description = "Self-hosted code execution sandbox for AI agents"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
||||
@@ -104,7 +104,7 @@ class DockerSandbox:
|
||||
container_name=name,
|
||||
extra_env=extra_env,
|
||||
)
|
||||
network_isolated = self.deny_egress
|
||||
network_isolated = self.deny_egress and not effective
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
argv,
|
||||
|
||||
@@ -90,8 +90,9 @@ _orig_connect = socket.socket.connect
|
||||
|
||||
def _host_ok(host: str) -> bool:
|
||||
h = (host or "").lower().strip("[]")
|
||||
if not h or h in {{"localhost", "127.0.0.1", "::1"}}:
|
||||
if not h:
|
||||
return True
|
||||
# localhost/loopback only if explicitly allowlisted (SSRF guard)
|
||||
if h in _ALLOWED_HOSTS or h in _ALLOWED_IPS:
|
||||
return True
|
||||
try:
|
||||
@@ -133,37 +134,100 @@ socket.socket.connect = _connect
|
||||
|
||||
|
||||
def install_node_hook(workspace: Path, hosts: list[str]) -> dict[str, str]:
|
||||
"""Write Node --require preload; return env vars to enable it."""
|
||||
"""Write Node --require preload; return env vars to enable it.
|
||||
|
||||
Covers net.Socket, net.connect, http(s).request/get, and global fetch
|
||||
(undici on Node 18+) — soft filter only, not a kernel firewall.
|
||||
"""
|
||||
path = workspace / ".agentbox_egress_preload.js"
|
||||
hosts_json = json.dumps(hosts)
|
||||
path.write_text(
|
||||
f"""/* agentbox egress soft allowlist — auto-generated */
|
||||
const net = require('net');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const {{ URL }} = require('url');
|
||||
const allowed = new Set({hosts_json}.map((h) => String(h).toLowerCase()));
|
||||
const allowedHosts = new Set([...allowed].map((h) => h.split(':')[0]));
|
||||
function hostOk(host) {{
|
||||
if (!host) return true;
|
||||
const h = String(host).toLowerCase().replace(/^\\[|\\]$/g, '');
|
||||
if (h === 'localhost' || h === '127.0.0.1' || h === '::1') return true;
|
||||
// localhost/loopback only if explicitly allowlisted (SSRF guard)
|
||||
return allowedHosts.has(h) || allowed.has(h);
|
||||
}}
|
||||
function deny(host) {{
|
||||
const err = new Error('agentbox egress denied: ' + host);
|
||||
err.code = 'EGRESS_DENIED';
|
||||
throw err;
|
||||
}}
|
||||
function hostFromConnectArgs(args) {{
|
||||
if (typeof args[0] === 'object' && args[0] !== null) {{
|
||||
return args[0].host || args[0].hostname || null;
|
||||
}}
|
||||
if (typeof args[1] === 'string') return args[1];
|
||||
if (typeof args[0] === 'string' && args[0].includes(':')) {{
|
||||
return args[0].split(':')[0];
|
||||
}}
|
||||
return null;
|
||||
}}
|
||||
function hostFromRequestArgs(args) {{
|
||||
let url = null;
|
||||
let opts = null;
|
||||
if (typeof args[0] === 'string' || args[0] instanceof URL) {{
|
||||
url = args[0];
|
||||
opts = typeof args[1] === 'object' ? args[1] : null;
|
||||
}} else if (typeof args[0] === 'object' && args[0] !== null) {{
|
||||
opts = args[0];
|
||||
}}
|
||||
if (opts && (opts.hostname || opts.host)) {{
|
||||
return opts.hostname || String(opts.host).split(':')[0];
|
||||
}}
|
||||
if (url) {{
|
||||
try {{ return new URL(url).hostname; }} catch (_) {{ return null; }}
|
||||
}}
|
||||
return null;
|
||||
}}
|
||||
function assertHost(host) {{
|
||||
if (host && !hostOk(host)) deny(host);
|
||||
}}
|
||||
const origConnect = net.Socket.prototype.connect;
|
||||
net.Socket.prototype.connect = function (...args) {{
|
||||
let host = null;
|
||||
if (typeof args[0] === 'object' && args[0] !== null) {{
|
||||
host = args[0].host || args[0].hostname;
|
||||
}} else if (typeof args[1] === 'string') {{
|
||||
host = args[1];
|
||||
}} else if (typeof args[0] === 'string' && args[0].includes(':')) {{
|
||||
host = args[0].split(':')[0];
|
||||
}}
|
||||
if (host && !hostOk(host)) {{
|
||||
const err = new Error('agentbox egress denied: ' + host);
|
||||
err.code = 'EGRESS_DENIED';
|
||||
throw err;
|
||||
}}
|
||||
assertHost(hostFromConnectArgs(args));
|
||||
return origConnect.apply(this, args);
|
||||
}};
|
||||
for (const name of ['connect', 'createConnection']) {{
|
||||
const orig = net[name];
|
||||
if (typeof orig !== 'function') continue;
|
||||
net[name] = function (...args) {{
|
||||
assertHost(hostFromConnectArgs(args));
|
||||
return orig.apply(this, args);
|
||||
}};
|
||||
}}
|
||||
function wrapHttp(mod) {{
|
||||
for (const name of ['request', 'get']) {{
|
||||
const orig = mod[name];
|
||||
if (typeof orig !== 'function') continue;
|
||||
mod[name] = function (...args) {{
|
||||
assertHost(hostFromRequestArgs(args));
|
||||
return orig.apply(this, args);
|
||||
}};
|
||||
}}
|
||||
}}
|
||||
wrapHttp(http);
|
||||
wrapHttp(https);
|
||||
if (typeof globalThis.fetch === 'function') {{
|
||||
const origFetch = globalThis.fetch;
|
||||
globalThis.fetch = function (input, init) {{
|
||||
let host = null;
|
||||
try {{
|
||||
const raw = typeof input === 'string' ? input
|
||||
: (input && typeof input.url === 'string' ? input.url : null);
|
||||
if (raw) host = new URL(raw).hostname;
|
||||
}} catch (_) {{}}
|
||||
assertHost(host);
|
||||
return origFetch.apply(this, arguments);
|
||||
}};
|
||||
}}
|
||||
""",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
@@ -96,21 +96,29 @@ class SubprocessSandbox:
|
||||
script.write_text(code, encoding="utf-8")
|
||||
argv = ["python3", str(script)]
|
||||
if self.deny_egress and effective:
|
||||
env.update(install_python_hook(workspace, effective))
|
||||
hook = install_python_hook(workspace, effective)
|
||||
prev = env.get("PYTHONPATH", "")
|
||||
env["PYTHONPATH"] = hook["PYTHONPATH"] + (
|
||||
(os.pathsep + prev) if prev else ""
|
||||
)
|
||||
elif lang in {"javascript", "node"}:
|
||||
script = workspace / "main.js"
|
||||
script.write_text(code, encoding="utf-8")
|
||||
node = shutil.which("node") or "node"
|
||||
argv = [node, str(script)]
|
||||
if self.deny_egress and effective:
|
||||
env.update(install_node_hook(workspace, effective))
|
||||
hook = install_node_hook(workspace, effective)
|
||||
prev = env.get("NODE_OPTIONS", "")
|
||||
require = hook["NODE_OPTIONS"]
|
||||
env["NODE_OPTIONS"] = f"{prev} {require}".strip() if prev else require
|
||||
else:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
network_isolated = False
|
||||
if self.deny_egress and not effective:
|
||||
argv, network_isolated = wrap_deny_egress(argv)
|
||||
elif self.deny_egress and effective:
|
||||
network_isolated = True
|
||||
# Soft allowlist keeps real networking; do not claim netns isolation.
|
||||
network_isolated = False
|
||||
preexec = _memory_preexec(mem) if mem else None
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
|
||||
@@ -102,7 +102,7 @@ def test_docker_sandbox_allowlist_skips_network_none(tmp_path: Path) -> None:
|
||||
):
|
||||
result = box.run("print(1)", language="python")
|
||||
|
||||
assert result.network_isolated is True
|
||||
assert result.network_isolated is False
|
||||
assert result.egress_allowlist == ["example.com"]
|
||||
argv = run_mock.call_args.args[0]
|
||||
assert "--network=none" not in argv
|
||||
|
||||
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from agentbox.sandbox.egress import (
|
||||
install_node_hook,
|
||||
install_python_hook,
|
||||
parse_allowlist,
|
||||
resolve_allowlist,
|
||||
@@ -44,7 +45,7 @@ def test_python_hook_blocks_disallowed(tmp_path: Path) -> None:
|
||||
" print('DENIED' if 'egress denied' in str(e) else type(e).__name__)\n",
|
||||
language="python",
|
||||
)
|
||||
assert result.network_isolated is True
|
||||
assert result.network_isolated is False
|
||||
assert result.egress_allowlist == ["example.com"]
|
||||
assert "DENIED" in result.stdout
|
||||
|
||||
@@ -61,13 +62,90 @@ def test_python_hook_allows_listed_host(tmp_path: Path) -> None:
|
||||
" print('ERR', type(e).__name__)\n",
|
||||
language="python",
|
||||
)
|
||||
assert result.network_isolated is True
|
||||
assert result.network_isolated is False
|
||||
# Offline CI may fail DNS; allow ERR URLError but never DENIED for listed host
|
||||
assert "DENIED" not in result.stdout
|
||||
assert "OK" in result.stdout or "ERR" in result.stdout
|
||||
|
||||
|
||||
def test_python_hook_blocks_localhost_unless_listed(tmp_path: Path) -> None:
|
||||
box = SubprocessSandbox(deny_egress=True, egress_allowlist=["example.com"], timeout_seconds=10)
|
||||
result = box.run(
|
||||
"import urllib.request\n"
|
||||
"try:\n"
|
||||
" urllib.request.urlopen('http://127.0.0.1:9/', timeout=2)\n"
|
||||
" print('REACHED')\n"
|
||||
"except OSError as e:\n"
|
||||
" print('DENIED' if 'egress denied' in str(e) else type(e).__name__)\n",
|
||||
language="python",
|
||||
)
|
||||
assert "DENIED" in result.stdout
|
||||
|
||||
|
||||
def test_python_hook_allows_explicit_localhost(tmp_path: Path) -> None:
|
||||
box = SubprocessSandbox(
|
||||
deny_egress=True, egress_allowlist=["127.0.0.1", "localhost"], timeout_seconds=10
|
||||
)
|
||||
result = box.run(
|
||||
"import urllib.request\n"
|
||||
"try:\n"
|
||||
" urllib.request.urlopen('http://127.0.0.1:9/', timeout=2)\n"
|
||||
" print('OK')\n"
|
||||
"except Exception as e:\n"
|
||||
" # Connection refused is fine — must not be egress denied\n"
|
||||
" print('DENIED' if 'egress denied' in str(e) else 'ERR')\n",
|
||||
language="python",
|
||||
)
|
||||
assert "DENIED" not in result.stdout
|
||||
assert "OK" in result.stdout or "ERR" in result.stdout
|
||||
|
||||
|
||||
def test_install_python_hook_writes_sitecustomize(tmp_path: Path) -> None:
|
||||
env = install_python_hook(tmp_path, ["api.openai.com"])
|
||||
assert (tmp_path / ".agentbox_egress" / "sitecustomize.py").is_file()
|
||||
assert "PYTHONPATH" in env
|
||||
|
||||
|
||||
def test_install_node_hook_covers_fetch(tmp_path: Path) -> None:
|
||||
env = install_node_hook(tmp_path, ["example.com"])
|
||||
text = (tmp_path / ".agentbox_egress_preload.js").read_text(encoding="utf-8")
|
||||
assert "NODE_OPTIONS" in env
|
||||
assert "globalThis.fetch" in text
|
||||
assert "wrapHttp" in text or "https.request" in text or "mod[name]" in text
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
__import__("shutil").which("node") is None, reason="node not installed"
|
||||
)
|
||||
def test_node_fetch_blocks_disallowed(tmp_path: Path) -> None:
|
||||
box = SubprocessSandbox(deny_egress=True, egress_allowlist=["example.com"], timeout_seconds=10)
|
||||
result = box.run(
|
||||
"try {\n"
|
||||
" const p = fetch('https://httpbin.org/get');\n"
|
||||
" p.then(() => console.log('REACHED'))"
|
||||
".catch((e) => console.log("
|
||||
"String(e && e.message || e).includes('egress denied') ? 'DENIED' : 'ERR'));\n"
|
||||
"} catch (e) {\n"
|
||||
" console.log(String(e.message || e).includes('egress denied') ? 'DENIED' : 'ERR');\n"
|
||||
"}\n",
|
||||
language="javascript",
|
||||
)
|
||||
assert result.network_isolated is False
|
||||
assert "DENIED" in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
__import__("shutil").which("node") is None, reason="node not installed"
|
||||
)
|
||||
def test_node_https_request_blocks_disallowed(tmp_path: Path) -> None:
|
||||
box = SubprocessSandbox(deny_egress=True, egress_allowlist=["example.com"], timeout_seconds=10)
|
||||
result = box.run(
|
||||
"const https = require('https');\n"
|
||||
"try {\n"
|
||||
" https.get('https://httpbin.org/get', () => console.log('REACHED'));\n"
|
||||
"} catch (e) {\n"
|
||||
" console.log(String(e.message || e).includes('egress denied') ? 'DENIED' : 'ERR');\n"
|
||||
"}\n",
|
||||
language="javascript",
|
||||
)
|
||||
assert "DENIED" in result.stdout
|
||||
|
||||
Reference in New Issue
Block a user