interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / test_sandbox.py

141 lines · 7150 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Escape tests for the allen-chat compile sandbox.
3
4Runs a static busybox (a verification tool, never shipped) through the exact
5sandboxed() call the gateway uses for omc and irwasm, and checks each guard
6with a negative control: the same probe outside the sandbox, or a permitted
7action inside it, must succeed, so a pass is not just a missing applet.
8Usage: test_sandbox.py [busybox path]. In probe scripts "@" stands for the
9busybox binary, because the sandbox has no PATH and no /bin.
10"""
11
12import os
13import subprocess
14import sys
15import time
16
17sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18from allen_chat import sandboxed # noqa: E402
19
20BB = sys.argv[1] if len(sys.argv) > 1 else "/usr/bin/busybox"
21results = []
22PRE = 'b() { (exec -a busybox /tool "$@"); }; '
23
24
25def inside(script, wall=5):
26 t0 = time.monotonic()
27 out, err, rc = sandboxed(BB, b"", wall, 1 << 20, ["sh", "-c", PRE + script.replace("@", "b ")],
28 argv0="busybox")
29 return out or b"", err or b"", rc, time.monotonic() - t0
30
31
32def outside(script):
33 p = subprocess.run([BB, "sh", "-c", script.replace("@", BB + " ")], capture_output=True, timeout=20)
34 return p.stdout, p.stderr, p.returncode
35
36
37def check(name, ok, detail):
38 results.append((name, ok))
39 print("%s %s: %s" % ("PASS" if ok else "FAIL", name, detail))
40
41
42# 0. Control: the sandbox runs busybox at all.
43o, e, rc, _ = inside("@echo ALIVE")
44check("sandbox runs probes (control)", o.strip() == b"ALIVE", "rc=%s out=%r err=%r" % (rc, o, e[:80]))
45
46# 1. Network: the model server on host loopback and the hub over the tailnet.
47for host, port in (("127.0.0.1", "18091"), ("100.64.0.3", "443")):
48 probe = "@echo | @nc -w 2 %s %s; echo rc=$?" % (host, port)
49 o, e, rc, _ = inside(probe)
50 co, ce, crc = outside(probe)
51 check("network denied to %s:%s" % (host, port), b"rc=0" not in o and b"rc=" in o,
52 "inside %r %r; control outside %r" % (o.strip(), e.strip()[:60], co.strip()))
53 check("network control %s:%s reachable outside" % (host, port), b"rc=0" in co, repr(co.strip()))
54
55# 2. Host files are invisible.
56probe = "@ls -d /home /etc/passwd /tmp/aien-gb10.lock /usr 2>&1; echo END"
57o, e, rc, _ = inside(probe)
58co, _, _ = outside(probe)
59seen = [p for p in (b"/home", b"/etc/passwd", b"/usr") if (p + b"\n") in o]
60check("host files invisible", not seen and b"END" in o,
61 "inside saw %r; control outside listed /home=%s" % (seen, b"/home\n" in co))
62
63# 3. Writes outside the tmpfs are refused; writes inside it work (control).
64o, e, rc, _ = inside("echo x > /evil 2>/dev/null && echo ROOTW; echo x > /tool 2>/dev/null && echo TOOLW; "
65 "echo x > /tmp/ok && echo TMPW")
66check("root and tool read-only", b"ROOTW" not in o and b"TOOLW" not in o, "out=%r" % o)
67check("tmpfs writable (control)", b"TMPW" in o, "out=%r" % o)
68
69# 4. File size caps: a 16 MiB write stops at the 4 MiB RLIMIT_FSIZE / 8 MiB tmpfs.
70o, e, rc, _ = inside("@dd if=/dev/zero of=/tmp/big bs=1M count=16 2>/dev/null; @wc -c < /tmp/big")
71size = int(o.split()[-1]) if o.split() else -1
72check("file size capped", 0 < size <= 8 << 20, "wrote %d bytes of 16 MiB" % size)
73
74# 5. CPU spin is killed by the CPU limit / wall clock.
75o, e, rc, dt = inside("while :; do :; done", wall=8)
76check("cpu spin killed", rc != 0 and 3 < dt < 7, "rc=%s after %.1fs (RLIMIT_CPU 4 s)" % (rc, dt))
77
78# 6. Sleeping past the wall clock is killed too (the CPU limit does not catch it).
79o, e, rc, dt = inside("@sleep 30; echo SLEPT", wall=3)
80check("wall clock kill", rc == -9 and dt < 5 and b"SLEPT" not in o, "rc=%s after %.1fs" % (rc, dt))
81
82# 7. Background children die with the sandbox (pid namespace, die-with-parent).
83import threading
84marker = "%d.25" % (100000 + os.getpid() % 100000)
85seen_running = []
86def watch():
87 time.sleep(1.0)
88 seen_running.append(subprocess.run(["pgrep", "-f", "sleep " + marker], capture_output=True).stdout.strip())
89w = threading.Thread(target=watch)
90w.start()
91inside("for i in 1 2 3 4 5; do @sleep %s & done; @sleep 30" % marker, wall=2)
92w.join()
93time.sleep(1)
94left = subprocess.run(["pgrep", "-f", "sleep " + marker], capture_output=True).stdout.strip()
95check("orphan control: children visible while the sandbox runs", bool(seen_running and seen_running[0]),
96 "pgrep saw %d processes" % len((seen_running or [b""])[0].split()))
97check("no orphans survive", not left, "pgrep found %r" % left)
98
99# 8. Memory cap: a 1 GiB allocation fails under RLIMIT_AS 512 MiB; 64 MiB works (control).
100o, e, rc, _ = inside("v=$(@head -c 1073741824 /dev/zero | @tr '\\0' a); echo ALLOC ${#v}", wall=8)
101check("memory capped", b"ALLOC 1073741824" not in o and rc is not None, "rc=%s out=%r err=%r" % (rc, o[:40], e[:60]))
102o, e, rc, _ = inside("v=$(@head -c 67108864 /dev/zero | @tr '\\0' a); echo ALLOC ${#v}", wall=8)
103check("64 MiB allocation works (control)", b"ALLOC 67108864" in o, "rc=%s out=%r" % (rc, o[:40]))
104
105# 9. Environment is cleared (no inherited secrets).
106os.environ["ALLENCHAT_CANARY"] = "should-not-leak"
107o, e, rc, _ = inside("@env; echo END")
108check("environment cleared", b"ALLENCHAT_CANARY" not in o and b"END" in o, "env=%r" % o[:120])
109
110# 10. No /proc: host processes and kernel state are not visible.
111o, e, rc, _ = inside("@ls /proc 2>&1; echo END")
112check("no /proc in the sandbox", b"END" in o and b"self" not in o, "out=%r" % o[:80])
113
114# 11. Output floods are cut while they are read, not after: stdout past the cap ends the run.
115t0 = time.monotonic()
116o, e, rc = sandboxed(BB, b"", 5, 1 << 20, ["sh", "-c", PRE + "b yes"], argv0="busybox")
117dt = time.monotonic() - t0
118check("stdout flood cut at the cap", o is None and e == b"output too large" and rc == -1 and dt < 3,
119 "rc=%s err=%r after %.1fs" % (rc, e, dt))
120# 12. A stderr flood keeps only 4096 bytes and still ends at the wall clock.
121t0 = time.monotonic()
122o, e, rc = sandboxed(BB, b"", 2, 1 << 20, ["sh", "-c", PRE + "b yes >&2"], argv0="busybox")
123dt = time.monotonic() - t0
124check("stderr flood bounded and timed out", rc == -9 and e == b"timeout" and dt < 4, "rc=%s after %.1fs" % (rc, dt))
125o, e, rc = sandboxed(BB, b"", 5, 1 << 20, ["sh", "-c", PRE + "b head -c 100000 /dev/zero | b tr '\\0' e >&2"],
126 argv0="busybox")
127check("stderr kept to its first 4096 bytes (control: the run completes)", rc == 0 and len(e) == 4096,
128 "rc=%s stderr %d bytes" % (rc, len(e)))
129# 13. 8 MiB of stdin is fed in full (control for the non-blocking writer).
130big = b"z" * (8 << 20)
131o, e, rc = sandboxed(BB, big, 10, 1 << 20, ["sh", "-c", PRE + "b wc -c"], argv0="busybox")
132check("8 MiB stdin delivered", rc == 0 and o and o.strip() == b"8388608", "rc=%s out=%r" % (rc, (o or b"")[:20]))
133# 14. A tool that never reads its 8 MiB stdin is still killed at the wall clock.
134t0 = time.monotonic()
135o, e, rc = sandboxed(BB, big, 2, 1 << 20, ["sh", "-c", PRE + "b sleep 30"], argv0="busybox")
136dt = time.monotonic() - t0
137check("unread stdin cannot outlast the wall clock", rc == -9 and dt < 4, "rc=%s after %.1fs" % (rc, dt))
138
139failed = [n for n, ok in results if not ok]
140print("%d/%d passed" % (len(results) - len(failed), len(results)))
141sys.exit(1 if failed else 0)