forgeproof-cli 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forge_gate/__init__.py +44 -0
- forge_gate/_deprecated_cli.py +16 -0
- forgeproof/__init__.py +3 -0
- forgeproof/catalog.py +110 -0
- forgeproof/cli.py +560 -0
- forgeproof/config.py +339 -0
- forgeproof/data/gate_catalog.json +66 -0
- forgeproof/data/host_sets.json +7 -0
- forgeproof/debug_caller.py +271 -0
- forgeproof/debug_core.py +368 -0
- forgeproof/fixture_engine.py +81 -0
- forgeproof/fixtures/__init__.py +19 -0
- forgeproof/fixtures/decision_tree_id3.py +90 -0
- forgeproof/fixtures/gradient_descent_momentum.py +73 -0
- forgeproof/fixtures/kmeans_clustering.py +98 -0
- forgeproof/fixtures/knn_classifier.py +79 -0
- forgeproof/fixtures/linear_regression_gd.py +77 -0
- forgeproof/fixtures/logistic_regression.py +85 -0
- forgeproof/fixtures/naive_bayes_text.py +114 -0
- forgeproof/fixtures/perceptron.py +84 -0
- forgeproof/fixtures/polynomial_regression.py +67 -0
- forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
- forgeproof/ledger.py +633 -0
- forgeproof/lens_tools/__init__.py +11 -0
- forgeproof/lens_tools/guard_lens.py +1250 -0
- forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
- forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
- forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
- forgeproof/lens_tools/invariant_gate.py +199 -0
- forgeproof/lens_tools/metamorphic/__init__.py +9 -0
- forgeproof/lens_tools/metamorphic/relations.py +962 -0
- forgeproof/lens_tools/metamorphic/runner.py +112 -0
- forgeproof/lens_tools/twin_consensus.py +395 -0
- forgeproof/lenses.py +923 -0
- forgeproof/paths.py +56 -0
- forgeproof/reference/ORIGIN.md +29 -0
- forgeproof/reference/decision_tree_id3.py +197 -0
- forgeproof/reference/gradient_descent_momentum.py +141 -0
- forgeproof/reference/kmeans_clustering.py +139 -0
- forgeproof/reference/knn_classifier.py +118 -0
- forgeproof/reference/linear_regression_gd.py +106 -0
- forgeproof/reference/logistic_regression.py +141 -0
- forgeproof/reference/naive_bayes_text.py +152 -0
- forgeproof/reference/perceptron.py +123 -0
- forgeproof/reference/polynomial_regression.py +125 -0
- forgeproof/reference/ridge_regression_normal_eq.py +165 -0
- forgeproof/runner.py +147 -0
- forgeproof/scout/__init__.py +7 -0
- forgeproof/scout/behaviour.py +365 -0
- forgeproof/scout/box.py +581 -0
- forgeproof/scout/cards.py +180 -0
- forgeproof/scout/contract.py +37 -0
- forgeproof/scout/corpus.py +104 -0
- forgeproof/scout/embed.py +217 -0
- forgeproof/scout/engines/__init__.py +1 -0
- forgeproof/scout/engines/chaos.py +454 -0
- forgeproof/scout/engines/chaos_port.py +1331 -0
- forgeproof/scout/engines/chaos_runner.py +178 -0
- forgeproof/scout/engines/executor_port.py +239 -0
- forgeproof/scout/envfit.py +54 -0
- forgeproof/scout/experience.py +161 -0
- forgeproof/scout/fetchproxy.py +368 -0
- forgeproof/scout/ghcache.py +395 -0
- forgeproof/scout/ghpool.py +253 -0
- forgeproof/scout/ghsearch.py +248 -0
- forgeproof/scout/ids.py +82 -0
- forgeproof/scout/intent_lens.py +170 -0
- forgeproof/scout/learn.py +583 -0
- forgeproof/scout/meaning_lens.py +231 -0
- forgeproof/scout/outcomes.py +42 -0
- forgeproof/scout/plant.py +327 -0
- forgeproof/scout/ratify.py +214 -0
- forgeproof/scout/report.py +448 -0
- forgeproof/scout/rule2.py +177 -0
- forgeproof/scout/shape.py +107 -0
- forgeproof/scout/shape_lens.py +71 -0
- forgeproof/scout/signature.py +52 -0
- forgeproof/scout/slots.py +39 -0
- forgeproof/scout/upstream_facts.py +536 -0
- forgeproof/unsupported.py +83 -0
- forgeproof/verifier.py +208 -0
- forgeproof/view_coverage.py +166 -0
- forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
- forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
- forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
- forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
- forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
- forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
- forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
forgeproof/scout/box.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
"""The isolation box (design v1.4.5 §4a.6, build step 4): where scout runs pool code.
|
|
2
|
+
|
|
3
|
+
RUN mode (built): bubblewrap with every namespace unshared, so network off (a fresh netns
|
|
4
|
+
has only its own loopback), no home folder and no secrets file visible (only /usr, /lib*,
|
|
5
|
+
/bin, /sbin and a few /etc files are mounted, read-only), the source mounted read-only at
|
|
6
|
+
/src, a throwaway copy at /work, an empty environment, uid 65534 inside the namespace, its
|
|
7
|
+
own process tree, killed with its parent. If FORGE_GATE_BOX_USER is set, bubblewrap itself
|
|
8
|
+
runs as that unprivileged user (sudo -n -u), so an escape lands as that user, not ours.
|
|
9
|
+
|
|
10
|
+
FETCH mode (built in step 7, slice 1): the same box, still in a fresh network namespace, plus
|
|
11
|
+
one way out: a unix socket bound at /proxy, served OUTSIDE the box by
|
|
12
|
+
:class:`fetchproxy.Proxy`, which opens a connection only to a member of the run's NAMED HOST
|
|
13
|
+
SET (V43-1; ``forgeproof/data/host_sets.json``) and logs every request. A forwarder inside the
|
|
14
|
+
box carries loopback traffic to that socket and runs the command with the proxy variables set.
|
|
15
|
+
No root, no firewall rules. Its red arm adds two attempts to the three below: a CONNECT to
|
|
16
|
+
hosts OUTSIDE the set must be refused (the proxy's own log is the witness), and a CONNECT to a
|
|
17
|
+
host INSIDE the set must succeed (otherwise the refusals prove nothing).
|
|
18
|
+
|
|
19
|
+
Every run first runs the RED ARM in its mode (V4-5): a planted probe tries to read a planted
|
|
20
|
+
canary secret, write a planted canary target outside its copy, and open the network. All
|
|
21
|
+
three must fail, judged from OUTSIDE (the secret's bytes absent from the output, the write
|
|
22
|
+
target unchanged), not from the probe's own word. If any succeeds, the run aborts as
|
|
23
|
+
BLIND(box-red-arm: ...). There is no exempt path.
|
|
24
|
+
|
|
25
|
+
THE FETCH RECORD (KD-13 a, GitHub-lane loop S1). A fetch-mode caller passes ``record_dir``, an
|
|
26
|
+
existing folder it owns. ``run`` then writes the record (set, members, every CONNECT the proxy
|
|
27
|
+
logged, box.py's own dial list) to ``record_dir/fetch-<utc>-<pid>-<hex>.json`` ITSELF: once as
|
|
28
|
+
``state: started`` before any socket opens, and again, atomically (temp file, fsync, rename), before
|
|
29
|
+
it returns AND when it raises. A caller that crashes after the run no longer loses it (step 7's
|
|
30
|
+
record died with its caller's script). A record that cannot be written makes the result BLIND.
|
|
31
|
+
|
|
32
|
+
Copies carry file DATA only (no modes, no ACLs; symlinks skipped and named in the result). So
|
|
33
|
+
nothing in the box is executable by path: callers run ``[interpreter, "/src/file"]``, never
|
|
34
|
+
``./file`` (6E BU-2, 2026-11-11).
|
|
35
|
+
"""
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import json
|
|
39
|
+
import os
|
|
40
|
+
import resource
|
|
41
|
+
import secrets
|
|
42
|
+
import shutil
|
|
43
|
+
import socket
|
|
44
|
+
import subprocess
|
|
45
|
+
import sys
|
|
46
|
+
import tempfile
|
|
47
|
+
from dataclasses import dataclass, field
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
|
|
50
|
+
from .. import config
|
|
51
|
+
from . import fetchproxy
|
|
52
|
+
from .outcomes import Outcome, blind, clean, found
|
|
53
|
+
|
|
54
|
+
BOX_USER_KEY = "FORGE_GATE_BOX_USER"
|
|
55
|
+
# Where the box's copies live when a box user is set: a folder that user can reach (it cannot
|
|
56
|
+
# reach our home, by design). Deploy host: /var/lib/forge-gate-box, owner au, group fgbox, 2770.
|
|
57
|
+
BOX_ROOT_KEY = "FORGE_GATE_BOX_ROOT"
|
|
58
|
+
_ETC = ("ld.so.cache", "ld.so.conf", "ld.so.conf.d", "alternatives", "localtime", "nsswitch.conf")
|
|
59
|
+
_SYS = ("/usr", "/bin", "/sbin", "/lib", "/lib64", "/lib32")
|
|
60
|
+
MEMORY_MB = 1024 # address-space cap for the box and everything in it (same mechanism as runner.run_file)
|
|
61
|
+
FETCH_MEMORY_MB = 3072 # git's index-pack maps the pack; 1 GiB is too tight for a cpython-sized fetch [guess]
|
|
62
|
+
# TLS trust roots only, read-only (fetch mode). Never all of /etc/ssl or /etc/pki: they hold
|
|
63
|
+
# private/ folders (review F3).
|
|
64
|
+
FETCH_ETC = ("ssl/certs", "ca-certificates", "pki/tls/certs", "pki/ca-trust")
|
|
65
|
+
KEEP_MAX_BYTES = 1024 * 1024 * 1024 # review F11: what fetch mode may carry out of the box
|
|
66
|
+
# Fetch red arm: hosts that must be refused. Same organisation, another port, an IP literal, a
|
|
67
|
+
# look-alike suffix, an unrelated host. Members of the run's set are removed from this list.
|
|
68
|
+
OUTSIDE_PROBES = ("api.github.com:443", "github.com:22", "1.1.1.1:443",
|
|
69
|
+
"github.com.evil.example:443", "example.com:443")
|
|
70
|
+
|
|
71
|
+
PROBE = r'''
|
|
72
|
+
import json, socket, sys
|
|
73
|
+
res = {}
|
|
74
|
+
try:
|
|
75
|
+
res["secret"] = "LEAKED:" + open(sys.argv[1]).read()
|
|
76
|
+
except Exception as e:
|
|
77
|
+
res["secret"] = "blocked:" + type(e).__name__
|
|
78
|
+
try:
|
|
79
|
+
with open(sys.argv[2], "w") as fh:
|
|
80
|
+
fh.write("written-from-inside")
|
|
81
|
+
res["write"] = "LEAKED"
|
|
82
|
+
except Exception as e:
|
|
83
|
+
res["write"] = "blocked:" + type(e).__name__
|
|
84
|
+
hits = []
|
|
85
|
+
targets = [("1.1.1.1", 443), ("8.8.8.8", 53), ("127.0.0.1", 22)]
|
|
86
|
+
if len(sys.argv) > 3:
|
|
87
|
+
targets.insert(0, ("127.0.0.1", int(sys.argv[3]))) # the parent's own listener: the control
|
|
88
|
+
for host, port in targets:
|
|
89
|
+
s = socket.socket()
|
|
90
|
+
s.settimeout(2)
|
|
91
|
+
try:
|
|
92
|
+
s.connect((host, port))
|
|
93
|
+
hits.append(f"{host}:{port}")
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
finally:
|
|
97
|
+
s.close()
|
|
98
|
+
res["network"] = ("LEAKED:" + ",".join(hits)) if hits else "blocked"
|
|
99
|
+
if len(sys.argv) > 4: # fetch mode: CONNECT attempts through the forwarder (the proxy judges them)
|
|
100
|
+
said = {}
|
|
101
|
+
for t in json.loads(sys.argv[4]):
|
|
102
|
+
s = socket.socket()
|
|
103
|
+
s.settimeout(25)
|
|
104
|
+
try:
|
|
105
|
+
s.connect(("127.0.0.1", int(sys.argv[5])))
|
|
106
|
+
s.sendall(("CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n" % (t, t)).encode())
|
|
107
|
+
said[t] = s.recv(256).split(b"\r\n", 1)[0].decode("latin-1")
|
|
108
|
+
except Exception as e:
|
|
109
|
+
said[t] = "error:" + type(e).__name__
|
|
110
|
+
finally:
|
|
111
|
+
s.close()
|
|
112
|
+
res["connect"] = said
|
|
113
|
+
print("PROBE " + json.dumps(res))
|
|
114
|
+
'''
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class BoxResult:
|
|
119
|
+
outcome: Outcome # FOUND = the command ran; BLIND(reason) = it did not
|
|
120
|
+
returncode: int | None = None
|
|
121
|
+
stdout: str = ""
|
|
122
|
+
stderr: str = ""
|
|
123
|
+
red_arm: dict = field(default_factory=dict)
|
|
124
|
+
skipped_links: list = field(default_factory=list) # 6E BU-1: left out of the copies, named
|
|
125
|
+
fetch_record: dict = field(default_factory=dict) # fetch mode: set, its file hash, every CONNECT
|
|
126
|
+
fetch_record_file: str | None = None # KD-13 (a): where run() wrote it (record_dir given)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def box_user() -> str | None:
|
|
130
|
+
return config.configured(BOX_USER_KEY)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def box_root() -> Path:
|
|
134
|
+
r = config.configured(BOX_ROOT_KEY)
|
|
135
|
+
if r:
|
|
136
|
+
return Path(r)
|
|
137
|
+
if box_user():
|
|
138
|
+
raise RuntimeError(f"{BOX_USER_KEY} is set but {BOX_ROOT_KEY} is not: the box user cannot "
|
|
139
|
+
"reach our scratch folder")
|
|
140
|
+
return config.scratch_dir() / "box"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def available() -> str | None:
|
|
144
|
+
"""None when the box can run here, else the reason it cannot."""
|
|
145
|
+
if sys.platform != "linux":
|
|
146
|
+
return f"box-unavailable: {sys.platform} (bubblewrap needs Linux)"
|
|
147
|
+
if shutil.which("bwrap") is None:
|
|
148
|
+
return "box-unavailable: bwrap not installed"
|
|
149
|
+
try:
|
|
150
|
+
root = box_root()
|
|
151
|
+
except RuntimeError as e:
|
|
152
|
+
return f"box-unavailable: {e}"
|
|
153
|
+
probe = root if root.exists() else root.parent
|
|
154
|
+
if not os.access(probe, os.W_OK | os.X_OK): # e.g. another user's box root
|
|
155
|
+
return f"box-unavailable: cannot write the box root {root} as {os.environ.get('USER', '?')}"
|
|
156
|
+
user = box_user()
|
|
157
|
+
if user:
|
|
158
|
+
r = subprocess.run(["sudo", "-n", "-u", user, "--", "true"], capture_output=True, text=True)
|
|
159
|
+
if r.returncode != 0: # e.g. a reviewer who may not act as the box user
|
|
160
|
+
return f"box-unavailable: cannot run as box user {user}: {r.stderr.strip()[:200]}"
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def start_failure() -> str | None:
|
|
165
|
+
"""None when bubblewrap can start a namespace here, else its stderr (B4-2: e.g. unprivileged
|
|
166
|
+
user namespaces disabled). Used to tell 'the box cannot start' from 'the box leaked'."""
|
|
167
|
+
try:
|
|
168
|
+
r = subprocess.run(["bwrap", "--unshare-all", "--ro-bind", "/", "/", "true"],
|
|
169
|
+
capture_output=True, text=True, timeout=20)
|
|
170
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
171
|
+
return f"{type(e).__name__}: {e}"
|
|
172
|
+
return None if r.returncode == 0 else (r.stderr.strip()[-300:] or f"exit {r.returncode}")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _bwrap_argv(src: Path, work: Path, argv: list[str], timeout: float = 60, ref: Path | None = None,
|
|
176
|
+
*, binds=(), ro_binds=(), etc_extra=(), memory_mb: int = MEMORY_MB) -> list[str]:
|
|
177
|
+
a = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--clearenv",
|
|
178
|
+
"--uid", "65534", "--gid", "65534",
|
|
179
|
+
"--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/work",
|
|
180
|
+
"--setenv", "LANG", "C.UTF-8", "--setenv", "PYTHONDONTWRITEBYTECODE", "1"]
|
|
181
|
+
for d in _SYS:
|
|
182
|
+
if Path(d).exists():
|
|
183
|
+
a += ["--ro-bind", d, d]
|
|
184
|
+
for e in tuple(_ETC) + tuple(etc_extra):
|
|
185
|
+
if Path("/etc", e).exists():
|
|
186
|
+
a += ["--ro-bind", f"/etc/{e}", f"/etc/{e}"] # bwrap creates the parent folders empty
|
|
187
|
+
a += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp",
|
|
188
|
+
"--ro-bind", str(src), "/src"]
|
|
189
|
+
if ref is not None: # a second, read-only tree (6E 6a pre-note: what we compare against is never writable)
|
|
190
|
+
a += ["--ro-bind", str(ref), "/ref"]
|
|
191
|
+
for host_path, inside in ro_binds:
|
|
192
|
+
a += ["--ro-bind", str(host_path), inside]
|
|
193
|
+
for host_path, inside in binds:
|
|
194
|
+
a += ["--bind", str(host_path), inside]
|
|
195
|
+
a += ["--bind", str(work), "/work", "--chdir", "/work", "--"]
|
|
196
|
+
a += argv
|
|
197
|
+
user = box_user()
|
|
198
|
+
if not user:
|
|
199
|
+
return a # limits are set by _exec's preexec_fn
|
|
200
|
+
# sudo resets resource limits (PAM), so a parent's setrlimit does not reach the box user:
|
|
201
|
+
# set them after sudo, on the command that starts bubblewrap (measured 2026-11-11).
|
|
202
|
+
cap = memory_mb * 1024 * 1024
|
|
203
|
+
return ["sudo", "-n", "-u", user, "--", "prlimit", f"--as={cap}", f"--cpu={int(timeout) + 1}",
|
|
204
|
+
"--"] + a
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _plain_copy(src: Path, dst: Path) -> list[str]:
|
|
208
|
+
"""Copy file DATA only into the box's copies. Not shutil.copytree: that copies metadata
|
|
209
|
+
(a source folder's ACL then overrides the box user's group access) and, by default,
|
|
210
|
+
follows symlinks (a link to a host file would carry that file's bytes into the box).
|
|
211
|
+
Symlinks are skipped and returned, so the caller can see what was left out."""
|
|
212
|
+
if not Path(src).is_dir():
|
|
213
|
+
raise FileNotFoundError(f"box source is not a folder: {src}")
|
|
214
|
+
skipped = []
|
|
215
|
+
dst.mkdir()
|
|
216
|
+
for dirpath, dirnames, filenames in os.walk(src, followlinks=False):
|
|
217
|
+
rel = Path(dirpath).relative_to(src)
|
|
218
|
+
for d in list(dirnames):
|
|
219
|
+
if (Path(dirpath) / d).is_symlink():
|
|
220
|
+
skipped.append(str(rel / d)); dirnames.remove(d)
|
|
221
|
+
else:
|
|
222
|
+
(dst / rel / d).mkdir()
|
|
223
|
+
for f in filenames:
|
|
224
|
+
sp = Path(dirpath) / f
|
|
225
|
+
if sp.is_symlink() or not sp.is_file():
|
|
226
|
+
skipped.append(str(rel / f)); continue
|
|
227
|
+
shutil.copyfile(sp, dst / rel / f, follow_symlinks=False)
|
|
228
|
+
return skipped
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _exec(src: Path, argv: list[str], timeout: float, *, unboxed: bool = False, ref: Path | None = None,
|
|
232
|
+
binds=(), ro_binds=(), etc_extra=(), memory_mb: int = MEMORY_MB, keep: Path | None = None):
|
|
233
|
+
"""``keep``: after a run that exits 0, the work copy's DATA is copied there (fetch mode's
|
|
234
|
+
result); it must not exist yet. Symlinks are skipped, as for every copy."""
|
|
235
|
+
user = None if unboxed else box_user()
|
|
236
|
+
root = box_root() if not unboxed else config.scratch_dir() / "box"
|
|
237
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
238
|
+
run_dir = Path(tempfile.mkdtemp(prefix="run-", dir=root))
|
|
239
|
+
work, src_copy = run_dir / "work", run_dir / "src"
|
|
240
|
+
try:
|
|
241
|
+
skipped = _plain_copy(src, work)
|
|
242
|
+
_plain_copy(src, src_copy) # /src is bound from this copy: the box user can reach it
|
|
243
|
+
ref_copy = None
|
|
244
|
+
if ref is not None:
|
|
245
|
+
ref_copy = run_dir / "ref"
|
|
246
|
+
skipped += ["ref/" + x for x in _plain_copy(ref, ref_copy)]
|
|
247
|
+
if user: # group (the box user's) may read the source copy and write the work copy
|
|
248
|
+
trees = [(src_copy, 0o2750, 0o640), (work, 0o2770, 0o660)]
|
|
249
|
+
if ref_copy is not None:
|
|
250
|
+
trees.append((ref_copy, 0o2750, 0o640))
|
|
251
|
+
for top, dmode, fmode in trees:
|
|
252
|
+
for dirpath, _dirs, files in os.walk(top):
|
|
253
|
+
os.chmod(dirpath, dmode)
|
|
254
|
+
for f in files:
|
|
255
|
+
os.chmod(Path(dirpath) / f, fmode)
|
|
256
|
+
os.chmod(run_dir, 0o2750)
|
|
257
|
+
full = argv if unboxed else _bwrap_argv(src_copy, work, argv, timeout, ref_copy, binds=binds,
|
|
258
|
+
ro_binds=ro_binds, etc_extra=etc_extra, memory_mb=memory_mb)
|
|
259
|
+
|
|
260
|
+
def _limits(): # inherited by bwrap and everything it starts
|
|
261
|
+
cap = memory_mb * 1024 * 1024
|
|
262
|
+
resource.setrlimit(resource.RLIMIT_AS, (cap, cap))
|
|
263
|
+
cpu = int(timeout) + 1
|
|
264
|
+
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
|
|
265
|
+
|
|
266
|
+
r = subprocess.run(full, capture_output=True, text=True, timeout=timeout,
|
|
267
|
+
cwd=work if unboxed else run_dir, start_new_session=True,
|
|
268
|
+
preexec_fn=None if unboxed else _limits)
|
|
269
|
+
if keep is not None and r.returncode == 0:
|
|
270
|
+
if user: # what the box user wrote must be readable by us before we copy it
|
|
271
|
+
subprocess.run(["sudo", "-n", "-u", user, "chmod", "-R", "g+rwX", str(work)],
|
|
272
|
+
capture_output=True, timeout=60)
|
|
273
|
+
size = sum(p.stat().st_size for p in work.rglob("*") if p.is_file() and not p.is_symlink())
|
|
274
|
+
if size > KEEP_MAX_BYTES:
|
|
275
|
+
return r.returncode, r.stdout, r.stderr + f"\nkeep-too-large: {size} bytes", skipped + ["KEEP-REFUSED"]
|
|
276
|
+
tmp_keep = Path(str(keep) + ".tmp") # review F11: atomic, no half-filled keep
|
|
277
|
+
try:
|
|
278
|
+
skipped += ["kept/" + x for x in _plain_copy(work, tmp_keep)]
|
|
279
|
+
os.replace(tmp_keep, keep)
|
|
280
|
+
finally:
|
|
281
|
+
shutil.rmtree(tmp_keep, ignore_errors=True)
|
|
282
|
+
return r.returncode, r.stdout, r.stderr, skipped
|
|
283
|
+
except subprocess.TimeoutExpired:
|
|
284
|
+
return None, "", f"timeout after {timeout}s", skipped
|
|
285
|
+
finally:
|
|
286
|
+
if user: # files the box user wrote: let us remove them (throwaway copy, created above)
|
|
287
|
+
subprocess.run(["sudo", "-n", "-u", user, "chmod", "-R", "g+rwX", str(work)],
|
|
288
|
+
capture_output=True, timeout=30)
|
|
289
|
+
shutil.rmtree(run_dir, ignore_errors=True) # throwaway copies, created above
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def red_arm(mode: str = "run", *, unboxed: bool = False, fetch: dict | None = None) -> dict:
|
|
293
|
+
"""Plant a canary secret and a canary write target, run the probe, judge from outside.
|
|
294
|
+
Returns {"secret","write","network": "blocked"|"LEAKED…", "ok": bool}. ``unboxed=True``
|
|
295
|
+
runs the same probe with no box: every attempt must then LEAK, which proves the targets
|
|
296
|
+
are real (a red arm whose targets cannot be reached passes vacuously).
|
|
297
|
+
|
|
298
|
+
Fetch mode (``fetch`` = the context :func:`run` builds: proxy, its folders, the set): the
|
|
299
|
+
probe runs behind the in-box forwarder and also sends CONNECTs. "proxy_outside" is blocked
|
|
300
|
+
only if the PROXY'S LOG shows every outside target refused and none dialled; "proxy_inside"
|
|
301
|
+
is reached only if the log shows the inside target dialled with upstream ok."""
|
|
302
|
+
if mode not in ("run", "fetch") or (mode == "fetch") != (fetch is not None) or (fetch and unboxed):
|
|
303
|
+
raise ValueError(f"red_arm: bad mode/context: {mode!r}, fetch={fetch is not None}, unboxed={unboxed}")
|
|
304
|
+
canary_dir = config.scratch_dir() / "box-canary"
|
|
305
|
+
canary_dir.mkdir(parents=True, exist_ok=True)
|
|
306
|
+
token = "FG-CANARY-" + secrets.token_hex(16)
|
|
307
|
+
secret = canary_dir / "secret.txt"
|
|
308
|
+
secret.write_text(token)
|
|
309
|
+
target = canary_dir / f"write-target-{secrets.token_hex(4)}"
|
|
310
|
+
# B4-1: the network control must not depend on the host having internet. A listener on our
|
|
311
|
+
# loopback is reachable unboxed and unreachable boxed (the box's loopback is a fresh netns).
|
|
312
|
+
lsock = socket.socket()
|
|
313
|
+
lsock.bind(("127.0.0.1", 0))
|
|
314
|
+
lsock.listen(8)
|
|
315
|
+
port = lsock.getsockname()[1]
|
|
316
|
+
connects: list[str] = []
|
|
317
|
+
try:
|
|
318
|
+
if port == fetchproxy.FORWARD_PORT: # inside the box that port is the forwarder's
|
|
319
|
+
raise RuntimeError("control listener landed on the forwarder's port; retry")
|
|
320
|
+
with tempfile.TemporaryDirectory(dir=canary_dir) as src:
|
|
321
|
+
(Path(src) / "probe.py").write_text(PROBE)
|
|
322
|
+
argv = ["python3", "/src/probe.py" if not unboxed else str(Path(src) / "probe.py"),
|
|
323
|
+
str(secret), str(target), str(port)]
|
|
324
|
+
kw = {}
|
|
325
|
+
if fetch is not None:
|
|
326
|
+
outside = [t for t in OUTSIDE_PROBES if t not in fetch["members"]]
|
|
327
|
+
inside = sorted(fetch["members"])[0]
|
|
328
|
+
connects = outside + [inside]
|
|
329
|
+
argv = (["python3", "/fwd/fwd.py", "/proxy/p.sock", str(fetchproxy.FORWARD_PORT), "--"]
|
|
330
|
+
+ argv + [json.dumps(connects), str(fetchproxy.FORWARD_PORT)])
|
|
331
|
+
kw = dict(ro_binds=[(fetch["proxy_dir"], "/proxy"), (fetch["fwd_dir"], "/fwd")],
|
|
332
|
+
etc_extra=FETCH_ETC)
|
|
333
|
+
fetch["proxy"].phase = "red-arm"
|
|
334
|
+
n0 = len(fetch["proxy"].log)
|
|
335
|
+
fetch["dials_n0"] = len(fetch["dials"])
|
|
336
|
+
rc, out, err, _ = _exec(Path(src), argv, 60 if fetch else 30, unboxed=unboxed, **kw)
|
|
337
|
+
lsock.setblocking(False)
|
|
338
|
+
try: # review F13: our own listener is the outside witness
|
|
339
|
+
c, _ = lsock.accept()
|
|
340
|
+
c.close()
|
|
341
|
+
witnessed = True
|
|
342
|
+
except (BlockingIOError, OSError):
|
|
343
|
+
witnessed = False
|
|
344
|
+
finally:
|
|
345
|
+
lsock.close()
|
|
346
|
+
line = next((l for l in out.splitlines() if l.startswith("PROBE ")), None)
|
|
347
|
+
said = json.loads(line[6:]) if line else {}
|
|
348
|
+
res = {
|
|
349
|
+
"secret": "LEAKED" if token in out or token in err else "blocked",
|
|
350
|
+
"write": "LEAKED" if target.exists() else "blocked",
|
|
351
|
+
# network has no outside witness; the probe's word is used, and a probe that did not
|
|
352
|
+
# report counts as LEAKED (fail closed).
|
|
353
|
+
"network": ("LEAKED:witnessed:" + f"127.0.0.1:{port}") if witnessed and not unboxed
|
|
354
|
+
else said.get("network", "LEAKED:no-probe-report"),
|
|
355
|
+
"probe": said, "rc": rc, "stderr": err[-500:], "control_target": f"127.0.0.1:{port}",
|
|
356
|
+
}
|
|
357
|
+
if target.exists():
|
|
358
|
+
target.unlink() # our own planted canary target, recreated per run
|
|
359
|
+
keys = ["secret", "write", "network"]
|
|
360
|
+
if fetch is not None:
|
|
361
|
+
log = fetch["proxy"].log[n0:]
|
|
362
|
+
res["proxy_log"] = log
|
|
363
|
+
inside, outside = connects[-1], connects[:-1]
|
|
364
|
+
bad = []
|
|
365
|
+
for t in outside:
|
|
366
|
+
seen = [e for e in log if e.get("target") == t]
|
|
367
|
+
if not seen:
|
|
368
|
+
bad.append(f"unattempted:{t}") # fail closed: an untried refusal proves nothing
|
|
369
|
+
elif any(e["decision"] == "allowed" for e in seen):
|
|
370
|
+
bad.append(t)
|
|
371
|
+
res["proxy_outside"] = "blocked" if not bad else "LEAKED:" + ",".join(bad)
|
|
372
|
+
dialled_out = [e["target"] for e in log if e["decision"] == "allowed" and e["target"] != inside]
|
|
373
|
+
# review F5: box.py's OWN count of dials (the proxy's resolver is wrapped below), so a proxy
|
|
374
|
+
# that dials and logs "denied" is still caught
|
|
375
|
+
dials = fetch["dials"][fetch.get("dials_n0", 0):]
|
|
376
|
+
dialled_out += [t for t in dials if t != inside]
|
|
377
|
+
if dialled_out: # anything dialled that is not the inside target is a leak, whatever it was
|
|
378
|
+
res["proxy_outside"] = "LEAKED:dialled:" + ",".join(dialled_out)
|
|
379
|
+
res["dials"] = list(dials)
|
|
380
|
+
ins = [e for e in log if e.get("target") == inside]
|
|
381
|
+
res["proxy_inside"] = ("reached" if any(e["decision"] == "allowed" and e["upstream"] == "ok" for e in ins)
|
|
382
|
+
and dials.count(inside) == 1
|
|
383
|
+
else "UNREACHED:" + (",".join(str(e.get("upstream")) for e in ins) or "unattempted"))
|
|
384
|
+
res["inside_target"] = inside
|
|
385
|
+
keys.append("proxy_outside")
|
|
386
|
+
res["ok"] = (all(res[k] == "blocked" for k in keys) and line is not None
|
|
387
|
+
and (fetch is None or res["proxy_inside"] == "reached"))
|
|
388
|
+
return res
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _fetch_context(host_set: str, sets: dict, resolve=None) -> dict:
|
|
392
|
+
"""Start the proxy and write the forwarder, in folders the box user can reach. The proxy's
|
|
393
|
+
resolver is wrapped so box.py itself counts every dial (review F5)."""
|
|
394
|
+
root = box_root()
|
|
395
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
396
|
+
proxy_dir = Path(tempfile.mkdtemp(prefix="proxy-", dir=root))
|
|
397
|
+
fwd_dir = Path(tempfile.mkdtemp(prefix="fwd-", dir=root))
|
|
398
|
+
try:
|
|
399
|
+
# The box root is setgid to the box user's group, so what is created in these folders
|
|
400
|
+
# inherits that group. A chmod by a non-member silently CLEARS a folder's setgid bit
|
|
401
|
+
# (Linux), so every file, the socket included, is created BEFORE its folder's chmod.
|
|
402
|
+
# Found by the live reach check on the deploy host, 2026-11-14: the socket came out au:au and the
|
|
403
|
+
# box user got EACCES (failed closed: zero dials).
|
|
404
|
+
(fwd_dir / "fwd.py").write_text(fetchproxy.FORWARDER)
|
|
405
|
+
os.chmod(fwd_dir / "fwd.py", 0o640)
|
|
406
|
+
members = sets[host_set]
|
|
407
|
+
dials: list[str] = []
|
|
408
|
+
base = resolve or (lambda t: (t.rpartition(":")[0], int(t.rpartition(":")[2])))
|
|
409
|
+
|
|
410
|
+
def counted(target):
|
|
411
|
+
dials.append(target)
|
|
412
|
+
return base(target)
|
|
413
|
+
proxy = fetchproxy.Proxy(proxy_dir / "p.sock", members, resolve=counted).start()
|
|
414
|
+
try:
|
|
415
|
+
os.chmod(proxy_dir, 0o750) # read + traverse for the box user's group; the socket is 0660
|
|
416
|
+
os.chmod(fwd_dir, 0o750)
|
|
417
|
+
if box_user():
|
|
418
|
+
want = root.stat().st_gid
|
|
419
|
+
for f in (proxy_dir / "p.sock", fwd_dir / "fwd.py"):
|
|
420
|
+
if f.stat().st_gid != want:
|
|
421
|
+
raise RuntimeError(f"{f.name} is group {f.stat().st_gid}, the box root's group is {want}: "
|
|
422
|
+
f"the box user could not reach it (is {root} setgid?)")
|
|
423
|
+
except BaseException:
|
|
424
|
+
proxy.stop()
|
|
425
|
+
raise
|
|
426
|
+
except BaseException: # review F12: nothing left behind when the proxy cannot start
|
|
427
|
+
shutil.rmtree(proxy_dir, ignore_errors=True)
|
|
428
|
+
shutil.rmtree(fwd_dir, ignore_errors=True)
|
|
429
|
+
raise
|
|
430
|
+
return {"proxy": proxy, "proxy_dir": proxy_dir, "fwd_dir": fwd_dir, "members": members, "dials": dials}
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _write_record(path: Path, record: dict) -> None:
|
|
434
|
+
"""Atomic and durable: temp file in the same folder, fsync, rename, fsync the folder."""
|
|
435
|
+
data = (json.dumps(record, sort_keys=True, default=str) + "\n").encode("utf-8")
|
|
436
|
+
tmp = path.with_name(path.name + ".part")
|
|
437
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o640)
|
|
438
|
+
try:
|
|
439
|
+
view = memoryview(data)
|
|
440
|
+
while view:
|
|
441
|
+
view = view[os.write(fd, view):]
|
|
442
|
+
os.fsync(fd)
|
|
443
|
+
finally:
|
|
444
|
+
os.close(fd)
|
|
445
|
+
os.replace(tmp, path)
|
|
446
|
+
dfd = os.open(path.parent, os.O_RDONLY)
|
|
447
|
+
try:
|
|
448
|
+
os.fsync(dfd)
|
|
449
|
+
finally:
|
|
450
|
+
os.close(dfd)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _utc() -> str:
|
|
454
|
+
import time
|
|
455
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def run(src: Path, argv: list[str], *, mode: str = "run", timeout: float = 60,
|
|
459
|
+
ref: Path | None = None, host_set: str | None = None, keep: Path | None = None,
|
|
460
|
+
record_dir: Path | None = None,
|
|
461
|
+
_host_sets_file: Path | None = None, _resolve=None, _same_user_ok: bool = False) -> BoxResult:
|
|
462
|
+
"""Run ``argv`` in the box. Fetch mode needs ``host_set`` (a name in host_sets.json); its
|
|
463
|
+
result's ``fetch_record`` names the set, the file's sha256 and every CONNECT of the run.
|
|
464
|
+
With ``record_dir`` (fetch mode only; an existing folder) the record is also written there by
|
|
465
|
+
this function, before it returns and when it raises (KD-13 a); ``fetch_record_file`` names it.
|
|
466
|
+
``_host_sets_file`` / ``_resolve`` exist for tests only (a fake set, a local fake upstream)."""
|
|
467
|
+
record: dict = {}
|
|
468
|
+
if record_dir is None:
|
|
469
|
+
return _run(src, argv, mode, timeout, ref, host_set, keep, _host_sets_file, _resolve,
|
|
470
|
+
_same_user_ok, record)
|
|
471
|
+
if mode != "fetch":
|
|
472
|
+
return BoxResult(blind("record-dir-is-for-fetch-mode"))
|
|
473
|
+
rdir = Path(record_dir)
|
|
474
|
+
if not rdir.is_dir(): # checked before anything runs: no fetch without a place for its record
|
|
475
|
+
return BoxResult(blind(f"fetch-record-dir-missing: {rdir}"))
|
|
476
|
+
stamp = _utc().replace("-", "").replace(":", "")
|
|
477
|
+
path = rdir / f"fetch-{stamp}-{os.getpid()}-{secrets.token_hex(3)}.json"
|
|
478
|
+
record.update(state="started", started_at=_utc(), mode="fetch", host_set=host_set,
|
|
479
|
+
argv=[str(a) for a in argv])
|
|
480
|
+
try:
|
|
481
|
+
_write_record(path, record)
|
|
482
|
+
except OSError as e:
|
|
483
|
+
return BoxResult(blind(f"fetch-record-unwritable: {e}"))
|
|
484
|
+
try:
|
|
485
|
+
res = _run(src, argv, mode, timeout, ref, host_set, keep, _host_sets_file, _resolve,
|
|
486
|
+
_same_user_ok, record)
|
|
487
|
+
except BaseException as e:
|
|
488
|
+
record.update(state="error", error=f"{type(e).__name__}: {e}"[:2000], ended_at=_utc())
|
|
489
|
+
try:
|
|
490
|
+
_write_record(path, record)
|
|
491
|
+
except OSError:
|
|
492
|
+
pass # the exception that is already in flight is the louder one; the started record stays
|
|
493
|
+
raise
|
|
494
|
+
record.update(state="done", ended_at=_utc(), outcome=res.outcome.label(), returncode=res.returncode)
|
|
495
|
+
res.fetch_record = record
|
|
496
|
+
try:
|
|
497
|
+
_write_record(path, record)
|
|
498
|
+
except OSError as e:
|
|
499
|
+
res.outcome = blind(f"fetch-record-unwritable: {e}")
|
|
500
|
+
return res
|
|
501
|
+
res.fetch_record_file = str(path)
|
|
502
|
+
return res
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _run(src, argv, mode, timeout, ref, host_set, keep, _host_sets_file, _resolve, _same_user_ok,
|
|
506
|
+
record: dict) -> BoxResult:
|
|
507
|
+
sets = sha = None
|
|
508
|
+
if mode == "fetch":
|
|
509
|
+
if not host_set:
|
|
510
|
+
return BoxResult(blind("fetch-needs-host-set"))
|
|
511
|
+
try:
|
|
512
|
+
sets, sha = fetchproxy.load_host_sets(_host_sets_file or fetchproxy.HOST_SETS_FILE)
|
|
513
|
+
except (OSError, ValueError) as e:
|
|
514
|
+
return BoxResult(blind(f"host-sets-unreadable: {e}"))
|
|
515
|
+
if host_set not in sets:
|
|
516
|
+
return BoxResult(blind(f"unknown-host-set: {host_set}"))
|
|
517
|
+
elif mode != "run":
|
|
518
|
+
return BoxResult(blind(f"unknown-mode: {mode}"))
|
|
519
|
+
elif host_set or keep is not None:
|
|
520
|
+
return BoxResult(blind("run-mode-takes-no-host-set-or-keep"))
|
|
521
|
+
why = available()
|
|
522
|
+
if why:
|
|
523
|
+
return BoxResult(blind(why))
|
|
524
|
+
for tree in (src, ref) if ref is not None else (src,):
|
|
525
|
+
if not Path(tree).is_dir(): # os.walk would read a missing folder as an empty one
|
|
526
|
+
return BoxResult(blind(f"source-missing: {tree}"))
|
|
527
|
+
if keep is not None and Path(keep).exists():
|
|
528
|
+
return BoxResult(blind(f"keep-exists: {keep}"))
|
|
529
|
+
if box_user() and shutil.which("prlimit") is None:
|
|
530
|
+
return BoxResult(blind("box-unavailable: prlimit not installed (needed to cap the box user)"))
|
|
531
|
+
if mode == "fetch" and not box_user() and not _same_user_ok:
|
|
532
|
+
# review F4 / §4a.6: fetch mode uses a throwaway user. Tests may waive it, recorded below.
|
|
533
|
+
return BoxResult(blind(f"fetch-needs-box-user: set {BOX_USER_KEY}"))
|
|
534
|
+
try:
|
|
535
|
+
fx = _fetch_context(host_set, sets, _resolve) if mode == "fetch" else None
|
|
536
|
+
except fetchproxy.SocketPathTooLong as e:
|
|
537
|
+
return BoxResult(blind(f"box-unavailable: {e}"))
|
|
538
|
+
try:
|
|
539
|
+
if fx is not None: # known before the red arm runs, so a raise there still records them
|
|
540
|
+
record.update({"mode": "fetch", "host_set": host_set, "members": sorted(fx["members"]),
|
|
541
|
+
"host_sets_sha256": sha, "box_user": box_user(),
|
|
542
|
+
"overrides": [k for k, v in (("host_sets_file", _host_sets_file), ("resolver", _resolve),
|
|
543
|
+
("same_user", _same_user_ok)) if v]})
|
|
544
|
+
arm = red_arm(mode) if fx is None else red_arm(mode, fetch=fx) # run mode: the call as before
|
|
545
|
+
if fx is not None:
|
|
546
|
+
record["red_arm_connects"] = arm.get("proxy_log", [])
|
|
547
|
+
if not arm.get("probe"):
|
|
548
|
+
cannot = start_failure()
|
|
549
|
+
if cannot:
|
|
550
|
+
return BoxResult(blind(f"box-unavailable: bwrap cannot start: {cannot}"), red_arm=arm,
|
|
551
|
+
fetch_record=record)
|
|
552
|
+
if not arm["ok"]:
|
|
553
|
+
keys = ("secret", "write", "network", "proxy_outside")
|
|
554
|
+
failed = [k for k in keys if k in arm and arm[k] != "blocked"]
|
|
555
|
+
if fx is not None and arm.get("proxy_inside") != "reached":
|
|
556
|
+
failed.append("proxy_inside")
|
|
557
|
+
return BoxResult(blind("box-red-arm: " + ",".join(failed or ["no-probe-report"])), red_arm=arm,
|
|
558
|
+
fetch_record=record)
|
|
559
|
+
kw = {}
|
|
560
|
+
if fx is not None:
|
|
561
|
+
fx["proxy"].phase = "run"
|
|
562
|
+
argv = ["python3", "/fwd/fwd.py", "/proxy/p.sock", str(fetchproxy.FORWARD_PORT), "--"] + list(argv)
|
|
563
|
+
kw = dict(ro_binds=[(fx["proxy_dir"], "/proxy"), (fx["fwd_dir"], "/fwd")],
|
|
564
|
+
etc_extra=FETCH_ETC, memory_mb=FETCH_MEMORY_MB, keep=keep)
|
|
565
|
+
rc, out, err, skipped = _exec(Path(src), argv, timeout, ref=Path(ref) if ref is not None else None, **kw)
|
|
566
|
+
finally:
|
|
567
|
+
if fx is not None:
|
|
568
|
+
log = fx["proxy"].stop()
|
|
569
|
+
# KD-13 (a): filled here, on the way out of every path, raises included
|
|
570
|
+
record["connects"] = [e for e in log if e["phase"] == "run"]
|
|
571
|
+
record.setdefault("red_arm_connects", [e for e in log if e["phase"] != "run"])
|
|
572
|
+
record["dials"] = list(fx["dials"])
|
|
573
|
+
shutil.rmtree(fx["proxy_dir"], ignore_errors=True) # our own folders, created above
|
|
574
|
+
shutil.rmtree(fx["fwd_dir"], ignore_errors=True)
|
|
575
|
+
if fx is not None:
|
|
576
|
+
if "KEEP-REFUSED" in skipped:
|
|
577
|
+
return BoxResult(blind("keep-too-large"), rc, out, err, arm, skipped, record)
|
|
578
|
+
note = f"; skipped {len(skipped)} symlink(s): {', '.join(skipped[:5])}" if skipped else ""
|
|
579
|
+
if rc is None:
|
|
580
|
+
return BoxResult(blind("timeout" + note), None, out, err, arm, skipped, record)
|
|
581
|
+
return BoxResult(found(f"ran, exit {rc}{note}"), rc, out, err, arm, skipped, record)
|