agent-jail-cli 0.1.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agent_jail/proxy.py ADDED
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env python3
2
+ """Lightweight, zero-dependency async forward proxy with domain allowlisting and SSRF protection.
3
+
4
+ Runs outside the sandbox on 127.0.0.1 to route approved outbound traffic.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import asyncio
11
+ import fnmatch
12
+ import ipaddress
13
+ import os
14
+ from pathlib import Path
15
+ import socket
16
+ import sys
17
+ from urllib.parse import urlparse
18
+
19
+
20
+ def parse_allowlist(path: str | Path) -> list[str]:
21
+ """Parse allowlist file, ignoring comments and blank lines."""
22
+ patterns: list[str] = []
23
+ if not path or not os.path.exists(path):
24
+ return patterns
25
+
26
+ try:
27
+ with open(path, "r", encoding="utf-8") as f:
28
+ for line in f:
29
+ line = line.strip()
30
+ if line and not line.startswith("#"):
31
+ patterns.append(line.lower())
32
+ except Exception:
33
+ pass
34
+ return patterns
35
+
36
+
37
+ LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "[::1]"}
38
+
39
+
40
+ def is_domain_allowed(host: str, port: int, patterns: list[str]) -> bool:
41
+ """Check if host:port matches any pattern in the allowlist.
42
+
43
+ Patterns can be:
44
+ - Hostname / wildcard: 'github.com', '*.github.com'
45
+ - Hostname with port: '127.0.0.1:11434', 'localhost:8080', '127.0.0.1:4000'
46
+ - IP address: '192.168.1.10'
47
+ """
48
+ host = host.lower().strip(".")
49
+ for pattern in patterns:
50
+ pattern = pattern.lower().strip()
51
+ if not pattern:
52
+ continue
53
+
54
+ # Check if pattern specifies a port (e.g., "127.0.0.1:11434")
55
+ if ":" in pattern:
56
+ pat_host, pat_port_str = pattern.rsplit(":", 1)
57
+ try:
58
+ pat_port = int(pat_port_str)
59
+ except ValueError:
60
+ continue
61
+
62
+ if port == pat_port:
63
+ pat_host_clean = pat_host.strip(".")
64
+ if (
65
+ host == pat_host_clean
66
+ or fnmatch.fnmatch(host, pat_host_clean)
67
+ or (host in LOOPBACK_HOSTS and pat_host_clean in LOOPBACK_HOSTS)
68
+ ):
69
+ return True
70
+ else:
71
+ # Pattern is host-only (matches any port)
72
+ if pattern.startswith("*."):
73
+ base = pattern[2:]
74
+ if host == base or host.endswith("." + base):
75
+ return True
76
+ elif fnmatch.fnmatch(host, pattern):
77
+ return True
78
+ elif host == pattern:
79
+ return True
80
+ elif host in LOOPBACK_HOSTS and pattern in LOOPBACK_HOSTS:
81
+ return True
82
+
83
+ return False
84
+
85
+
86
+ def is_ip_allowed(ip_str: str, port: int, patterns: list[str]) -> bool:
87
+ """Validate resolved IP.
88
+
89
+ If the user explicitly allowlisted the IP or IP:port (or localhost:port for loopback)
90
+ in their configuration, it is permitted. Otherwise, private, loopback, link-local
91
+ (cloud metadata), and reserved IP ranges are blocked to prevent SSRF.
92
+ """
93
+ # Explicit bypass if directly listed in allowlist patterns
94
+ for pattern in patterns:
95
+ pattern = pattern.lower().strip()
96
+ if pattern == ip_str or pattern == f"{ip_str}:{port}":
97
+ return True
98
+ if ip_str in LOOPBACK_HOSTS and (
99
+ pattern in LOOPBACK_HOSTS
100
+ or any(pattern == f"{lh}:{port}" for lh in LOOPBACK_HOSTS)
101
+ ):
102
+ return True
103
+
104
+ try:
105
+ ip = ipaddress.ip_address(ip_str)
106
+ if (
107
+ ip.is_loopback
108
+ or ip.is_private
109
+ or ip.is_link_local
110
+ or ip.is_multicast
111
+ or ip.is_unspecified
112
+ or ip.is_reserved
113
+ ):
114
+ return False
115
+ return True
116
+ except ValueError:
117
+ return False
118
+
119
+
120
+ def report_deny(host: str, port: int, method: str, reason: str = "") -> None:
121
+ """Print blocked outbound attempt directly to stderr for developer visibility."""
122
+ reason_str = f" ({reason})" if reason else ""
123
+ sys.stderr.write(f"agent-jail [proxy]: 🚫 Blocked {method} to {host}:{port}{reason_str}\n")
124
+ sys.stderr.flush()
125
+
126
+
127
+ async def tunnel(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
128
+ """Bi-directional byte pump between client and upstream target."""
129
+ try:
130
+ while not reader.at_eof():
131
+ data = await reader.read(65536)
132
+ if not data:
133
+ break
134
+ writer.write(data)
135
+ await writer.drain()
136
+ except Exception:
137
+ pass
138
+ finally:
139
+ try:
140
+ writer.close()
141
+ await writer.wait_closed()
142
+ except Exception:
143
+ pass
144
+
145
+
146
+ async def handle_client(
147
+ client_reader: asyncio.StreamReader,
148
+ client_writer: asyncio.StreamWriter,
149
+ allowlist_path: str,
150
+ ) -> None:
151
+ """Handle incoming HTTP CONNECT or standard HTTP proxy requests."""
152
+ try:
153
+ line = await client_reader.readline()
154
+ if not line:
155
+ client_writer.close()
156
+ return
157
+
158
+ request_line = line.decode("utf-8", errors="replace").strip()
159
+ parts = request_line.split()
160
+ if len(parts) < 2:
161
+ client_writer.close()
162
+ return
163
+
164
+ method, target = parts[0], parts[1]
165
+
166
+ # Parse host and port
167
+ if method.upper() == "CONNECT":
168
+ if ":" in target:
169
+ host, port_str = target.split(":", 1)
170
+ try:
171
+ port = int(port_str)
172
+ except ValueError:
173
+ port = 443
174
+ else:
175
+ host, port = target, 443
176
+ else:
177
+ parsed = urlparse(target)
178
+ host = parsed.hostname or ""
179
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
180
+
181
+ headers: list[bytes] = []
182
+ while True:
183
+ hdr = await client_reader.readline()
184
+ if not hdr or hdr in (b"\r\n", b"\n"):
185
+ break
186
+ headers.append(hdr)
187
+
188
+ patterns = parse_allowlist(allowlist_path)
189
+
190
+ # 1. Check host & port against allowlist
191
+ if not is_domain_allowed(host, port, patterns):
192
+ report_deny(host, port, method, "Domain not in allowlist")
193
+ err_body = f"403 Forbidden: '{host}:{port}' is not in the agent-jail allowlist.\n"
194
+ resp = (
195
+ f"HTTP/1.1 403 Forbidden\r\n"
196
+ f"Content-Type: text/plain\r\n"
197
+ f"Content-Length: {len(err_body)}\r\n"
198
+ f"Connection: close\r\n\r\n"
199
+ f"{err_body}"
200
+ )
201
+ client_writer.write(resp.encode("utf-8"))
202
+ await client_writer.drain()
203
+ client_writer.close()
204
+ await client_writer.wait_closed()
205
+ return
206
+
207
+ # 2. DNS Resolution & SSRF Protection
208
+ loop = asyncio.get_running_loop()
209
+ try:
210
+ addr_info = await loop.getaddrinfo(
211
+ host, port, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
212
+ )
213
+ except Exception as e:
214
+ err_body = f"502 Bad Gateway: Failed to resolve '{host}': {e}\n"
215
+ resp = (
216
+ f"HTTP/1.1 502 Bad Gateway\r\n"
217
+ f"Content-Type: text/plain\r\n"
218
+ f"Content-Length: {len(err_body)}\r\n"
219
+ f"Connection: close\r\n\r\n"
220
+ f"{err_body}"
221
+ )
222
+ client_writer.write(resp.encode("utf-8"))
223
+ await client_writer.drain()
224
+ client_writer.close()
225
+ await client_writer.wait_closed()
226
+ return
227
+
228
+ # Filter resolved IPs against private/loopback/link-local ranges unless explicitly allowed
229
+ valid_ip = None
230
+ for item in addr_info:
231
+ target_ip = item[4][0]
232
+ if is_ip_allowed(target_ip, port, patterns):
233
+ valid_ip = target_ip
234
+ break
235
+ else:
236
+ report_deny(host, port, method, f"SSRF blocked: resolved to {target_ip}")
237
+
238
+ if not valid_ip:
239
+ err_body = f"403 Forbidden: '{host}' resolved to non-public/private IP address.\n"
240
+ resp = (
241
+ f"HTTP/1.1 403 Forbidden\r\n"
242
+ f"Content-Type: text/plain\r\n"
243
+ f"Content-Length: {len(err_body)}\r\n"
244
+ f"Connection: close\r\n\r\n"
245
+ f"{err_body}"
246
+ )
247
+ client_writer.write(resp.encode("utf-8"))
248
+ await client_writer.drain()
249
+ client_writer.close()
250
+ await client_writer.wait_closed()
251
+ return
252
+
253
+ # 3. Connect to validated upstream IP
254
+ try:
255
+ remote_reader, remote_writer = await asyncio.wait_for(
256
+ asyncio.open_connection(valid_ip, port), timeout=15.0
257
+ )
258
+ except Exception as e:
259
+ err_body = f"502 Bad Gateway: Failed to connect to {host} ({valid_ip}:{port}): {e}\n"
260
+ resp = (
261
+ f"HTTP/1.1 502 Bad Gateway\r\n"
262
+ f"Content-Type: text/plain\r\n"
263
+ f"Content-Length: {len(err_body)}\r\n"
264
+ f"Connection: close\r\n\r\n"
265
+ f"{err_body}"
266
+ )
267
+ client_writer.write(resp.encode("utf-8"))
268
+ await client_writer.drain()
269
+ client_writer.close()
270
+ await client_writer.wait_closed()
271
+ return
272
+
273
+ if method.upper() == "CONNECT":
274
+ client_writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
275
+ await client_writer.drain()
276
+ await asyncio.gather(
277
+ tunnel(client_reader, remote_writer),
278
+ tunnel(remote_reader, client_writer),
279
+ )
280
+ else:
281
+ remote_writer.write(line)
282
+ for h in headers:
283
+ remote_writer.write(h)
284
+ remote_writer.write(b"\r\n")
285
+ await remote_writer.drain()
286
+ await asyncio.gather(
287
+ tunnel(client_reader, remote_writer),
288
+ tunnel(remote_reader, client_writer),
289
+ )
290
+ except Exception:
291
+ pass
292
+ finally:
293
+ try:
294
+ client_writer.close()
295
+ await client_writer.wait_closed()
296
+ except Exception:
297
+ pass
298
+
299
+
300
+ async def run_proxy(allowlist: str, port: int = 0, host: str = "127.0.0.1") -> None:
301
+ """Run proxy server and emit PORT=<assigned_port> to stdout."""
302
+ server = await asyncio.start_server(
303
+ lambda r, w: handle_client(r, w, allowlist),
304
+ host=host,
305
+ port=port,
306
+ )
307
+
308
+ assigned_port = server.sockets[0].getsockname()[1]
309
+ sys.stdout.write(f"PORT={assigned_port}\n")
310
+ sys.stdout.flush()
311
+
312
+ async with server:
313
+ await server.serve_forever()
314
+
315
+
316
+ def main() -> None:
317
+ parser = argparse.ArgumentParser(description="Agent Jail Forward Proxy with SSRF Protection")
318
+ parser.add_argument("--allowlist", required=True, help="Path to domain allowlist file")
319
+ parser.add_argument("--port", type=int, default=0, help="Port to listen on (0 for dynamic)")
320
+ parser.add_argument("--host", default="127.0.0.1", help="Host interface to bind to")
321
+ args = parser.parse_args()
322
+
323
+ try:
324
+ asyncio.run(run_proxy(allowlist=args.allowlist, port=args.port, host=args.host))
325
+ except (KeyboardInterrupt, SystemExit):
326
+ pass
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
@@ -0,0 +1 @@
1
+ """Resource assets for agent-jail."""
@@ -0,0 +1,99 @@
1
+ ;; agent-jail Seatbelt profile (macOS sandbox-exec)
2
+ ;; Hardened kernel-level sandbox with universal DEFAULT-DENY for writes and user/mount spaces.
3
+ ;; In SBPL the LAST matching rule wins, BUT only for the same operation name:
4
+ ;; a deny on file-read-data beats an allow on file-read*, so allows must use file-read-data too.
5
+ (version 1)
6
+ (allow default)
7
+
8
+ ;; =========================================================================
9
+ ;; 1. UNIVERSAL WRITE POLICY: DENY ALL WRITES EVERYWHERE BY DEFAULT
10
+ ;; =========================================================================
11
+ (deny file-write*)
12
+
13
+ ;; Allow writes ONLY to explicitly needed locations
14
+ (allow file-write*
15
+ (subpath (param "RUN_TMP"))
16
+ (subpath (string-append (param "HOME") "/.pi"))
17
+ (literal "/dev/null")
18
+ (literal "/dev/zero")
19
+ (literal "/dev/tty")
20
+ (literal "/dev/stdout")
21
+ (literal "/dev/stderr")
22
+ (literal "/dev/ptmx")
23
+ (literal "/dev/dtracehelper"))
24
+
25
+ ;; __DYNAMIC_WRITE_RULES__
26
+
27
+ ;; Explicit write denials inside the allowed areas (anti-tampering & persistence traps)
28
+ (deny file-write*
29
+ ;; Harness anti-tampering
30
+ (subpath (string-append (param "HOME") "/.pi/agent/extensions"))
31
+ (subpath (string-append (param "HOME") "/.pi/agent/skills"))
32
+ (subpath (string-append (param "HOME") "/.pi/agent/bin"))
33
+ (literal (string-append (param "HOME") "/.pi/agent/settings.json"))
34
+ (literal (string-append (param "HOME") "/.pi/agent/models.json"))
35
+ (literal (string-append (param "HOME") "/.pi/agent/auth.json"))
36
+ (literal (string-append (param "HOME") "/.pi/agent/trust.json"))
37
+ (literal (string-append (param "HOME") "/.pi/agent/allowed_domains.default"))
38
+ ;; Developer delayed-jailbreak traps inside $PROJECT
39
+ (subpath (string-append (param "PROJECT") "/.git/hooks"))
40
+ (literal (string-append (param "PROJECT") "/.git/config"))
41
+ (literal (string-append (param "PROJECT") "/.envrc"))
42
+ (literal (string-append (param "PROJECT") "/.mcp.json"))
43
+ (subpath (string-append (param "PROJECT") "/.vscode"))
44
+ ;; Agent instruction persistence traps inside $PROJECT
45
+ (literal (string-append (param "PROJECT") "/AGENTS.md"))
46
+ (literal (string-append (param "PROJECT") "/CLAUDE.md"))
47
+ (literal (string-append (param "PROJECT") "/.cursorrules"))
48
+ ;; Config anti-tampering
49
+ (literal (string-append (param "PROJECT") "/aj-conf.yaml"))
50
+ (literal (string-append (param "PROJECT") "/aj-conf.yml"))
51
+ (literal (string-append (param "PROJECT") "/aj-conf.toml"))
52
+ ;; Network policy anti-tampering
53
+ (literal (string-append (param "PROJECT") "/.allowed_domains"))
54
+ (literal (string-append (param "PROJECT") "/.allowed_domains.txt")))
55
+
56
+ ;; =========================================================================
57
+ ;; 2. READ ACCESS POLICY: BLANKET DENY ON ALL USER DATA & MOUNT TREES
58
+ ;; =========================================================================
59
+ ;; Deny reading all user accounts, external mounts, and network shares
60
+ (deny file-read-data
61
+ (subpath "/Users")
62
+ (subpath "/Volumes")
63
+ (subpath "/net"))
64
+
65
+ ;; Re-allow reading ONLY temp dir, Pi state, and standard language runtimes:
66
+ (allow file-read-data
67
+ (subpath (param "RUN_TMP"))
68
+ (subpath (string-append (param "HOME") "/.pi"))
69
+ (subpath (string-append (param "HOME") "/.local"))
70
+ (subpath (string-append (param "HOME") "/.cache"))
71
+ (subpath (string-append (param "HOME") "/Library/Caches/uv"))
72
+ (subpath (string-append (param "HOME") "/Library/Application Support/uv"))
73
+ (subpath (string-append (param "HOME") "/.pyenv"))
74
+ (subpath (string-append (param "HOME") "/.nvm"))
75
+ (subpath (string-append (param "HOME") "/.fnm"))
76
+ (subpath (string-append (param "HOME") "/.volta"))
77
+ (subpath (string-append (param "HOME") "/.bun"))
78
+ (subpath (string-append (param "HOME") "/.cargo"))
79
+ (subpath (string-append (param "HOME") "/.rustup")))
80
+
81
+ ;; __DYNAMIC_READ_RULES__
82
+
83
+ ;; __DYNAMIC_HIDE_RULES__
84
+
85
+ ;; =========================================================================
86
+ ;; 3. IPC & OS SECURITY
87
+ ;; =========================================================================
88
+ ;; Block reading macOS clipboard (pasteboard) and SecurityServer (keychain daemon)
89
+ (deny mach-lookup
90
+ (global-name "com.apple.pasteboard.1")
91
+ (global-name "com.apple.SecurityServer"))
92
+
93
+ ;; =========================================================================
94
+ ;; 4. NETWORK CONTAINMENT
95
+ ;; =========================================================================
96
+ ;; Drop all raw outbound network except dynamic forward proxy and authorized localhost ports
97
+ (deny network-outbound)
98
+ (allow network-outbound
99
+ (to tcp (string-append "localhost:" (param "PROXY_PORT"))))
@@ -0,0 +1,21 @@
1
+ """Platform-specific sandboxing runners."""
2
+
3
+ import sys
4
+ from agent_jail.runners.base import BaseRunner
5
+ from agent_jail.runners.macos import MacOSRunner
6
+ from agent_jail.runners.linux import LinuxRunner
7
+
8
+
9
+ def get_runner() -> BaseRunner:
10
+ """Return the appropriate sandbox runner for the current operating system."""
11
+ if sys.platform == "darwin":
12
+ return MacOSRunner()
13
+ elif sys.platform.startswith("linux"):
14
+ return LinuxRunner()
15
+ else:
16
+ raise NotImplementedError(
17
+ f"agent-jail is currently supported on macOS and Linux (got: {sys.platform})"
18
+ )
19
+
20
+
21
+ __all__ = ["BaseRunner", "MacOSRunner", "LinuxRunner", "get_runner"]
@@ -0,0 +1,67 @@
1
+ """Base abstract runner interface for sandbox execution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ import os
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING
9
+
10
+ if TYPE_CHECKING:
11
+ from agent_jail.config import JailConfig
12
+
13
+
14
+ class BaseRunner(ABC):
15
+ """Abstract interface defining platform sandboxing behavior."""
16
+
17
+ @abstractmethod
18
+ def check_prerequisites(self) -> None:
19
+ """Validate required OS binaries (e.g., sandbox-exec or bwrap)."""
20
+ pass
21
+
22
+ @abstractmethod
23
+ def build_command(
24
+ self,
25
+ project: Path,
26
+ home: Path,
27
+ proxy_port: int,
28
+ run_tmp: Path,
29
+ cmd: list[str],
30
+ config: JailConfig,
31
+ ) -> list[str]:
32
+ """Construct the sandbox launcher command and arguments."""
33
+ pass
34
+
35
+ def build_safe_env(
36
+ self, proxy_port: int, run_tmp: Path, config: JailConfig | None = None
37
+ ) -> dict[str, str]:
38
+ """Return a scrubbed environment dictionary stripping host secrets and credentials."""
39
+ proxy_url = f"http://127.0.0.1:{proxy_port}"
40
+ safe_env = {
41
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin:/usr/sbin:/sbin"),
42
+ "HOME": str(Path.home().resolve()),
43
+ "USER": os.environ.get("USER", "user"),
44
+ "LOGNAME": os.environ.get("LOGNAME", os.environ.get("USER", "user")),
45
+ "SHELL": os.environ.get("SHELL", "/bin/bash"),
46
+ "TERM": os.environ.get("TERM", "xterm-256color"),
47
+ "LANG": os.environ.get("LANG", "en_US.UTF-8"),
48
+ "TMPDIR": str(run_tmp),
49
+ "HTTP_PROXY": proxy_url,
50
+ "HTTPS_PROXY": proxy_url,
51
+ "ALL_PROXY": proxy_url,
52
+ "NO_PROXY": "localhost,127.0.0.1",
53
+ "http_proxy": proxy_url,
54
+ "https_proxy": proxy_url,
55
+ "all_proxy": proxy_url,
56
+ "no_proxy": "localhost,127.0.0.1",
57
+ }
58
+ if "VIRTUAL_ENV" in os.environ:
59
+ safe_env["VIRTUAL_ENV"] = os.environ["VIRTUAL_ENV"]
60
+
61
+ # User-configured passthrough environment variables
62
+ if config and config.env_passthrough:
63
+ for var in config.env_passthrough:
64
+ if var in os.environ:
65
+ safe_env[var] = os.environ[var]
66
+
67
+ return safe_env