@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.41
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.
- package/dist/containers.d.ts +7 -2
- package/dist/containers.js +7 -3
- package/dist/device-service-conformance.d.ts +38 -0
- package/dist/device-service-conformance.js +142 -0
- package/dist/dual-replica.d.ts +23 -1
- package/dist/dual-replica.js +53 -0
- package/dist/fake-channel.d.ts +44 -5
- package/dist/fake-channel.js +63 -2
- package/dist/fake-dial-in-machine.d.ts +173 -0
- package/dist/fake-dial-in-machine.js +429 -0
- package/dist/fake-e2b.d.ts +34 -0
- package/dist/fake-e2b.js +95 -1
- package/dist/fake-git-server.d.ts +32 -4
- package/dist/fake-git-server.js +87 -19
- package/dist/fake-lark.d.ts +12 -1
- package/dist/fake-lark.js +63 -10
- package/dist/fake-oauth-server.d.ts +62 -2
- package/dist/fake-oauth-server.js +86 -5
- package/dist/fake-slack.d.ts +17 -1
- package/dist/fake-slack.js +98 -0
- package/dist/fake-telegram.d.ts +173 -0
- package/dist/fake-telegram.js +632 -0
- package/dist/fixtures.d.ts +24 -8
- package/dist/fixtures.js +31 -8
- package/dist/index.d.ts +15 -9
- package/dist/index.js +10 -4
- package/dist/kernel-helpers.d.ts +16 -4
- package/dist/kernel-helpers.js +39 -4
- package/dist/media-samples.d.ts +2 -0
- package/dist/media-samples.js +2 -0
- package/dist/model-conformance.d.ts +15 -10
- package/dist/model-conformance.js +87 -14
- package/dist/push-conformance.d.ts +31 -0
- package/dist/push-conformance.js +160 -0
- package/dist/replica-runner.js +2 -0
- package/dist/sandbox-native-conformance.d.ts +31 -0
- package/dist/sandbox-native-conformance.js +153 -0
- package/dist/sandbox-permission-conformance.d.ts +310 -0
- package/dist/sandbox-permission-conformance.js +1491 -0
- package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
- package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
- package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
- package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
- package/fixtures/extensions/fake-client/package.json +12 -0
- package/fixtures/extensions/fake-client/src/client.tsx +51 -0
- package/fixtures/extensions/fake-client/src/index.ts +43 -0
- package/fixtures/extensions/fake-client/themes/fake.json +11 -0
- package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-client-broken/package.json +12 -0
- package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
- package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
- package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
- package/fixtures/extensions/fake-connector/src/index.ts +64 -34
- package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-context/package.json +12 -0
- package/fixtures/extensions/fake-context/src/index.ts +78 -0
- package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
- package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
- package/fixtures/extensions/fake-embed/src/index.ts +26 -26
- package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
- package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
- package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
- package/fixtures/extensions/fake-im/src/channel.ts +22 -1
- package/fixtures/extensions/fake-im/src/checks.ts +94 -0
- package/fixtures/extensions/fake-im/src/directory.ts +44 -20
- package/fixtures/extensions/fake-im/src/index.ts +59 -11
- package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
- package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
- package/fixtures/extensions/fake-lifecycle/package.json +12 -0
- package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
- package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
- package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
- package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
- package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
- package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
- package/fixtures/extensions/fake-push/package.json +12 -0
- package/fixtures/extensions/fake-push/src/check.ts +40 -0
- package/fixtures/extensions/fake-push/src/index.ts +56 -0
- package/fixtures/extensions/fake-push/src/push.ts +103 -0
- package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
- package/fixtures/extensions/fake-web/src/index.ts +5 -4
- package/fixtures/extensions/fake-web/src/web.ts +11 -7
- package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
- package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
- package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
- package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
- package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
- package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
- package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
- package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
- package/fixtures/plugins/fake-theme/logo.svg +1 -0
- package/fixtures/plugins/fake-theme/package.json +8 -0
- package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
- package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
- package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
- package/package.json +6 -5
|
@@ -0,0 +1,1491 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { isIP, isIPv4 } from "node:net";
|
|
4
|
+
import { posix } from "node:path";
|
|
5
|
+
import { classifyAddress, isSandboxPermissionUnsupportedError, isSandboxScopeDeniedError, isSandboxScopeValidationError, OPEN_PUBLIC_DENIED_CLASSES, SANDBOX_RESERVED_NAME_PREFIX, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
6
|
+
const text = (data) => (data === null ? null : Buffer.from(data).toString());
|
|
7
|
+
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
8
|
+
/** A Python program in which one thread rewrites a syscall's pointer argument mid-call. */
|
|
9
|
+
const FLIP_PROGRAM = String.raw `
|
|
10
|
+
import ctypes, socket, struct, sys, threading
|
|
11
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
12
|
+
mode, rounds = sys.argv[1], int(sys.argv[2])
|
|
13
|
+
stop = threading.Event()
|
|
14
|
+
def flipper(buffer, good, bad):
|
|
15
|
+
while not stop.is_set():
|
|
16
|
+
ctypes.memmove(buffer, bad, len(bad))
|
|
17
|
+
ctypes.memmove(buffer, good, len(good))
|
|
18
|
+
ok = 0
|
|
19
|
+
if mode == "connect":
|
|
20
|
+
def sockaddr(host, port):
|
|
21
|
+
if sys.platform == "darwin":
|
|
22
|
+
# BSD sockaddr_in: a length byte, then a one-byte family
|
|
23
|
+
return struct.pack("BBH4s8x", 16, socket.AF_INET, socket.htons(port), socket.inet_aton(host))
|
|
24
|
+
return struct.pack("HH4s8x", socket.AF_INET, socket.htons(port), socket.inet_aton(host))
|
|
25
|
+
if sys.argv[3] == "proxy":
|
|
26
|
+
# The allowed target is the operation's own HTTP proxy, taken from its environment.
|
|
27
|
+
import os, urllib.parse
|
|
28
|
+
proxy = urllib.parse.urlsplit(os.environ.get("http_proxy") or os.environ["HTTP_PROXY"])
|
|
29
|
+
good = sockaddr(socket.gethostbyname(proxy.hostname), proxy.port)
|
|
30
|
+
else:
|
|
31
|
+
good = sockaddr(sys.argv[3], int(sys.argv[4]))
|
|
32
|
+
bad = sockaddr(sys.argv[5], int(sys.argv[6]))
|
|
33
|
+
buffer = ctypes.create_string_buffer(good, len(good))
|
|
34
|
+
thread = threading.Thread(target=flipper, args=(buffer, good, bad))
|
|
35
|
+
thread.start()
|
|
36
|
+
for _ in range(rounds):
|
|
37
|
+
fd = libc.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
|
|
38
|
+
if fd >= 0 and libc.connect(fd, buffer, len(good)) == 0:
|
|
39
|
+
ok += 1
|
|
40
|
+
if fd >= 0:
|
|
41
|
+
libc.close(fd)
|
|
42
|
+
else:
|
|
43
|
+
good, bad = sys.argv[3].encode() + b"\0", sys.argv[4].encode() + b"\0"
|
|
44
|
+
size = max(len(good), len(bad))
|
|
45
|
+
good, bad = good.ljust(size, b"\0"), bad.ljust(size, b"\0")
|
|
46
|
+
buffer = ctypes.create_string_buffer(good, size)
|
|
47
|
+
thread = threading.Thread(target=flipper, args=(buffer, good, bad))
|
|
48
|
+
thread.start()
|
|
49
|
+
for index in range(rounds):
|
|
50
|
+
if libc.chmod(buffer, 0o640 if index % 2 else 0o600) == 0:
|
|
51
|
+
ok += 1
|
|
52
|
+
stop.set()
|
|
53
|
+
thread.join()
|
|
54
|
+
print("ok=%d" % ok)
|
|
55
|
+
`;
|
|
56
|
+
/** Binds and listens on each address; restricted none/allowlist must allow loopback only. */
|
|
57
|
+
const BIND_PROGRAM = `
|
|
58
|
+
import socket
|
|
59
|
+
out = []
|
|
60
|
+
for family, host in ((socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1"),
|
|
61
|
+
(socket.AF_INET, "0.0.0.0"), (socket.AF_INET6, "::")):
|
|
62
|
+
s = socket.socket(family, socket.SOCK_STREAM)
|
|
63
|
+
try:
|
|
64
|
+
s.bind((host, 0))
|
|
65
|
+
s.listen(1)
|
|
66
|
+
out.append(host + "=ok")
|
|
67
|
+
except OSError:
|
|
68
|
+
out.append(host + "=denied")
|
|
69
|
+
s.close()
|
|
70
|
+
# Dissolving an association (connect AF_UNSPEC) must not turn listen() into a bind to any address.
|
|
71
|
+
import ctypes
|
|
72
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
73
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
74
|
+
libc.connect(s.fileno(), ctypes.create_string_buffer(16), 16)
|
|
75
|
+
try:
|
|
76
|
+
s.listen(1)
|
|
77
|
+
out.append("unspec=" + s.getsockname()[0])
|
|
78
|
+
except OSError:
|
|
79
|
+
out.append("unspec=denied")
|
|
80
|
+
print(" ".join(out))
|
|
81
|
+
`;
|
|
82
|
+
/** A Full-access UNIX service (stream, seqpacket, datagram) counting every client it sees. */
|
|
83
|
+
const UNIX_SERVER = `
|
|
84
|
+
import errno, os, socket, sys, threading
|
|
85
|
+
UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
|
|
86
|
+
path, counter = sys.argv[1], sys.argv[2]
|
|
87
|
+
lock = threading.Lock()
|
|
88
|
+
count = [0]
|
|
89
|
+
def seen():
|
|
90
|
+
with lock:
|
|
91
|
+
count[0] += 1
|
|
92
|
+
with open(counter + ".tmp", "w") as handle:
|
|
93
|
+
handle.write(str(count[0]))
|
|
94
|
+
os.replace(counter + ".tmp", counter)
|
|
95
|
+
def serve(kind, suffix):
|
|
96
|
+
try:
|
|
97
|
+
s = socket.socket(socket.AF_UNIX, kind)
|
|
98
|
+
except OSError as error:
|
|
99
|
+
if error.errno not in UNSUPPORTED:
|
|
100
|
+
raise
|
|
101
|
+
# this OS has no such UNIX socket type (macOS: SOCK_SEQPACKET): mark it and stop
|
|
102
|
+
open(path + suffix, "w").close()
|
|
103
|
+
return
|
|
104
|
+
s.bind(path + suffix)
|
|
105
|
+
if kind == socket.SOCK_DGRAM:
|
|
106
|
+
while True:
|
|
107
|
+
s.recv(100)
|
|
108
|
+
seen()
|
|
109
|
+
s.listen(16)
|
|
110
|
+
while True:
|
|
111
|
+
s.accept()[0].close()
|
|
112
|
+
seen()
|
|
113
|
+
threads = [threading.Thread(target=serve, args=a, daemon=True)
|
|
114
|
+
for a in ((socket.SOCK_STREAM, ""), (socket.SOCK_SEQPACKET, ".seq"), (socket.SOCK_DGRAM, ".dgram"))]
|
|
115
|
+
for thread in threads:
|
|
116
|
+
thread.start()
|
|
117
|
+
with open(counter + ".tmp", "w") as handle:
|
|
118
|
+
handle.write("0")
|
|
119
|
+
while not all(os.path.exists(path + suffix) for suffix in ("", ".seq", ".dgram")):
|
|
120
|
+
pass
|
|
121
|
+
os.replace(counter + ".tmp", counter)
|
|
122
|
+
threading.Event().wait()
|
|
123
|
+
`;
|
|
124
|
+
/** Tries every way to reach the outside UNIX service; prints ok/denied per attempt. */
|
|
125
|
+
const UNIX_CLIENT = `
|
|
126
|
+
import errno, socket, sys
|
|
127
|
+
UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
|
|
128
|
+
path, link = sys.argv[1], sys.argv[2]
|
|
129
|
+
class Unsupported(Exception):
|
|
130
|
+
pass
|
|
131
|
+
def make(create):
|
|
132
|
+
# the OS has no such UNIX socket type at all (macOS: SOCK_SEQPACKET, SOCK_RAW)
|
|
133
|
+
try:
|
|
134
|
+
return create()
|
|
135
|
+
except OSError as error:
|
|
136
|
+
if error.errno in UNSUPPORTED:
|
|
137
|
+
raise Unsupported()
|
|
138
|
+
raise
|
|
139
|
+
def attempt(name, action):
|
|
140
|
+
try:
|
|
141
|
+
action()
|
|
142
|
+
return name + "=ok"
|
|
143
|
+
except Unsupported:
|
|
144
|
+
return name + "=unsupported"
|
|
145
|
+
except OSError:
|
|
146
|
+
return name + "=denied"
|
|
147
|
+
def connect(kind, target):
|
|
148
|
+
make(lambda: socket.socket(socket.AF_UNIX, kind)).connect(target)
|
|
149
|
+
def send(kind):
|
|
150
|
+
make(lambda: socket.socket(socket.AF_UNIX, kind)).sendto(b"x", path + ".dgram")
|
|
151
|
+
def pair(kind):
|
|
152
|
+
# An explicit address on a socketpair datagram socket is honoured by the kernel.
|
|
153
|
+
first, _ = make(lambda: socket.socketpair(socket.AF_UNIX, kind))
|
|
154
|
+
try:
|
|
155
|
+
first.sendto(b"x", path + ".dgram")
|
|
156
|
+
except OSError as error:
|
|
157
|
+
# the OS ignores no explicit address on a connected socket (macOS): no such vector there
|
|
158
|
+
if error.errno == errno.EISCONN:
|
|
159
|
+
raise Unsupported()
|
|
160
|
+
raise
|
|
161
|
+
print(" ".join([
|
|
162
|
+
attempt("stream", lambda: connect(socket.SOCK_STREAM, path)),
|
|
163
|
+
attempt("seqpacket", lambda: connect(socket.SOCK_SEQPACKET, path + ".seq")),
|
|
164
|
+
attempt("dgram", lambda: send(socket.SOCK_DGRAM)),
|
|
165
|
+
attempt("raw", lambda: send(socket.SOCK_RAW)),
|
|
166
|
+
attempt("link", lambda: connect(socket.SOCK_STREAM, link)),
|
|
167
|
+
attempt("pair-dgram", lambda: pair(socket.SOCK_DGRAM)),
|
|
168
|
+
attempt("pair-raw", lambda: pair(socket.SOCK_RAW)),
|
|
169
|
+
]))
|
|
170
|
+
`;
|
|
171
|
+
/**
|
|
172
|
+
* Connects to a UNIX service another process made inside the root (stream, and seqpacket where the
|
|
173
|
+
* OS has it), by the relative path and by `argv[2]` (absolute); prints ok/denied/unsupported.
|
|
174
|
+
*/
|
|
175
|
+
const FOREIGN_UNIX_CLIENT = `
|
|
176
|
+
import errno, socket, sys
|
|
177
|
+
UNSUPPORTED = (errno.EPROTONOSUPPORT, errno.ESOCKTNOSUPPORT, errno.EPROTOTYPE, errno.EOPNOTSUPP)
|
|
178
|
+
out = []
|
|
179
|
+
for name, kind, suffix in (("stream", socket.SOCK_STREAM, ""), ("seqpacket", socket.SOCK_SEQPACKET, ".seq")):
|
|
180
|
+
for spelling, path in (("", sys.argv[1]), ("-absolute", sys.argv[2])):
|
|
181
|
+
try:
|
|
182
|
+
s = socket.socket(socket.AF_UNIX, kind)
|
|
183
|
+
except OSError as error:
|
|
184
|
+
out.append(name + spelling + ("=unsupported" if error.errno in UNSUPPORTED else "=denied"))
|
|
185
|
+
continue
|
|
186
|
+
try:
|
|
187
|
+
s.settimeout(10)
|
|
188
|
+
s.connect(path + suffix)
|
|
189
|
+
out.append(name + spelling + "=ok")
|
|
190
|
+
except OSError:
|
|
191
|
+
out.append(name + spelling + "=denied")
|
|
192
|
+
s.close()
|
|
193
|
+
print("foreign-unix-client " + " ".join(out))
|
|
194
|
+
`;
|
|
195
|
+
/** A UNIX stream server and client inside the root talk to each other. */
|
|
196
|
+
const UNIX_ROUNDTRIP = `
|
|
197
|
+
import socket, sys
|
|
198
|
+
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
199
|
+
server.bind(sys.argv[1])
|
|
200
|
+
server.listen(1)
|
|
201
|
+
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
202
|
+
client.connect(sys.argv[1])
|
|
203
|
+
peer = server.accept()[0]
|
|
204
|
+
client.sendall(b"ping")
|
|
205
|
+
print("roundtrip=ok" if peer.recv(4) == b"ping" else "roundtrip=bad")
|
|
206
|
+
`;
|
|
207
|
+
/** Atomically exchanges a directory with a symlink to an outside path until a stop file exists. */
|
|
208
|
+
const SWAP_PROGRAM = `
|
|
209
|
+
import ctypes, os, sys
|
|
210
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
211
|
+
base, outside, stop = sys.argv[1], sys.argv[2], sys.argv[3]
|
|
212
|
+
os.makedirs(base + "/dir")
|
|
213
|
+
os.symlink(outside, base + "/link")
|
|
214
|
+
open(base + "/swapping", "w").close()
|
|
215
|
+
swaps = 0
|
|
216
|
+
def exchange(a, b):
|
|
217
|
+
if sys.platform == "darwin":
|
|
218
|
+
return libc.renamex_np(a, b, 2) # RENAME_SWAP
|
|
219
|
+
return libc.renameat2(-100, a, -100, b, 2) # RENAME_EXCHANGE
|
|
220
|
+
while not os.path.exists(stop):
|
|
221
|
+
if exchange((base + "/dir").encode(), (base + "/link").encode()) == 0:
|
|
222
|
+
swaps += 1
|
|
223
|
+
print("swaps=%d" % swaps)
|
|
224
|
+
`;
|
|
225
|
+
/**
|
|
226
|
+
* Run by a same-uid process outside every operation: tries `PTRACE_ATTACH` and opens `mem` and
|
|
227
|
+
* `environ` of a control child of its own (proving the probe sees real access) and of the target.
|
|
228
|
+
*/
|
|
229
|
+
const OUTSIDE_PROBE = `
|
|
230
|
+
import ctypes, errno, json, os, signal, sys, time
|
|
231
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
232
|
+
libc.ptrace.restype = ctypes.c_long
|
|
233
|
+
libc.ptrace.argtypes = (ctypes.c_long, ctypes.c_long, ctypes.c_void_p, ctypes.c_void_p)
|
|
234
|
+
PTRACE_ATTACH, PTRACE_DETACH, WALL = 16, 17, 0x40000000
|
|
235
|
+
def name(code):
|
|
236
|
+
return errno.errorcode.get(code, str(code))
|
|
237
|
+
def opened(pid, entry):
|
|
238
|
+
try:
|
|
239
|
+
fd = os.open("/proc/%d/%s" % (pid, entry), os.O_RDONLY)
|
|
240
|
+
except OSError as error:
|
|
241
|
+
return name(error.errno)
|
|
242
|
+
try:
|
|
243
|
+
if entry == "environ":
|
|
244
|
+
os.read(fd, 1)
|
|
245
|
+
finally:
|
|
246
|
+
os.close(fd)
|
|
247
|
+
return "ALLOWED"
|
|
248
|
+
def attach(pid):
|
|
249
|
+
if libc.ptrace(PTRACE_ATTACH, pid, None, None) < 0:
|
|
250
|
+
return name(ctypes.get_errno())
|
|
251
|
+
# Undo at once (the attach stopped the target) so even a failing check leaves it running.
|
|
252
|
+
os.waitpid(pid, WALL)
|
|
253
|
+
libc.ptrace(PTRACE_DETACH, pid, None, None)
|
|
254
|
+
return "ALLOWED"
|
|
255
|
+
def probe(pid):
|
|
256
|
+
return {"mem": opened(pid, "mem"), "environ": opened(pid, "environ"), "attach": attach(pid)}
|
|
257
|
+
child = os.fork()
|
|
258
|
+
if child == 0:
|
|
259
|
+
time.sleep(600)
|
|
260
|
+
os._exit(0)
|
|
261
|
+
control = probe(child)
|
|
262
|
+
os.kill(child, signal.SIGKILL)
|
|
263
|
+
os.waitpid(child, 0)
|
|
264
|
+
target = int(sys.argv[1])
|
|
265
|
+
def identity(pid):
|
|
266
|
+
with open("/proc/%d/status" % pid) as handle:
|
|
267
|
+
uid = [int(line.split()[1]) for line in handle if line.startswith("Uid:")][0]
|
|
268
|
+
with open("/proc/%d/cmdline" % pid, "rb") as handle:
|
|
269
|
+
return {"uid": uid, "cmdline": handle.read().replace(b"\\0", b" ").decode().strip()}
|
|
270
|
+
print(json.dumps({"uid": os.getuid(), "who": identity(target), "control": control,
|
|
271
|
+
"target": probe(target)}))
|
|
272
|
+
`;
|
|
273
|
+
/**
|
|
274
|
+
* Listens on loopback and connects to its own listener (refused: no sandboxed client reaches a
|
|
275
|
+
* loopback listener, its own included), then tries to join a reuseport group (refused).
|
|
276
|
+
*/
|
|
277
|
+
const OWN_LOOPBACK = `
|
|
278
|
+
import json, socket
|
|
279
|
+
out = {}
|
|
280
|
+
for family, host in ((socket.AF_INET, "127.0.0.1"), (socket.AF_INET6, "::1")):
|
|
281
|
+
server = socket.socket(family, socket.SOCK_STREAM)
|
|
282
|
+
server.bind((host, 0))
|
|
283
|
+
server.listen(4)
|
|
284
|
+
client = socket.socket(family, socket.SOCK_STREAM)
|
|
285
|
+
client.settimeout(5)
|
|
286
|
+
try:
|
|
287
|
+
client.connect((host, server.getsockname()[1]))
|
|
288
|
+
out["own " + host] = "ok"
|
|
289
|
+
except OSError:
|
|
290
|
+
out["own " + host] = "denied"
|
|
291
|
+
s = socket.socket()
|
|
292
|
+
try:
|
|
293
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
|
294
|
+
out["reuseport"] = "ok"
|
|
295
|
+
except OSError:
|
|
296
|
+
out["reuseport"] = "denied"
|
|
297
|
+
print(json.dumps(out, sort_keys=True))
|
|
298
|
+
`;
|
|
299
|
+
/** Listens on loopback, publishes its port and prints what the first client sends. */
|
|
300
|
+
const LOOPBACK_SERVICE = `
|
|
301
|
+
import os, socket, sys
|
|
302
|
+
server = socket.socket()
|
|
303
|
+
server.bind(("127.0.0.1", 0))
|
|
304
|
+
server.listen(1)
|
|
305
|
+
server.settimeout(60)
|
|
306
|
+
with open(sys.argv[1] + ".tmp", "w") as handle:
|
|
307
|
+
handle.write(str(server.getsockname()[1]))
|
|
308
|
+
os.rename(sys.argv[1] + ".tmp", sys.argv[1])
|
|
309
|
+
peer = server.accept()[0]
|
|
310
|
+
peer.settimeout(10)
|
|
311
|
+
print(peer.recv(16).decode())
|
|
312
|
+
`;
|
|
313
|
+
const CHECK_PART = {
|
|
314
|
+
"outside-switch": "processes",
|
|
315
|
+
environment: "filesystem",
|
|
316
|
+
"reserved-names": "filesystem",
|
|
317
|
+
"link-chain": "filesystem",
|
|
318
|
+
"closed-granted": "network",
|
|
319
|
+
loopback: "network",
|
|
320
|
+
"open-network": "network",
|
|
321
|
+
"foreign-unix": "network",
|
|
322
|
+
};
|
|
323
|
+
/** The innocent-looking planted name a denylist would let through (see `deviceEnvironment`). */
|
|
324
|
+
const SECRET_LOOKING = /SECRET|TOKEN|KEY|PASS|CREDENTIAL|^CAPYBARA_/i;
|
|
325
|
+
/** The minimal environment's fixed names (see `deviceEnvironment`). */
|
|
326
|
+
const MINIMAL_ENVIRONMENT = new Set([
|
|
327
|
+
"PATH",
|
|
328
|
+
"LANG",
|
|
329
|
+
"HOME",
|
|
330
|
+
"TMPDIR",
|
|
331
|
+
"TMP",
|
|
332
|
+
"TEMP",
|
|
333
|
+
"PWD",
|
|
334
|
+
"OLDPWD",
|
|
335
|
+
"SHLVL",
|
|
336
|
+
"_",
|
|
337
|
+
]);
|
|
338
|
+
/**
|
|
339
|
+
* Proves an actual provider's permission boundary on one shared device (approval-only profiles
|
|
340
|
+
* design). The sandbox is the device's and the same under every profile: a profile only chooses
|
|
341
|
+
* who approves a crossing, so every profile's ordinary call is sandboxed, and only the escalated
|
|
342
|
+
* pair (the device filesystem with the environment network, legal only together) runs outside it,
|
|
343
|
+
* and only with outside-sandbox support while the owner allows it.
|
|
344
|
+
*
|
|
345
|
+
* An operation-boundary provider (a local device) is proved with positive controls; sibling,
|
|
346
|
+
* symlink, protected-path, mandatory-deny, reserved-name, protected-link-chain and network
|
|
347
|
+
* denials; every profile sandboxed with the minimal environment; the open network (closed classes
|
|
348
|
+
* refused by resolved address, rebinding and fake-IP names included) and the allowlist (closed
|
|
349
|
+
* classes refused even for granted names); loopback listeners (Linux: loopback only, no sandboxed
|
|
350
|
+
* connect to any, its own included, no `SO_REUSEPORT`; macOS: none at all); escalated-pair
|
|
351
|
+
* controls outside the sandbox; both overlap orders; component/root swaps and mutable syscall
|
|
352
|
+
* pointers during access; exact cancellation; a supervisor closed to same-uid outsiders (when the
|
|
353
|
+
* fixture can run one) and fresh narrowed scopes. Pathname UNIX services outside the roots stay
|
|
354
|
+
* unreachable under every sandbox network, and so does one another process made inside a write
|
|
355
|
+
* root (only the operation's own sockets are reachable). A provider that reports restricted unsupported must
|
|
356
|
+
* refuse restricted operations (fail closed); nothing here substitutes a fixture flag for support.
|
|
357
|
+
*
|
|
358
|
+
* An instance-boundary provider (a cloud device: the container or microVM is the sandbox) is
|
|
359
|
+
* proved with every profile running alike in the instance (its whole filesystem the scope),
|
|
360
|
+
* nothing outside it, the outer network (open or allowlist) for every operation, and exact
|
|
361
|
+
* cancellation.
|
|
362
|
+
*
|
|
363
|
+
* Not covered, by design (known limitations, not passes): metadata reads outside the roots (stat,
|
|
364
|
+
* readlink, xattrs, statfs), and the world-readable `/proc/<pid>` entries of other processes of the
|
|
365
|
+
* same uid, such as `cmdline`, `stat` and `status`. A restricted operation can therefore read the
|
|
366
|
+
* command line of a concurrent escalated command on the device: Landlock cannot scope `/proc` to the
|
|
367
|
+
* operation's own process tree (see the Linux launcher's known limitations). Providers keep secrets
|
|
368
|
+
* out of command lines; ptrace-guarded entries (`environ`, `mem`, `maps`, `fd`) stay closed.
|
|
369
|
+
*/
|
|
370
|
+
export async function runSandboxPermissionConformance(fixture, options = {}) {
|
|
371
|
+
const { root, sibling } = fixture;
|
|
372
|
+
const unavailable = [];
|
|
373
|
+
const report = () => ({ unavailable: [...unavailable] });
|
|
374
|
+
const part = (name) => options.parts === undefined || options.parts.includes(name);
|
|
375
|
+
/** The parts' other checks run only in a run that does not pick single checks. */
|
|
376
|
+
const whole = (name) => options.checks === undefined && part(name);
|
|
377
|
+
const want = (check) => options.checks === undefined ? part(CHECK_PART[check]) : options.checks.includes(check);
|
|
378
|
+
const at = (base, name) => posix.join(base, name);
|
|
379
|
+
const secret = `sibling-secret-${randomUUID()}`;
|
|
380
|
+
// the project is the fixture's root; what a sandboxed operation reads is the provider's rule
|
|
381
|
+
const scoped = (writeRoots) => ({
|
|
382
|
+
kind: "scoped",
|
|
383
|
+
projectRoot: root,
|
|
384
|
+
writeRoots,
|
|
385
|
+
});
|
|
386
|
+
const restricted = (network = { kind: "none" }, writeRoots = [root]) => ({
|
|
387
|
+
profile: "approve-for-me",
|
|
388
|
+
filesystem: scoped(writeRoots),
|
|
389
|
+
network,
|
|
390
|
+
});
|
|
391
|
+
/**
|
|
392
|
+
* The escalated pair: one call run outside the sandbox (the device filesystem with the
|
|
393
|
+
* environment network). Only an outside-sandbox grant makes it legal, under any profile; the
|
|
394
|
+
* profile names who approved it, nothing more.
|
|
395
|
+
*/
|
|
396
|
+
const escalated = {
|
|
397
|
+
profile: "request-approval",
|
|
398
|
+
filesystem: { kind: "device" },
|
|
399
|
+
network: { kind: "environment" },
|
|
400
|
+
};
|
|
401
|
+
const PROFILES = [
|
|
402
|
+
"request-approval",
|
|
403
|
+
"approve-for-me",
|
|
404
|
+
"full-access",
|
|
405
|
+
];
|
|
406
|
+
const { granted, ungranted, access } = fixture.endpoints;
|
|
407
|
+
const proxied = access === "proxy";
|
|
408
|
+
const allowlisted = { kind: "allowlist", hosts: [granted.name] };
|
|
409
|
+
const exec = async (grant, command, signal = new AbortController().signal, timeoutMs = 120_000) => (await fixture.operation(grant)).exec({
|
|
410
|
+
command,
|
|
411
|
+
cwd: root,
|
|
412
|
+
timeoutMs,
|
|
413
|
+
maxOutputBytes: 1 << 20,
|
|
414
|
+
signal,
|
|
415
|
+
});
|
|
416
|
+
const native = async (grant) => {
|
|
417
|
+
const operation = await fixture.operation(grant);
|
|
418
|
+
assert(operation.list && operation.scan, "Permission conformance requires list and scan");
|
|
419
|
+
return operation;
|
|
420
|
+
};
|
|
421
|
+
const signal = new AbortController().signal;
|
|
422
|
+
const denied = async (promise, what) => {
|
|
423
|
+
await assert.rejects(promise, (error) => isSandboxScopeDeniedError(error), what);
|
|
424
|
+
};
|
|
425
|
+
const waitFor = (path, pending) => waitForFile(fixture.inspect.readFile, path, pending);
|
|
426
|
+
/**
|
|
427
|
+
* Asserts that every process of `pids` ends. A kill is asynchronous: the operation can report
|
|
428
|
+
* its cancel or timeout while a killed descendant is still being delivered its signal or waits
|
|
429
|
+
* for its reaper, so this polls `alive` until none is left, failing with the survivors after
|
|
430
|
+
* 10 s.
|
|
431
|
+
*/
|
|
432
|
+
const ended = async (pids, message) => {
|
|
433
|
+
const deadline = Date.now() + 10_000;
|
|
434
|
+
let left = await fixture.inspect.alive(pids);
|
|
435
|
+
while (left.length > 0 && Date.now() < deadline) {
|
|
436
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
437
|
+
left = await fixture.inspect.alive(left);
|
|
438
|
+
}
|
|
439
|
+
assert.deepEqual(left, [], message);
|
|
440
|
+
};
|
|
441
|
+
const receipts = async () => Promise.all([granted, ...ungranted].map((endpoint) => endpoint.receipts()));
|
|
442
|
+
const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.address)}, ${endpoint.port}), 10).close()`)}`;
|
|
443
|
+
/** An HTTP request by name; curl and Python use the environment's proxy when there is one. */
|
|
444
|
+
const byName = (endpoint) => `curl -fsS -m 10 -o /dev/null http://${endpoint.name}:${endpoint.port}/`;
|
|
445
|
+
const url = (target) => `http://${isIP(target.host) === 6 ? `[${target.host}]` : target.host}:${target.port}/`;
|
|
446
|
+
/**
|
|
447
|
+
* Asks for each target by URL in one sandboxed command and returns the HTTP status per label
|
|
448
|
+
* ("000": no answer at all). `viaProxy`: every request goes to the environment's proxy (curl
|
|
449
|
+
* `--noproxy ''`, overriding a `NO_PROXY` list); otherwise curl follows the environment as an
|
|
450
|
+
* ordinary client does (a `NO_PROXY` entry connects directly, which the sandbox must refuse).
|
|
451
|
+
*/
|
|
452
|
+
const probeTargets = async (grant, targets, viaProxy) => {
|
|
453
|
+
if (targets.length === 0)
|
|
454
|
+
return {};
|
|
455
|
+
const noProxy = viaProxy ? "--noproxy '' " : "";
|
|
456
|
+
const result = await exec(grant, targets
|
|
457
|
+
.map((target) => `printf '%s %s\\n' ${quote(target.label)} "$(curl -sS -m 10 ${noProxy}-o /dev/null -w '%{http_code}' ${quote(url(target))} 2>/dev/null)"`)
|
|
458
|
+
.join("; "));
|
|
459
|
+
assert.equal(result.exitCode, 0, `the target probe must run: ${result.stderr}`);
|
|
460
|
+
return Object.fromEntries(result.stdout
|
|
461
|
+
.trim()
|
|
462
|
+
.split("\n")
|
|
463
|
+
.map((line) => line.split(" ")));
|
|
464
|
+
};
|
|
465
|
+
const counts = async (targets) => Promise.all(targets.map(async (target) => (target.receipts ? target.receipts() : 0)));
|
|
466
|
+
const reached = (status) => status !== undefined && /^[23]\d\d$/.test(status);
|
|
467
|
+
/**
|
|
468
|
+
* Every closed target is refused (a proxied provider answers its own 403 before any dial) and
|
|
469
|
+
* none sees a connection; every reachable target answers and, where counted, sees one.
|
|
470
|
+
*/
|
|
471
|
+
const proveTargets = async (grant, reachable, closed, what) => {
|
|
472
|
+
const before = await counts([...reachable, ...closed]);
|
|
473
|
+
// as an ordinary client: closed targets stay unreached whatever NO_PROXY says
|
|
474
|
+
const plain = await probeTargets(grant, closed, false);
|
|
475
|
+
for (const target of closed)
|
|
476
|
+
assert(!reached(plain[target.label]), `${what}: ${target.label} (${url(target)}) must not be reached: ${JSON.stringify(plain)}`);
|
|
477
|
+
const statuses = await probeTargets(grant, [...reachable, ...closed], proxied);
|
|
478
|
+
const after = await counts([...reachable, ...closed]);
|
|
479
|
+
reachable.forEach((target, index) => {
|
|
480
|
+
assert(reached(statuses[target.label]), `${what}: ${target.label} (${url(target)}) must be reached: ${JSON.stringify(statuses)}`);
|
|
481
|
+
if (target.receipts)
|
|
482
|
+
assert((after[index] ?? 0) > (before[index] ?? 0), `${what}: ${target.label} must see the connection`);
|
|
483
|
+
});
|
|
484
|
+
closed.forEach((target, offset) => {
|
|
485
|
+
const index = reachable.length + offset;
|
|
486
|
+
const status = statuses[target.label];
|
|
487
|
+
assert(proxied ? status === "403" : !reached(status), `${what}: ${target.label} (${url(target)}) must be refused${proxied ? " by the proxy (403)" : ""}: ${JSON.stringify(statuses)}`);
|
|
488
|
+
assert.equal(after[index], before[index], `${what}: ${target.label} must see no connection`);
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
/** The names of the planted device variables a command under `grant` can see, and its names. */
|
|
492
|
+
const environmentOf = async (grant) => {
|
|
493
|
+
const planted = fixture.deviceEnvironment?.variables ?? {};
|
|
494
|
+
const result = await exec(grant, "env");
|
|
495
|
+
assert.equal(result.exitCode, 0, `env must run: ${result.stderr}`);
|
|
496
|
+
const names = result.stdout
|
|
497
|
+
.split("\n")
|
|
498
|
+
.filter((line) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(line))
|
|
499
|
+
.map((line) => line.slice(0, line.indexOf("=")));
|
|
500
|
+
return {
|
|
501
|
+
leaked: Object.entries(planted)
|
|
502
|
+
.filter(([, value]) => result.stdout.includes(value))
|
|
503
|
+
.map(([name]) => name),
|
|
504
|
+
names,
|
|
505
|
+
};
|
|
506
|
+
};
|
|
507
|
+
const leakedVariables = async (grant) => (await environmentOf(grant)).leaked;
|
|
508
|
+
/**
|
|
509
|
+
* A sandboxed command under `grant` sees no planted value and, on an operation boundary, only
|
|
510
|
+
* the minimal environment's names (a denylist would pass the first, never the second).
|
|
511
|
+
*/
|
|
512
|
+
const proveMinimalEnvironment = async (grant, minimalNames) => {
|
|
513
|
+
const environment = fixture.deviceEnvironment;
|
|
514
|
+
if (!environment)
|
|
515
|
+
return;
|
|
516
|
+
const { leaked, names } = await environmentOf(grant);
|
|
517
|
+
assert.deepEqual(leaked, [], `${grant.profile}: no device variable reaches a sandboxed command`);
|
|
518
|
+
if (!minimalNames)
|
|
519
|
+
return;
|
|
520
|
+
const allowed = new Set([...MINIMAL_ENVIRONMENT, ...(environment.allowed ?? [])]);
|
|
521
|
+
const extra = names.filter((name) => !allowed.has(name) && !/proxy/i.test(name));
|
|
522
|
+
assert.deepEqual(extra, [], `${grant.profile}: a sandboxed command gets the minimal environment only (PATH, LANG, HOME, ` +
|
|
523
|
+
"TMPDIR/TMP/TEMP, the proxy variables, the stated tool homes), never a filtered copy of " +
|
|
524
|
+
"the device's");
|
|
525
|
+
};
|
|
526
|
+
/** The closed-class names behind allowlist grants, or none (reported unavailable). */
|
|
527
|
+
const closedGrantedTargets = () => {
|
|
528
|
+
const closed = fixture.endpoints.closedGranted;
|
|
529
|
+
if (closed === undefined)
|
|
530
|
+
return [];
|
|
531
|
+
if ("unavailable" in closed)
|
|
532
|
+
return [];
|
|
533
|
+
return closed;
|
|
534
|
+
};
|
|
535
|
+
const namedReachAvailable = () => {
|
|
536
|
+
const reach = fixture.endpoints.namedReach;
|
|
537
|
+
if (reach === undefined || reach === "available")
|
|
538
|
+
return true;
|
|
539
|
+
unavailable.push({ item: "allowlist positive by name", reason: reach.unavailable });
|
|
540
|
+
return false;
|
|
541
|
+
};
|
|
542
|
+
/** The escalated pair is refused before anything runs (typed), and leaves no trace. */
|
|
543
|
+
const escalationRefused = async (what) => {
|
|
544
|
+
const marker = `escalated-${randomUUID()}`;
|
|
545
|
+
await assert.rejects(exec(escalated, `printf ran > ${quote(at(root, marker))}`), (error) => isSandboxScopeDeniedError(error) ||
|
|
546
|
+
isSandboxPermissionUnsupportedError(error) ||
|
|
547
|
+
isSandboxScopeValidationError(error), what);
|
|
548
|
+
assert.equal(await fixture.inspect.readFile(at(root, marker)), null, `${what}: nothing ran`);
|
|
549
|
+
};
|
|
550
|
+
/** A sandboxed filesystem with the environment network is refused as invalid (typed). */
|
|
551
|
+
const environmentPairRefused = async (writeRoots) => {
|
|
552
|
+
const marker = `env-ran-${randomUUID()}`;
|
|
553
|
+
await assert.rejects(exec({
|
|
554
|
+
profile: "full-access",
|
|
555
|
+
filesystem: scoped(writeRoots),
|
|
556
|
+
network: { kind: "environment" },
|
|
557
|
+
}, `printf ran > ${quote(at(root, marker))}`), (error) => isSandboxScopeValidationError(error) || isSandboxScopeDeniedError(error), "the environment network without the device filesystem must be refused before it runs " +
|
|
558
|
+
"(only the escalated pair carries it)");
|
|
559
|
+
assert.equal(await fixture.inspect.readFile(at(root, marker)), null, "nothing ran");
|
|
560
|
+
};
|
|
561
|
+
/** The open network under every profile (approval-only profiles design, "Open network"). */
|
|
562
|
+
const proveOpenNetwork = async (writeRoots) => {
|
|
563
|
+
const open = fixture.openNetwork;
|
|
564
|
+
assert(open, "a provider reporting network.openPublic needs the openNetwork fixture");
|
|
565
|
+
assert(open.closed.length > 0, "the open network needs closed targets");
|
|
566
|
+
// the closed targets cover every closed class (by their literal host or served address)
|
|
567
|
+
const covered = new Set(open.closed
|
|
568
|
+
.map((target) => target.address ?? target.host)
|
|
569
|
+
.filter((host) => isIP(host) !== 0)
|
|
570
|
+
.map((host) => classifyAddress(host)));
|
|
571
|
+
const missing = OPEN_PUBLIC_DENIED_CLASSES.filter((cls) => !covered.has(cls));
|
|
572
|
+
assert.deepEqual(missing, [], "the open network's closed targets cover every closed class");
|
|
573
|
+
const reachable = "unavailable" in open.reachable ? [] : open.reachable;
|
|
574
|
+
if ("unavailable" in open.reachable)
|
|
575
|
+
unavailable.push({
|
|
576
|
+
item: "open network: public targets",
|
|
577
|
+
reason: open.reachable.unavailable,
|
|
578
|
+
});
|
|
579
|
+
const fake = open.fakeIp && !("unavailable" in open.fakeIp) ? open.fakeIp : undefined;
|
|
580
|
+
if (open.fakeIp === undefined)
|
|
581
|
+
unavailable.push({ item: "open network: fake-IP names", reason: "no fakeIp fixture" });
|
|
582
|
+
else if ("unavailable" in open.fakeIp)
|
|
583
|
+
unavailable.push({ item: "open network: fake-IP names", reason: open.fakeIp.unavailable });
|
|
584
|
+
assert(reachable.length + (fake?.reachable.length ?? 0) > 0 || open.allowNoPositive === true, "the open network needs a reachable public target (set allowNoPositive only for an offline run)");
|
|
585
|
+
for (const profile of PROFILES) {
|
|
586
|
+
const grant = {
|
|
587
|
+
profile,
|
|
588
|
+
filesystem: scoped(writeRoots),
|
|
589
|
+
network: { kind: "open-public" },
|
|
590
|
+
};
|
|
591
|
+
await proveTargets(grant, [...reachable, ...(fake?.reachable ?? [])], [...open.closed, ...(fake?.closed ?? [])], `open network (${profile})`);
|
|
592
|
+
if (proxied)
|
|
593
|
+
// only the proxy dials: a raw connect to a public address bypasses it and is refused
|
|
594
|
+
for (const target of reachable.filter((t) => t.address !== undefined)) {
|
|
595
|
+
const raw = await exec(grant, `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(target.address)}, ${target.port}), 10).close()`)}`);
|
|
596
|
+
assert.notEqual(raw.exitCode, 0, `open network (${profile}): raw ${target.label}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
const urlopen = (endpoint) => `python3 -c ${quote(`import urllib.request; urllib.request.urlopen("http://${endpoint.name}:${endpoint.port}/", timeout=10).read()`)}`;
|
|
601
|
+
/** Exact cancellation and timeouts of operations under `grant` (whose roots cover `root`). */
|
|
602
|
+
const proveCancellation = async (grant) => {
|
|
603
|
+
// Exact cancellation: detached descendants end; a sibling operation keeps running.
|
|
604
|
+
const keepAlive = exec(grant, `printf r > ready-keep; until [ -e release-keep ]; do sleep 0.01; done; printf done > kept`);
|
|
605
|
+
await waitFor(at(root, "ready-keep"), keepAlive);
|
|
606
|
+
const abort = new AbortController();
|
|
607
|
+
const regrouped = fixture.regroupedDescendants !== "not-promised";
|
|
608
|
+
const cancelled = exec(grant, `(sleep 1000 & echo $! > p1); nohup sh -c 'sleep 1001' > /dev/null 2>&1 & echo $! > p2; ` +
|
|
609
|
+
`setsid sleep 1002 > /dev/null 2>&1 & ` +
|
|
610
|
+
(regrouped
|
|
611
|
+
? `python3 -c ${quote("import os, time\nif os.fork() == 0:\n os.setpgid(0, 0)\n open('p3.tmp', 'w').write(str(os.getpid()))\n os.rename('p3.tmp', 'p3')\n time.sleep(1003)")} & ` +
|
|
612
|
+
`until [ -e p3 ]; do sleep 0.01; done; `
|
|
613
|
+
: "") +
|
|
614
|
+
`printf r > ready-cancel; sleep 1004`, abort.signal);
|
|
615
|
+
await waitFor(at(root, "ready-cancel"), cancelled);
|
|
616
|
+
const pids = await Promise.all((regrouped ? ["p1", "p2", "p3"] : ["p1", "p2"]).map(async (name) => Number(text(await fixture.inspect.readFile(at(root, name))))));
|
|
617
|
+
assert.deepEqual(await fixture.inspect.alive(pids), pids, "descendants run before cancel");
|
|
618
|
+
abort.abort();
|
|
619
|
+
const stopped = await cancelled;
|
|
620
|
+
assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
|
|
621
|
+
await ended(pids, "cancellation ends every descendant");
|
|
622
|
+
await exec(grant, "touch release-keep");
|
|
623
|
+
assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
|
|
624
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
|
|
625
|
+
// Timeout ends the whole owned tree as well.
|
|
626
|
+
const timed = await exec(grant, `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
|
|
627
|
+
assert.equal(timed.timedOut, true, "a restricted timeout is reported");
|
|
628
|
+
const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
|
|
629
|
+
await ended([p4], "timeout ends background children");
|
|
630
|
+
};
|
|
631
|
+
/**
|
|
632
|
+
* An instance-boundary provider (a cloud device): the container or microVM is the sandbox, its
|
|
633
|
+
* whole filesystem the scope, its outer network the sandbox network. Every profile runs there
|
|
634
|
+
* alike, nothing runs outside it, and the outer network holds for every operation.
|
|
635
|
+
*/
|
|
636
|
+
const proveInstanceBoundary = async (support) => {
|
|
637
|
+
assert.equal(support.restricted, null, "an instance boundary has no per-operation restriction");
|
|
638
|
+
assert.equal(support.outsideSandbox, false, "an instance boundary has nothing outside");
|
|
639
|
+
assert.equal(support.network.perOperationHosts, false, "an instance's outer network covers every operation: no per-operation hosts");
|
|
640
|
+
const network = fixture.instanceNetwork;
|
|
641
|
+
assert(network, "an instance-boundary fixture names its outer network (instanceNetwork)");
|
|
642
|
+
const closedGranted = fixture.endpoints.closedGranted;
|
|
643
|
+
assert(Array.isArray(closedGranted) &&
|
|
644
|
+
closedGranted.some((target) => target.address !== undefined && classifyAddress(target.address) === "metadata"), "an instance boundary needs closedGranted with a name served at a cloud metadata address");
|
|
645
|
+
const whole = ["/"];
|
|
646
|
+
const instanceGrant = (profile, kind = network === "open" ? "open-public" : "allowlist") => ({
|
|
647
|
+
profile,
|
|
648
|
+
filesystem: scoped(whole),
|
|
649
|
+
network: kind === "allowlist"
|
|
650
|
+
? {
|
|
651
|
+
kind: "allowlist",
|
|
652
|
+
hosts: [granted.name, ...closedGrantedTargets().map((t) => t.host)],
|
|
653
|
+
}
|
|
654
|
+
: { kind },
|
|
655
|
+
});
|
|
656
|
+
await fixture.seed([
|
|
657
|
+
{ path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
|
|
658
|
+
]);
|
|
659
|
+
// nothing runs outside the instance, and the environment network comes only with it
|
|
660
|
+
await escalationRefused("an instance boundary must refuse the escalated pair");
|
|
661
|
+
await environmentPairRefused(whole);
|
|
662
|
+
// every profile runs alike inside: the whole instance is the scope, root and sibling included
|
|
663
|
+
const bytes = new Uint8Array([7, 8, 9]);
|
|
664
|
+
for (const profile of PROFILES) {
|
|
665
|
+
const shell = await exec(instanceGrant(profile), `printf ${profile} > ${quote(at(root, `${profile}.txt`))} && cat ${quote(at(sibling, "secret"))}`);
|
|
666
|
+
assert.equal(shell.exitCode, 0, `${profile} runs in the instance: ${shell.stderr}`);
|
|
667
|
+
assert.equal(shell.stdout, secret, `${profile} reads anywhere in the instance`);
|
|
668
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, `${profile}.txt`))), profile);
|
|
669
|
+
await (await native(instanceGrant(profile))).writeFile(at(sibling, `${profile}.bin`), bytes, signal);
|
|
670
|
+
assert.deepEqual(await (await native(instanceGrant(profile))).readFile(at(sibling, `${profile}.bin`), {
|
|
671
|
+
maxBytes: 10,
|
|
672
|
+
signal,
|
|
673
|
+
}), { data: bytes, truncated: false });
|
|
674
|
+
if (fixture.deviceEnvironment)
|
|
675
|
+
assert.deepEqual(await leakedVariables(instanceGrant(profile)), [], `${profile}: no provider variable reaches a command`);
|
|
676
|
+
}
|
|
677
|
+
// the outer network holds for every operation and profile
|
|
678
|
+
if (network === "open") {
|
|
679
|
+
assert(support.network.openPublic, "an open outer network must be reported as openPublic");
|
|
680
|
+
await proveOpenNetwork(whole);
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
assert(support.network.allowlist, "an allowlist outer network must be reported as allowlist");
|
|
684
|
+
assert(ungranted.length > 0, "an allowlist outer network needs an ungranted endpoint");
|
|
685
|
+
const named = namedReachAvailable();
|
|
686
|
+
for (const profile of PROFILES) {
|
|
687
|
+
const before = await receipts();
|
|
688
|
+
const grant = instanceGrant(profile);
|
|
689
|
+
let positives = 0;
|
|
690
|
+
if (named) {
|
|
691
|
+
const result = await exec(grant, byName(granted));
|
|
692
|
+
assert.equal(result.exitCode, 0, `${profile}: the allowlisted name: ${result.stderr}`);
|
|
693
|
+
positives++;
|
|
694
|
+
}
|
|
695
|
+
for (const endpoint of ungranted)
|
|
696
|
+
for (const command of [connect(endpoint), byName(endpoint)]) {
|
|
697
|
+
const result = await exec(grant, command);
|
|
698
|
+
assert.notEqual(result.exitCode, 0, `${profile}: ungranted ${endpoint.name}: ${command}`);
|
|
699
|
+
}
|
|
700
|
+
// a scope that names an ungranted host widens nothing: the instance's list holds for
|
|
701
|
+
// every operation (no per-operation hosts)
|
|
702
|
+
const asked = {
|
|
703
|
+
...grant,
|
|
704
|
+
network: {
|
|
705
|
+
kind: "allowlist",
|
|
706
|
+
hosts: [granted.name, ...ungranted.map((endpoint) => endpoint.name)],
|
|
707
|
+
},
|
|
708
|
+
};
|
|
709
|
+
for (const endpoint of ungranted) {
|
|
710
|
+
const result = await exec(asked, byName(endpoint));
|
|
711
|
+
assert.notEqual(result.exitCode, 0, `${profile}: an ungranted name in the scope's hosts must still be refused: ${endpoint.name}`);
|
|
712
|
+
}
|
|
713
|
+
await proveTargets(grant, [], closedGrantedTargets(), `${profile} allowlist`);
|
|
714
|
+
const after = await receipts();
|
|
715
|
+
assert.equal(after[0], (before[0] ?? 0) + positives, `${profile}: granted receipts`);
|
|
716
|
+
assert.deepEqual(after.slice(1), before.slice(1), `${profile}: ungranted see nothing`);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
await proveCancellation(instanceGrant("full-access"));
|
|
720
|
+
};
|
|
721
|
+
try {
|
|
722
|
+
assert(options.parts === undefined || options.parts.length > 0, "parts must not be empty");
|
|
723
|
+
assert(options.checks === undefined || options.checks.length > 0, "checks must not be empty");
|
|
724
|
+
for (const [label, endpoint] of [
|
|
725
|
+
["granted", granted],
|
|
726
|
+
...ungranted.map((endpoint) => ["ungranted", endpoint]),
|
|
727
|
+
]) {
|
|
728
|
+
const problems = validateAllowHost(endpoint.name);
|
|
729
|
+
assert(problems.length === 0, `${label} endpoint name ${endpoint.name} is not a valid allowlist host: ${problems.join("; ")}`);
|
|
730
|
+
assert(isIP(endpoint.address) !== 0, `${label} endpoint address ${endpoint.address} is not a numeric address`);
|
|
731
|
+
}
|
|
732
|
+
assert(isIPv4(granted.address), "the granted endpoint address must be IPv4 (race program)");
|
|
733
|
+
assert(ungranted.every((endpoint) => endpoint.name !== granted.name), "ungranted endpoints need names other than the granted one");
|
|
734
|
+
const support = await fixture.support();
|
|
735
|
+
assert.equal(support.version, 2, "permission support must be version 2");
|
|
736
|
+
if (support.boundary === "instance") {
|
|
737
|
+
await proveInstanceBoundary(support);
|
|
738
|
+
return report();
|
|
739
|
+
}
|
|
740
|
+
if (support.restricted === null) {
|
|
741
|
+
// Fail closed: no restricted operation may run, and nothing falls back to the escalated pair.
|
|
742
|
+
await assert.rejects((async () => (await fixture.operation(restricted())).exec({
|
|
743
|
+
command: "true",
|
|
744
|
+
cwd: root,
|
|
745
|
+
timeoutMs: 10_000,
|
|
746
|
+
maxOutputBytes: 1024,
|
|
747
|
+
signal,
|
|
748
|
+
}))(), (error) => isSandboxPermissionUnsupportedError(error), "an unsupported runtime must refuse restricted operations");
|
|
749
|
+
return report();
|
|
750
|
+
}
|
|
751
|
+
assert.deepEqual(support.restricted, { filesystem: true, network: true, native: true, concurrentScopes: true }, "restricted support requires all four claims together");
|
|
752
|
+
// the approval-only inputs a provider with restricted support must give the harness
|
|
753
|
+
const planted = fixture.deviceEnvironment?.variables ?? {};
|
|
754
|
+
assert(Object.keys(planted).some((name) => SECRET_LOOKING.test(name)) &&
|
|
755
|
+
Object.keys(planted).some((name) => !SECRET_LOOKING.test(name)), "deviceEnvironment must plant a secret-looking and an innocent-looking variable");
|
|
756
|
+
assert(fixture.endpoints.closedGranted !== undefined, "closedGranted is required (or { unavailable } with the reason)");
|
|
757
|
+
if (Array.isArray(fixture.endpoints.closedGranted))
|
|
758
|
+
assert(fixture.endpoints.closedGranted.length > 0, "closedGranted must not be empty");
|
|
759
|
+
else
|
|
760
|
+
unavailable.push({
|
|
761
|
+
item: "allowlisted names in closed classes",
|
|
762
|
+
reason: fixture.endpoints.closedGranted.unavailable,
|
|
763
|
+
});
|
|
764
|
+
if (support.outsideSandbox)
|
|
765
|
+
assert(fixture.withoutOutsideSandbox, "withoutOutsideSandbox is required with outside-sandbox support");
|
|
766
|
+
assert(fixture.home, "home is required (or { unavailable } with the reason)");
|
|
767
|
+
if ("unavailable" in fixture.home)
|
|
768
|
+
unavailable.push({ item: "protected link chains", reason: fixture.home.unavailable });
|
|
769
|
+
await fixture.seed([
|
|
770
|
+
{ path: at(sibling, "secret"), kind: "file", data: new TextEncoder().encode(secret) },
|
|
771
|
+
{ path: at(root, "inroot.txt"), kind: "file", data: new TextEncoder().encode("inroot") },
|
|
772
|
+
{ path: at(root, "escape"), kind: "symlink", target: at(sibling, "secret") },
|
|
773
|
+
{ path: at(root, "linked"), kind: "symlink", target: sibling },
|
|
774
|
+
]);
|
|
775
|
+
const siblingMode = await fixture.inspect.mode(at(sibling, "secret"));
|
|
776
|
+
const siblingIntact = async (label) => {
|
|
777
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "secret"))), secret, label);
|
|
778
|
+
assert.equal(await fixture.inspect.mode(at(sibling, "secret")), siblingMode, label);
|
|
779
|
+
};
|
|
780
|
+
// Positive controls: ordinary shell, Python, Node and native work inside the root.
|
|
781
|
+
const shell = await exec(restricted(), "cat inroot.txt && printf shell > shell.txt && mkdir -p d/e && printf x > d/e/f && " +
|
|
782
|
+
"chmod 755 d/e/f && touch -t 200101010000 d/e/f && ln -s shell.txt alias && cat alias");
|
|
783
|
+
assert.equal(shell.exitCode, 0, `restricted shell work must succeed: ${shell.stderr}`);
|
|
784
|
+
assert.equal(shell.stdout, "inrootshell");
|
|
785
|
+
assert.equal(await fixture.inspect.mode(at(root, "d/e/f")), 0o755, "chmod inside the root");
|
|
786
|
+
const python = await exec(restricted(), `python3 -c ${quote("import pathlib; p = pathlib.Path('py.txt'); p.write_text('py'); print(p.read_text())")}`);
|
|
787
|
+
assert.equal(python.exitCode, 0, `restricted Python work must succeed: ${python.stderr}`);
|
|
788
|
+
assert.equal(python.stdout.trim(), "py");
|
|
789
|
+
const node = await exec(restricted(), `node -e ${quote("const fs = require('fs'); fs.writeFileSync('node.txt', 'node'); console.log(fs.readFileSync('node.txt', 'utf8'))")}`);
|
|
790
|
+
assert.equal(node.exitCode, 0, `restricted Node work must succeed: ${node.stderr}`);
|
|
791
|
+
assert.equal(node.stdout.trim(), "node");
|
|
792
|
+
const bytes = new Uint8Array([0, 1, 2, 255]);
|
|
793
|
+
await (await native(restricted())).writeFile(at(root, "native/n.bin"), bytes, signal);
|
|
794
|
+
assert.deepEqual(await (await native(restricted())).readFile(at(root, "native/n.bin"), {
|
|
795
|
+
maxBytes: 10,
|
|
796
|
+
signal,
|
|
797
|
+
}), { data: bytes, truncated: false });
|
|
798
|
+
assert.deepEqual(await (await native(restricted())).stat(at(root, "native/n.bin"), signal), {
|
|
799
|
+
size: 4,
|
|
800
|
+
isDir: false,
|
|
801
|
+
});
|
|
802
|
+
assert.deepEqual(await (await native(restricted())).list(at(root, "native"), {
|
|
803
|
+
limit: 10,
|
|
804
|
+
signal,
|
|
805
|
+
}), { entries: [{ name: "n.bin", isDir: false }], truncated: false });
|
|
806
|
+
// The scope contract: the environment network comes only with the device filesystem (the
|
|
807
|
+
// escalated pair), which runs only with outside-sandbox support and while the owner allows it.
|
|
808
|
+
await environmentPairRefused([root]);
|
|
809
|
+
if (!support.outsideSandbox)
|
|
810
|
+
await escalationRefused("without outside-sandbox support the escalated pair is refused");
|
|
811
|
+
else if (want("outside-switch") && fixture.withoutOutsideSandbox) {
|
|
812
|
+
const restore = await fixture.withoutOutsideSandbox();
|
|
813
|
+
try {
|
|
814
|
+
await escalationRefused("the escalated pair while the owner's outside-sandbox setting is off");
|
|
815
|
+
}
|
|
816
|
+
finally {
|
|
817
|
+
await restore();
|
|
818
|
+
}
|
|
819
|
+
const control = await exec(escalated, `printf ran > ${quote(at(root, "escalated-ran"))}`);
|
|
820
|
+
assert.equal(control.exitCode, 0, `the escalated pair runs again: ${control.stderr}`);
|
|
821
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "escalated-ran"))), "ran");
|
|
822
|
+
}
|
|
823
|
+
if (whole("filesystem")) {
|
|
824
|
+
// Mandatory write denies inside a granted root (the macOS set, shared through the SDK): git
|
|
825
|
+
// configuration and hooks (a later unsandboxed `git` there would run them), shell startup
|
|
826
|
+
// files and editor/agent configuration. Direct writes, creation, renames, hard and symbolic
|
|
827
|
+
// links, and the same paths in a repository the command creates itself all stay refused.
|
|
828
|
+
await fixture.seed([
|
|
829
|
+
{ path: at(root, "repo/.git/config"), kind: "file", data: new TextEncoder().encode("cfg") },
|
|
830
|
+
{
|
|
831
|
+
path: at(root, "repo/.git/hooks/pre-commit.sample"),
|
|
832
|
+
kind: "file",
|
|
833
|
+
data: new TextEncoder().encode("s"),
|
|
834
|
+
},
|
|
835
|
+
{
|
|
836
|
+
path: at(root, "repo/.git/HEAD"),
|
|
837
|
+
kind: "file",
|
|
838
|
+
data: new TextEncoder().encode("ref: x"),
|
|
839
|
+
},
|
|
840
|
+
]);
|
|
841
|
+
const evil = '[core]\n\tfsmonitor = "touch escaped; false"\n';
|
|
842
|
+
const denies = await exec(restricted(), [
|
|
843
|
+
`cd repo`,
|
|
844
|
+
`printf ${quote(evil)} > .git/config`,
|
|
845
|
+
`printf x >> .git/config`,
|
|
846
|
+
`mkdir -p .git/hooks; printf '#!/bin/sh' > .git/hooks/pre-commit`,
|
|
847
|
+
`chmod 755 .git/hooks/pre-commit.sample`,
|
|
848
|
+
`printf x > staged-config; mv staged-config .git/config`,
|
|
849
|
+
`printf x > staged-hook; ln staged-hook .git/hooks/post-checkout`,
|
|
850
|
+
`ln -s ../staged-hook .git/hooks/pre-push`,
|
|
851
|
+
`ln -s .git/config cfg-link; printf x > cfg-link`,
|
|
852
|
+
`mkdir moved; printf x > moved/config; mkdir -p sub; mv moved sub/.git`,
|
|
853
|
+
`mkdir -p ../ptr && printf 'gitdir: /tmp' > ../ptr/.git`,
|
|
854
|
+
`cd ..; git init -q nested 2>/dev/null; mkdir -p nested/.git/hooks; printf x > nested/.git/hooks/pre-commit; printf x > nested/.git/config`,
|
|
855
|
+
`printf x > .bashrc; printf x > .zshrc; printf x > .profile; printf x > .gitconfig; printf x > .gitmodules; printf x > .mcp.json`,
|
|
856
|
+
`mkdir -p .vscode && printf x > .vscode/settings.json; mkdir -p .idea && printf x > .idea/x`,
|
|
857
|
+
`mkdir -p .claude/commands .claude/agents; printf x > .claude/commands/c.md; printf x > .claude/agents/a.md`,
|
|
858
|
+
`mkdir -p deep/er; printf x > deep/er/.bash_profile`,
|
|
859
|
+
`printf ok > allowed.txt`,
|
|
860
|
+
`true`,
|
|
861
|
+
].join("; "));
|
|
862
|
+
assert.equal(denies.exitCode, 0, `the mandatory-deny probe must run: ${denies.stderr}`);
|
|
863
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "allowed.txt"))), "ok", "ordinary writes");
|
|
864
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", ".git/config");
|
|
865
|
+
assert.equal((await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-commit.sample"))) !== 0o755, true, "hook mode");
|
|
866
|
+
for (const path of [
|
|
867
|
+
"repo/.git/hooks/pre-commit",
|
|
868
|
+
"repo/.git/hooks/post-checkout",
|
|
869
|
+
"repo/.git/hooks/pre-push",
|
|
870
|
+
"repo/sub/.git/config",
|
|
871
|
+
"ptr/.git",
|
|
872
|
+
"nested/.git/hooks/pre-commit",
|
|
873
|
+
"nested/.git/config",
|
|
874
|
+
".bashrc",
|
|
875
|
+
".zshrc",
|
|
876
|
+
".profile",
|
|
877
|
+
".gitconfig",
|
|
878
|
+
".gitmodules",
|
|
879
|
+
".mcp.json",
|
|
880
|
+
".vscode/settings.json",
|
|
881
|
+
".idea/x",
|
|
882
|
+
".claude/commands/c.md",
|
|
883
|
+
".claude/agents/a.md",
|
|
884
|
+
"deep/er/.bash_profile",
|
|
885
|
+
])
|
|
886
|
+
assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
|
|
887
|
+
assert.equal(await fixture.inspect.mode(at(root, "repo/.git/hooks/pre-push")), null, "a symbolic link into the hooks is refused too");
|
|
888
|
+
await denied((await native(restricted())).writeFile(at(root, "repo/.git/config"), bytes, signal), "native write of .git/config");
|
|
889
|
+
await denied((await native(restricted())).writeFile(at(root, "repo/.git/hooks/post-merge"), bytes, signal), "native write of a git hook");
|
|
890
|
+
await denied((await native(restricted())).writeFile(at(root, ".vscode/tasks.json"), bytes, signal), "native write of editor configuration");
|
|
891
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg");
|
|
892
|
+
// Inside a .git directory only git's ordinary internals are writable: the gitdirs of
|
|
893
|
+
// submodules and worktrees keep their configuration, hooks and pointers too. A bare-repository
|
|
894
|
+
// lookalike (a HEAD file outside .git) and moving .git away are refused as well, and the
|
|
895
|
+
// matching folds case and Unicode compatibility forms.
|
|
896
|
+
await fixture.seed([
|
|
897
|
+
{
|
|
898
|
+
path: at(root, "repo/.git/modules/sub/config"),
|
|
899
|
+
kind: "file",
|
|
900
|
+
data: new TextEncoder().encode("cfg"),
|
|
901
|
+
},
|
|
902
|
+
{ path: at(root, "repo/.git/modules/sub/hooks"), kind: "directory" },
|
|
903
|
+
{ path: at(root, "repo/.git/modules/sub/objects"), kind: "directory" },
|
|
904
|
+
{
|
|
905
|
+
path: at(root, "repo/.git/worktrees/wt/commondir"),
|
|
906
|
+
kind: "file",
|
|
907
|
+
data: new TextEncoder().encode("../.."),
|
|
908
|
+
},
|
|
909
|
+
]);
|
|
910
|
+
const internals = await exec(restricted(), [
|
|
911
|
+
"cd repo",
|
|
912
|
+
"printf x >> .git/modules/sub/config",
|
|
913
|
+
"printf x > .git/modules/sub/hooks/pre-commit",
|
|
914
|
+
"printf x > .git/worktrees/wt/commondir",
|
|
915
|
+
"printf x > .git/worktrees/wt/config.worktree",
|
|
916
|
+
"printf x > .git/worktrees/wt/gitdir",
|
|
917
|
+
"printf x > .git/info-attributes-probe; mkdir -p .git/info; printf x > .git/info/attributes",
|
|
918
|
+
"printf x > .git/modules/sub/objects/ok-object",
|
|
919
|
+
"mkdir -p ../bare/objects ../bare/refs; printf 'ref: refs/heads/main' > ../bare/HEAD; printf x > ../bare/config",
|
|
920
|
+
"mv .git ../moved-git; printf x >> ../moved-git/config",
|
|
921
|
+
"cd ..",
|
|
922
|
+
"printf x > .envrc; printf x > .npmrc; mkdir -p deep; printf x > deep/.npmrc",
|
|
923
|
+
"printf x > .BASHRC; printf x > .envrc",
|
|
924
|
+
"true",
|
|
925
|
+
].join("; "));
|
|
926
|
+
assert.equal(internals.exitCode, 0, `the git-internals probe must run: ${internals.stderr}`);
|
|
927
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/config"))), "cfg", "submodule config");
|
|
928
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/worktrees/wt/commondir"))), "../..", "worktree commondir");
|
|
929
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/modules/sub/objects/ok-object"))), "x", "submodule objects stay writable");
|
|
930
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "repo/.git/config"))), "cfg", "moving .git away");
|
|
931
|
+
for (const path of [
|
|
932
|
+
"repo/.git/modules/sub/hooks/pre-commit",
|
|
933
|
+
"repo/.git/worktrees/wt/config.worktree",
|
|
934
|
+
"repo/.git/worktrees/wt/gitdir",
|
|
935
|
+
"repo/.git/info-attributes-probe",
|
|
936
|
+
"repo/.git/info/attributes",
|
|
937
|
+
"bare/HEAD",
|
|
938
|
+
"moved-git/config",
|
|
939
|
+
".envrc",
|
|
940
|
+
".npmrc",
|
|
941
|
+
"deep/.npmrc",
|
|
942
|
+
...(fixture.foldedNames === "filesystem" ? [".bashrc"] : [".BASHRC", ".envrc"]),
|
|
943
|
+
])
|
|
944
|
+
assert.equal(await fixture.inspect.readFile(at(root, path)), null, `mandatory deny: ${path}`);
|
|
945
|
+
if (fixture.foldedNames === "filesystem") {
|
|
946
|
+
// fullwidth spellings are their own files on such a filesystem, never the protected ones
|
|
947
|
+
for (const path of [".BASHRC", ".envrc"])
|
|
948
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, path))), "x", `distinct ${path}`);
|
|
949
|
+
}
|
|
950
|
+
await denied((await native(restricted())).writeFile(at(root, "repo/.git/modules/sub/config"), bytes, signal), "native write of a submodule's config");
|
|
951
|
+
await denied((await native(restricted())).writeFile(at(root, "bare2/HEAD"), bytes, signal), "native write of a bare-repository HEAD");
|
|
952
|
+
// No repository can be forged inside git's own allowlisted subtrees, and hook managers
|
|
953
|
+
// files stay out of reach.
|
|
954
|
+
const forged = await exec(restricted(), [
|
|
955
|
+
"cd repo/.git",
|
|
956
|
+
"mkdir -p objects/zz/.git/objects objects/zz/.git/refs",
|
|
957
|
+
"printf 'ref: refs/heads/main' > objects/zz/.git/HEAD",
|
|
958
|
+
"printf x > objects/zz/.git/config",
|
|
959
|
+
"mkdir -p objects/yy/objects objects/yy/refs; printf 'ref: refs/heads/main' > objects/yy/HEAD",
|
|
960
|
+
"mkdir -p logs/objects; printf ../.. > logs/commondir",
|
|
961
|
+
"mkdir -p refs/remotes/o/objects",
|
|
962
|
+
"cd ../..",
|
|
963
|
+
"mkdir -p .husky .lefthook .githooks .config",
|
|
964
|
+
"printf x > .husky/pre-commit; printf x > .pre-commit-config.yaml; printf x > lefthook.yml",
|
|
965
|
+
"printf x > .lefthook/x; printf x > .githooks/pre-commit; printf x > .config/lefthook.yml",
|
|
966
|
+
"true",
|
|
967
|
+
].join("; "));
|
|
968
|
+
assert.equal(forged.exitCode, 0, `the forged-repository probe must run: ${forged.stderr}`);
|
|
969
|
+
for (const path of [
|
|
970
|
+
"repo/.git/objects/zz/.git/HEAD",
|
|
971
|
+
"repo/.git/objects/zz/.git/config",
|
|
972
|
+
"repo/.git/objects/yy/HEAD",
|
|
973
|
+
"repo/.git/logs/objects",
|
|
974
|
+
"repo/.git/logs/commondir",
|
|
975
|
+
"repo/.git/refs/remotes/o/objects",
|
|
976
|
+
".husky/pre-commit",
|
|
977
|
+
".pre-commit-config.yaml",
|
|
978
|
+
"lefthook.yml",
|
|
979
|
+
".lefthook/x",
|
|
980
|
+
".githooks/pre-commit",
|
|
981
|
+
".config/lefthook.yml",
|
|
982
|
+
])
|
|
983
|
+
assert.equal(await fixture.inspect.mode(at(root, path)), null, `mandatory deny: ${path}`);
|
|
984
|
+
}
|
|
985
|
+
if (want("reserved-names")) {
|
|
986
|
+
// The reserved staging prefix (the Linux broker's staging and quarantine names) is denied to
|
|
987
|
+
// every sandboxed write, at any depth and in any case; a name merely containing it is not.
|
|
988
|
+
const reserved = SANDBOX_RESERVED_NAME_PREFIX;
|
|
989
|
+
const upper = reserved.toUpperCase();
|
|
990
|
+
const staging = await exec(restricted(), [
|
|
991
|
+
`mkdir ${reserved}a`,
|
|
992
|
+
`printf x > ${reserved}b`,
|
|
993
|
+
`mkdir -p deep/${upper}c`,
|
|
994
|
+
`printf x > deep/${upper}d`,
|
|
995
|
+
"mkdir -p plain-dir",
|
|
996
|
+
`mv plain-dir ${reserved}e`,
|
|
997
|
+
`printf ok > not${reserved}f`,
|
|
998
|
+
"true",
|
|
999
|
+
].join("; "));
|
|
1000
|
+
assert.equal(staging.exitCode, 0, `the reserved-name probe must run: ${staging.stderr}`);
|
|
1001
|
+
for (const path of [
|
|
1002
|
+
`${reserved}a`,
|
|
1003
|
+
`${reserved}b`,
|
|
1004
|
+
`deep/${upper}c`,
|
|
1005
|
+
`deep/${upper}d`,
|
|
1006
|
+
`${reserved}e`,
|
|
1007
|
+
])
|
|
1008
|
+
assert.equal(await fixture.inspect.mode(at(root, path)), null, `reserved name: ${path}`);
|
|
1009
|
+
assert.notEqual(await fixture.inspect.mode(at(root, "plain-dir")), null, "the move was refused");
|
|
1010
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, `not${reserved}f`))), "ok");
|
|
1011
|
+
await denied((await native(restricted())).writeFile(at(root, `${reserved}n`), bytes, signal), "native write of a reserved name");
|
|
1012
|
+
}
|
|
1013
|
+
// A protected home location linked into the granted root (a dotfile manager's chain): every
|
|
1014
|
+
// link on the chain and the target are denied, and no hop can be retargeted or moved away.
|
|
1015
|
+
if (want("link-chain") && fixture.home && "path" in fixture.home) {
|
|
1016
|
+
const home = fixture.home;
|
|
1017
|
+
const chain = at(root, "dotfiles");
|
|
1018
|
+
await fixture.seed([
|
|
1019
|
+
{ path: at(chain, "v1/zprofile"), kind: "file", data: new TextEncoder().encode("rc1") },
|
|
1020
|
+
{ path: at(chain, "v2/zprofile"), kind: "file", data: new TextEncoder().encode("rc2") },
|
|
1021
|
+
{ path: at(chain, "current"), kind: "symlink", target: "v1" },
|
|
1022
|
+
{
|
|
1023
|
+
path: at(home.path, ".zprofile"),
|
|
1024
|
+
kind: "symlink",
|
|
1025
|
+
target: at(chain, "current/zprofile"),
|
|
1026
|
+
},
|
|
1027
|
+
]);
|
|
1028
|
+
try {
|
|
1029
|
+
const hops = await exec(restricted(), [
|
|
1030
|
+
"cd dotfiles",
|
|
1031
|
+
"(printf x >> v1/zprofile) 2>/dev/null && echo wrote-target",
|
|
1032
|
+
"(printf x > current/zprofile) 2>/dev/null && echo wrote-through",
|
|
1033
|
+
"ln -sfn v2 current 2>/dev/null && echo retargeted",
|
|
1034
|
+
"mv current c2 2>/dev/null && echo moved-link",
|
|
1035
|
+
"rm current 2>/dev/null && echo removed-link",
|
|
1036
|
+
"mv v1 gone 2>/dev/null && echo moved-target",
|
|
1037
|
+
"cd .. && mv dotfiles gone 2>/dev/null && echo moved-ancestor",
|
|
1038
|
+
"true",
|
|
1039
|
+
].join("; "));
|
|
1040
|
+
assert.equal(hops.exitCode, 0, `the link-chain probe must run: ${hops.stderr}`);
|
|
1041
|
+
assert.equal(hops.stdout.trim(), "", `no hop of a protected chain is writable: ${hops.stdout}`);
|
|
1042
|
+
assert.equal(text(await fixture.inspect.readFile(at(chain, "current/zprofile"))), "rc1");
|
|
1043
|
+
assert.equal(text(await fixture.inspect.readFile(at(chain, "v2/zprofile"))), "rc2");
|
|
1044
|
+
await denied((await native(restricted())).writeFile(at(chain, "v1/zprofile"), bytes, signal), "native write of a protected chain's target");
|
|
1045
|
+
}
|
|
1046
|
+
finally {
|
|
1047
|
+
await home.remove(at(home.path, ".zprofile"));
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
if (whole("filesystem") && support.outsideSandbox) {
|
|
1051
|
+
// ordinary git work in a restricted repository keeps working under these rules
|
|
1052
|
+
await exec(escalated, `cd ${quote(root)} && git init -q work && git -C work -c user.name=t -c user.email=t@t commit -q --allow-empty -m init`);
|
|
1053
|
+
const git = await exec(restricted(), "cd work && printf a > f && git add f && git -c user.name=t -c user.email=t@t commit -qm m && " +
|
|
1054
|
+
"git checkout -qb topic && git status --short && git log --oneline | wc -l");
|
|
1055
|
+
assert.equal(git.exitCode, 0, `ordinary restricted git work: ${git.stderr}`);
|
|
1056
|
+
assert.equal(git.stdout.trim(), "2", "the restricted commit landed");
|
|
1057
|
+
// stash, pack-refs and gc write git internals of their own (index.stash.<n>,
|
|
1058
|
+
// packed-refs.new, MERGE_AUTOSTASH) that the allowlist keeps writable
|
|
1059
|
+
const housekeeping = await exec(restricted(), 'cd work && g() { git -c user.name=t -c user.email=t@t -c gc.auto=0 "$@"; } && ' +
|
|
1060
|
+
"printf b >> f && g stash -q && g stash pop -q && g commit -qam s && " +
|
|
1061
|
+
"g pack-refs --all && g gc -q && git stash list | wc -l");
|
|
1062
|
+
assert.equal(housekeeping.exitCode, 0, `restricted stash, pack-refs and gc: ${housekeeping.stderr}`);
|
|
1063
|
+
}
|
|
1064
|
+
if (whole("filesystem")) {
|
|
1065
|
+
// Negative controls: sibling, symlink escapes and protected paths stay out of reach.
|
|
1066
|
+
const reads = await exec(restricted(), `cat ${quote(at(sibling, "secret"))}; cat escape; cat linked/secret; true`);
|
|
1067
|
+
assert(!reads.stdout.includes(secret), "restricted reads must not reach the sibling");
|
|
1068
|
+
await exec(restricted(), `printf pwn > ${quote(at(sibling, "w1"))}; printf pwn > linked/w2; printf pwn > escape; ` +
|
|
1069
|
+
`chmod 777 ${quote(at(sibling, "secret"))}; chmod 777 escape; ` +
|
|
1070
|
+
`touch -t 200101010000 ${quote(at(sibling, "secret"))}; true`);
|
|
1071
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "w1")), null, "sibling write");
|
|
1072
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "w2")), null, "symlinked dir write");
|
|
1073
|
+
await siblingIntact("restricted writes and chmod must not change the sibling");
|
|
1074
|
+
for (const path of fixture.protectedPaths) {
|
|
1075
|
+
const before = text(await fixture.inspect.readFile(path));
|
|
1076
|
+
await exec(restricted(), `printf pwn >> ${quote(path)}; true`);
|
|
1077
|
+
assert.equal(text(await fixture.inspect.readFile(path)), before, `protected ${path}`);
|
|
1078
|
+
}
|
|
1079
|
+
await denied((await native(restricted())).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), "native sibling read");
|
|
1080
|
+
await denied((await native(restricted())).readFile(at(root, "escape"), { maxBytes: 100, signal }), "native symlink escape read");
|
|
1081
|
+
await denied((await native(restricted())).writeFile(at(sibling, "n1"), bytes, signal), "native sibling write");
|
|
1082
|
+
await denied((await native(restricted())).writeFile(at(root, "linked/n2"), bytes, signal), "native write through a directory symlink");
|
|
1083
|
+
await denied((await native(restricted())).stat(at(sibling, "secret"), signal), "stat");
|
|
1084
|
+
await denied((await native(restricted())).list(sibling, { limit: 5, signal }), "list");
|
|
1085
|
+
await siblingIntact("native denials must leave the sibling unchanged");
|
|
1086
|
+
// Every profile is sandboxed: Full access only skips the approvals, never the sandbox. Under
|
|
1087
|
+
// each profile a call keeps the scope, the fixed denies, the network and the minimal
|
|
1088
|
+
// environment (no device variable reaches it).
|
|
1089
|
+
{
|
|
1090
|
+
const before = await receipts();
|
|
1091
|
+
for (const profile of PROFILES) {
|
|
1092
|
+
const grant = {
|
|
1093
|
+
profile,
|
|
1094
|
+
filesystem: scoped([root]),
|
|
1095
|
+
network: { kind: "none" },
|
|
1096
|
+
};
|
|
1097
|
+
const probe = await exec(grant, [
|
|
1098
|
+
`cat ${quote(at(sibling, "secret"))}`,
|
|
1099
|
+
`printf pwn > ${quote(at(sibling, `profile-${profile}`))}`,
|
|
1100
|
+
...fixture.protectedPaths.map((path) => `printf pwn >> ${quote(path)}`),
|
|
1101
|
+
connect(ungranted[0] ?? granted),
|
|
1102
|
+
`printf ok > ${quote(`in-root-${profile}`)}`,
|
|
1103
|
+
"true",
|
|
1104
|
+
].join("; "));
|
|
1105
|
+
assert.equal(probe.exitCode, 0, `${profile}: the probe must run: ${probe.stderr}`);
|
|
1106
|
+
assert(!probe.stdout.includes(secret), `${profile}: the sibling stays out of reach`);
|
|
1107
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, `profile-${profile}`)), null);
|
|
1108
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, `in-root-${profile}`))), "ok");
|
|
1109
|
+
await denied((await native(grant)).readFile(at(sibling, "secret"), { maxBytes: 100, signal }), `${profile}: native sibling read`);
|
|
1110
|
+
}
|
|
1111
|
+
for (const path of fixture.protectedPaths)
|
|
1112
|
+
assert(!text(await fixture.inspect.readFile(path))?.includes("pwn"), `protected ${path} under every profile`);
|
|
1113
|
+
assert.deepEqual(await receipts(), before, "no profile reaches an endpoint on network none");
|
|
1114
|
+
await siblingIntact("every profile leaves the sibling unchanged");
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
// The minimal environment under every profile: no planted value and no name beyond the
|
|
1118
|
+
// minimal set; the planted values are real (an escalated call sees them).
|
|
1119
|
+
if (want("environment")) {
|
|
1120
|
+
for (const profile of PROFILES)
|
|
1121
|
+
await proveMinimalEnvironment({ profile, filesystem: scoped([root]), network: { kind: "none" } }, true);
|
|
1122
|
+
if (fixture.deviceEnvironment?.escalatedControl && support.outsideSandbox) {
|
|
1123
|
+
// the planted values are real: an escalated call (outside the sandbox) sees them, except
|
|
1124
|
+
// the device's own CAPYBARA_ variables
|
|
1125
|
+
const seen = await leakedVariables(escalated);
|
|
1126
|
+
const planted = Object.keys(fixture.deviceEnvironment.variables);
|
|
1127
|
+
assert.deepEqual(seen.sort(), planted.filter((name) => !/^CAPYBARA_/.test(name)).sort(), "an escalated call gets the device environment minus every CAPYBARA_ variable");
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
{
|
|
1131
|
+
if (whole("network")) {
|
|
1132
|
+
// Network: only the granted endpoint, and only while allowlisted.
|
|
1133
|
+
const base = await receipts();
|
|
1134
|
+
const namedReach = namedReachAvailable();
|
|
1135
|
+
const positives = !namedReach
|
|
1136
|
+
? []
|
|
1137
|
+
: proxied
|
|
1138
|
+
? [byName(granted), urlopen(granted)]
|
|
1139
|
+
: [
|
|
1140
|
+
connect(granted),
|
|
1141
|
+
`curl -fsS -m 10 -o /dev/null http://${granted.address}:${granted.port}/`,
|
|
1142
|
+
`node -e ${quote(`require("net").connect(${granted.port}, ${JSON.stringify(granted.address)}).on("connect", function () { this.end() })`)}`,
|
|
1143
|
+
];
|
|
1144
|
+
for (const command of positives) {
|
|
1145
|
+
const result = await exec(restricted(allowlisted), command);
|
|
1146
|
+
assert.equal(result.exitCode, 0, `granted endpoint must work: ${command}: ${result.stderr}`);
|
|
1147
|
+
}
|
|
1148
|
+
for (const endpoint of ungranted) {
|
|
1149
|
+
// Raw connects to an ungranted address fail; through a proxy, so does a request by name.
|
|
1150
|
+
for (const command of proxied
|
|
1151
|
+
? [connect(endpoint), byName(endpoint)]
|
|
1152
|
+
: [connect(endpoint)]) {
|
|
1153
|
+
const result = await exec(restricted(allowlisted), command);
|
|
1154
|
+
assert.notEqual(result.exitCode, 0, `ungranted ${endpoint.name}: ${command}`);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (proxied) {
|
|
1158
|
+
// allowlisted traffic goes through the proxy: a raw connect to the granted address bypasses
|
|
1159
|
+
// it and must be refused as well
|
|
1160
|
+
const raw = await exec(restricted(allowlisted), connect(granted));
|
|
1161
|
+
assert.notEqual(raw.exitCode, 0, `a proxied provider must refuse a raw connect: ${granted.name}`);
|
|
1162
|
+
}
|
|
1163
|
+
for (const command of [connect(granted), byName(granted)]) {
|
|
1164
|
+
const none = await exec(restricted(), command);
|
|
1165
|
+
assert.notEqual(none.exitCode, 0, `network none must refuse even the granted endpoint: ${command}`);
|
|
1166
|
+
}
|
|
1167
|
+
const after = await receipts();
|
|
1168
|
+
assert.equal(after[0], (base[0] ?? 0) + positives.length, "granted endpoint receipts");
|
|
1169
|
+
assert.deepEqual(after.slice(1), base.slice(1), "ungranted endpoints must see no connection");
|
|
1170
|
+
}
|
|
1171
|
+
// An allowlist grant never reaches a closed address class, not even for a granted name.
|
|
1172
|
+
const closedGranted = closedGrantedTargets();
|
|
1173
|
+
if (want("closed-granted") && closedGranted.length > 0) {
|
|
1174
|
+
const before = await receipts();
|
|
1175
|
+
await proveTargets(restricted({
|
|
1176
|
+
kind: "allowlist",
|
|
1177
|
+
hosts: [granted.name, ...closedGranted.map((t) => t.host)],
|
|
1178
|
+
}), [], closedGranted, "allowlisted names resolving into a closed class");
|
|
1179
|
+
assert.deepEqual(await receipts(), before, "no endpoint sees a closed-class grant");
|
|
1180
|
+
}
|
|
1181
|
+
if (want("loopback")) {
|
|
1182
|
+
// Restricted network none/allowlist may listen on loopback only.
|
|
1183
|
+
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
1184
|
+
const binds = await exec(restricted(network), `python3 -c ${quote(BIND_PROGRAM)}`);
|
|
1185
|
+
assert.equal(binds.stdout.trim(), fixture.restrictedLoopbackListen === "refused"
|
|
1186
|
+
? "127.0.0.1=denied ::1=denied 0.0.0.0=denied ::=denied unspec=denied"
|
|
1187
|
+
: "127.0.0.1=ok ::1=ok 0.0.0.0=denied ::=denied unspec=denied", `restricted ${network.kind} binds loopback only: ${binds.stderr}`);
|
|
1188
|
+
}
|
|
1189
|
+
if (fixture.restrictedLoopbackListen !== "refused") {
|
|
1190
|
+
// No sandboxed client connects to a loopback listener, its own included (a listener cannot
|
|
1191
|
+
// be told from another process's at the address dialled), and no reuseport group is joined.
|
|
1192
|
+
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
1193
|
+
const own = await exec(restricted(network), `python3 -c ${quote(OWN_LOOPBACK)}`);
|
|
1194
|
+
assert.equal(own.exitCode, 0, `the own-loopback probe must run: ${own.stderr}`);
|
|
1195
|
+
assert.deepEqual(JSON.parse(own.stdout), { "own 127.0.0.1": "denied", "own ::1": "denied", reuseport: "denied" }, `restricted ${network.kind}: no loopback connect, no SO_REUSEPORT`);
|
|
1196
|
+
}
|
|
1197
|
+
if (support.outsideSandbox) {
|
|
1198
|
+
// a client outside the sandbox (an escalated call) reaches the command's listener
|
|
1199
|
+
const portFile = at(root, "loopback-port");
|
|
1200
|
+
const service = exec(restricted(), `python3 -c ${quote(LOOPBACK_SERVICE)} ${quote(portFile)}`);
|
|
1201
|
+
await waitFor(portFile, service);
|
|
1202
|
+
const port = Number(text(await fixture.inspect.readFile(portFile)));
|
|
1203
|
+
const client = await exec(escalated, `python3 -c ${quote(`import socket\ns = socket.create_connection(("127.0.0.1", ${port}), 10)\ns.sendall(b"from-outside")\ns.close()`)}`);
|
|
1204
|
+
assert.equal(client.exitCode, 0, `the outside client must connect: ${client.stderr}`);
|
|
1205
|
+
const served = await service;
|
|
1206
|
+
assert.equal(served.stdout.trim(), "from-outside", `the listener serves it: ${served.stderr}`);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
if (want("open-network") && support.network.openPublic)
|
|
1211
|
+
await proveOpenNetwork([root]);
|
|
1212
|
+
// A UNIX socket another process made inside a write root (a user D-Bus, a rootless
|
|
1213
|
+
// docker.sock, ssh-agent or tmux in a granted directory) is code execution outside the
|
|
1214
|
+
// sandbox: no sandboxed command connects to it, under any sandbox network. An escalated call
|
|
1215
|
+
// stands in for that process; the same client there proves the probe is real.
|
|
1216
|
+
if (want("foreign-unix") && support.outsideSandbox) {
|
|
1217
|
+
const server = new AbortController();
|
|
1218
|
+
const outside = exec(escalated, `python3 -c ${quote(UNIX_SERVER)} foreign.sock foreign.count`, server.signal);
|
|
1219
|
+
try {
|
|
1220
|
+
await waitFor(at(root, "foreign.count"), outside);
|
|
1221
|
+
const client = `python3 -c ${quote(FOREIGN_UNIX_CLIENT)} foreign.sock ${quote(at(root, "foreign.sock"))}`;
|
|
1222
|
+
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
1223
|
+
const probe = await exec(restricted(network), client);
|
|
1224
|
+
const reached = probe.stdout
|
|
1225
|
+
.trim()
|
|
1226
|
+
.split(" ")
|
|
1227
|
+
.slice(1)
|
|
1228
|
+
.filter((entry) => entry.endsWith("=ok"));
|
|
1229
|
+
assert.equal(probe.stdout.trim().startsWith("foreign-unix-client stream=") && reached.length === 0, true, `restricted ${network.kind} must not connect to a socket another process made in the root: ${probe.stdout} ${probe.stderr}`);
|
|
1230
|
+
}
|
|
1231
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "foreign.count"))), "0", "the foreign UNIX service in the root must see no sandboxed client");
|
|
1232
|
+
const control = await exec(escalated, client);
|
|
1233
|
+
assert.match(control.stdout, /^foreign-unix-client stream=ok /, `the escalated control reaches the foreign UNIX service: ${control.stderr}`);
|
|
1234
|
+
}
|
|
1235
|
+
finally {
|
|
1236
|
+
server.abort();
|
|
1237
|
+
await outside.catch(() => undefined);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
// Pathname UNIX sockets: a service outside the roots (run by an escalated call) is unreachable
|
|
1241
|
+
// under every sandbox network; one inside the root works.
|
|
1242
|
+
if (whole("network") && support.outsideSandbox) {
|
|
1243
|
+
const server = new AbortController();
|
|
1244
|
+
const outside = exec(escalated, `python3 -c ${quote(UNIX_SERVER)} ${quote(at(sibling, "srv.sock"))} ${quote(at(sibling, "srv.count"))}`, server.signal);
|
|
1245
|
+
await waitFor(at(sibling, "srv.count"), outside);
|
|
1246
|
+
await fixture.seed([
|
|
1247
|
+
{ path: at(root, "srv-link.sock"), kind: "symlink", target: at(sibling, "srv.sock") },
|
|
1248
|
+
]);
|
|
1249
|
+
// The OS's own UNIX socket types, probed outside every restriction (unsupported types are
|
|
1250
|
+
// reported as such by an escalated call and expected the same in restricted operations)
|
|
1251
|
+
const types = await exec(escalated, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "missing.sock"))} missing-link.sock`);
|
|
1252
|
+
const kinds = types.stdout
|
|
1253
|
+
.trim()
|
|
1254
|
+
.split(" ")
|
|
1255
|
+
.map((entry) => entry.split("="));
|
|
1256
|
+
for (const name of ["stream", "dgram", "link"])
|
|
1257
|
+
assert.notEqual(kinds.find(([kind]) => kind === name)?.[1], "unsupported", `UNIX ${name} sockets are required: ${types.stdout} ${types.stderr}`);
|
|
1258
|
+
const expectWhen = (reachable) => kinds
|
|
1259
|
+
.map(([kind, state]) => state === "unsupported"
|
|
1260
|
+
? `${kind}=unsupported`
|
|
1261
|
+
: `${kind}=${reachable ? "ok" : "denied"}`)
|
|
1262
|
+
.join(" ");
|
|
1263
|
+
for (const network of [{ kind: "none" }, allowlisted]) {
|
|
1264
|
+
const probe = await exec(restricted(network), `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
|
|
1265
|
+
assert.equal(
|
|
1266
|
+
// a type the OS lacks may also be refused before the OS says so: both reach nothing
|
|
1267
|
+
probe.stdout
|
|
1268
|
+
.trim()
|
|
1269
|
+
.split(" ")
|
|
1270
|
+
.map((entry) => entry.endsWith("=denied") &&
|
|
1271
|
+
kinds.some(([kind, state]) => `${kind}=denied` === entry && state === "unsupported")
|
|
1272
|
+
? entry.replace("=denied", "=unsupported")
|
|
1273
|
+
: entry)
|
|
1274
|
+
.join(" "), expectWhen(false), `restricted ${network.kind} must not reach a UNIX service outside the roots: ${probe.stderr}`);
|
|
1275
|
+
const inside = await exec(restricted(network), `python3 -c ${quote(UNIX_ROUNDTRIP)} ${quote(at(root, `own-${network.kind}.sock`))}`);
|
|
1276
|
+
if (fixture.restrictedLoopbackListen === "refused")
|
|
1277
|
+
// no listener at all: binding a UNIX socket fails before any roundtrip
|
|
1278
|
+
assert.notEqual(inside.stdout.trim(), "roundtrip=ok", "no restricted UNIX listener");
|
|
1279
|
+
else
|
|
1280
|
+
assert.equal(inside.stdout.trim(), "roundtrip=ok", `in-root UNIX socket: ${inside.stderr}`);
|
|
1281
|
+
}
|
|
1282
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "srv.count"))), "0", "the outside UNIX service must see no client");
|
|
1283
|
+
// The same client in an escalated call reaches the service seven times: the probe is real.
|
|
1284
|
+
const control = await exec(escalated, `python3 -c ${quote(UNIX_CLIENT)} ${quote(at(sibling, "srv.sock"))} srv-link.sock`);
|
|
1285
|
+
assert.equal(control.stdout.trim(), expectWhen(true), `escalated UNIX control: ${control.stderr}`);
|
|
1286
|
+
const reached = String(kinds.filter(([, state]) => state !== "unsupported").length);
|
|
1287
|
+
await waitForFile(async (path) => {
|
|
1288
|
+
const data = await fixture.inspect.readFile(path);
|
|
1289
|
+
return text(data) === reached ? data : null;
|
|
1290
|
+
}, at(sibling, "srv.count"), outside);
|
|
1291
|
+
server.abort();
|
|
1292
|
+
await outside;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
if (!whole("processes"))
|
|
1296
|
+
return report();
|
|
1297
|
+
// Escalated-pair controls on the same device: outside the sandbox no restricted filter applies.
|
|
1298
|
+
if (support.outsideSandbox) {
|
|
1299
|
+
const before = await receipts();
|
|
1300
|
+
const control = await exec(escalated, `cat ${quote(at(sibling, "secret"))} && printf full > ${quote(at(sibling, "full"))} && ${connect(ungranted[0] ?? granted)}`);
|
|
1301
|
+
assert.equal(control.exitCode, 0, `the escalated control must succeed: ${control.stderr}`);
|
|
1302
|
+
assert(control.stdout.includes(secret), "the escalated call reads the sibling");
|
|
1303
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "full"))), "full");
|
|
1304
|
+
assert.equal((await receipts())[1], (before[1] ?? 0) + 1, "the escalated call reaches an ungranted endpoint");
|
|
1305
|
+
}
|
|
1306
|
+
// Both overlap orders: a live escalated call never widens a restricted one, and vice versa.
|
|
1307
|
+
if (support.outsideSandbox) {
|
|
1308
|
+
const first = exec(restricted(), `printf r > ready-a; until [ -e barrier-a ]; do sleep 0.01; done; ` +
|
|
1309
|
+
`printf pwn > ${quote(at(sibling, "overlap-a"))}; cat ${quote(at(sibling, "secret"))}; true`);
|
|
1310
|
+
await waitFor(at(root, "ready-a"), first);
|
|
1311
|
+
await exec(escalated, `printf full > ${quote(at(sibling, "full-a"))} && touch barrier-a`);
|
|
1312
|
+
assert(!(await first).stdout.includes(secret), "restricted after a live escalated call");
|
|
1313
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-a")), null);
|
|
1314
|
+
const fullFirst = exec(escalated, `printf r > ready-b; until [ -e barrier-b ]; do sleep 0.01; done; ` +
|
|
1315
|
+
`printf full > ${quote(at(sibling, "full-b"))}`);
|
|
1316
|
+
await waitFor(at(root, "ready-b"), fullFirst);
|
|
1317
|
+
const second = await exec(restricted(), `printf pwn > ${quote(at(sibling, "overlap-b"))}; cat ${quote(at(sibling, "secret"))}; touch barrier-b`);
|
|
1318
|
+
assert(!second.stdout.includes(secret), "restricted while an escalated call is live");
|
|
1319
|
+
assert.equal((await fullFirst).exitCode, 0);
|
|
1320
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, "overlap-b")), null);
|
|
1321
|
+
assert.equal(text(await fixture.inspect.readFile(at(sibling, "full-b"))), "full");
|
|
1322
|
+
}
|
|
1323
|
+
// Component swaps during native and shell access never escape.
|
|
1324
|
+
if (support.outsideSandbox) {
|
|
1325
|
+
const race = at(root, "race");
|
|
1326
|
+
const swapper = exec(escalated, `python3 -c ${quote(SWAP_PROGRAM)} ${quote(race)} ${quote(sibling)} ${quote(at(root, "race-stop"))}`);
|
|
1327
|
+
await waitFor(at(race, "swapping"), swapper);
|
|
1328
|
+
for (let index = 0; index < 30; index++) {
|
|
1329
|
+
const op = await native(restricted());
|
|
1330
|
+
try {
|
|
1331
|
+
await op.writeFile(at(race, `dir/n-${index}`), bytes, signal);
|
|
1332
|
+
}
|
|
1333
|
+
catch { }
|
|
1334
|
+
const read = await (await native(restricted()))
|
|
1335
|
+
.readFile(at(race, "dir/secret"), { maxBytes: 200, signal })
|
|
1336
|
+
.catch(() => null);
|
|
1337
|
+
assert.notEqual(read && text(read.data), secret, "native read escaped during a swap");
|
|
1338
|
+
}
|
|
1339
|
+
const shellRace = await exec(restricted(), `i=0; while [ $i -lt 400 ]; do printf pwn > race/dir/x-$i; cat race/dir/secret; ` +
|
|
1340
|
+
`chmod 777 race/dir/secret; i=$((i+1)); done 2>/dev/null; true`);
|
|
1341
|
+
assert(!shellRace.stdout.includes(secret), "shell read escaped during a swap");
|
|
1342
|
+
await exec(escalated, "touch race-stop");
|
|
1343
|
+
assert.equal((await swapper).exitCode, 0);
|
|
1344
|
+
for (let index = 0; index < 400; index++) {
|
|
1345
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, `x-${index}`)), null);
|
|
1346
|
+
if (index < 30)
|
|
1347
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, `n-${index}`)), null);
|
|
1348
|
+
}
|
|
1349
|
+
await siblingIntact("component swaps must not reach the sibling");
|
|
1350
|
+
// A swap of the root path itself during a live operation, then a fresh operation.
|
|
1351
|
+
const moved = `${root}.moved-${randomUUID()}`;
|
|
1352
|
+
const live = exec(restricted(), `printf r > ready-root; until [ -e ${quote(at(moved, "barrier-root"))} ]; do sleep 0.01; done; ` +
|
|
1353
|
+
`printf pwn > ${quote(at(root, "after-swap"))}; cat ${quote(at(root, "secret"))}; printf ok > in-place; true`);
|
|
1354
|
+
await waitFor(at(root, "ready-root"), live);
|
|
1355
|
+
await exec(escalated, `mv ${quote(root)} ${quote(moved)} && ln -s ${quote(sibling)} ${quote(root)} && touch ${quote(at(moved, "barrier-root"))}`);
|
|
1356
|
+
const swapped = await live;
|
|
1357
|
+
assert(!swapped.stdout.includes(secret), "a live operation must not follow a root swap");
|
|
1358
|
+
// an inode-pinned runtime (Landlock) keeps writing in the moved root; a path-based one
|
|
1359
|
+
// (Seatbelt) refuses the moved path: either way nothing follows the swap
|
|
1360
|
+
assert([null, "ok"].includes(text(await fixture.inspect.readFile(at(moved, "in-place")))), "a live operation writes in place or nowhere");
|
|
1361
|
+
await denied((async () => (await native(restricted())).writeFile(at(root, "fresh"), bytes, signal))(), "a fresh native operation must reject a swapped root");
|
|
1362
|
+
const fresh = await (await fixture.operation(restricted()))
|
|
1363
|
+
.exec({
|
|
1364
|
+
command: "printf pwn > fresh-exec",
|
|
1365
|
+
cwd: root,
|
|
1366
|
+
timeoutMs: 30_000,
|
|
1367
|
+
maxOutputBytes: 1024,
|
|
1368
|
+
signal,
|
|
1369
|
+
})
|
|
1370
|
+
.catch((error) => error);
|
|
1371
|
+
assert(isSandboxScopeDeniedError(fresh) || fresh.exitCode !== 0, "a fresh exec must not run in a swapped root");
|
|
1372
|
+
await exec(escalated, `rm ${quote(root)} && mv ${quote(moved)} ${quote(root)}`);
|
|
1373
|
+
for (const name of ["after-swap", "fresh", "fresh-exec"]) {
|
|
1374
|
+
assert.equal(await fixture.inspect.readFile(at(sibling, name)), null, `root swap ${name}`);
|
|
1375
|
+
}
|
|
1376
|
+
await siblingIntact("root swaps must not reach the sibling");
|
|
1377
|
+
}
|
|
1378
|
+
// A mutable syscall pointer: another thread rewrites the address/path during the check.
|
|
1379
|
+
// Direct access flips between the granted and an ungranted address; proxied access between the
|
|
1380
|
+
// operation's proxy (from its environment) and an ungranted address.
|
|
1381
|
+
const target = ungranted.find((endpoint) => isIPv4(endpoint.address));
|
|
1382
|
+
if (target) {
|
|
1383
|
+
const before = await receipts();
|
|
1384
|
+
const good = proxied ? "proxy -" : `${granted.address} ${granted.port}`;
|
|
1385
|
+
const flip = await exec(restricted(allowlisted), `python3 -c ${quote(FLIP_PROGRAM)} connect 1500 ${good} ${target.address} ${target.port}`);
|
|
1386
|
+
assert.equal(flip.exitCode, 0, `pointer race program must run: ${flip.stderr}`);
|
|
1387
|
+
const flipped = await receipts();
|
|
1388
|
+
assert.deepEqual(flipped.slice(1), before.slice(1), "a flipped sockaddr must not escape");
|
|
1389
|
+
assert.notEqual(flip.stdout.trim(), "ok=0", "the race must also reach the allowed target");
|
|
1390
|
+
if (!proxied) {
|
|
1391
|
+
assert((flipped[0] ?? 0) > (before[0] ?? 0), "the race must reach the granted endpoint");
|
|
1392
|
+
}
|
|
1393
|
+
const chmods = await exec(restricted(), `python3 -c ${quote(FLIP_PROGRAM)} chmod 3000 ${quote(at(root, "inroot.txt"))} ${quote(at(sibling, "secret"))}`);
|
|
1394
|
+
assert.equal(chmods.exitCode, 0, `chmod race program must run: ${chmods.stderr}`);
|
|
1395
|
+
assert.notEqual(chmods.stdout.trim(), "ok=0", "in-root chmods must succeed");
|
|
1396
|
+
await siblingIntact("a flipped path must not chmod the sibling");
|
|
1397
|
+
}
|
|
1398
|
+
// The supervisor of a restricted command (its parent) is closed to a same-uid process outside
|
|
1399
|
+
// the operation: no ptrace attach, no mem or environ, while the command itself runs normally.
|
|
1400
|
+
if (fixture.inspect.outside) {
|
|
1401
|
+
const held = exec(restricted(), `echo $PPID > supervisor-pid; printf r > ready-held; ` +
|
|
1402
|
+
`until [ -e release-held ]; do sleep 0.01; done; printf ran > held.txt`);
|
|
1403
|
+
await waitFor(at(root, "ready-held"), held);
|
|
1404
|
+
const supervisor = Number(text(await fixture.inspect.readFile(at(root, "supervisor-pid"))));
|
|
1405
|
+
let probed;
|
|
1406
|
+
try {
|
|
1407
|
+
probed = await fixture.inspect.outside(OUTSIDE_PROBE, [String(supervisor)]);
|
|
1408
|
+
}
|
|
1409
|
+
finally {
|
|
1410
|
+
await exec(restricted(), "touch release-held");
|
|
1411
|
+
}
|
|
1412
|
+
assert.equal((await held).exitCode, 0, "the supervised command runs normally");
|
|
1413
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "held.txt"))), "ran");
|
|
1414
|
+
const { uid, who, control, target } = JSON.parse(probed);
|
|
1415
|
+
// Not vacuous: the target is a live process of the outsider's own uid.
|
|
1416
|
+
assert.equal(who?.uid, uid, `the supervisor must run as the outsider's uid: ${probed}`);
|
|
1417
|
+
assert.notEqual(who?.cmdline ?? "", "", `the supervisor must still be running: ${probed}`);
|
|
1418
|
+
assert.equal(control?.mem, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
|
|
1419
|
+
assert.equal(control?.environ, "ALLOWED", `the probe must read a same-uid control: ${probed}`);
|
|
1420
|
+
assert.deepEqual(target, { mem: "EACCES", environ: "EACCES", attach: "EPERM" }, `a same-uid outsider must not ptrace or read the supervisor ${supervisor}: ${probed}`);
|
|
1421
|
+
}
|
|
1422
|
+
await proveCancellation(restricted());
|
|
1423
|
+
// A fresh narrowed scope (after revocation) is enforced on the very next operation, while an
|
|
1424
|
+
// operation that started with the broader grant keeps it.
|
|
1425
|
+
await fixture.seed([{ path: at(root, "narrow/keep"), kind: "directory" }]);
|
|
1426
|
+
const narrowed = restricted({ kind: "none" }, [at(root, "narrow/keep")]);
|
|
1427
|
+
const broad = exec(restricted(), `printf r > ready-broad; until [ -e narrow/keep/release-broad ]; do sleep 0.01; done; ` +
|
|
1428
|
+
`printf broad > broad.txt`);
|
|
1429
|
+
await waitFor(at(root, "ready-broad"), broad);
|
|
1430
|
+
const overlapping = await (await fixture.operation(narrowed)).exec({
|
|
1431
|
+
command: `printf pwn > ${quote(at(root, "overlapping.txt"))}; touch release-broad; true`,
|
|
1432
|
+
cwd: at(root, "narrow/keep"),
|
|
1433
|
+
timeoutMs: 30_000,
|
|
1434
|
+
maxOutputBytes: 1024,
|
|
1435
|
+
signal,
|
|
1436
|
+
});
|
|
1437
|
+
assert.equal(overlapping.exitCode, 0);
|
|
1438
|
+
assert.equal((await broad).exitCode, 0, "the broader live grant is retained");
|
|
1439
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "broad.txt"))), "broad");
|
|
1440
|
+
assert.equal(await fixture.inspect.readFile(at(root, "overlapping.txt")), null, "a concurrent narrower scope stays narrow");
|
|
1441
|
+
const narrow = await (await fixture.operation(narrowed)).exec({
|
|
1442
|
+
command: `printf ok > keep.txt; printf pwn > ${quote(at(root, "revoked.txt"))}; true`,
|
|
1443
|
+
cwd: at(root, "narrow/keep"),
|
|
1444
|
+
timeoutMs: 30_000,
|
|
1445
|
+
maxOutputBytes: 1024,
|
|
1446
|
+
signal,
|
|
1447
|
+
});
|
|
1448
|
+
assert.equal(narrow.exitCode, 0);
|
|
1449
|
+
assert.equal(text(await fixture.inspect.readFile(at(root, "narrow/keep/keep.txt"))), "ok");
|
|
1450
|
+
assert.equal(await fixture.inspect.readFile(at(root, "revoked.txt")), null, "revoked root");
|
|
1451
|
+
await denied((await native(narrowed)).writeFile(at(root, "revoked-native"), bytes, signal), "native write after narrowing");
|
|
1452
|
+
return report();
|
|
1453
|
+
}
|
|
1454
|
+
finally {
|
|
1455
|
+
await fixture.dispose();
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
/**
|
|
1459
|
+
* Polls a trusted read until `path` exists, racing the operation that should create it: if that
|
|
1460
|
+
* operation settles first (refused, failed or exited without the file), this throws at once with
|
|
1461
|
+
* the operation's error or exit, after one last read. The operation's rejection is always handled.
|
|
1462
|
+
*/
|
|
1463
|
+
export async function waitForFile(read, path, pending) {
|
|
1464
|
+
let ended;
|
|
1465
|
+
pending.then((value) => {
|
|
1466
|
+
ended = { value };
|
|
1467
|
+
}, (error) => {
|
|
1468
|
+
ended = { error };
|
|
1469
|
+
});
|
|
1470
|
+
for (;;) {
|
|
1471
|
+
if ((await read(path)) !== null)
|
|
1472
|
+
return;
|
|
1473
|
+
if (ended) {
|
|
1474
|
+
// The operation may have written the file just before it ended.
|
|
1475
|
+
if ((await read(path)) !== null)
|
|
1476
|
+
return;
|
|
1477
|
+
if ("error" in ended) {
|
|
1478
|
+
const reason = ended.error instanceof Error ? ended.error.message : String(ended.error);
|
|
1479
|
+
throw new Error(`operation ended before ${path} existed: ${reason}`, {
|
|
1480
|
+
cause: ended.error,
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1483
|
+
const result = ended.value;
|
|
1484
|
+
const detail = result && "exitCode" in result
|
|
1485
|
+
? `exit ${result.exitCode}${result.timedOut ? " (timed out)" : ""}: ${result.stderr ?? ""}`
|
|
1486
|
+
: "it returned";
|
|
1487
|
+
throw new Error(`operation ended before ${path} existed: ${detail}`);
|
|
1488
|
+
}
|
|
1489
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
1490
|
+
}
|
|
1491
|
+
}
|