omega-mcp
aien-dev/omega-mcp
Brought by drakestapleton
| 1 | #!/usr/bin/env python3 |
| 2 | """Trust-boundary negative gate for omega-mcp (verification oracle; it is not part of the server). |
| 3 | |
| 4 | It drives build/omega-mcp over MCP stdio JSON-RPC, exactly as an agent would, and sends four hostile |
| 5 | programs through the `run` tool: |
| 6 | 1 read read a canary file under ~/.local/state and open ~/.local/state itself |
| 7 | 2 forkbomb every process forks in an unbounded loop; plus a counting program (20 forks) |
| 8 | 3 loop an effectively infinite loop (10^24 iterations), once against the wall clock, once against cpu |
| 9 | 4 write write 10 GiB (10240 x 1 MiB) to a file in the sandbox and to stdout |
| 10 | Each attack must be refused or killed. Every row has a negative control run by a second server started |
| 11 | with --test-only-no-isolation, which must show the attack succeeding (bounded so the host stays safe: |
| 12 | the control never runs the unbounded fork bomb or the 10 GiB write), so a gate that cannot see the |
| 13 | attack fails. After every attack the gate checks that no sandboxed process outlived the reply. |
| 14 | |
| 15 | python3 gates/trust.py [--server build/omega-mcp] [--out evidence/trust-gate.json] |
| 16 | Exit 0 PASS, 1 FAIL. The protected paths /tmp/aien-gb10.lock, ~/.local/state/aien-q36 and |
| 17 | ~/.local/state/aien-coordinator are never named by any program. |
| 18 | """ |
| 19 | import argparse, json, os, secrets, subprocess, sys, threading, time |
| 20 | |
| 21 | HOME = os.path.expanduser("~") |
| 22 | STATE = os.path.join(HOME, ".local", "state") |
| 23 | CANDIR = os.path.join(STATE, "omega-mcp-gate") |
| 24 | CANARY = os.path.join(CANDIR, "canary") |
| 25 | |
| 26 | |
| 27 | def om_text(s): |
| 28 | return s.replace("\\", "\\\\").replace('"', '\\"') |
| 29 | |
| 30 | |
| 31 | READ_SRC = f'''note trust gate 1: read a canary under ~/.local/state, then open ~/.local/state itself |
| 32 | text canary "{om_text(CANARY)}" |
| 33 | text sdir "{om_text(STATE)}" |
| 34 | global buf uchar 256 |
| 35 | fn main to int |
| 36 | f = fopen canary 0 len canary 0 0 |
| 37 | if ge f 0 |
| 38 | r = read int f buf 0 256 |
| 39 | if gt r 0 |
| 40 | w = write 1 buf 0 ulong r |
| 41 | end |
| 42 | ret 10 |
| 43 | end |
| 44 | d = fopen sdir 0 len sdir 0 0 |
| 45 | if ge d 0 |
| 46 | ret 20 |
| 47 | end |
| 48 | ret 0 |
| 49 | end |
| 50 | ''' |
| 51 | |
| 52 | BOMB_SRC = '''note trust gate 2: fork bomb; parent and every child fork in an unbounded loop |
| 53 | fn main to int |
| 54 | n = ulong 0 |
| 55 | for i ulong 1000000000000 |
| 56 | for j ulong 1000000000000 |
| 57 | p = fork |
| 58 | if gt p 0 |
| 59 | n = add n 1 |
| 60 | end |
| 61 | end |
| 62 | end |
| 63 | ret int and n 1 |
| 64 | end |
| 65 | ''' |
| 66 | |
| 67 | COUNT_SRC = '''note trust gate 2 (count): fork 20 children that sleep 2 s; exit status = forks that succeeded |
| 68 | fn main to int |
| 69 | n = int 0 |
| 70 | for i ulong 20 |
| 71 | p = fork |
| 72 | if eq p 0 |
| 73 | z = sleepns 2000000000 |
| 74 | exit 0 |
| 75 | end |
| 76 | if gt p 0 |
| 77 | n = add n 1 |
| 78 | end |
| 79 | end |
| 80 | ret n |
| 81 | end |
| 82 | ''' |
| 83 | |
| 84 | LOOP_SRC = '''note trust gate 3: an effectively infinite loop (10^24 iterations) |
| 85 | fn main to int |
| 86 | x = ulong 0 |
| 87 | for i ulong 1000000000000 |
| 88 | for j ulong 1000000000000 |
| 89 | x = add x 1 |
| 90 | end |
| 91 | end |
| 92 | ret int and x 1 |
| 93 | end |
| 94 | ''' |
| 95 | |
| 96 | |
| 97 | def write_src(mib, to_file): |
| 98 | open_line = ('f = int fopen big 0 len big 577 420\nif lt f 0\nret 3\nend\n' if to_file else 'f = int 1\n') |
| 99 | return (f'note trust gate 4: write {mib} MiB in 1 MiB writes to {"a file in the working directory" if to_file else "stdout"}\n' |
| 100 | 'text big "big"\nglobal buf uchar 1048576\nfn main to int\n' |
| 101 | 'for i ulong 1048576\nput buf i 120\nend\n' + open_line + |
| 102 | f'for i ulong {mib}\nw = write f buf 0 1048576\nif lt w 0\nret 4\nend\nend\nret 0\nend\n') |
| 103 | |
| 104 | |
| 105 | class Server: |
| 106 | def __init__(self, path, noiso): |
| 107 | args = [path] + (["--test-only-no-isolation"] if noiso else []) |
| 108 | self.p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 109 | self.n = 0 |
| 110 | self.log = [] |
| 111 | r = self.req("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, |
| 112 | "clientInfo": {"name": "omega-mcp-trust-gate", "version": "1"}}) |
| 113 | assert r["result"]["serverInfo"]["name"] == "omega-mcp", r |
| 114 | self.notify("notifications/initialized") |
| 115 | |
| 116 | def notify(self, method): |
| 117 | self.p.stdin.write((json.dumps({"jsonrpc": "2.0", "method": method}) + "\n").encode()) |
| 118 | self.p.stdin.flush() |
| 119 | |
| 120 | def req(self, method, params): |
| 121 | self.n += 1 |
| 122 | m = {"jsonrpc": "2.0", "id": self.n, "method": method, "params": params} |
| 123 | self.p.stdin.write((json.dumps(m) + "\n").encode()) |
| 124 | self.p.stdin.flush() |
| 125 | line = self.p.stdout.readline() |
| 126 | if not line: |
| 127 | raise SystemExit(f"server closed stdout; stderr: {self.p.stderr.read().decode()}") |
| 128 | r = json.loads(line) |
| 129 | assert r.get("id") == self.n, r |
| 130 | return r |
| 131 | |
| 132 | def run(self, src, timeout_ms): |
| 133 | t0 = time.monotonic() |
| 134 | r = self.req("tools/call", {"name": "run", "arguments": {"source": src, "timeout_ms": timeout_ms}}) |
| 135 | dt = time.monotonic() - t0 |
| 136 | sc = r["result"]["structuredContent"] |
| 137 | return sc, dt |
| 138 | |
| 139 | def close(self): |
| 140 | self.p.stdin.close() |
| 141 | err = self.p.stderr.read().decode() |
| 142 | rc = self.p.wait(30) |
| 143 | return rc, err |
| 144 | |
| 145 | |
| 146 | def leftovers(): |
| 147 | """Processes of this user that look like a sandboxed program, its reaper or its bwrap. |
| 148 | The bwrap of src/sandbox.om ends with the words `/r reap /p`; matching "/r" as a substring also caught other |
| 149 | agents' unrelated bwrap jobs on a shared machine (a path containing "/refunk/") and failed the gate.""" |
| 150 | out = subprocess.run(["ps", "-u", str(os.getuid()), "-o", "pid=,args="], capture_output=True, text=True).stdout |
| 151 | bad = [] |
| 152 | for line in out.splitlines(): |
| 153 | pid, _, args = line.strip().partition(" ") |
| 154 | if args == "/p" or args.startswith("/r reap") or ( |
| 155 | args.startswith("/usr/bin/bwrap --unshare-all") and args.split()[-3:] == ["/r", "reap", "/p"]): |
| 156 | bad.append(line.strip()) |
| 157 | return bad |
| 158 | |
| 159 | |
| 160 | def summary(sc): |
| 161 | e = sc.get("exit", {}) |
| 162 | return {"compile_ok": sc.get("compile", {}).get("ok"), "exit": e, "stdout": sc.get("stdout", "")[:120], |
| 163 | "stdout_bytes": sc.get("stdout_bytes"), "isolation": sc.get("isolation")} |
| 164 | |
| 165 | |
| 166 | def main(): |
| 167 | ap = argparse.ArgumentParser() |
| 168 | here = os.path.dirname(os.path.abspath(__file__)) |
| 169 | ap.add_argument("--server", default=os.path.join(here, "..", "build", "omega-mcp")) |
| 170 | ap.add_argument("--out", default=os.path.join(here, "..", "evidence", "trust-gate.json")) |
| 171 | a = ap.parse_args() |
| 172 | |
| 173 | os.makedirs(CANDIR, mode=0o700, exist_ok=True) |
| 174 | secret = "omega-mcp-canary-" + secrets.token_hex(8) |
| 175 | with open(CANARY, "w") as f: |
| 176 | f.write(secret + "\n") |
| 177 | |
| 178 | rows, fails = [], [] |
| 179 | |
| 180 | def row(gate, case, mode, sc, dt, ok, want, mid_run=None): |
| 181 | left = leftovers() |
| 182 | if left: |
| 183 | ok = False |
| 184 | r = {"gate": gate, "case": case, "server": mode, "seconds": round(dt, 2), "want": want, |
| 185 | "observed": summary(sc), "leftover_processes": left, "pass": ok} |
| 186 | if mid_run is not None: |
| 187 | r["mid_run_processes"] = mid_run |
| 188 | rows.append(r) |
| 189 | print(f"{'PASS' if ok else 'FAIL'} {gate:9} {case:28} {mode:7} {dt:6.2f}s exit={json.dumps(sc.get('exit'))} " |
| 190 | f"stdout_bytes={sc.get('stdout_bytes')} leftovers={len(left)}", flush=True) |
| 191 | if not ok: |
| 192 | fails.append(f"{gate}/{case}/{mode}") |
| 193 | |
| 194 | iso = Server(a.server, False) |
| 195 | ctl = Server(a.server, True) |
| 196 | kind = lambda sc: sc.get("exit", {}).get("kind") |
| 197 | |
| 198 | # 1 read ~/.local/state |
| 199 | sc, dt = iso.run(READ_SRC, 5000) |
| 200 | row("read", "canary + state dir", "sandbox", sc, dt, |
| 201 | kind(sc) == "normal" and sc["exit"].get("code") == 0 and secret not in sc.get("stdout", ""), |
| 202 | "exit 0: canary and ~/.local/state both invisible, secret absent from stdout") |
| 203 | sc, dt = ctl.run(READ_SRC, 5000) |
| 204 | row("read", "canary + state dir (control)", "noiso", sc, dt, |
| 205 | kind(sc) == "normal" and sc["exit"].get("code") == 10 and secret in sc.get("stdout", ""), |
| 206 | "exit 10 and the secret on stdout (the gate sees a leak)") |
| 207 | |
| 208 | # 2 fork bomb. Sampled mid-run, leftovers() must see the sandbox (control for the leftover check: its bwrap, |
| 209 | # its reaper /r reap and 1..5 bomb processes /p, so every clause of leftovers() is shown to match a live |
| 210 | # sandbox) and the bomb processes must stay within nproc 5. One sample at a fixed 1.5 s saw none of them in one |
| 211 | # run on a loaded machine (load 16, core 1; the 3 s run itself was normal), so sample every 0.1 s for the whole |
| 212 | # run: the first sample that shows all three is kept, and no sample may show more than 5 bomb processes. |
| 213 | def census(m): |
| 214 | margs = [x.split(" ", 1)[1] for x in m] |
| 215 | return (sum(1 for a in margs if a == "/p"), sum(1 for a in margs if a.startswith("/usr/bin/bwrap ")), |
| 216 | sum(1 for a in margs if a.startswith("/r reap"))) |
| 217 | box = {} |
| 218 | th = threading.Thread(target=lambda: box.update(r=iso.run(BOMB_SRC, 3000))) |
| 219 | th.start() |
| 220 | mid, most = [], 0 |
| 221 | while th.is_alive(): |
| 222 | m = leftovers() |
| 223 | nbomb, nbwrap, nreap = census(m) |
| 224 | most = max(most, nbomb) |
| 225 | if not mid and nbomb >= 1 and nbwrap >= 1 and nreap >= 1: |
| 226 | mid = m |
| 227 | time.sleep(0.1) |
| 228 | th.join() |
| 229 | sc, dt = box["r"] |
| 230 | nbomb, nbwrap, nreap = census(mid) |
| 231 | row("forkbomb", "unbounded bomb", "sandbox", sc, dt, |
| 232 | kind(sc) in ("limit", "signal") and dt < 15 and 1 <= nbomb and most <= 5 and nbwrap >= 1 and nreap >= 1, |
| 233 | "stopped by a limit or the wall clock within 15 s; mid-run the sandbox's bwrap, its reaper and 1..5 bomb " |
| 234 | "processes seen (most bomb processes in any 0.1 s sample <= 5); none left", |
| 235 | mid_run=mid) |
| 236 | sc, dt = iso.run(COUNT_SRC, 10000) |
| 237 | n_iso = sc.get("exit", {}).get("code") |
| 238 | row("forkbomb", "count 20 forks", "sandbox", sc, dt, |
| 239 | kind(sc) == "normal" and isinstance(n_iso, int) and n_iso <= 5, |
| 240 | "at most 5 forks succeed (nproc 5)") |
| 241 | sc, dt = ctl.run(COUNT_SRC, 10000) |
| 242 | row("forkbomb", "count 20 forks (control)", "noiso", sc, dt, |
| 243 | kind(sc) == "normal" and sc["exit"].get("code") == 20, |
| 244 | "all 20 forks succeed without the limit") |
| 245 | time.sleep(2.5) |
| 246 | |
| 247 | # 3 infinite loop |
| 248 | sc, dt = iso.run(LOOP_SRC, 2000) |
| 249 | row("loop", "wall clock 2 s", "sandbox", sc, dt, |
| 250 | kind(sc) == "limit" and sc["exit"].get("limit") == "wall_clock" and dt < 6, |
| 251 | "killed at the 2 s wall clock") |
| 252 | sc, dt = iso.run(LOOP_SRC, 30000) |
| 253 | row("loop", "cpu limit (wall 30 s)", "sandbox", sc, dt, |
| 254 | kind(sc) == "limit" and sc["exit"].get("limit") == "cpu_time" and dt < 20, |
| 255 | "killed by RLIMIT_CPU (10 s) before the 30 s wall clock") |
| 256 | sc, dt = ctl.run(LOOP_SRC, 30000) |
| 257 | row("loop", "cpu limit (control)", "noiso", sc, dt, |
| 258 | kind(sc) == "limit" and sc["exit"].get("limit") == "wall_clock" and dt >= 29, |
| 259 | "without prlimit only the 30 s wall clock stops it") |
| 260 | |
| 261 | # 4 10 GiB write |
| 262 | sc, dt = iso.run(write_src(10240, True), 30000) |
| 263 | row("write", "10 GiB to a file", "sandbox", sc, dt, |
| 264 | kind(sc) == "limit" and sc["exit"].get("limit") == "file_size", |
| 265 | "SIGXFSZ at the 1 MiB file-size limit") |
| 266 | sc, dt = iso.run(write_src(10240, False), 30000) |
| 267 | row("write", "10 GiB to stdout", "sandbox", sc, dt, |
| 268 | kind(sc) == "limit" and sc["exit"].get("limit") == "file_size" and (sc.get("stdout_bytes") or 0) <= 1048576, |
| 269 | "SIGXFSZ; at most 1 MiB reached the host capture file") |
| 270 | sc, dt = ctl.run(write_src(8, False), 30000) |
| 271 | row("write", "8 MiB to stdout (control)", "noiso", sc, dt, |
| 272 | kind(sc) == "normal" and sc["exit"].get("code") == 0 and sc.get("stdout_bytes") == 8388608, |
| 273 | "without the limit all 8 MiB are written") |
| 274 | |
| 275 | rc1, err1 = iso.close() |
| 276 | rc2, err2 = ctl.close() |
| 277 | os.remove(CANARY) |
| 278 | os.rmdir(CANDIR) |
| 279 | res = {"server": os.path.abspath(a.server), "rows": rows, "fails": fails, |
| 280 | "server_exit": [rc1, rc2], "server_stderr": {"sandbox": err1, "noiso": err2}, |
| 281 | "verdict": "PASS" if not fails else "FAIL"} |
| 282 | os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) |
| 283 | with open(a.out, "w") as f: |
| 284 | json.dump(res, f, indent=1) |
| 285 | f.write("\n") |
| 286 | print(res["verdict"], f"{len(rows) - len(fails)}/{len(rows)} rows") |
| 287 | return 0 if not fails else 1 |
| 288 | |
| 289 | |
| 290 | if __name__ == "__main__": |
| 291 | sys.exit(main()) |