interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / infra / test / seccomp-order.py

116 lines · 5336 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Check from strace -f logs that the socket filter covers every program the sandbox runs.
3
4Usage: seccomp-order.py TRACE[=ARG]... (strace -f -e trace=network,ioctl,process,prctl -o TRACE).
5bwrap starts the wrapper's program as /app/forged (forged, or git or ssh-keygen when the wrapper is
6given those). With =ARG, one filtered start of /app/forged must carry ARG among its arguments.
7A process is filtered after its own successful prctl(PR_SET_SECCOMP, ...), or when it first
8appears after the first such install in the trace. Every process outside the sandbox (the wrapper's
9bash, env, forged-listen, the two bubblewrap processes) exists before bubblewrap installs the filter
10and execs the program, so every later process descends from a filtered one. (Fork results cannot be
11used: inside the private PID namespace they are namespace pids.) For every trace:
12 - each successful execve of /app/forged (the program bwrap starts) is filtered;
13 - no filtered process opens a netlink, inet or packet socket, or gets an answer from an ioctl
14 outside the filter's allowlist;
15 - such calls outside the filter (bubblewrap bringing up lo in the new namespace, forged-listen
16 binding the port on the host) are counted.
17Exit 0 when all hold, 1 otherwise.
18"""
19import re
20import sys
21
22ALLOWED_IOCTL = {'FIOCLEX', 'FIONCLEX', 'FIONBIO', 'FIONREAD', 'TCGETS', 'TIOCGWINSZ'}
23NET_FAMILIES = ('AF_NETLINK', 'AF_INET', 'AF_INET6', 'AF_PACKET')
24LINE = re.compile(r'^(\d+) +(.*)$')
25RESULT = re.compile(r'=\s+(-?\d+)')
26STRING = re.compile(r'"((?:[^"\\]|\\.)*)"')
27
28
29def argv(text):
30 """The argument list of an execve line, as strace printed it (long ones end in ...)."""
31 start = text.find('[')
32 end = text.find(']', start)
33 return STRING.findall(text[start:end]) if start >= 0 and end > start else []
34
35
36def check(path, want=None):
37 lines = []
38 with open(path, errors='replace') as f:
39 for raw in f:
40 m = LINE.match(raw.rstrip('\n'))
41 if m:
42 lines.append((int(m.group(1)), m.group(2)))
43 pending = {}
44 own = {} # pid -> line index of its own successful filter install
45 first = {} # pid -> line index of its first line
46 for i, (pid, text) in enumerate(lines):
47 first.setdefault(pid, i)
48 if 'PR_SET_SECCOMP' in text:
49 res = RESULT.search(text)
50 if res and res.group(1) == '0':
51 own.setdefault(pid, i)
52 elif '<unfinished' in text:
53 pending[pid] = i
54 elif pid in pending and 'prctl resumed' in text:
55 res = RESULT.search(text)
56 if res and res.group(1) == '0':
57 own.setdefault(pid, pending[pid])
58 del pending[pid]
59 t0 = min(own.values()) if own else len(lines)
60
61 def filtered(pid, at):
62 return (pid in own and own[pid] < at) or first[pid] > t0
63
64 bad, before, under, forged_exec, execs, execing, starts = [], 0, 0, 0, {}, {}, []
65 for i, (pid, text) in enumerate(lines):
66 res = RESULT.search(text)
67 ok = res is not None and int(res.group(1)) >= 0
68 args = None
69 if text.startswith('execve(') and '<unfinished' in text:
70 execing[pid] = (i, text.split('"')[1], argv(text))
71 continue
72 if '<... execve resumed>' in text and pid in execing:
73 at, prog, args = execing.pop(pid)
74 text = f'execve("{prog}") {text.split(">", 1)[1]}'
75 res = RESULT.search(text)
76 ok = res is not None and int(res.group(1)) >= 0
77 if text.startswith('execve(') and ok:
78 prog = text.split('"')[1]
79 if filtered(pid, i):
80 execs[prog] = execs.get(prog, 0) + 1
81 if prog == '/app/forged':
82 forged_exec += 1
83 starts.append(args if args is not None else argv(text))
84 elif prog == '/app/forged':
85 bad.append(f'{pid} unfiltered execve /app/forged')
86 continue
87 leak = False
88 if text.startswith('socket(') and ok and text[7:].split(',')[0] in NET_FAMILIES:
89 leak = True
90 if text.startswith('ioctl(') and ok:
91 req = text.split(',')[1].strip()
92 leak = req not in ALLOWED_IOCTL
93 if leak:
94 if filtered(pid, i):
95 under += 1
96 bad.append(f'{pid} under the filter: {text[:120]}')
97 else:
98 before += 1
99 print(f'{path}: filter installs {len(own)}; execs under the filter: ' +
100 ', '.join(f'{p} {n}' for p, n in sorted(execs.items())))
101 print(f' netlink/inet sockets and interface ioctls outside the filter (bubblewrap bringing up lo, forged-listen): {before}; '
102 f'under the filter: {under}')
103 for b in bad[:20]:
104 print(' BAD', b)
105 for a in starts[:3]:
106 print(' filtered start:', ' '.join(a[:4]))
107 if want is not None and not any(want in a[1:] for a in starts):
108 bad.append(f'no filtered start of /app/forged with argument {want}')
109 print(f' BAD no filtered start of /app/forged with argument {want}')
110 if forged_exec == 0:
111 bad.append('no filtered execve of /app/forged')
112 print(' BAD no filtered execve of /app/forged')
113 return not bad
114
115
116sys.exit(0 if all([check(*a.split('=', 1)) for a in sys.argv[1:]]) else 1)