phiward 0.2.0b1__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.
- phiward/__init__.py +8 -0
- phiward/__main__.py +5 -0
- phiward/_toml.py +211 -0
- phiward/adapters/__init__.py +105 -0
- phiward/adapters/claude.py +429 -0
- phiward/broker.py +831 -0
- phiward/carryover.py +1613 -0
- phiward/claude_settings.py +1307 -0
- phiward/cli.py +110 -0
- phiward/config.py +936 -0
- phiward/confine.py +476 -0
- phiward/copying.py +533 -0
- phiward/core.py +105 -0
- phiward/data/agents-section.md +43 -0
- phiward/doctor.py +1132 -0
- phiward/fasthook.py +70 -0
- phiward/fsinfo.py +241 -0
- phiward/gateway.py +159 -0
- phiward/githooks.py +248 -0
- phiward/guards/__init__.py +0 -0
- phiward/guards/protected_paths.py +1138 -0
- phiward/hidden.py +281 -0
- phiward/init.py +155 -0
- phiward/install.py +828 -0
- phiward/inventory.py +173 -0
- phiward/mcp.py +186 -0
- phiward/mcp_config.py +1736 -0
- phiward/names.py +5 -0
- phiward/packs/dates.toml +17 -0
- phiward/packs/genomics.toml +51 -0
- phiward/packs/msk.toml +32 -0
- phiward/pathid.py +403 -0
- phiward/pathmatch.py +98 -0
- phiward/paths.py +942 -0
- phiward/pin.py +214 -0
- phiward/procinfo.py +73 -0
- phiward/remote.py +448 -0
- phiward/run.py +788 -0
- phiward/safeio.py +84 -0
- phiward/sanitize.py +691 -0
- phiward/selfcheck.py +1506 -0
- phiward/service.py +321 -0
- phiward/session_note.py +86 -0
- phiward/setup_cmd.py +886 -0
- phiward/shell.py +504 -0
- phiward/wholetool.py +1463 -0
- phiward-0.2.0b1.dist-info/METADATA +147 -0
- phiward-0.2.0b1.dist-info/RECORD +53 -0
- phiward-0.2.0b1.dist-info/WHEEL +5 -0
- phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
- phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
- phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
- phiward-0.2.0b1.dist-info/top_level.txt +1 -0
phiward/confine.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""Kernel confinement: the boundary that the command text cannot give.
|
|
2
|
+
|
|
3
|
+
The gateway's profile, built for two backends (macOS Seatbelt via `sandbox-exec`, Linux
|
|
4
|
+
bubblewrap); `launch` (Mode B) builds its own from the same parts. The agent's shell is confined
|
|
5
|
+
by Claude Code's sandbox, not here.
|
|
6
|
+
- GATEWAY: the protected roots can be read; writes go only to the user's protected roots, a
|
|
7
|
+
scratch folder and the folders the operator granted; no network unless granted; no channel to
|
|
8
|
+
other processes (macOS: no mach-lookup, IPC, notifications or signals out; Linux: new IPC, PID
|
|
9
|
+
and network namespaces, a seccomp filter, Landlock). Only the broker starts it.
|
|
10
|
+
|
|
11
|
+
On Linux the gateway needs Landlock ABI 2 or later as its second write layer; without it the
|
|
12
|
+
gateway refuses to run. No backend (Windows, or bubblewrap missing or blocked) raises
|
|
13
|
+
ConfineError. Callers fail closed.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import platform
|
|
18
|
+
import shutil
|
|
19
|
+
import struct
|
|
20
|
+
import subprocess
|
|
21
|
+
import sys
|
|
22
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
23
|
+
|
|
24
|
+
from phiward import pathmatch
|
|
25
|
+
|
|
26
|
+
SANDBOX_EXEC = "/usr/bin/sandbox-exec"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConfineError(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def backend() -> Optional[str]:
|
|
34
|
+
if sys.platform == "darwin" and os.path.exists(SANDBOX_EXEC):
|
|
35
|
+
return "seatbelt"
|
|
36
|
+
if sys.platform.startswith("linux") and shutil.which("bwrap"):
|
|
37
|
+
return "bwrap"
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _spellings(paths_: Sequence[str]) -> List[str]:
|
|
42
|
+
"""Each path as written, with its symlinks resolved, and in canonical spelling (pathid: a
|
|
43
|
+
root written through the /System/Volumes/Data firmlink is denied on its normal path too),
|
|
44
|
+
without duplicates."""
|
|
45
|
+
from phiward import pathid
|
|
46
|
+
out: List[str] = []
|
|
47
|
+
for p in paths_:
|
|
48
|
+
for v in pathid.spellings(p):
|
|
49
|
+
if v not in out:
|
|
50
|
+
out.append(v)
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _mount_point(path: str) -> str:
|
|
55
|
+
"""`path` with the links in its folder resolved, its last part kept as written: where
|
|
56
|
+
bubblewrap can mount over it (it cannot make a mount point through a link)."""
|
|
57
|
+
return os.path.join(os.path.realpath(os.path.dirname(path)), os.path.basename(path))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _ancestors(paths_: Sequence[str]) -> List[str]:
|
|
61
|
+
"""Every folder above each path (both spellings), shallowest first, without "/"."""
|
|
62
|
+
out: List[str] = []
|
|
63
|
+
for p in _spellings(paths_):
|
|
64
|
+
d = os.path.dirname(p)
|
|
65
|
+
while d and d != "/":
|
|
66
|
+
if d not in out:
|
|
67
|
+
out.append(d)
|
|
68
|
+
d = os.path.dirname(d)
|
|
69
|
+
return sorted(out, key=lambda x: x.count("/"))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _pattern_matches(patterns: Sequence[str]) -> List[str]:
|
|
73
|
+
out: List[str] = []
|
|
74
|
+
for p in patterns:
|
|
75
|
+
out.extend(pathmatch.matches(p)) # dot-names too, never through a link
|
|
76
|
+
return out
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def gateway_places(writable: Sequence[str], patterns: Sequence[str]) -> List[str]:
|
|
80
|
+
"""The folders the gateway may write, never through a link:
|
|
81
|
+
each `writable` folder exactly as given, which must still be a real folder (else
|
|
82
|
+
ConfineError: the caller resolved it, and a link put on its path since then is refused),
|
|
83
|
+
and each match of a pattern that is a real folder (a match that is a link is skipped)."""
|
|
84
|
+
out: List[str] = []
|
|
85
|
+
for w in writable:
|
|
86
|
+
n = os.path.normpath(w)
|
|
87
|
+
if not os.path.isdir(n) or os.path.realpath(n) != n:
|
|
88
|
+
raise ConfineError("a write place is no longer a real folder (a link is on its "
|
|
89
|
+
"path); nothing runs")
|
|
90
|
+
if n not in out:
|
|
91
|
+
out.append(n)
|
|
92
|
+
for m in _pattern_matches(patterns):
|
|
93
|
+
n = os.path.normpath(m)
|
|
94
|
+
if os.path.isdir(n) and os.path.realpath(n) == n and n not in out:
|
|
95
|
+
out.append(n)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _pattern_spellings(patterns: Sequence[str]) -> List[str]:
|
|
100
|
+
"""Each pattern as written and with its literal leading part resolved (/tmp ->
|
|
101
|
+
/private/tmp on macOS): Seatbelt matches the resolved path."""
|
|
102
|
+
from phiward.paths import _realpath_prefix
|
|
103
|
+
out: List[str] = []
|
|
104
|
+
for p in patterns:
|
|
105
|
+
for v in (os.path.normpath(p), _realpath_prefix(p)):
|
|
106
|
+
if v not in out:
|
|
107
|
+
out.append(v)
|
|
108
|
+
return out
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _pattern_prefix(pattern: str) -> str:
|
|
112
|
+
"""The folder part of a glob pattern before its first wildcard."""
|
|
113
|
+
head = pattern.split("*", 1)[0].split("?", 1)[0].split("[", 1)[0]
|
|
114
|
+
return head if head.endswith("/") else os.path.dirname(head)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# -- Seatbelt -----------------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
def _sb_str(p: str) -> str:
|
|
120
|
+
return '"' + p.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _sb_regex_for_pattern(pattern: str) -> str:
|
|
124
|
+
"""A Seatbelt regex for a glob pattern (the shared meaning: pathmatch), matching the
|
|
125
|
+
pattern and everything below it."""
|
|
126
|
+
return '#"' + pathmatch.regex(pattern).replace('"', '\\"') + '(/.*)?$"'
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _sb_paths(roots: Sequence[str], patterns: Sequence[str]) -> List[str]:
|
|
130
|
+
rules = [f"(subpath {_sb_str(r)})" for r in _spellings(roots)]
|
|
131
|
+
rules += [f"(regex {_sb_regex_for_pattern(p)})" for p in _spellings(patterns)]
|
|
132
|
+
return rules
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
_DEVICES = ("/dev/null", "/dev/zero", "/dev/dtracehelper", "/dev/stdout", "/dev/stderr")
|
|
136
|
+
# DNS, only with the network grant (Codex keeps a list of the same kind)
|
|
137
|
+
_NET_SERVICES = ("com.apple.dnssd.service", "com.apple.SystemConfiguration.configd",
|
|
138
|
+
"com.apple.SystemConfiguration.DNSConfiguration")
|
|
139
|
+
# user and group lookups (getpwuid): ssh refuses to start without the operator's user name
|
|
140
|
+
# ("No user exists for uid", found in a first run on HPC)
|
|
141
|
+
_USER_SERVICES = ("com.apple.system.opendirectoryd.libinfo",
|
|
142
|
+
"com.apple.system.DirectoryService.libinfo_v1",
|
|
143
|
+
"com.apple.system.opendirectoryd.membership")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def seatbelt_gateway_profile(writable: Sequence[str], patterns: Sequence[str], net: bool,
|
|
147
|
+
deny_read: Sequence[str] = (), socket: str = "",
|
|
148
|
+
allow_read: Sequence[str] = ()) -> str:
|
|
149
|
+
"""`socket`: no network at all except a connection to that one unix socket (the operator's
|
|
150
|
+
shared SSH connection); `net` is then ignored."""
|
|
151
|
+
# the places as resolved; a pattern rule matches the resolved path of each write, so a link
|
|
152
|
+
# under a pattern does not carry a write elsewhere
|
|
153
|
+
allow = [f"(subpath {_sb_str(w)})" for w in gateway_places(writable, [])]
|
|
154
|
+
allow += [f"(regex {_sb_regex_for_pattern(p)})" for p in _pattern_spellings(patterns)]
|
|
155
|
+
allow += [f"(literal {_sb_str(d)})" for d in _DEVICES]
|
|
156
|
+
profile = "(version 1)(allow default)"
|
|
157
|
+
profile += "(deny file-write* (require-not (require-any " + " ".join(allow) + ")))"
|
|
158
|
+
# no write to any Claude Code settings, even inside a write place: a write place may hold a
|
|
159
|
+
# project, and its settings can turn the guards off
|
|
160
|
+
profile += '(deny file-write* (regex #"/\\.claude(/.*)?$"))'
|
|
161
|
+
if deny_read:
|
|
162
|
+
profile += "(deny file-read* file-write* " + " ".join(
|
|
163
|
+
f"(subpath {_sb_str(p)})" for p in _spellings(list(deny_read))) + ")"
|
|
164
|
+
# Kerberos ticket caches in the temp folders, by name: made at any time, never listed
|
|
165
|
+
profile += '(deny file-read* file-write* (regex #"^/private/(var/)?tmp/krb5cc[^/]*"))'
|
|
166
|
+
if allow_read: # single files the request needs back (the operator's ssh config)
|
|
167
|
+
profile += "(allow file-read* " + " ".join(
|
|
168
|
+
f"(literal {_sb_str(p)})" for p in _spellings(list(allow_read))) + ")"
|
|
169
|
+
# Seatbelt matches the resolved path (/tmp is /private/tmp): every spelling of the socket
|
|
170
|
+
profile += "(deny mach-lookup)(deny ipc-posix*)(deny ipc-sysv*)"
|
|
171
|
+
profile += "(deny darwin-notification-post)(deny distributed-notification-post)"
|
|
172
|
+
profile += "(deny signal (require-not (target same-sandbox)))"
|
|
173
|
+
profile += "(deny process-info* (require-not (target same-sandbox)))"
|
|
174
|
+
if socket:
|
|
175
|
+
# connecting needs only network-outbound: no file right on the socket, so a request
|
|
176
|
+
# cannot remove or replace the operator's socket
|
|
177
|
+
profile += "(allow mach-lookup " + " ".join(
|
|
178
|
+
f"(global-name {_sb_str(m)})" for m in _USER_SERVICES) + ")"
|
|
179
|
+
profile += "(deny network*)"
|
|
180
|
+
profile += "(allow network-outbound " + " ".join(
|
|
181
|
+
f"(remote unix-socket (path-literal {_sb_str(p)}))" for p in _spellings([socket])) + ")"
|
|
182
|
+
elif net:
|
|
183
|
+
profile += "(allow mach-lookup " + " ".join(
|
|
184
|
+
f"(global-name {_sb_str(s)})" for s in _NET_SERVICES) + ")"
|
|
185
|
+
# the network, but no unix socket: an SSH agent's or a shared connection's would log
|
|
186
|
+
# in to HPC as the operator; name lookups go through mDNSResponder
|
|
187
|
+
profile += "(deny network-outbound (remote unix-socket))"
|
|
188
|
+
profile += ('(allow network-outbound (remote unix-socket '
|
|
189
|
+
'(subpath "/private/var/run/mDNSResponder")))')
|
|
190
|
+
else:
|
|
191
|
+
profile += "(deny network*)" # also unix socket connects
|
|
192
|
+
return profile
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# -- bubblewrap, seccomp and Landlock -----------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
_BWRAP_BASE = ["--dev", "/dev", "--proc", "/proc", "--unshare-pid", "--die-with-parent"]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def open_place(path: str) -> int:
|
|
201
|
+
"""An O_PATH descriptor of the folder `path`, reached part by part without following a
|
|
202
|
+
link, so the folder checked is the folder bound (check by path, then bind
|
|
203
|
+
by path, let a swap in between move the bind)."""
|
|
204
|
+
flags = os.O_PATH | os.O_NOFOLLOW | os.O_DIRECTORY | os.O_CLOEXEC # type: ignore[attr-defined]
|
|
205
|
+
fd = os.open("/", flags)
|
|
206
|
+
try:
|
|
207
|
+
for part in [p for p in path.split("/") if p]:
|
|
208
|
+
nxt = os.open(part, flags, dir_fd=fd)
|
|
209
|
+
os.close(fd)
|
|
210
|
+
fd = nxt
|
|
211
|
+
except OSError:
|
|
212
|
+
os.close(fd)
|
|
213
|
+
raise ConfineError("a write place is no longer a real folder (a link is on its path); "
|
|
214
|
+
"nothing runs")
|
|
215
|
+
return fd
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def bwrap_gateway_args(writable: Sequence[str], patterns: Sequence[str], net: bool,
|
|
219
|
+
fds: Optional[Dict[str, int]] = None,
|
|
220
|
+
deny_read: Sequence[str] = (), socket: str = "",
|
|
221
|
+
allow_read: Sequence[str] = ()) -> List[str]:
|
|
222
|
+
"""`fds` maps each place to a descriptor from open_place; each place is bound from its
|
|
223
|
+
descriptor (/proc/self/fd/N), never by its path."""
|
|
224
|
+
args = ["--ro-bind", "/", "/"] + _BWRAP_BASE + [
|
|
225
|
+
"--unshare-ipc", "--new-session"]
|
|
226
|
+
if socket:
|
|
227
|
+
# fresh, empty folders where sockets usually live (an SSH agent's, X11's, other shared
|
|
228
|
+
# connections'): masking by name misses a socket that was renamed after it was bound,
|
|
229
|
+
# as OpenSSH's own master does; the places are bound back below
|
|
230
|
+
home = os.environ.get("HOME", "")
|
|
231
|
+
for d in ("/tmp", "/var/tmp") + ((home,) if home.startswith("/") and home != "/" else ()):
|
|
232
|
+
if os.path.isdir(d):
|
|
233
|
+
args += ["--tmpfs", d]
|
|
234
|
+
# no empty /tmp: it would hide a request folder (or a root) under /tmp, and bubblewrap would
|
|
235
|
+
# then run the command in $HOME without a word. The host /tmp stays
|
|
236
|
+
# read-only, like all of /; the command's TMPDIR is its private scratch folder.
|
|
237
|
+
for w in gateway_places(writable, patterns):
|
|
238
|
+
src = f"/proc/self/fd/{fds[w]}" if fds and w in fds else w
|
|
239
|
+
args += ["--bind", src, w]
|
|
240
|
+
# Claude Code settings inside a write place stay read-only; a new one can
|
|
241
|
+
# still be made in a write place that has none (docs/threat-model.md)
|
|
242
|
+
for w in gateway_places(writable, patterns):
|
|
243
|
+
c = os.path.join(w, ".claude")
|
|
244
|
+
if os.path.isdir(c) and not os.path.islink(c):
|
|
245
|
+
args += ["--ro-bind", c, c]
|
|
246
|
+
# what the command may not read (credentials, traces): masked last, over every bind, each at
|
|
247
|
+
# its real place (bubblewrap cannot make a mount point through a link: /var/run -> /run)
|
|
248
|
+
masked: List[str] = []
|
|
249
|
+
for p in _spellings(list(deny_read)):
|
|
250
|
+
p = _mount_point(p)
|
|
251
|
+
if p in masked:
|
|
252
|
+
continue
|
|
253
|
+
masked.append(p)
|
|
254
|
+
if os.path.isdir(p) and not os.path.islink(p):
|
|
255
|
+
args += ["--tmpfs", p]
|
|
256
|
+
elif os.path.lexists(p) and not os.path.islink(p):
|
|
257
|
+
args += ["--ro-bind", "/dev/null", p]
|
|
258
|
+
hidden = [os.path.realpath(h) for h in deny_read]
|
|
259
|
+
for p in allow_read:
|
|
260
|
+
# the file itself, also when the name is a link (dotfile managers): bound from its
|
|
261
|
+
# resolved target, unless that target is hidden
|
|
262
|
+
real = os.path.realpath(p)
|
|
263
|
+
if os.path.isfile(real) and not any(real == h or real.startswith(h + "/") for h in hidden):
|
|
264
|
+
args += ["--ro-bind", real, _mount_point(p)]
|
|
265
|
+
if socket:
|
|
266
|
+
# every other socket that has a path (an SSH agent's, X11's, another shared
|
|
267
|
+
# connection's) is masked: a read-only bind does not stop a connect;
|
|
268
|
+
# then the one socket, bound back over the masks; and no network besides it
|
|
269
|
+
for s in _path_sockets():
|
|
270
|
+
if s != socket and os.path.lexists(s) and not any(
|
|
271
|
+
s == d or s.startswith(d + "/") for d in ("/tmp", "/var/tmp")):
|
|
272
|
+
args += ["--ro-bind", "/dev/null", s]
|
|
273
|
+
args += ["--bind", socket, LINUX_SOCKET, "--unshare-net"]
|
|
274
|
+
elif not net:
|
|
275
|
+
args.append("--unshare-net")
|
|
276
|
+
return args
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# where the shared connection's socket appears inside a Linux request: a fixed
|
|
280
|
+
# name in a fresh /tmp, so no other socket in /tmp, /var/tmp or the home folder is reachable
|
|
281
|
+
LINUX_SOCKET = "/tmp/phiward-cm"
|
|
282
|
+
|
|
283
|
+
# system name-service sockets stay reachable (user and group lookups: sssd, nscd)
|
|
284
|
+
_NSS_SOCKETS = ("/var/lib/sss/pipes", "/var/run/nscd", "/run/nscd", "/run/systemd/userdb")
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _path_sockets() -> List[str]:
|
|
288
|
+
"""Unix sockets that have a path (from /proc/net/unix; the path is the rest of the line after
|
|
289
|
+
seven fields, so it may hold spaces), name-service sockets aside."""
|
|
290
|
+
out: List[str] = []
|
|
291
|
+
try:
|
|
292
|
+
with open("/proc/net/unix", encoding="utf-8", errors="replace") as fh:
|
|
293
|
+
next(fh, None)
|
|
294
|
+
for line in fh:
|
|
295
|
+
parts = line.rstrip("\n").split(None, 7)
|
|
296
|
+
if len(parts) == 8 and parts[7].startswith("/"):
|
|
297
|
+
p = parts[7]
|
|
298
|
+
if not any(p == n or p.startswith(n + "/") for n in _NSS_SOCKETS) and \
|
|
299
|
+
p not in out:
|
|
300
|
+
out.append(p)
|
|
301
|
+
except OSError:
|
|
302
|
+
pass
|
|
303
|
+
return out
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# Syscalls the gateway may not make (seccomp). Numbers per architecture.
|
|
307
|
+
_AUDIT_ARCH = {"x86_64": 0xC000003E, "aarch64": 0xC00000B7}
|
|
308
|
+
_DENY = { # name: (x86_64, aarch64)
|
|
309
|
+
"ptrace": (101, 117), "process_vm_readv": (310, 270), "process_vm_writev": (311, 271),
|
|
310
|
+
"unshare": (272, 97), "setns": (308, 268), "mount": (165, 40), "umount2": (166, 39),
|
|
311
|
+
"pivot_root": (155, 41), "io_uring_setup": (425, 425), "io_uring_enter": (426, 426),
|
|
312
|
+
"io_uring_register": (427, 427), "open_tree": (428, 428), "move_mount": (429, 429),
|
|
313
|
+
"fsopen": (430, 430), "fsconfig": (431, 431), "fsmount": (432, 432), "fspick": (433, 433),
|
|
314
|
+
"mount_setattr": (442, 442), "bpf": (321, 280), "perf_event_open": (298, 241),
|
|
315
|
+
"userfaultfd": (323, 282), "keyctl": (250, 219), "add_key": (248, 217),
|
|
316
|
+
"request_key": (249, 218),
|
|
317
|
+
}
|
|
318
|
+
_SOCKET = (41, 198)
|
|
319
|
+
_CLONE3 = (435, 435)
|
|
320
|
+
_AF_UNIX = 1
|
|
321
|
+
_EPERM, _ENOSYS = 1, 38
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _machine() -> str:
|
|
325
|
+
m = platform.machine().lower()
|
|
326
|
+
return {"amd64": "x86_64", "arm64": "aarch64"}.get(m, m)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def seccomp_program(machine: Optional[str] = None, unix: bool = False) -> bytes:
|
|
330
|
+
"""A classic BPF program for bwrap's --seccomp: deny the syscalls in _DENY (EPERM), make
|
|
331
|
+
clone3 fail with ENOSYS (the C library then uses clone), and deny socket(AF_UNIX) unless
|
|
332
|
+
`unix` (the shared-connection ssh, which runs with no network and one socket bound in)."""
|
|
333
|
+
machine = machine or _machine()
|
|
334
|
+
if machine not in _AUDIT_ARCH:
|
|
335
|
+
raise ConfineError(f"no seccomp filter for the {machine} architecture")
|
|
336
|
+
col = 0 if machine == "x86_64" else 1
|
|
337
|
+
allow, kill = 0x7FFF0000, 0x80000000
|
|
338
|
+
eperm, enosys = 0x00050000 | _EPERM, 0x00050000 | _ENOSYS
|
|
339
|
+
ld, jeq, jge, ret = 0x20, 0x15, 0x35, 0x06
|
|
340
|
+
prog: List[Tuple[int, int, int, int]] = [(ld, 0, 0, 4), (jeq, 1, 0, _AUDIT_ARCH[machine]),
|
|
341
|
+
(ret, 0, 0, kill), (ld, 0, 0, 0)]
|
|
342
|
+
if machine == "x86_64":
|
|
343
|
+
prog += [(jge, 0, 1, 0x40000000), (ret, 0, 0, eperm)] # the x32 ABI
|
|
344
|
+
for nums in _DENY.values():
|
|
345
|
+
prog += [(jeq, 0, 1, nums[col]), (ret, 0, 0, eperm)]
|
|
346
|
+
prog += [(jeq, 0, 1, _CLONE3[col]), (ret, 0, 0, enosys)]
|
|
347
|
+
if not unix:
|
|
348
|
+
prog += [(jeq, 0, 3, _SOCKET[col]), (ld, 0, 0, 16), (jeq, 0, 1, _AF_UNIX),
|
|
349
|
+
(ret, 0, 0, eperm)]
|
|
350
|
+
prog += [(ret, 0, 0, allow)]
|
|
351
|
+
return b"".join(struct.pack("<HBBI", *ins) for ins in prog)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
# Runs inside bubblewrap before the command: Landlock allows writes only below the given paths.
|
|
355
|
+
# argv: N PATH... CMD [ARG]... Exit 126 when Landlock (ABI 2 or later) is not available.
|
|
356
|
+
LANDLOCK_HELPER = r"""
|
|
357
|
+
import ctypes, os, struct, sys
|
|
358
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
359
|
+
libc.syscall.restype = ctypes.c_long
|
|
360
|
+
def fail(msg):
|
|
361
|
+
sys.stderr.write("phiward gateway: " + msg + "; nothing runs\n"); os._exit(126)
|
|
362
|
+
abi = libc.syscall(444, None, ctypes.c_size_t(0), ctypes.c_uint32(1))
|
|
363
|
+
if abi < 2:
|
|
364
|
+
fail("Landlock ABI 2 or later is needed (the kernel has %s)" % ("none" if abi < 0 else abi))
|
|
365
|
+
fs = 0
|
|
366
|
+
for bit in (1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13): # write, remove, make, refer
|
|
367
|
+
fs |= 1 << bit
|
|
368
|
+
if abi >= 3: fs |= 1 << 14 # truncate
|
|
369
|
+
if abi >= 5: fs |= 1 << 15 # ioctl on devices
|
|
370
|
+
attr = struct.pack("<Q", fs)
|
|
371
|
+
if abi >= 4: attr += struct.pack("<Q", 0)
|
|
372
|
+
if abi >= 6: attr += struct.pack("<Q", 3) # scope: abstract unix sockets, signals
|
|
373
|
+
buf = ctypes.create_string_buffer(attr, len(attr))
|
|
374
|
+
rs = libc.syscall(444, buf, ctypes.c_size_t(len(attr)), ctypes.c_uint32(0))
|
|
375
|
+
if rs < 0: fail("Landlock cannot make a ruleset")
|
|
376
|
+
n = int(sys.argv[1]); entries = sys.argv[2:2 + n]
|
|
377
|
+
k = int(sys.argv[2 + n]); close = sys.argv[3 + n:3 + n + k]; cmd = sys.argv[3 + n + k:]
|
|
378
|
+
for c in close: # the broker's descriptors of the places: the command does not get them
|
|
379
|
+
try:
|
|
380
|
+
os.close(int(c))
|
|
381
|
+
except OSError:
|
|
382
|
+
pass
|
|
383
|
+
filebits = (1 << 1) | (fs & ((1 << 14) | (1 << 15)))
|
|
384
|
+
for e in entries:
|
|
385
|
+
p, dev, ino = e.rsplit("|", 2)
|
|
386
|
+
try:
|
|
387
|
+
fd = os.open(p, os.O_PATH | os.O_CLOEXEC | (os.O_NOFOLLOW if dev != "-" else 0))
|
|
388
|
+
except OSError:
|
|
389
|
+
continue
|
|
390
|
+
st = os.fstat(fd)
|
|
391
|
+
if dev != "-" and (st.st_dev, st.st_ino) != (int(dev), int(ino)):
|
|
392
|
+
fail("a write place changed before the command started") # the bound folder only
|
|
393
|
+
bits = fs if os.path.isdir(p) else filebits
|
|
394
|
+
rule = ctypes.create_string_buffer(struct.pack("<Qi", bits, fd), 12)
|
|
395
|
+
if libc.syscall(445, ctypes.c_int(rs), ctypes.c_int(1), rule, ctypes.c_uint32(0)) < 0:
|
|
396
|
+
fail("Landlock cannot add a rule")
|
|
397
|
+
os.close(fd)
|
|
398
|
+
if libc.prctl(38, 1, 0, 0, 0) != 0: fail("no_new_privs cannot be set")
|
|
399
|
+
if libc.syscall(446, ctypes.c_int(rs), ctypes.c_uint32(0)) < 0: fail("Landlock cannot be enforced")
|
|
400
|
+
os.close(rs)
|
|
401
|
+
try:
|
|
402
|
+
os.execvp(cmd[0], cmd)
|
|
403
|
+
except OSError:
|
|
404
|
+
sys.stderr.write("phiward gateway: the command could not start\n"); os._exit(127)
|
|
405
|
+
"""
|
|
406
|
+
|
|
407
|
+
_GATEWAY_DEVICES = ("/dev/null", "/dev/zero") # no /dev/tty: the gateway has no terminal
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
# -- entry points -------------------------------------------------------------------------------
|
|
411
|
+
|
|
412
|
+
_NO_BACKEND = ("no confinement backend on this system (needs macOS sandbox-exec or Linux "
|
|
413
|
+
"bubblewrap)")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def gateway_command(argv: Sequence[str], writable: Sequence[str], patterns: Sequence[str],
|
|
417
|
+
net: bool = False, deny_read: Sequence[str] = (),
|
|
418
|
+
socket: str = "", allow_read: Sequence[str] = ()) -> Tuple[List[str], List[int]]:
|
|
419
|
+
"""`argv` wrapped so that it writes only to `writable` (and pattern matches), with no
|
|
420
|
+
network unless `net`, and the file descriptors that must stay open for it (Linux: the
|
|
421
|
+
seccomp program). The caller closes the descriptors after the process starts."""
|
|
422
|
+
b = backend()
|
|
423
|
+
if b == "seatbelt":
|
|
424
|
+
return [SANDBOX_EXEC, "-p", seatbelt_gateway_profile(writable, patterns, net, deny_read,
|
|
425
|
+
socket, allow_read)] + \
|
|
426
|
+
list(argv), []
|
|
427
|
+
if b == "bwrap":
|
|
428
|
+
prog = seccomp_program(unix=bool(socket))
|
|
429
|
+
r, w = os.pipe()
|
|
430
|
+
os.write(w, prog) # small: it fits in the pipe buffer
|
|
431
|
+
os.close(w)
|
|
432
|
+
fds: Dict[str, int] = {}
|
|
433
|
+
try:
|
|
434
|
+
for p in gateway_places(writable, patterns):
|
|
435
|
+
fds[p] = open_place(p)
|
|
436
|
+
except ConfineError:
|
|
437
|
+
for fd in list(fds.values()) + [r]:
|
|
438
|
+
os.close(fd)
|
|
439
|
+
raise
|
|
440
|
+
entries = []
|
|
441
|
+
for p, fd in fds.items():
|
|
442
|
+
os.set_inheritable(fd, True)
|
|
443
|
+
st = os.fstat(fd)
|
|
444
|
+
entries.append(f"{p}|{st.st_dev}|{st.st_ino}")
|
|
445
|
+
entries += [f"{d}|-|-" for d in _GATEWAY_DEVICES]
|
|
446
|
+
held = [str(fd) for fd in fds.values()]
|
|
447
|
+
helper = [sys.executable, "-I", "-S", "-c", LANDLOCK_HELPER, str(len(entries))] + \
|
|
448
|
+
entries + [str(len(held))] + held
|
|
449
|
+
return [shutil.which("bwrap") or "bwrap", "--seccomp", str(r)] + \
|
|
450
|
+
bwrap_gateway_args(writable, patterns, net, fds, deny_read, socket, allow_read) + \
|
|
451
|
+
["--"] + helper + \
|
|
452
|
+
list(argv), \
|
|
453
|
+
[r] + list(fds.values())
|
|
454
|
+
raise ConfineError(_NO_BACKEND)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def self_test() -> Optional[str]:
|
|
458
|
+
"""Why the gateway's confinement does not work here, or None. It runs `true` in the
|
|
459
|
+
gateway profile."""
|
|
460
|
+
try:
|
|
461
|
+
cmd, fds = gateway_command(["true"], [], [], False)
|
|
462
|
+
try:
|
|
463
|
+
r = subprocess.run(cmd, capture_output=True, timeout=30, pass_fds=fds)
|
|
464
|
+
finally:
|
|
465
|
+
for fd in fds:
|
|
466
|
+
os.close(fd)
|
|
467
|
+
if r.returncode != 0:
|
|
468
|
+
why = r.stderr.decode("utf-8", "replace").strip().splitlines()
|
|
469
|
+
return f"the gateway profile cannot start a process here (exit {r.returncode}" + \
|
|
470
|
+
(f": {why[-1]}" if why else "; on Ubuntu 24.04, unprivileged user namespaces "
|
|
471
|
+
"may be blocked by AppArmor") + ")"
|
|
472
|
+
except ConfineError as exc:
|
|
473
|
+
return str(exc)
|
|
474
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
475
|
+
return f"the confinement backend failed ({type(exc).__name__})"
|
|
476
|
+
return None
|