@jbkjr/relay 0.0.0-stage → 1.2.1
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/LICENSE +21 -0
- package/LICENSES/Apache-2.0.txt +201 -0
- package/LICENSES/README.md +19 -0
- package/LICENSES/codex-NOTICE.txt +6 -0
- package/README.md +386 -2
- package/SECURITY.md +145 -0
- package/adapters/briefs/claude.md +43 -0
- package/adapters/briefs/codex.md +56 -0
- package/adapters/briefs/models.json +33 -0
- package/adapters/build.mjs +8 -0
- package/adapters/claude/.claude-plugin/marketplace.json +13 -0
- package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
- package/adapters/claude/relay/agents/codex.md +21 -0
- package/adapters/claude/relay/agents/operator.md +21 -0
- package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
- package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
- package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
- package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
- package/adapters/claude/relay/skills/review/SKILL.md +21 -0
- package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
- package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
- package/adapters/codex/.agents/plugins/marketplace.json +20 -0
- package/adapters/codex/AGENTS.snippet.md +5 -0
- package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
- package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
- package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
- package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
- package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
- package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
- package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
- package/adapters/generate.mjs +124 -0
- package/bin/relay +59 -0
- package/codex-pin.json +12 -0
- package/dist/backends/acp.js +1424 -0
- package/dist/backends/claude.js +890 -0
- package/dist/backends/cli-version.js +112 -0
- package/dist/backends/codex-app.js +1525 -0
- package/dist/backends/codex-daybreak.js +75 -0
- package/dist/backends/codex-env.js +656 -0
- package/dist/backends/codex-network.js +304 -0
- package/dist/backends/codex-pin.js +320 -0
- package/dist/backends/codex-shell-policy.js +182 -0
- package/dist/backends/codex-stage2.js +998 -0
- package/dist/backends/codex-subagents.js +47 -0
- package/dist/backends/codex.js +637 -0
- package/dist/backends/copilot.js +246 -0
- package/dist/backends/env.js +147 -0
- package/dist/backends/gemini.js +607 -0
- package/dist/backends/grok.js +337 -0
- package/dist/backends/index.js +8 -0
- package/dist/backends/native-temp.js +187 -0
- package/dist/backends/never-admission.js +90 -0
- package/dist/backends/run.js +67 -0
- package/dist/backends/stream.js +230 -0
- package/dist/backends/tool-discovery.js +15 -0
- package/dist/backends/types.js +264 -0
- package/dist/build-info.json +5 -0
- package/dist/cli.js +344 -0
- package/dist/confine/bridge.js +113 -0
- package/dist/confine/broker-core.js +76 -0
- package/dist/confine/broker-http.js +650 -0
- package/dist/confine/broker-names.js +9 -0
- package/dist/confine/broker.js +258 -0
- package/dist/confine/canary.js +380 -0
- package/dist/confine/diagnostics.js +122 -0
- package/dist/confine/gemini-tools-main.js +8 -0
- package/dist/confine/gemini-tools.js +181 -0
- package/dist/confine/hardlinks.js +58 -0
- package/dist/confine/harness-config.js +16 -0
- package/dist/confine/index.js +117 -0
- package/dist/confine/leases.js +217 -0
- package/dist/confine/paths.js +6 -0
- package/dist/confine/peer.js +115 -0
- package/dist/confine/port-policy.js +8 -0
- package/dist/confine/ports.js +365 -0
- package/dist/confine/private-root.js +208 -0
- package/dist/confine/probe-stage2.js +501 -0
- package/dist/confine/probe.js +1109 -0
- package/dist/confine/proxy.js +783 -0
- package/dist/confine/sbcheck.js +208 -0
- package/dist/confine/seatbelt-never.js +41 -0
- package/dist/confine/seatbelt-stage2.js +139 -0
- package/dist/confine/seatbelt.js +1129 -0
- package/dist/confine/sockets.js +36 -0
- package/dist/confine/turn-probe.js +19 -0
- package/dist/confine/turn.js +86 -0
- package/dist/core/adoption.js +124 -0
- package/dist/core/api-keys.js +423 -0
- package/dist/core/approvals.js +740 -0
- package/dist/core/build-identity.js +248 -0
- package/dist/core/caller.js +749 -0
- package/dist/core/calls.js +102 -0
- package/dist/core/claude-settings.js +1045 -0
- package/dist/core/config.js +453 -0
- package/dist/core/context.js +186 -0
- package/dist/core/db.js +753 -0
- package/dist/core/dispatch.js +110 -0
- package/dist/core/env-broker.js +505 -0
- package/dist/core/env-policy.js +182 -0
- package/dist/core/escalation-authority.js +76 -0
- package/dist/core/escalation-contract.js +13 -0
- package/dist/core/escalation-person-path.js +131 -0
- package/dist/core/escalation-policy.js +79 -0
- package/dist/core/escalation-runtime.js +135 -0
- package/dist/core/escalation-state.js +42 -0
- package/dist/core/escalations.js +191 -0
- package/dist/core/events.js +235 -0
- package/dist/core/executables.js +147 -0
- package/dist/core/extensions.js +645 -0
- package/dist/core/families.js +204 -0
- package/dist/core/git.js +657 -0
- package/dist/core/identity.js +113 -0
- package/dist/core/liveness.js +68 -0
- package/dist/core/mediated-network-provider.js +81 -0
- package/dist/core/never-checkpoint.js +76 -0
- package/dist/core/never-coverage.js +97 -0
- package/dist/core/never-network.js +49 -0
- package/dist/core/never-policy.js +302 -0
- package/dist/core/never-proxy-policy.js +109 -0
- package/dist/core/never-schema.js +61 -0
- package/dist/core/never-tools.js +56 -0
- package/dist/core/notices.js +48 -0
- package/dist/core/ops.js +959 -0
- package/dist/core/outcome.js +224 -0
- package/dist/core/params.js +32 -0
- package/dist/core/presence.js +174 -0
- package/dist/core/procs.js +546 -0
- package/dist/core/prompts.js +363 -0
- package/dist/core/protected-config.js +238 -0
- package/dist/core/raw-network.js +192 -0
- package/dist/core/redact.js +152 -0
- package/dist/core/refusal.js +33 -0
- package/dist/core/relay-command.js +310 -0
- package/dist/core/reported.js +3 -0
- package/dist/core/restart-overlay.js +651 -0
- package/dist/core/retention.js +1135 -0
- package/dist/core/secrets.js +329 -0
- package/dist/core/session-token.js +175 -0
- package/dist/core/session.js +744 -0
- package/dist/core/shell.js +2 -0
- package/dist/core/shipped-pin.js +47 -0
- package/dist/core/shown.js +42 -0
- package/dist/core/slots.js +67 -0
- package/dist/core/stage2-executors.js +453 -0
- package/dist/core/stage2-switch.js +5 -0
- package/dist/core/steering.js +149 -0
- package/dist/core/storage.js +358 -0
- package/dist/core/toml.js +175 -0
- package/dist/core/views.js +324 -0
- package/dist/core/wait.js +114 -0
- package/dist/core/wake.js +207 -0
- package/dist/core/watch.js +247 -0
- package/dist/core/worktree.js +213 -0
- package/dist/hosts/claude-desktop.js +274 -0
- package/dist/hosts/claude.js +249 -0
- package/dist/hosts/codex.js +329 -0
- package/dist/hosts/desktop-shared.js +20 -0
- package/dist/hosts/index.js +11 -0
- package/dist/hosts/types.js +4 -0
- package/dist/install/basics.js +18 -0
- package/dist/install/claude-init.js +133 -0
- package/dist/install/common.js +655 -0
- package/dist/install/doctor.js +629 -0
- package/dist/install/qualify-codex.js +205 -0
- package/dist/install.js +524 -0
- package/dist/mcp/elicit.js +209 -0
- package/dist/mcp/gateway.js +218 -0
- package/dist/mcp/host.js +253 -0
- package/dist/mcp/server.js +1124 -0
- package/dist/mcp/stdio.js +37 -0
- package/dist/modes/discussion.js +393 -0
- package/dist/modes/review.js +722 -0
- package/dist/native/relay-sbcheck +0 -0
- package/dist/targets/briefs.js +86 -0
- package/dist/targets/claude.js +94 -0
- package/dist/targets/codex.js +66 -0
- package/dist/targets/copilot.js +93 -0
- package/dist/targets/gemini.js +119 -0
- package/dist/targets/grok.js +126 -0
- package/dist/targets/index.js +192 -0
- package/dist/targets/types.js +18 -0
- package/dist/targets/verified.js +35 -0
- package/dist/worker.js +113 -0
- package/docs/UPGRADING.md +1502 -0
- package/docs/pinned-codex.md +321 -0
- package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
- package/experiments/stage2-redteam/lib/report.mjs +35 -0
- package/npm-shrinkwrap.json +1632 -0
- package/package.json +82 -4
- package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
- package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
- package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
- package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
- package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
- package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
- package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
- package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
- package/scripts/codex-qualify/main-module.mjs +14 -0
- package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
- package/scripts/codex-qualify/scratch-env.mjs +31 -0
- package/scripts/codex-qualify/session.mjs +96 -0
- package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
- package/test/codex-permissions.test.ts +875 -0
- package/test/fixtures/boundary-probes.mjs +17 -0
- package/test/fixtures/denial-stream-host.mjs +7 -0
- package/test/fixtures/families.json +246 -0
- package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
- package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
- package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
- package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
- package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
- package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
- package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
- package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
- package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
- package/test/fixtures/link-parent.mjs +6 -0
- package/test/fixtures/mediated-command.cjs +72 -0
- package/test/fixtures/native-skill-isolation.json +280 -0
- package/test/fixtures/pinned-codex-app-server.mjs +25 -0
- package/test/fixtures/qualified-ext-adapters.mjs +36 -0
- package/test/fixtures/refusals/README.md +52 -0
- package/test/fixtures/refusals/claude-source-result.json +7 -0
- package/test/fixtures/refusals/openai-app-capacity.json +24 -0
- package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
- package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
- package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
- package/test/fixtures/refusals/openai-review-capacity.json +24 -0
- package/test/fixtures/relay-0.2.0.sql +57 -0
- package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
- package/test/fixtures/relay-0.9.1.sql +340 -0
- package/test/fixtures/slow-boundary-probes.mjs +37 -0
- package/test/fixtures/stable-surfaces/config.json +1122 -0
- package/test/fixtures/stable-surfaces/escalation.json +128 -0
- package/test/fixtures/stable-surfaces/events.json +37 -0
- package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
- package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
- package/test/fixtures/stable-surfaces/notice.txt +1 -0
- package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
- package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
- package/test/fixtures/stable-surfaces/registry.json +49 -0
- package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
- package/test/fixtures/stable-surfaces/tools.json +716 -0
- package/test/fixtures/stable-surfaces/usage.txt +46 -0
- package/test/fixtures/stage2-acp-native.mjs +138 -0
- package/test/fixtures/stage2-app-server.mjs +23 -0
- package/test/fixtures/stage2-catalog.json +91 -0
- package/test/fixtures/stage2-hostile-web.mjs +35 -0
- package/test/fixtures/stage2-native-network.mjs +62 -0
- package/test/fixtures/stage2-worker.ts +87 -0
- package/test/fixtures/status-views/expected.json +7825 -0
- package/test/fixtures/status-views/registries.json +1 -0
- package/test/fixtures/steering.json +209 -0
- package/test/helpers.ts +740 -0
- package/test/host-env.ts +7 -0
- package/test/keychain-decoy.ts +197 -0
- package/test/live-scope.ts +44 -0
- package/test/mediated-network.test.ts +192 -0
- package/test/mediated-proxy.test.ts +264 -0
- package/test/native-temp-alias.ts +10 -0
- package/test/never-policy.test.ts +629 -0
- package/test/never-tools.test.ts +136 -0
- package/test/process-home.ts +18 -0
- package/test/proxy.test.ts +531 -0
- package/test/restart-overlay-live.test.ts +85 -0
- package/test/restart-overlay-profile.test.ts +66 -0
- package/test/restart-overlay.test.ts +416 -0
- package/test/stable-surfaces.test.ts +249 -0
- package/test/stage2-escalation-live.test.ts +544 -0
- package/test/stage2-escalation-qualification.test.ts +170 -0
- package/test/stage2-escalation.test.ts +747 -0
- package/test/stage2-executor.test.ts +849 -0
- package/test/stage2-grant.test.ts +603 -0
- package/test/stage2-native-live.test.ts +647 -0
- package/test/stage2-network-decisions.test.ts +70 -0
- package/test/stage2-probe.test.ts +845 -0
- package/test/stage2-standing-live.test.ts +203 -0
- package/test/stubs/broker-host.mjs +59 -0
- package/test/stubs/broker-peer.mjs +20 -0
- package/test/stubs/confined-harness.mjs +91 -0
- package/test/stubs/ext-broken-server.mjs +2 -0
- package/test/stubs/ext-odd-server.mjs +21 -0
- package/test/stubs/ext-server.mjs +31 -0
- package/test/stubs/fake-host-cli.mjs +218 -0
- package/test/stubs/procargs.mjs +30 -0
- package/test/stubs/stub-acp +4 -0
- package/test/stubs/stub-agent.mjs +322 -0
- package/test/stubs/stub-claude +4 -0
- package/test/stubs/stub-codex +4 -0
- package/test/stubs/targets/acp.mjs +307 -0
- package/test/stubs/targets/claude.mjs +149 -0
- package/test/stubs/targets/codex.mjs +479 -0
- package/test/stubs/targets/gemini.mjs +604 -0
- package/test/temp-root.ts +11 -0
- package/test/wp4-adapters.test.ts +353 -0
- package/test/wp4-interlock.test.ts +136 -0
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { relayHome, VERSION } from "../core/config.js";
|
|
9
|
+
import { within } from "./paths.js";
|
|
10
|
+
import { boundaryPaths, canonical, F_MAKECOMPRESSED, F_TRANSFEREXTENTS, persistentState } from "./seatbelt.js";
|
|
11
|
+
import { ensureRelaySocketsDir, relaySocketsDir } from "./sockets.js";
|
|
12
|
+
import { planStage2Network } from "./probe-stage2.js";
|
|
13
|
+
import { isGroupSignalRefusal, sendGroupSignal } from "../core/procs.js";
|
|
14
|
+
/**
|
|
15
|
+
* Per-turn boundary probes. Before each confined launch relay runs the canary (canary.ts) under
|
|
16
|
+
* exactly the confinement the harness is about to get (same profile and parameters, same working
|
|
17
|
+
* directory, and the variables relay sets for the launch, all of which the fingerprint covers; not
|
|
18
|
+
* the variables the harness inherits besides) and refuses the launch if anything that must be denied
|
|
19
|
+
* is not, or anything that must work does not. Each probe is a real attempt against a real target relay set up outside the
|
|
20
|
+
* sandbox, so a denial means the boundary held, not that the target was missing. Nothing is cached:
|
|
21
|
+
* every turn is probed with its own profile.
|
|
22
|
+
*/
|
|
23
|
+
const CANARY = path.join(path.dirname(fileURLToPath(import.meta.url)), "canary.js");
|
|
24
|
+
/** The whole canary run may take this long before the launch is refused. It takes about half a second when idle; a short limit refused turns on a busy Mac. */
|
|
25
|
+
const CANARY_TIMEOUT_MS = 30000;
|
|
26
|
+
/** How long a connect or a lookup the sandbox should refuse at once may hang before it counts as not refused. */
|
|
27
|
+
const STEP_TIMEOUT_MS = 1000;
|
|
28
|
+
/** Never routed (TEST-NET-1): a connect there is refused by the sandbox at once, or it hangs. */
|
|
29
|
+
const UNROUTABLE = "192.0.2.1";
|
|
30
|
+
/** The IPv6 documentation prefix, never routed either. */
|
|
31
|
+
const UNROUTABLE_V6 = "2001:db8::1";
|
|
32
|
+
/** A name that resolves wherever DNS works. */
|
|
33
|
+
const DNS_NAME = "www.apple.com";
|
|
34
|
+
/** The system resolver's socket: getaddrinfo reaches DNS only through it. */
|
|
35
|
+
const MDNS_SOCKET = "/private/var/run/mDNSResponder";
|
|
36
|
+
/** The system log's socket, which the profile allows (a local log, as Codex's does). */
|
|
37
|
+
const SYSLOG_SOCKET = "/private/var/run/syslog";
|
|
38
|
+
/** macOS keeps 104 bytes for a Unix socket's path, its terminating NUL included. */
|
|
39
|
+
const MAX_SOCKET_PATH = 103;
|
|
40
|
+
/** <sys/socket.h> */
|
|
41
|
+
const AF_ROUTE = 17;
|
|
42
|
+
const SOCK_RAW = 3;
|
|
43
|
+
/** <sys/sysctl.h>: kern.proc.pid.<pid> and kern.procargs2.<pid> by MIB. */
|
|
44
|
+
const CTL_KERN = 1;
|
|
45
|
+
const KERN_PROC = 14;
|
|
46
|
+
const KERN_PROC_PID = 1;
|
|
47
|
+
const KERN_PROCARGS2 = 49;
|
|
48
|
+
/** The canary's native checks run in osascript, a process of the canary's own: "self" is resolved there. */
|
|
49
|
+
const SELF = -1;
|
|
50
|
+
/**
|
|
51
|
+
* Addresses configured on the loopback interface besides the ones Seatbelt's "localhost" covers
|
|
52
|
+
* (127.0.0.1, ::1 and lo0's link-local fe80::1): an alias someone added for a local service.
|
|
53
|
+
* With the network on, the profile's loopback rule does not cover such an address (seen on macOS
|
|
54
|
+
* 27.0: a connect to 127.0.0.2 was not refused), so each one found is probed and must be refused.
|
|
55
|
+
*/
|
|
56
|
+
export function loopbackAliases(interfaces = os.networkInterfaces()) {
|
|
57
|
+
const covered = new Set(["127.0.0.1", "::1", "fe80::1"]);
|
|
58
|
+
return (interfaces.lo0 ?? []).map((a) => a.address.split("%")[0]).filter((a) => !covered.has(a));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Every address a connect could reach this Mac at (review R1): loopback, the unspecified addresses,
|
|
62
|
+
* each address `os.networkInterfaces()` reports (link-local ones with their interface, without which
|
|
63
|
+
* they cannot be connected to), and the IPv6 spellings of each IPv4 one: IPv4-mapped (`::ffff:a.b.c.d`;
|
|
64
|
+
* 0.0.0.0's also written out, `0:0:0:0:0:ffff:0:0`) and IPv4-compatible (`::a.b.c.d`). Seatbelt's
|
|
65
|
+
* "localhost" matches the plain addresses but not the IPv4-mapped ones, loopback's apart: through
|
|
66
|
+
* 1.0.5, ::ffff:0.0.0.0 reached loopback and ::ffff:<a LAN or tailnet address> that address past the
|
|
67
|
+
* network-on rule (measured on macOS 27.0.1). The probes try every spelling.
|
|
68
|
+
*/
|
|
69
|
+
export function localAddressSpellings(interfaces = os.networkInterfaces()) {
|
|
70
|
+
const out = ["127.0.0.1", "::1", "0.0.0.0", "::", "fe80::1%lo0"];
|
|
71
|
+
const v4 = new Set(["127.0.0.1", "0.0.0.0"]);
|
|
72
|
+
for (const [name, addrs] of Object.entries(interfaces)) {
|
|
73
|
+
for (const a of addrs ?? []) {
|
|
74
|
+
const bare = a.address.split("%")[0];
|
|
75
|
+
if (a.family === "IPv4")
|
|
76
|
+
v4.add(bare);
|
|
77
|
+
out.push(a.family === "IPv6" && /^fe[89ab][0-9a-f]:/i.test(bare) ? `${bare}%${name}` : bare);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// ::0.0.0.0 is :: itself.
|
|
81
|
+
for (const a of v4)
|
|
82
|
+
out.push(`::ffff:${a}`, ...(a === "0.0.0.0" ? ["0:0:0:0:0:ffff:0:0"] : [`::${a}`]));
|
|
83
|
+
return [...new Set(out)];
|
|
84
|
+
}
|
|
85
|
+
/** Thrown when relay will not launch a confined harness; `check` names the probe or check that failed. */
|
|
86
|
+
export class ConfinementRefused extends Error {
|
|
87
|
+
check;
|
|
88
|
+
report;
|
|
89
|
+
constructor(check, message, report) {
|
|
90
|
+
super(message);
|
|
91
|
+
this.check = check;
|
|
92
|
+
this.report = report;
|
|
93
|
+
this.name = "ConfinementRefused";
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const allowed = (g) => g === "allowed";
|
|
97
|
+
/**
|
|
98
|
+
* The sandbox's own refusal: EPERM. Not EACCES, which ordinary Unix permissions give too; any other
|
|
99
|
+
* failure proves nothing.
|
|
100
|
+
*/
|
|
101
|
+
const sandboxDenied = (g) => g === "EPERM";
|
|
102
|
+
/** A lookup that got no answer, promptly: not a timeout, which proves nothing. Judged together with the DNS channels' own denials. */
|
|
103
|
+
const noAnswer = (g) => g !== "allowed" && g !== "timeout" && g !== "missing" && /^E[A-Z]+$/.test(g);
|
|
104
|
+
/** A Mach lookup the sandbox refused: BOOTSTRAP_NOT_PRIVILEGED (1100), not "unknown service" (1102), which only means absent. */
|
|
105
|
+
const machDenied = (g) => g === "kr 44c";
|
|
106
|
+
/** A Mach lookup that was answered: the bootstrap server returned a port (KERN_SUCCESS), not any error. */
|
|
107
|
+
const machAnswered = (g) => g === "allowed";
|
|
108
|
+
/** An IOKit user client the sandbox refused: kIOReturnNotPermitted (0xe00002e2). */
|
|
109
|
+
const iokitDenied = (g) => g === "kr e00002e2";
|
|
110
|
+
/** A sysctl write the sandbox let reach the kernel: anything but its own EPERM (the kernel may then reject the value, e.g. EINVAL). */
|
|
111
|
+
const notSandboxBlocked = (g) => g !== "EPERM" && /^(allowed|E[A-Z]+)$/.test(g);
|
|
112
|
+
/** LaunchServices refused to open the app: a failed exit with its own error, not just any failure. */
|
|
113
|
+
const launchServicesRefused = (g) => /^exit [1-9]\d*: .*(kLS|LSOpen|-10\d{3}|cannot be opened)/s.test(g) || sandboxDenied(g);
|
|
114
|
+
/**
|
|
115
|
+
* An Apple event that never left the sandbox: osascript could not even find the Finder (-1728),
|
|
116
|
+
* because LaunchServices, which the profile closes, could not be asked; or it could not start. Not
|
|
117
|
+
* any execution error: privacy controls refusing the event (-1743) are not the sandbox.
|
|
118
|
+
*/
|
|
119
|
+
const appleEventRefused = (g) => /^exit [1-9]\d*: .*execution error: Can.t get application "Finder"\. \(-1728\)/s.test(g) || sandboxDenied(g);
|
|
120
|
+
/** launchd refused the job: a failed exit (launchd says nothing more to a sandboxed caller); relay also checks afterwards that no job was made. */
|
|
121
|
+
const launchdRefused = (g) => /^exit [1-9]\d*(:|$)/.test(g) || sandboxDenied(g);
|
|
122
|
+
/** A connect to a listening port the sandbox permits: connected, or refused by the peer, never by the sandbox. */
|
|
123
|
+
const reachable = (g) => g === "allowed" || g === "ECONNREFUSED";
|
|
124
|
+
/** An app bundle whose only act, if LaunchServices ever started it, would be to leave a marker. */
|
|
125
|
+
function probeApp(dir, marker) {
|
|
126
|
+
const app = path.join(dir, "RelayProbe.app");
|
|
127
|
+
fs.mkdirSync(path.join(app, "Contents", "MacOS"), { recursive: true });
|
|
128
|
+
fs.writeFileSync(path.join(app, "Contents", "MacOS", "probe"), `#!/bin/sh\n: > '${marker.replace(/'/g, `'\\''`)}'\n`, { mode: 0o755 });
|
|
129
|
+
fs.writeFileSync(path.join(app, "Contents", "Info.plist"), `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` +
|
|
130
|
+
`<plist version="1.0"><dict><key>CFBundleExecutable</key><string>probe</string><key>CFBundleIdentifier</key><string>me.jbkjr.relay.probe</string>` +
|
|
131
|
+
`<key>CFBundlePackageType</key><string>APPL</string><key>LSBackgroundOnly</key><true/></dict></plist>\n`);
|
|
132
|
+
return app;
|
|
133
|
+
}
|
|
134
|
+
/** How long the decoy semaphores' helper may take to make them, and then to remove them, before it is killed. */
|
|
135
|
+
const SEMAPHORE_TIMEOUT_MS = 5000;
|
|
136
|
+
/**
|
|
137
|
+
* Removes named POSIX semaphores outside the sandbox through osascript's JavaScript bridge (Node has
|
|
138
|
+
* none), one process for each: only names relay made. Failures are swallowed: they are probe
|
|
139
|
+
* targets, not the boundary.
|
|
140
|
+
*/
|
|
141
|
+
function unlinkSemaphores(names) {
|
|
142
|
+
for (const name of names) {
|
|
143
|
+
try {
|
|
144
|
+
execFileSync("/usr/bin/osascript", ["-l", "JavaScript", "-e", `ObjC.bindFunction('sem_unlink',['int',['char *']]); function run(a){$.sem_unlink(a[0]);return '';}`, name], { stdio: "ignore", timeout: SEMAPHORE_TIMEOUT_MS });
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// Gone already, or never made.
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The probes' decoy named POSIX semaphores, made outside the sandbox so the confined canary can be
|
|
153
|
+
* shown it cannot touch another process's semaphore, and removed once the probes are over. One
|
|
154
|
+
* osascript process (its JavaScript bridge; Node has no POSIX semaphores) does both: it creates each
|
|
155
|
+
* name exclusively, with O_CREAT | O_EXCL (0x0200 | 0x0800), and closes its own handle at once, so
|
|
156
|
+
* that during the canary the names exist with nothing holding them open; it says on its stdout
|
|
157
|
+
* which names it made, and unlinks those, and only those, when relay closes its stdin (or relay is
|
|
158
|
+
* gone). A name that already exists is another program's semaphore: it is neither probed nor
|
|
159
|
+
* removed. Started before the other targets are set up (by prepareLaunch, before its hard-link
|
|
160
|
+
* walk); the canary waits for `made`. A helper that fails, or takes longer than SEMAPHORE_TIMEOUT_MS,
|
|
161
|
+
* is killed: a decoy relay did not make fails its probes loudly, which refuses the launch, and
|
|
162
|
+
* `remove` then unlinks one by one the names the helper said it made. One it never said it made is
|
|
163
|
+
* left: its name is random, and leaving a decoy behind is better than removing a semaphore relay
|
|
164
|
+
* may not own. Whoever starts them removes them, whatever happens.
|
|
165
|
+
*/
|
|
166
|
+
export function startDecoySemaphores() {
|
|
167
|
+
const id = crypto.randomBytes(6).toString("hex");
|
|
168
|
+
const names = { outside: `/rp${id}`, mp: `/mp-rp${id}` };
|
|
169
|
+
return { names, ...decoySemaphores([names.outside, names.mp]) };
|
|
170
|
+
}
|
|
171
|
+
function decoySemaphores(names) {
|
|
172
|
+
// __sem_open, the non-variadic trap behind sem_open: sem_open itself is variadic, and on arm64 a
|
|
173
|
+
// fixed-argument call would leave its mode and value to whatever is on the stack (a decoy nobody,
|
|
174
|
+
// even its owner, could open). The bridge hands a long back as a string, hence Number(). The
|
|
175
|
+
// helper says which it made as one digit per name, in order.
|
|
176
|
+
const script = `ObjC.bindFunction('__sem_open',['long',['char *','int','int','int']]);
|
|
177
|
+
ObjC.bindFunction('sem_close',['int',['long']]);
|
|
178
|
+
ObjC.bindFunction('sem_unlink',['int',['char *']]);
|
|
179
|
+
function run(a) {
|
|
180
|
+
var mine = a.map(function (n) { var s = $.__sem_open(n, 2560, 384, 1); if (Number(s) === -1) return false; $.sem_close(s); return true; });
|
|
181
|
+
$.NSFileHandle.fileHandleWithStandardOutput.writeData($('made ' + mine.map(function (m) { return m ? '1' : '0'; }).join('') + '\\n').dataUsingEncoding($.NSUTF8StringEncoding));
|
|
182
|
+
$.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;
|
|
183
|
+
a.forEach(function (n, i) { if (mine[i]) $.sem_unlink(n); });
|
|
184
|
+
return '';
|
|
185
|
+
}`;
|
|
186
|
+
let exited;
|
|
187
|
+
let child = null;
|
|
188
|
+
const gone = new Promise((resolve) => {
|
|
189
|
+
try {
|
|
190
|
+
child = spawn("/usr/bin/osascript", ["-l", "JavaScript", "-e", script, ...names], { stdio: ["pipe", "pipe", "ignore"] });
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
exited = null;
|
|
194
|
+
return resolve();
|
|
195
|
+
}
|
|
196
|
+
child.stdin.on("error", () => { });
|
|
197
|
+
child.once("error", () => ((exited ??= null), resolve()));
|
|
198
|
+
child.once("close", (code) => ((exited ??= code), resolve()));
|
|
199
|
+
});
|
|
200
|
+
const kill = () => {
|
|
201
|
+
try {
|
|
202
|
+
child?.kill("SIGKILL");
|
|
203
|
+
}
|
|
204
|
+
catch { }
|
|
205
|
+
};
|
|
206
|
+
/** The names the helper said it made, once it has said: until then, and if it never does, none. */
|
|
207
|
+
let mine = null;
|
|
208
|
+
const made = new Promise((resolve) => {
|
|
209
|
+
if (!child)
|
|
210
|
+
return resolve(new Set());
|
|
211
|
+
let out = "";
|
|
212
|
+
const timer = setTimeout(() => (kill(), resolve(mine ?? new Set())), SEMAPHORE_TIMEOUT_MS);
|
|
213
|
+
child.stdout.on("data", (d) => {
|
|
214
|
+
out += d;
|
|
215
|
+
const said = /^made ([01]*)\n/.exec(out);
|
|
216
|
+
if (!said || mine)
|
|
217
|
+
return;
|
|
218
|
+
mine = new Set(names.filter((_, i) => said[1][i] === "1"));
|
|
219
|
+
clearTimeout(timer);
|
|
220
|
+
resolve(mine);
|
|
221
|
+
});
|
|
222
|
+
void gone.then(() => (clearTimeout(timer), resolve(mine ?? new Set())));
|
|
223
|
+
});
|
|
224
|
+
let removed;
|
|
225
|
+
const remove = async () => {
|
|
226
|
+
if (exited === undefined) {
|
|
227
|
+
child.stdin.end();
|
|
228
|
+
let timer;
|
|
229
|
+
await Promise.race([gone, new Promise((r) => (timer = setTimeout(() => (kill(), r()), SEMAPHORE_TIMEOUT_MS)))]);
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
await gone;
|
|
232
|
+
}
|
|
233
|
+
// Only a helper that was asked to remove them and then ended cleanly has: otherwise each name it
|
|
234
|
+
// said it made is removed on its own.
|
|
235
|
+
if (exited !== 0 && mine)
|
|
236
|
+
unlinkSemaphores([...mine]);
|
|
237
|
+
};
|
|
238
|
+
return { made, remove: () => (removed ??= remove()) };
|
|
239
|
+
}
|
|
240
|
+
function listen(server, at, host = "127.0.0.1") {
|
|
241
|
+
return new Promise((resolve, reject) => {
|
|
242
|
+
server.once("error", reject);
|
|
243
|
+
const done = () => (server.off("error", reject), resolve());
|
|
244
|
+
if (typeof at === "string")
|
|
245
|
+
server.listen(at, done);
|
|
246
|
+
else
|
|
247
|
+
server.listen(at, host, done);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* A pseudo-terminal relay makes for itself, through script(1) (every Mac has it): the slave's path,
|
|
252
|
+
* read from `tty` run inside it, so it is never one of the person's own terminals.
|
|
253
|
+
*/
|
|
254
|
+
export function foreignPty() {
|
|
255
|
+
return new Promise((resolve, reject) => {
|
|
256
|
+
const c = spawn("/usr/bin/script", ["-q", "/dev/null", "/bin/sh", "-c", "/usr/bin/tty; exec /bin/sleep 60"], { stdio: ["ignore", "pipe", "pipe"] });
|
|
257
|
+
let out = "";
|
|
258
|
+
let err = "";
|
|
259
|
+
const close = () => {
|
|
260
|
+
try {
|
|
261
|
+
c.kill("SIGKILL");
|
|
262
|
+
}
|
|
263
|
+
catch { }
|
|
264
|
+
};
|
|
265
|
+
const timer = setTimeout(() => (close(), reject(new Error(`script(1) gave no terminal within 5 s: ${err.trim()}`))), 5000);
|
|
266
|
+
c.stdout.on("data", (d) => {
|
|
267
|
+
out += d;
|
|
268
|
+
const m = /\/dev\/ttys[0-9]+/.exec(out);
|
|
269
|
+
if (m) {
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
resolve({ path: m[0], close });
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
c.stderr.on("data", (d) => (err += d));
|
|
275
|
+
c.on("error", (e) => (clearTimeout(timer), reject(e)));
|
|
276
|
+
c.on("exit", () => (clearTimeout(timer), reject(new Error(`script(1) exited before giving a terminal: ${err.trim()}`))));
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Runs the boundary probes for one launch. `launch` is what the mechanism's `wrap` returned for
|
|
281
|
+
* `policy`; the canary runs through `launch.rewrap`, so it gets the same profile and parameters.
|
|
282
|
+
*/
|
|
283
|
+
export async function probeBoundary(launch, policy,
|
|
284
|
+
/**
|
|
285
|
+
* `wrap`: the same mechanism's wrap, for a decoy of a login store under the same rules (required with one).
|
|
286
|
+
* `semaphores`: the decoy semaphores, when the caller has started them already; removed here, whatever happens.
|
|
287
|
+
*/
|
|
288
|
+
opts = {}) {
|
|
289
|
+
const started = performance.now();
|
|
290
|
+
const tag = `.relay-probe-${crypto.randomBytes(6).toString("hex")}`;
|
|
291
|
+
const servers = [];
|
|
292
|
+
const closers = [];
|
|
293
|
+
const created = [];
|
|
294
|
+
/** Config-probe paths created exclusively with the tag as marker: removed only when still that marker-bearing file (review C1/X1). */
|
|
295
|
+
const configMarkers = [];
|
|
296
|
+
/** Renames the probes tried, [from, to]: put back from outside should one have got through. */
|
|
297
|
+
const moved = [];
|
|
298
|
+
const label = `me.jbkjr.relay.probe.${tag.slice(13)}`;
|
|
299
|
+
const results = [];
|
|
300
|
+
let sems = opts.semaphores;
|
|
301
|
+
/** The probes' scratch directory, once it is made: removed with everything in it, whatever happens. */
|
|
302
|
+
let scratchDir;
|
|
303
|
+
// Everything from here is inside the clean-up below, so that semaphores the caller handed over
|
|
304
|
+
// are removed even when the probes cannot be set up (a full disk, a policy relay cannot place).
|
|
305
|
+
try {
|
|
306
|
+
let bounds;
|
|
307
|
+
try {
|
|
308
|
+
bounds = boundaryPaths(policy);
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
throw new ConfinementRefused("boundary", err.message);
|
|
312
|
+
}
|
|
313
|
+
const { worktree, tmpDir, writable } = bounds;
|
|
314
|
+
const insideWritable = (p) => writable.some((w) => within(p, w));
|
|
315
|
+
const denied = bounds.denied;
|
|
316
|
+
// Targets outside the sandbox: a directory with a file to link to, a Unix socket, a TCP port, an app.
|
|
317
|
+
scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), "relay-probe-"));
|
|
318
|
+
const scratch = (scratchDir = fs.realpathSync(scratchDir));
|
|
319
|
+
if (insideWritable(scratch)) {
|
|
320
|
+
throw new ConfinementRefused("outside-target", `relay cannot probe this turn's confinement: its outside target ${scratch} lies inside a writable directory (is tmpDir the shared temporary directory?)`);
|
|
321
|
+
}
|
|
322
|
+
// The decoy semaphores (below) are made while the other targets are set up, if the caller has not begun already.
|
|
323
|
+
sems ??= startDecoySemaphores();
|
|
324
|
+
const { outside: semName, mp: mpName } = sems.names;
|
|
325
|
+
const victim = path.join(scratch, "victim");
|
|
326
|
+
fs.writeFileSync(victim, "outside\n");
|
|
327
|
+
const unixPath = path.join(scratch, "s.sock");
|
|
328
|
+
const unix = net.createServer((s) => s.destroy());
|
|
329
|
+
const tcp = net.createServer((s) => s.destroy());
|
|
330
|
+
servers.push(unix, tcp);
|
|
331
|
+
await listen(unix, unixPath);
|
|
332
|
+
await listen(tcp, 0);
|
|
333
|
+
// IPv6 loopback, where the machine has it (every Mac's lo0 does).
|
|
334
|
+
const tcp6 = net.createServer((s) => s.destroy());
|
|
335
|
+
let v6;
|
|
336
|
+
try {
|
|
337
|
+
await listen(tcp6, 0, "::1");
|
|
338
|
+
servers.push(tcp6);
|
|
339
|
+
v6 = tcp6.address().port;
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
if (err.code !== "EADDRNOTAVAIL")
|
|
343
|
+
throw err;
|
|
344
|
+
v6 = "this machine has no IPv6 loopback address";
|
|
345
|
+
}
|
|
346
|
+
const app = probeApp(scratch, path.join(scratch, "app-ran"));
|
|
347
|
+
// A process of relay's own outside the sandbox, to signal and inspect: a decoy with an empty
|
|
348
|
+
// environment, so that even an inspection that got through would find nothing of the person's.
|
|
349
|
+
const outsider = spawn("/bin/sleep", ["60"], { stdio: "ignore", env: {} });
|
|
350
|
+
closers.push(() => outsider.kill("SIGKILL"));
|
|
351
|
+
if (!outsider.pid)
|
|
352
|
+
throw new ConfinementRefused("signal-outside", "relay could not start a process to probe signals with");
|
|
353
|
+
let pty;
|
|
354
|
+
try {
|
|
355
|
+
pty = await foreignPty();
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
throw new ConfinementRefused("foreign-pty", `relay could not make a terminal to probe this turn's confinement with (${err.message}), so it does not launch the harness`);
|
|
359
|
+
}
|
|
360
|
+
closers.push(pty.close);
|
|
361
|
+
const checks = {};
|
|
362
|
+
const allow = (name, step, judge = allowed) => (checks[name] = { step, expect: "allow", judge });
|
|
363
|
+
const deny = (name, step, judge = sandboxDenied) => (checks[name] = { step, expect: "deny", judge });
|
|
364
|
+
const skip = (name, expect, why) => (checks[name] = { skip: why, expect });
|
|
365
|
+
// Stage 2's network checks, run in a second canary under the same rules with decoy ports and, on a
|
|
366
|
+
// read turn, a decoy cwd (probe-stage2.ts).
|
|
367
|
+
let stage2Decoy;
|
|
368
|
+
const decoy = (decoyPolicy) => {
|
|
369
|
+
if (stage2Decoy)
|
|
370
|
+
throw new Error("the stage-2 decoy was planned twice");
|
|
371
|
+
const c = {};
|
|
372
|
+
stage2Decoy = { policy: decoyPolicy, checks: c };
|
|
373
|
+
return {
|
|
374
|
+
allow: (name, step, judge = allowed) => void (c[name] = { step, expect: "allow", judge }),
|
|
375
|
+
deny: (name, step, judge = sandboxDenied) => void (c[name] = { step, expect: "deny", judge }),
|
|
376
|
+
};
|
|
377
|
+
};
|
|
378
|
+
// Whether relay created this turn's worktree (a write job): then it owns the worktree and its
|
|
379
|
+
// neighbourhood (its parent is relay's worktrees directory, its siblings other jobs' worktrees).
|
|
380
|
+
const relayOwnsWorktree = policy.worktreePin !== undefined;
|
|
381
|
+
allow("write-tmpdir", { kind: "write", path: path.join(tmpDir, tag) });
|
|
382
|
+
created.push(path.join(tmpDir, tag));
|
|
383
|
+
allow("read-worktree", { kind: "readdir", path: worktree });
|
|
384
|
+
if (policy.worktreeWritable) {
|
|
385
|
+
allow("write-worktree", { kind: "write", path: path.join(worktree, tag) });
|
|
386
|
+
created.push(path.join(worktree, tag));
|
|
387
|
+
}
|
|
388
|
+
else if (relayOwnsWorktree) {
|
|
389
|
+
// A read turn on a worktree relay created: safe to write a tag into relay's own directory.
|
|
390
|
+
deny("write-worktree", { kind: "write", path: path.join(worktree, tag) });
|
|
391
|
+
created.push(path.join(worktree, tag));
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
// A read turn in the person's own checkout: relay does not aim a write at it; a generator test
|
|
395
|
+
// covers that a read turn's worktree is not writable (review C6/X4).
|
|
396
|
+
skip("write-worktree", "deny", "the worktree is the person's own checkout; a generator test covers that a read turn writes nothing there");
|
|
397
|
+
}
|
|
398
|
+
deny("write-outside", { kind: "write", path: path.join(scratch, "written") });
|
|
399
|
+
// For a read turn the worktree is the person's own checkout, and its
|
|
400
|
+
// parent, siblings and .git are the person's; relay does not aim a write at them, even one that
|
|
401
|
+
// would only land on a sandbox bug. The rules for them are covered by generator tests against
|
|
402
|
+
// scratch copies (test/confine.test.ts), as decided for C3.
|
|
403
|
+
const beside = path.dirname(worktree);
|
|
404
|
+
if (!relayOwnsWorktree)
|
|
405
|
+
skip("write-beside-worktree", "deny", "the worktree is the person's own checkout; a generator test covers that its parent is not writable");
|
|
406
|
+
else if (insideWritable(beside))
|
|
407
|
+
skip("write-beside-worktree", "deny", "the worktree's parent is writable by grant");
|
|
408
|
+
else {
|
|
409
|
+
deny("write-beside-worktree", { kind: "write", path: path.join(beside, tag) });
|
|
410
|
+
created.push(path.join(beside, tag));
|
|
411
|
+
}
|
|
412
|
+
// Discovery that fails refuses the turn; only a genuine absence skips a probe.
|
|
413
|
+
const sibling = !relayOwnsWorktree ? undefined : fs.readdirSync(beside, { withFileTypes: true })
|
|
414
|
+
.filter((d) => d.isDirectory())
|
|
415
|
+
.map((d) => path.join(beside, d.name))
|
|
416
|
+
.find((p) => p !== worktree && !insideWritable(p) && !denied.some((d) => within(p, d)));
|
|
417
|
+
if (sibling) {
|
|
418
|
+
deny("write-sibling-worktree", { kind: "write", path: path.join(sibling, tag) });
|
|
419
|
+
created.push(path.join(sibling, tag));
|
|
420
|
+
}
|
|
421
|
+
else
|
|
422
|
+
skip("write-sibling-worktree", "deny", relayOwnsWorktree ? "no sibling directory beside the worktree" : "the worktree is the person's own checkout; a generator test covers that a sibling is not writable");
|
|
423
|
+
const { gitPointer, gitDir, commonDir } = bounds;
|
|
424
|
+
if (!relayOwnsWorktree) {
|
|
425
|
+
// A read turn's checkout .git is the person's: not live-probed (the whole checkout is unwritable
|
|
426
|
+
// on a read turn anyway); the deny rules for it are covered by generator tests.
|
|
427
|
+
skip("write-git-pointer", "deny", "the worktree is the person's own checkout; the git deny rules are covered by generator tests");
|
|
428
|
+
}
|
|
429
|
+
else {
|
|
430
|
+
const pointer = fs.lstatSync(gitPointer, { throwIfNoEntry: false });
|
|
431
|
+
if (pointer?.isDirectory()) {
|
|
432
|
+
// A checkout's own .git directory (a read turn in the repository itself): a new file in it.
|
|
433
|
+
deny("write-git-pointer", { kind: "write", path: path.join(gitPointer, tag) });
|
|
434
|
+
created.push(path.join(gitPointer, tag));
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
if (!pointer)
|
|
438
|
+
created.push(gitPointer);
|
|
439
|
+
deny("write-git-pointer", { kind: "open-append", path: gitPointer });
|
|
440
|
+
}
|
|
441
|
+
// A .git below the repository's (the worktree's own, in a subdirectory), which would hide it from discovery.
|
|
442
|
+
bounds.nestedGitPointers.forEach((p, i) => {
|
|
443
|
+
if (fs.lstatSync(p, { throwIfNoEntry: false }))
|
|
444
|
+
throw new Error(`${p} appeared while relay was probing`);
|
|
445
|
+
deny(`write-nested-git-pointer-${i}`, { kind: "write", path: p });
|
|
446
|
+
created.push(p);
|
|
447
|
+
});
|
|
448
|
+
for (const [name, d] of [["write-git-dir", gitDir], ["write-git-common-dir", commonDir]]) {
|
|
449
|
+
if (!d || d === gitPointer || (name === "write-git-common-dir" && d === gitDir))
|
|
450
|
+
continue;
|
|
451
|
+
deny(name, { kind: "write", path: path.join(d, tag) });
|
|
452
|
+
created.push(path.join(d, tag));
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
denied.forEach((d, i) => {
|
|
456
|
+
const what = i === 0 ? "control-dir" : `denied-${i}`;
|
|
457
|
+
if (!fs.lstatSync(d, { throwIfNoEntry: false }))
|
|
458
|
+
return skip(`read-${what}`, "deny", `${d} does not exist`);
|
|
459
|
+
if (!fs.statSync(d).isDirectory()) {
|
|
460
|
+
// DM8 adds individual config/install files. Open existing files without truncating or
|
|
461
|
+
// writing any bytes: even a broken policy must never change the person's config.
|
|
462
|
+
deny(`read-${what}`, { kind: "open", path: d, flags: "r" });
|
|
463
|
+
deny(`exists-${what}`, { kind: "exists", path: d });
|
|
464
|
+
deny(`write-${what}`, { kind: "open", path: d, flags: "w" });
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
deny(`read-${what}`, { kind: "readdir", path: d });
|
|
468
|
+
// Whether a name exists there (access), which Seatbelt checks apart from reads: relay's control
|
|
469
|
+
// directory holds relay.db, the name probed (rule precedence, seatbelt.ts top).
|
|
470
|
+
const known = fs.readdirSync(d).find((n) => n !== "." && n !== "..");
|
|
471
|
+
if (known)
|
|
472
|
+
deny(`exists-${what}`, { kind: "exists", path: path.join(d, known) });
|
|
473
|
+
else
|
|
474
|
+
skip(`exists-${what}`, "deny", `${d} is empty`);
|
|
475
|
+
// These include the person's API key directory. Never aim a creating operation at
|
|
476
|
+
// it, even when a broken sandbox would be the only way the write could land.
|
|
477
|
+
// Write denials are exercised on the decoy below and by exact-rule generator tests.
|
|
478
|
+
// Relay's own control and socket directories remain safe live write targets.
|
|
479
|
+
if (d === canonical(relayHome()) || d === canonical(relaySocketsDir())) {
|
|
480
|
+
deny(`write-${what}`, { kind: "write", path: path.join(d, tag) });
|
|
481
|
+
created.push(path.join(d, tag));
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
// State that outlives the turn — the real home, the real login store beside its token files, the
|
|
485
|
+
// harness binary — is the person's own, so relay aims no write at it, not even one that would
|
|
486
|
+
// land only on a sandbox bug. A decoy directory of relay's own, outside the writable roots, is
|
|
487
|
+
// the live stand-in that the sandbox denies such a write; the rules for the real paths (home not
|
|
488
|
+
// writable, login store not writable though its token file is, harness binary's directory not
|
|
489
|
+
// writable) are generator tests against scratch copies (test/confine.test.ts, test/state.test.ts).
|
|
490
|
+
const decoyOutside = path.join(fs.mkdtempSync(path.join(scratch, "decoy-")), "home-or-store-or-bin");
|
|
491
|
+
fs.mkdirSync(decoyOutside);
|
|
492
|
+
deny("write-decoy-outside", { kind: "write", path: path.join(decoyOutside, tag) });
|
|
493
|
+
// Relay-owned persistent state: its writable subdirectories work; the rest of it, the files relay
|
|
494
|
+
// wrote there (settings) included, cannot be changed or added to.
|
|
495
|
+
const persistent = policy.state?.persistent ? persistentState(policy.state.persistent) : null;
|
|
496
|
+
if (persistent) {
|
|
497
|
+
persistent.writable.forEach((d, i) => {
|
|
498
|
+
allow(`write-persistent-${i}`, { kind: "write", path: path.join(d, tag) });
|
|
499
|
+
created.push(path.join(d, tag));
|
|
500
|
+
});
|
|
501
|
+
deny("write-persistent-root", { kind: "write", path: path.join(persistent.root, tag) });
|
|
502
|
+
created.push(path.join(persistent.root, tag));
|
|
503
|
+
for (const e of fs.readdirSync(persistent.root, { withFileTypes: true })) {
|
|
504
|
+
const f = path.join(persistent.root, e.name);
|
|
505
|
+
// Regular files only: never through a link (it may lead to the person's own files), never an executable.
|
|
506
|
+
if (!e.isFile() || fs.statSync(f).mode & 0o111)
|
|
507
|
+
continue;
|
|
508
|
+
deny(`modify-persistent:${e.name}`, { kind: "open-append", path: f });
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
// The harness binary's directory is the person's install location; that it is not writable is a
|
|
512
|
+
// generator test (it is not among the writable roots), not a live write beside their binary.
|
|
513
|
+
// Harness and tool configuration an agent could plant at the top of a writable root. Only the
|
|
514
|
+
// worktree's is live-probed (the grants are the person's, so their config names are covered by
|
|
515
|
+
// generator tests, not live writes — review C1/X1). A name already there (a project's own
|
|
516
|
+
// .vscode, .mcp.json, a .claude/ directory) is never written or deleted: it is checked
|
|
517
|
+
// non-destructively (open for writing without truncating a file; an exclusive marker inside a
|
|
518
|
+
// directory). A name that is absent is created exclusively with a marker, so nothing is clobbered,
|
|
519
|
+
// and only a marker-bearing file the probe made is removed. The marker is the probe's tag.
|
|
520
|
+
const marker = `${tag}\n`;
|
|
521
|
+
const worktreeConfig = bounds.configDenied.filter((c) => within(c, worktree));
|
|
522
|
+
worktreeConfig.forEach((c, i) => {
|
|
523
|
+
const st = fs.lstatSync(c, { throwIfNoEntry: false });
|
|
524
|
+
if (!st) {
|
|
525
|
+
deny(`write-config-${i}`, { kind: "write-excl", path: c, marker });
|
|
526
|
+
configMarkers.push(c);
|
|
527
|
+
}
|
|
528
|
+
else if (st.isDirectory()) {
|
|
529
|
+
const inside = path.join(c, `${tag}-cfg`);
|
|
530
|
+
deny(`write-config-${i}`, { kind: "write-excl", path: inside, marker });
|
|
531
|
+
configMarkers.push(inside);
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
// A file already there: opened for writing without truncating it, so its content is untouched whether the open is refused or (on a bug) allowed.
|
|
535
|
+
deny(`write-config-${i}`, { kind: "open", path: c, flags: "w" });
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
// The positive control: a lookalike name not on the list, created exclusively, must be writable.
|
|
539
|
+
if (worktreeConfig.length) {
|
|
540
|
+
const lookalike = path.join(worktree, ".mcp.jsonx");
|
|
541
|
+
if (!fs.lstatSync(lookalike, { throwIfNoEntry: false })) {
|
|
542
|
+
allow("write-config-lookalike", { kind: "write-excl", path: lookalike, marker });
|
|
543
|
+
configMarkers.push(lookalike);
|
|
544
|
+
}
|
|
545
|
+
else
|
|
546
|
+
skip("write-config-lookalike", "allow", "a file of that name is already there");
|
|
547
|
+
}
|
|
548
|
+
deny("hardlink-to-outside", { kind: "hardlink", from: victim, to: path.join(tmpDir, `${tag}-hl`) });
|
|
549
|
+
created.push(path.join(tmpDir, `${tag}-hl`));
|
|
550
|
+
deny("symlink-escape", { kind: "symlink-write", target: scratch, link: path.join(tmpDir, `${tag}-ln`), file: path.join(tmpDir, `${tag}-ln`, "through-link") });
|
|
551
|
+
created.push(path.join(tmpDir, `${tag}-ln`));
|
|
552
|
+
// fcntl commands that change a file through a descriptor opened read-only (F_MAKECOMPRESSED,
|
|
553
|
+
// F_TRANSFEREXTENTS): tried on a decoy of relay's own outside the writable directories.
|
|
554
|
+
const fcntlDecoy = path.join(scratch, "fcntl-decoy");
|
|
555
|
+
fs.writeFileSync(fcntlDecoy, "decoy\n");
|
|
556
|
+
deny("fcntl-makecompressed", { kind: "native", check: { op: "fcntl", path: fcntlDecoy, cmd: F_MAKECOMPRESSED } });
|
|
557
|
+
deny("fcntl-transferextents", { kind: "native", check: { op: "fcntl", path: fcntlDecoy, cmd: F_TRANSFEREXTENTS } });
|
|
558
|
+
// Moving a root or a protected path's ancestor away (to leave a link, or to edit what its rule
|
|
559
|
+
// protects and move it back): a rename into another of relay's own writable directories, which
|
|
560
|
+
// the canary undoes at once if it got through, and relay from outside if the canary did not.
|
|
561
|
+
// Only directories relay made and owns are ever renamed: the worktree it created (pinned), the
|
|
562
|
+
// temp dir, the state directories and relay-owned state. Never the person's granted directories
|
|
563
|
+
// or anything in them: the profile's generator and the pre-turn checks cover those
|
|
564
|
+
// (test/confine.test.ts), not a probe that would move the person's files if the sandbox failed.
|
|
565
|
+
const relayWorktree = policy.worktreeWritable && policy.worktreePin !== undefined;
|
|
566
|
+
const stateRoots = [...(policy.stateDirs ?? []).map((p) => canonical(p)), ...(bounds.persistent?.writable ?? [])];
|
|
567
|
+
const owned = [tmpDir, ...stateRoots, ...(relayWorktree ? [worktree] : [])];
|
|
568
|
+
const renameProbe = (name, from) => {
|
|
569
|
+
const into = owned.find((w) => !within(w, from));
|
|
570
|
+
if (!into)
|
|
571
|
+
return skip(name, "deny", "no other directory of relay's own to move it into");
|
|
572
|
+
const to = path.join(into, `${tag}-mv-${moved.length}`);
|
|
573
|
+
moved.push([from, to]);
|
|
574
|
+
deny(name, { kind: "rename", from, to });
|
|
575
|
+
};
|
|
576
|
+
if (relayWorktree)
|
|
577
|
+
renameProbe("rename-worktree-root", worktree);
|
|
578
|
+
else
|
|
579
|
+
skip("rename-worktree-root", "deny", policy.worktreeWritable ? "the worktree is not one relay created (no pin), so relay does not move it" : "the worktree is not writable this turn (write-worktree shows it)");
|
|
580
|
+
renameProbe("rename-tmpdir-root", tmpDir);
|
|
581
|
+
stateRoots.forEach((d, i) => renameProbe(`rename-state-root-${i}`, d));
|
|
582
|
+
const ancestors = bounds.fixed.filter((f) => !writable.includes(f) && f !== worktree && owned.some((o) => within(f, o)) && !bounds.hardDenied.some((d) => within(f, d)));
|
|
583
|
+
if (!ancestors.length)
|
|
584
|
+
skip("move-protected-ancestor", "deny", "no protected path has an ancestor inside relay's own writable directories but the roots themselves");
|
|
585
|
+
ancestors.forEach((a, i) => renameProbe(`move-protected-ancestor-${i}`, a));
|
|
586
|
+
const tcpPort = tcp.address().port;
|
|
587
|
+
// Stage 2 (WP-B) allows loopback but its denied ports, listening on its block, and worktree sockets
|
|
588
|
+
// on write turns: its own plan replaces the checks below that it reverses (review X4).
|
|
589
|
+
const stage2 = policy.network.mode === "stage2";
|
|
590
|
+
if (policy.network.mode === "stage2")
|
|
591
|
+
await planStage2Network({ allow, deny, skip, created, closers, servers, decoy }, { ...policy, network: policy.network }, { tag, worktree, tmpDir, scratch });
|
|
592
|
+
if (!stage2) {
|
|
593
|
+
deny("tcp-loopback", { kind: "tcp", host: "127.0.0.1", port: tcpPort, timeoutMs: STEP_TIMEOUT_MS });
|
|
594
|
+
if (typeof v6 === "number")
|
|
595
|
+
deny("tcp-loopback-v6", { kind: "tcp", host: "::1", port: v6, timeoutMs: STEP_TIMEOUT_MS });
|
|
596
|
+
else
|
|
597
|
+
skip("tcp-loopback-v6", "deny", v6);
|
|
598
|
+
// Loopback by its other names: lo0's IPv6 link-local address, and any further address configured
|
|
599
|
+
// on lo0, refused in both modes; and, with the network off, any other 127/8 address (127.0.0.2).
|
|
600
|
+
deny("tcp-loopback-link-local", { kind: "tcp", host: "fe80::1%lo0", port: typeof v6 === "number" ? v6 : tcpPort, timeoutMs: STEP_TIMEOUT_MS });
|
|
601
|
+
// Every other address of this Mac's own, IPv4-mapped and -compatible spellings included (review
|
|
602
|
+
// R1: ::ffff:0.0.0.0 and ::ffff:<a LAN address> got past the network-on rule through 1.0.5),
|
|
603
|
+
// refused in both modes. lo0 aliases are probed as such, next.
|
|
604
|
+
const probedElsewhere = new Set(["127.0.0.1", "::1", "fe80::1%lo0", ...loopbackAliases()]);
|
|
605
|
+
for (const host of localAddressSpellings())
|
|
606
|
+
if (!probedElsewhere.has(host))
|
|
607
|
+
deny(`tcp-local@${host}`, { kind: "tcp", host, port: tcpPort, timeoutMs: STEP_TIMEOUT_MS });
|
|
608
|
+
loopbackAliases().forEach((a, i) => deny(`tcp-loopback-alias-${i}`, { kind: "tcp", host: a, port: tcpPort, timeoutMs: STEP_TIMEOUT_MS }));
|
|
609
|
+
}
|
|
610
|
+
if (policy.network.mode === "off-except-proxy")
|
|
611
|
+
deny("tcp-loopback-127-0-0-2", { kind: "tcp", host: "127.0.0.2", port: tcpPort, timeoutMs: STEP_TIMEOUT_MS });
|
|
612
|
+
else
|
|
613
|
+
skip("tcp-loopback-127-0-0-2", "deny", "with the network on, an unconfigured 127/8 address leads nowhere, and configured ones are probed as aliases");
|
|
614
|
+
deny("unix-socket", { kind: "unix", path: unixPath });
|
|
615
|
+
// Unix sockets: the turn may make its own under its temp dir (the positive control), not in another
|
|
616
|
+
// writable directory; and it can neither see nor reach another turn's broker, for which a decoy of
|
|
617
|
+
// relay's own stands in, inside relay's sockets directory. AF_ROUTE sockets are refused outright.
|
|
618
|
+
// A short name: a socket's path may not exceed 103 bytes.
|
|
619
|
+
const sockName = `rp${tag.slice(13, 19)}.sock`;
|
|
620
|
+
const socketProbe = (name, expect, dir) => {
|
|
621
|
+
const at = path.join(dir, sockName);
|
|
622
|
+
// In the worktree, the canary's working directory, the name alone will do, however deep it is.
|
|
623
|
+
const given = dir === worktree ? sockName : at;
|
|
624
|
+
if (Buffer.byteLength(given) > MAX_SOCKET_PATH)
|
|
625
|
+
return skip(name, expect, `${dir} is too deep for a Unix socket path`);
|
|
626
|
+
// Allowed: listened on and connected to. Denied: the listening itself is what must be refused.
|
|
627
|
+
(expect === "allow" ? allow : deny)(name, { kind: "listen-unix", path: given, connect: expect === "allow" });
|
|
628
|
+
created.push(at);
|
|
629
|
+
};
|
|
630
|
+
socketProbe("unix-listen-tmpdir", "allow", tmpDir);
|
|
631
|
+
if (stage2) { /* WP-B: planStage2Network covers worktree sockets by turn kind */ }
|
|
632
|
+
else if (policy.worktreeWritable && !within(worktree, tmpDir))
|
|
633
|
+
socketProbe("unix-listen-worktree", "deny", worktree);
|
|
634
|
+
else
|
|
635
|
+
skip("unix-listen-worktree", "deny", "the worktree is not writable this turn");
|
|
636
|
+
const decoyTurn = fs.realpathSync(fs.mkdtempSync(path.join(ensureRelaySocketsDir(), "relay-probe-")));
|
|
637
|
+
closers.push(() => fs.rmSync(decoyTurn, { recursive: true, force: true }));
|
|
638
|
+
const decoySocket = net.createServer((c) => c.destroy());
|
|
639
|
+
servers.push(decoySocket);
|
|
640
|
+
await listen(decoySocket, path.join(decoyTurn, "relay.sock"));
|
|
641
|
+
deny("relay-socket-other-turn", { kind: "unix", path: path.join(decoyTurn, "relay.sock") });
|
|
642
|
+
deny("read-relay-sockets", { kind: "readdir", path: relaySocketsDir() });
|
|
643
|
+
deny("socket-route", { kind: "native", check: { op: "socket", domain: AF_ROUTE, type: SOCK_RAW, protocol: 0 } });
|
|
644
|
+
// Mach services: an allowed one answers (the positive control, a known-present system service that
|
|
645
|
+
// the allowlist grants — a controlled-allow comparison test shows it is denied once its allow is
|
|
646
|
+
// removed, so the control cannot pass for the wrong reason); the pasteboard and a name of the
|
|
647
|
+
// probe's own, which exists nowhere, are refused by the sandbox: 1100 (kr 44c), where an absent
|
|
648
|
+
// allowed name would give 1102 (kr 44e).
|
|
649
|
+
allow("mach-allowed", { kind: "native", check: { op: "mach", name: "com.apple.system.notification_center" } }, machAnswered);
|
|
650
|
+
deny("mach-pasteboard", { kind: "native", check: { op: "mach", name: "com.apple.pasteboard.1" } }, machDenied);
|
|
651
|
+
deny("mach-unlisted", { kind: "native", check: { op: "mach", name: `${label}.mach` } }, machDenied);
|
|
652
|
+
// The certificate-trust daemon: refused by default, but when a harness takes the downgrade it must
|
|
653
|
+
// answer — a real positive control that the downgrade grants it, not merely that it is not denied.
|
|
654
|
+
if (policy.certificateTrust)
|
|
655
|
+
allow("mach-trustd", { kind: "native", check: { op: "mach", name: "com.apple.trustd" } }, machAnswered);
|
|
656
|
+
else
|
|
657
|
+
deny("mach-trustd", { kind: "native", check: { op: "mach", name: "com.apple.trustd" } }, machDenied);
|
|
658
|
+
// The system log's socket, the one Unix socket the profile names besides the bridge: connected,
|
|
659
|
+
// never written to, so the probe adds nothing to the system log.
|
|
660
|
+
allow("syslog-socket", { kind: "native", check: { op: "unix-dgram-connect", path: SYSLOG_SOCKET } });
|
|
661
|
+
if (!stage2) {
|
|
662
|
+
deny("listen-loopback", { kind: "listen", host: "127.0.0.1" });
|
|
663
|
+
deny("listen-any", { kind: "listen", host: "0.0.0.0" });
|
|
664
|
+
}
|
|
665
|
+
// Another session's terminal, by path (a detached harness has none of its own unless policy.tty).
|
|
666
|
+
deny("foreign-pty-read", { kind: "open", path: pty.path, flags: "r" });
|
|
667
|
+
deny("foreign-pty-write", { kind: "open", path: pty.path, flags: "w" });
|
|
668
|
+
// A pseudo-terminal of the turn's own (a harness running commands in one) does open.
|
|
669
|
+
allow("pty-own", { kind: "native", check: { op: "openpty" } });
|
|
670
|
+
// IOKit: no user client is reachable, the power-domain one (RootDomainUserClient, through
|
|
671
|
+
// IOPMrootDomain) included (hardening 14). Both are refused with kIOReturnNotPermitted, which an
|
|
672
|
+
// absent service (a different return) cannot imitate, so neither can pass for the wrong reason.
|
|
673
|
+
deny("iokit-rootdomain", { kind: "native", check: { op: "iokit-open", serviceClass: "IOPMrootDomain" } }, iokitDenied);
|
|
674
|
+
deny("iokit-foreign", { kind: "native", check: { op: "iokit-open", serviceClass: "IOSurfaceRoot" } }, iokitDenied);
|
|
675
|
+
// sysctl writes: the base allows only kern.grade_cputype (the kernel then rejects the dummy value,
|
|
676
|
+
// which still shows the sandbox let it through); any other sysctl write is refused.
|
|
677
|
+
allow("sysctl-write-allowed", { kind: "native", check: { op: "sysctl-write", name: "kern.grade_cputype", value: "\0\0\0\0" } }, notSandboxBlocked);
|
|
678
|
+
deny("sysctl-write-foreign", { kind: "native", check: { op: "sysctl-write", name: "kern.threadname", value: "relay-probe" } });
|
|
679
|
+
if (policy.bridgeSocket !== undefined)
|
|
680
|
+
allow("bridge-socket", { kind: "unix", path: canonical(policy.bridgeSocket) });
|
|
681
|
+
// The bridge secret's file, where a harness's own tool helper reads it: that one file reads, and
|
|
682
|
+
// nothing else of the broker directory does (its listing), nor does the file open for writing
|
|
683
|
+
// (opened without truncating; nothing is written).
|
|
684
|
+
if (policy.bridgeSecret !== undefined) {
|
|
685
|
+
const secretFile = canonical(policy.bridgeSecret);
|
|
686
|
+
allow("bridge-secret-read", { kind: "open", path: secretFile, flags: "r" });
|
|
687
|
+
deny("bridge-secret-write", { kind: "open", path: secretFile, flags: "w" });
|
|
688
|
+
deny("bridge-dir-list", { kind: "readdir", path: path.dirname(secretFile) });
|
|
689
|
+
}
|
|
690
|
+
if (policy.network.mode === "off-except-proxy") {
|
|
691
|
+
deny("tcp-direct", { kind: "tcp", host: UNROUTABLE, port: 443, timeoutMs: STEP_TIMEOUT_MS });
|
|
692
|
+
deny("tcp-direct-v6", { kind: "tcp", host: UNROUTABLE_V6, port: 443, timeoutMs: STEP_TIMEOUT_MS });
|
|
693
|
+
// DNS: both channels must be refused by the sandbox itself (the resolver's socket, which exists
|
|
694
|
+
// here outside the sandbox, and UDP), and a lookup must come back without an answer, promptly.
|
|
695
|
+
if (!fs.lstatSync(MDNS_SOCKET, { throwIfNoEntry: false })?.isSocket())
|
|
696
|
+
throw new ConfinementRefused("dns", `relay cannot probe DNS: the system resolver's socket ${MDNS_SOCKET} is not there to be refused`);
|
|
697
|
+
deny("dns-resolver-socket", { kind: "unix", path: MDNS_SOCKET });
|
|
698
|
+
deny("dns-udp", { kind: "udp", host: UNROUTABLE, port: 53, timeoutMs: STEP_TIMEOUT_MS });
|
|
699
|
+
deny("dns-lookup", { kind: "dns", name: DNS_NAME, timeoutMs: STEP_TIMEOUT_MS }, noAnswer);
|
|
700
|
+
allow("proxy-port", { kind: "tcp", host: "127.0.0.1", port: policy.network.proxyPort, timeoutMs: STEP_TIMEOUT_MS }, reachable);
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
skip("tcp-direct", "deny", "the network is on for this turn");
|
|
704
|
+
skip("tcp-direct-v6", "deny", "the network is on for this turn");
|
|
705
|
+
skip("dns-resolver-socket", "deny", "the network is on for this turn");
|
|
706
|
+
skip("dns-udp", "deny", "the network is on for this turn");
|
|
707
|
+
skip("dns-lookup", "deny", "the network is on for this turn");
|
|
708
|
+
}
|
|
709
|
+
// Executables: the system's run; one outside the turn's list does not, even a harmless script.
|
|
710
|
+
const script = path.join(scratch, "probe.sh");
|
|
711
|
+
fs.writeFileSync(script, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
|
712
|
+
allow("exec-system", { kind: "exec", command: "/usr/bin/true", args: [], timeoutMs: 5000 });
|
|
713
|
+
deny("exec-outside-list", { kind: "exec", command: script, args: [], timeoutMs: 5000 });
|
|
714
|
+
deny("launchctl-submit", { kind: "exec", command: "/bin/launchctl", args: ["submit", "-l", label, "--", "/usr/bin/true"], timeoutMs: 5000 }, launchdRefused);
|
|
715
|
+
// Apple events: a read-only one to the Finder; refused before it leaves the sandbox.
|
|
716
|
+
deny("apple-events", { kind: "exec", command: "/usr/bin/osascript", args: ["-e", 'tell application "Finder" to count windows'], timeoutMs: 5000 }, appleEventRefused);
|
|
717
|
+
// A named POSIX semaphore relay creates outside the sandbox (decoySemaphores, started above): the
|
|
718
|
+
// confined canary must not open, post or unlink it (hardening 12).
|
|
719
|
+
deny("sem-open-outside", { kind: "native", check: { op: "sem-open", name: semName } });
|
|
720
|
+
deny("sem-post-outside", { kind: "native", check: { op: "sem-post", name: semName } });
|
|
721
|
+
deny("sem-unlink-outside", { kind: "native", check: { op: "sem-unlink", name: semName } });
|
|
722
|
+
// The one namespace the profile opens, /mp- (Python's multiprocessing names its semaphores
|
|
723
|
+
// /mp-<random>): a decoy of relay's own there can be opened from inside. That is the positive
|
|
724
|
+
// control for the deny probes above, and it shows the stated residual: the namespace is
|
|
725
|
+
// machine-wide, so a /mp- semaphore of another process is reachable by its (random) name.
|
|
726
|
+
allow("sem-open-mp-prefix", { kind: "native", check: { op: "sem-open", name: mpName } });
|
|
727
|
+
/** The semaphore probes, each with the decoy it is aimed at. */
|
|
728
|
+
const onDecoy = new Map([["sem-open-outside", semName], ["sem-post-outside", semName], ["sem-unlink-outside", semName], ["sem-open-mp-prefix", mpName]]);
|
|
729
|
+
deny("signal-outside", { kind: "signal", pid: outsider.pid, signal: 0 });
|
|
730
|
+
// Inspecting processes outside the sandbox: the decoy's path, its details and command line and
|
|
731
|
+
// environment (KERN_PROCARGS2), its kinfo_proc, and the list of every process. The turn's own
|
|
732
|
+
// process is the positive control, as is a hardware sysctl.
|
|
733
|
+
deny("proc-pidpath-outside", { kind: "native", check: { op: "pidpath", pid: outsider.pid } });
|
|
734
|
+
deny("proc-pidinfo-outside", { kind: "native", check: { op: "pidinfo", pid: outsider.pid } });
|
|
735
|
+
deny("proc-listpids", { kind: "native", check: { op: "listpids" } });
|
|
736
|
+
deny("sysctl-proc-all", { kind: "native", check: { op: "sysctl-read", name: "kern.proc.all" } });
|
|
737
|
+
deny("sysctl-proc-pid-outside", { kind: "native", check: { op: "sysctl-read", mib: [CTL_KERN, KERN_PROC, KERN_PROC_PID, outsider.pid] } });
|
|
738
|
+
deny("sysctl-procargs-outside", { kind: "native", check: { op: "sysctl-read", mib: [CTL_KERN, KERN_PROCARGS2, outsider.pid] } });
|
|
739
|
+
allow("proc-pidpath-self", { kind: "native", check: { op: "pidpath", pid: SELF } });
|
|
740
|
+
allow("sysctl-read-hw", { kind: "native", check: { op: "sysctl-read", name: "hw.ncpu" } });
|
|
741
|
+
// A read-only System V IPC limit a runtime reads through sysconf (SC_SEM_NSEMS_MAX): allowed, and
|
|
742
|
+
// names no process, unlike kern.proc.* above (review C2).
|
|
743
|
+
allow("sysctl-read-sysv", { kind: "native", check: { op: "sysctl-read", name: "kern.sysv.semmns" } });
|
|
744
|
+
// -W: had LaunchServices started the app, open would return only after it ran (and left its marker).
|
|
745
|
+
deny("open-app", { kind: "exec", command: "/usr/bin/open", args: ["-W", "-g", "-j", "-n", app], timeoutMs: 5000 }, launchServicesRefused);
|
|
746
|
+
// A stop that came while the targets above were being set up: no canary is started (review r_f0fce42b X2).
|
|
747
|
+
const stopped = () => new ConfinementRefused("stopped", "the turn was stopped while relay was probing its sandbox, so it does not launch the harness");
|
|
748
|
+
/** Runs the canary with `plan` under `l`'s confinement; what each step got. */
|
|
749
|
+
const canary = async (l, plan) => {
|
|
750
|
+
const run = l.rewrap(process.execPath, [CANARY, JSON.stringify(plan)]);
|
|
751
|
+
if (opts.signal?.aborted)
|
|
752
|
+
throw stopped();
|
|
753
|
+
const outcome = await new Promise((resolve) => {
|
|
754
|
+
// Detached, as harnesses are launched: a new session with no controlling terminal, and a process
|
|
755
|
+
// group of its own, which a timeout or a stop ends whole: the canary's osascript helper with it
|
|
756
|
+
// (review r_f0fce42b X1).
|
|
757
|
+
const c = spawn(run.command, run.args, { cwd: worktree, env: { ...(opts.env ?? { PATH: "/usr/bin:/bin:/usr/sbin:/sbin" }), ...l.env }, stdio: ["ignore", "pipe", "pipe"], detached: true });
|
|
758
|
+
const killGroup = () => {
|
|
759
|
+
try {
|
|
760
|
+
if (c.pid)
|
|
761
|
+
sendGroupSignal(c.pid, "SIGKILL");
|
|
762
|
+
}
|
|
763
|
+
catch (err) {
|
|
764
|
+
if (!isGroupSignalRefusal(err))
|
|
765
|
+
c.kill("SIGKILL");
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
let stdout = "";
|
|
769
|
+
let stderr = "";
|
|
770
|
+
let timedOut = false;
|
|
771
|
+
const timer = setTimeout(() => ((timedOut = true), killGroup()), CANARY_TIMEOUT_MS);
|
|
772
|
+
// A stop of the turn ends the canary at once; the launch is then refused, and cleaned up below.
|
|
773
|
+
if (opts.signal?.aborted)
|
|
774
|
+
killGroup();
|
|
775
|
+
else
|
|
776
|
+
opts.signal?.addEventListener("abort", killGroup, { once: true });
|
|
777
|
+
c.once("close", () => opts.signal?.removeEventListener("abort", killGroup));
|
|
778
|
+
c.stdout.on("data", (d) => (stdout += d));
|
|
779
|
+
c.stderr.on("data", (d) => (stderr += d));
|
|
780
|
+
c.on("error", (e) => (stderr += String(e)));
|
|
781
|
+
c.on("close", (code) => (clearTimeout(timer), resolve({ code, stdout, stderr, timedOut })));
|
|
782
|
+
});
|
|
783
|
+
if (opts.signal?.aborted)
|
|
784
|
+
throw stopped();
|
|
785
|
+
try {
|
|
786
|
+
if (outcome.timedOut)
|
|
787
|
+
throw new Error(`it did not finish within ${CANARY_TIMEOUT_MS} ms`);
|
|
788
|
+
if (outcome.code !== 0)
|
|
789
|
+
throw new Error(`it exited with ${outcome.code}: ${outcome.stderr.trim().slice(0, 400)}`);
|
|
790
|
+
return JSON.parse(outcome.stdout);
|
|
791
|
+
}
|
|
792
|
+
catch (err) {
|
|
793
|
+
throw new ConfinementRefused("canary", `relay could not run its boundary probes under this turn's confinement, so it will not launch the harness: ${err.message}`);
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
// The decoy semaphores exist (or could not be made) before the canary starts. A probe of one
|
|
797
|
+
// relay did not make is not run: the name may be another program's semaphore, which a probe
|
|
798
|
+
// that got through would post or remove. It fails, which refuses the launch.
|
|
799
|
+
const ours = await sems.made;
|
|
800
|
+
const unmade = new Set([...onDecoy].filter(([, decoy]) => !ours.has(decoy)).map(([n]) => n));
|
|
801
|
+
const plan = Object.fromEntries(Object.entries(checks).flatMap(([n, c]) => ("step" in c && !unmade.has(n) ? [[n, c.step]] : [])));
|
|
802
|
+
const got = await canary(launch, plan);
|
|
803
|
+
for (const n of unmade)
|
|
804
|
+
got[n] = "not run: relay could not make this decoy semaphore (or its name was already taken)";
|
|
805
|
+
// Side effects, checked from outside: no launchd job and no app run, whatever the commands said.
|
|
806
|
+
if (got["launchctl-submit"] !== undefined && launchdListed(label))
|
|
807
|
+
got["launchctl-submit"] = "allowed (launchd has the job)";
|
|
808
|
+
if (got["open-app"] !== undefined && fs.existsSync(path.join(scratch, "app-ran")))
|
|
809
|
+
got["open-app"] = "allowed (the app ran)";
|
|
810
|
+
for (const [name, c] of Object.entries(checks)) {
|
|
811
|
+
if ("skip" in c)
|
|
812
|
+
results.push({ name, expect: c.expect, got: `skipped: ${c.skip}`, ok: true });
|
|
813
|
+
else {
|
|
814
|
+
const g = got[name] ?? "missing";
|
|
815
|
+
results.push({ name, expect: c.expect, target: stepTarget(c.step), got: g, ok: c.judge(g) });
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
// Stage 2's ports and a read turn's cwd: the turn's rules with decoy values (its denied ports and
|
|
819
|
+
// the person's cwd are never aimed at), which must be exactly the turn's rules, as for a login
|
|
820
|
+
// store's decoy below.
|
|
821
|
+
if (stage2Decoy) {
|
|
822
|
+
if (!opts.wrap)
|
|
823
|
+
throw new ConfinementRefused("probe-setup", "relay cannot probe a stage-2 turn's network without aiming its rules at decoys, so it does not launch the harness");
|
|
824
|
+
const decoyLaunch = opts.wrap(stage2Decoy.policy);
|
|
825
|
+
if (decoyLaunch.rules !== launch.rules)
|
|
826
|
+
throw new Error("the stage-2 decoys (ports, and a read turn's cwd) are not under this turn's rules");
|
|
827
|
+
const s2 = stage2Decoy.checks;
|
|
828
|
+
const s2Got = await canary(decoyLaunch, Object.fromEntries(Object.entries(s2).map(([n, c]) => [n, c.step])));
|
|
829
|
+
for (const [name, c] of Object.entries(s2)) {
|
|
830
|
+
const g = s2Got[name] ?? "missing";
|
|
831
|
+
results.push({ name, expect: c.expect, target: stepTarget(c.step), got: g, ok: c.judge(g) });
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
// A login store (TokenStore) is the person's own, so relay aims nothing at it: the same rules,
|
|
835
|
+
// their parameters pointed at a decoy store of relay's own laid out the same, get the store's
|
|
836
|
+
// probes (docs/design-token-store.md). The refresh itself is the positive control.
|
|
837
|
+
if (bounds.store) {
|
|
838
|
+
const real = bounds.store;
|
|
839
|
+
if (!opts.wrap)
|
|
840
|
+
throw new ConfinementRefused("probe-setup", `relay cannot probe ${real.name} without aiming its rules at a decoy, so it does not launch the harness`);
|
|
841
|
+
const decoy = path.join(scratch, "decoy-store");
|
|
842
|
+
fs.mkdirSync(decoy, { mode: 0o700 });
|
|
843
|
+
const named = [...real.files, ...real.locks].map((f) => path.basename(f));
|
|
844
|
+
const plain = (n) => !real.tempName.test(n) && !named.includes(n);
|
|
845
|
+
for (const f of real.files)
|
|
846
|
+
fs.writeFileSync(path.join(decoy, path.basename(f)), "decoy token\n", { mode: 0o600 });
|
|
847
|
+
real.subdirs.forEach((_, j) => fs.mkdirSync(path.join(decoy, `decoy-sub-${j}`), { mode: 0o700 }));
|
|
848
|
+
const other = path.join(decoy, "decoy-other");
|
|
849
|
+
fs.writeFileSync(other, "decoy\n", { mode: 0o600 });
|
|
850
|
+
if (![path.basename(other), `decoy-new${tag}`, ...real.subdirs.map((_, j) => `decoy-sub-${j}`)].every(plain))
|
|
851
|
+
throw new Error(`the decoy names clash with ${real.name}'s pattern`);
|
|
852
|
+
const state = policy.state;
|
|
853
|
+
const decoyLaunch = opts.wrap({ ...policy, state: { ...state, tokenStore: { ...state.tokenStore, dir: decoy } } });
|
|
854
|
+
if (decoyLaunch.rules !== launch.rules)
|
|
855
|
+
throw new Error(`the decoy for ${real.name} is not under this turn's rules`);
|
|
856
|
+
const temps = tempNames(real.tempName, 6).map((n) => path.join(decoy, n));
|
|
857
|
+
const token = path.join(decoy, path.basename(real.files[0]));
|
|
858
|
+
const s = {};
|
|
859
|
+
const yes = (name, step) => (s[name] = { step, expect: "allow", judge: allowed });
|
|
860
|
+
const no = (name, step) => (s[name] = { step, expect: "deny", judge: sandboxDenied });
|
|
861
|
+
yes("store-rewrite-token", { kind: "open-append", path: token });
|
|
862
|
+
yes("store-refresh", { kind: "refresh", temp: temps[0], onto: token });
|
|
863
|
+
if (real.locks.length)
|
|
864
|
+
yes("store-lock", { kind: "lock", path: path.join(decoy, path.basename(real.locks[0])) });
|
|
865
|
+
no("store-other-name", { kind: "write", path: path.join(decoy, `decoy-new${tag}`) });
|
|
866
|
+
no("store-other-file", { kind: "open-append", path: other });
|
|
867
|
+
no("store-symlink-temp", { kind: "symlink", target: victim, link: temps[1] });
|
|
868
|
+
no("store-hardlink-temp", { kind: "hardlink", from: victim, to: temps[2] });
|
|
869
|
+
// A file the turn may write, linked in: only the store's file-link deny stops this one (measured).
|
|
870
|
+
const own = path.join(tmpDir, `${tag}-own`);
|
|
871
|
+
fs.writeFileSync(own, "decoy\n", { mode: 0o600 });
|
|
872
|
+
created.push(own);
|
|
873
|
+
no("store-hardlink-own-temp", { kind: "hardlink", from: own, to: temps[5] });
|
|
874
|
+
no("store-mkdir-temp", { kind: "mkdir", path: temps[3] });
|
|
875
|
+
no("store-symlink-onto-token", { kind: "symlink-rename", target: victim, link: path.join(tmpDir, `${tag}-link`), onto: token });
|
|
876
|
+
no("store-token-out-tmp", { kind: "hardlink", from: token, to: path.join(tmpDir, `${tag}-token`) });
|
|
877
|
+
no("store-other-mode", { kind: "chmod", path: other, mode: 0o644 });
|
|
878
|
+
if (real.subdirs.length)
|
|
879
|
+
no("store-subdir-temp", { kind: "write", path: path.join(decoy, "decoy-sub-0", path.basename(temps[4])) });
|
|
880
|
+
created.push(path.join(tmpDir, `${tag}-link`), path.join(tmpDir, `${tag}-token`));
|
|
881
|
+
// Review r_75bf1f48: other file types and a file of two names brought in, exchanges, ordinary
|
|
882
|
+
// renames across the store's edge, an unescaped dot, xattrs; a rename in is the positive control.
|
|
883
|
+
const more = tempNames(real.tempName, 12).slice(6).map((n) => path.join(decoy, n));
|
|
884
|
+
const own2 = (n) => path.join(tmpDir, `${tag}-${n}`);
|
|
885
|
+
created.push(own2("d"), own2("fifo"), own2("a"), own2("b"), own2("in"), own2("swap"));
|
|
886
|
+
no("store-dir-rename-in", { kind: "mkdir-rename", dir: own2("d"), onto: more[0] });
|
|
887
|
+
no("store-fifo-rename-in", { kind: "fifo-rename", fifo: own2("fifo"), onto: more[1] });
|
|
888
|
+
no("store-pair-rename-in", { kind: "pair-rename", a: own2("a"), b: own2("b"), onto: more[2] });
|
|
889
|
+
fs.writeFileSync(own2("in"), "decoy\n", { mode: 0o600 });
|
|
890
|
+
yes("store-rename-in", { kind: "rename", from: own2("in"), to: more[3] });
|
|
891
|
+
no("store-rename-token-away", { kind: "rename", from: token, to: path.join(decoy, `decoy-away${tag}`) });
|
|
892
|
+
no("store-rename-other-in", { kind: "rename", from: other, to: more[4] });
|
|
893
|
+
if (real.locks.length) {
|
|
894
|
+
const lockPath = path.join(decoy, path.basename(real.locks[0]));
|
|
895
|
+
if (!fs.existsSync(lockPath))
|
|
896
|
+
fs.writeFileSync(lockPath, "decoy\n", { mode: 0o600 });
|
|
897
|
+
no("store-lock-unlink", { kind: "unlink", path: lockPath });
|
|
898
|
+
// The exchange's other side, a link of relay's own in the turn's temp dir, made from outside.
|
|
899
|
+
fs.symlinkSync(victim, own2("swap"));
|
|
900
|
+
no("store-exchange-lock", { kind: "native", check: { op: "rename-swap", from: own2("swap"), to: lockPath } });
|
|
901
|
+
}
|
|
902
|
+
no("store-xattr-token", { kind: "native", check: { op: "setxattr", path: token } });
|
|
903
|
+
// A name the pattern would match were its dots not escaped (the temp name with its first "." made "x").
|
|
904
|
+
const undotted = path.basename(temps[0]).replace(".", "x");
|
|
905
|
+
if (!real.tempName.test(undotted) && undotted !== path.basename(temps[0]))
|
|
906
|
+
no("store-dot-escape", { kind: "write", path: path.join(decoy, undotted) });
|
|
907
|
+
const storeGot = await canary(decoyLaunch, Object.fromEntries(Object.entries(s).map(([n, c]) => [n, c.step])));
|
|
908
|
+
for (const [name, c] of Object.entries(s)) {
|
|
909
|
+
const g = storeGot[name] ?? "missing";
|
|
910
|
+
results.push({ name, expect: c.expect, target: stepTarget(c.step), got: g, ok: c.judge(g) });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
catch (err) {
|
|
915
|
+
if (err instanceof ConfinementRefused)
|
|
916
|
+
throw err;
|
|
917
|
+
throw new ConfinementRefused("probe-setup", `relay could not set up its boundary probes for this turn (${err.message}), so it does not launch the harness`);
|
|
918
|
+
}
|
|
919
|
+
finally {
|
|
920
|
+
// The decoy semaphores go while the rest is cleaned up; removed before this returns.
|
|
921
|
+
const unsems = sems?.remove();
|
|
922
|
+
for (const s of servers)
|
|
923
|
+
s.close();
|
|
924
|
+
for (const c of closers)
|
|
925
|
+
c();
|
|
926
|
+
// A rename that got through and was not undone inside: put back before anything is removed.
|
|
927
|
+
for (const [from, to] of moved) {
|
|
928
|
+
if (!fs.lstatSync(from, { throwIfNoEntry: false }) && fs.lstatSync(to, { throwIfNoEntry: false })) {
|
|
929
|
+
try {
|
|
930
|
+
fs.renameSync(to, from);
|
|
931
|
+
}
|
|
932
|
+
catch { }
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
// Undo whatever the probes managed: theirs inside, and anything an escape left outside. Only the
|
|
936
|
+
// regular files and links the probes make are removed, each on its own; a directory at one of
|
|
937
|
+
// these paths is never deleted, let alone recursively (a `.git` the probe did not create, say, or
|
|
938
|
+
// repository metadata another process made since — review C2).
|
|
939
|
+
for (const p of created)
|
|
940
|
+
removeProbeArtifact(p);
|
|
941
|
+
// Config markers: removed only when the path is still the exact marker-bearing file the probe
|
|
942
|
+
// created, so a project's own config file that happens to share the path is never deleted (C1/X1).
|
|
943
|
+
for (const p of configMarkers)
|
|
944
|
+
removeProbeMarker(p, `${tag}\n`);
|
|
945
|
+
if (launchdListed(label)) {
|
|
946
|
+
try {
|
|
947
|
+
execFileSync("/bin/launchctl", ["remove", label], { stdio: "ignore" });
|
|
948
|
+
}
|
|
949
|
+
catch { }
|
|
950
|
+
}
|
|
951
|
+
if (scratchDir)
|
|
952
|
+
fs.rmSync(scratchDir, { recursive: true, force: true });
|
|
953
|
+
await unsems;
|
|
954
|
+
}
|
|
955
|
+
const failed = results.find((r) => !r.ok);
|
|
956
|
+
return { ok: !failed, profile: launch.fingerprint, relay: VERSION, os: osBuild(), ms: Math.round(performance.now() - started), results, ...(failed ? { failed } : {}) };
|
|
957
|
+
}
|
|
958
|
+
/** The kernel release and the OS build (kern.osversion), asked every time: an update between turns shows. */
|
|
959
|
+
function osBuild() {
|
|
960
|
+
let build = "unknown build";
|
|
961
|
+
try {
|
|
962
|
+
build = execFileSync("/usr/sbin/sysctl", ["-n", "kern.osversion"], { encoding: "utf8", timeout: 5000 }).trim();
|
|
963
|
+
}
|
|
964
|
+
catch { }
|
|
965
|
+
return `${os.release()} (${build})`;
|
|
966
|
+
}
|
|
967
|
+
/** What a step is tried against, for the report. */
|
|
968
|
+
/**
|
|
969
|
+
* `n` distinct names matching a login store's temp pattern (of the form tokenStore checks): each
|
|
970
|
+
* atom once, its first character for a class, and the first repeated atom repeated more each time.
|
|
971
|
+
*/
|
|
972
|
+
export function tempNames(pattern, n) {
|
|
973
|
+
const atoms = [...pattern.source.slice(1, -1).matchAll(/(\\\.|\[([A-Za-z0-9-]+)\]|[A-Za-z0-9_-])([+*]?)/g)].map((m) => ({ ch: m[1] === "\\." ? "." : m[2] ? m[2][0] : m[1], q: m[3] }));
|
|
974
|
+
const grow = atoms.findIndex((a) => a.q);
|
|
975
|
+
const out = Array.from({ length: n }, (_, i) => atoms.map((a, j) => a.ch.repeat(j === grow ? i + 1 : a.q === "*" ? 0 : 1)).join(""));
|
|
976
|
+
if (grow < 0 || !out.every((x) => pattern.test(x)) || new Set(out).size !== n)
|
|
977
|
+
throw new Error(`relay could not make names for the temp pattern ${pattern.source}`);
|
|
978
|
+
return out;
|
|
979
|
+
}
|
|
980
|
+
function stepTarget(s) {
|
|
981
|
+
switch (s.kind) {
|
|
982
|
+
case "tcp":
|
|
983
|
+
case "udp":
|
|
984
|
+
case "listen-port":
|
|
985
|
+
case "udp-bind":
|
|
986
|
+
return `${s.host}:${s.port}`;
|
|
987
|
+
case "listen":
|
|
988
|
+
return s.host;
|
|
989
|
+
case "dns":
|
|
990
|
+
return s.name;
|
|
991
|
+
case "exec":
|
|
992
|
+
return [s.command, ...s.args].join(" ");
|
|
993
|
+
case "hardlink":
|
|
994
|
+
case "rename":
|
|
995
|
+
return `${s.from} -> ${s.to}`;
|
|
996
|
+
case "symlink-write":
|
|
997
|
+
return s.file;
|
|
998
|
+
case "refresh":
|
|
999
|
+
return `${s.temp} -> ${s.onto}`;
|
|
1000
|
+
case "symlink":
|
|
1001
|
+
return s.link;
|
|
1002
|
+
case "symlink-rename":
|
|
1003
|
+
return `${s.link} -> ${s.onto}`;
|
|
1004
|
+
case "mkdir-rename":
|
|
1005
|
+
return `${s.dir} -> ${s.onto}`;
|
|
1006
|
+
case "fifo-rename":
|
|
1007
|
+
return `${s.fifo} -> ${s.onto}`;
|
|
1008
|
+
case "pair-rename":
|
|
1009
|
+
return `${s.b} -> ${s.onto}`;
|
|
1010
|
+
case "signal":
|
|
1011
|
+
return `pid ${s.pid}`;
|
|
1012
|
+
case "native":
|
|
1013
|
+
return nativeTarget(s.check);
|
|
1014
|
+
default:
|
|
1015
|
+
return s.path;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
/** What a native check is tried against, for the report. */
|
|
1019
|
+
function nativeTarget(c) {
|
|
1020
|
+
switch (c.op) {
|
|
1021
|
+
case "fcntl":
|
|
1022
|
+
return `fcntl ${c.cmd} on ${c.path}`;
|
|
1023
|
+
case "pidpath":
|
|
1024
|
+
case "pidinfo":
|
|
1025
|
+
return `${c.op} of pid ${c.pid}`;
|
|
1026
|
+
case "listpids":
|
|
1027
|
+
return "proc_listpids";
|
|
1028
|
+
case "sysctl-read":
|
|
1029
|
+
return "name" in c ? `sysctl ${c.name}` : `sysctl ${c.mib.join(".")}`;
|
|
1030
|
+
case "socket":
|
|
1031
|
+
return `socket(${c.domain}, ${c.type}, ${c.protocol})`;
|
|
1032
|
+
case "unix-dgram-connect":
|
|
1033
|
+
return c.path;
|
|
1034
|
+
case "mach":
|
|
1035
|
+
return `mach-lookup ${c.name}`;
|
|
1036
|
+
case "openpty":
|
|
1037
|
+
return "openpty";
|
|
1038
|
+
case "iokit-open":
|
|
1039
|
+
return `IOServiceOpen ${c.serviceClass}`;
|
|
1040
|
+
case "sysctl-write":
|
|
1041
|
+
return `sysctl-write ${c.name}`;
|
|
1042
|
+
case "sem-open":
|
|
1043
|
+
case "sem-post":
|
|
1044
|
+
case "sem-unlink":
|
|
1045
|
+
return `${c.op} ${c.name}`;
|
|
1046
|
+
case "rename-swap":
|
|
1047
|
+
return `${c.from} <-> ${c.to}`;
|
|
1048
|
+
case "setxattr":
|
|
1049
|
+
return `setxattr ${c.path}`;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Removes one thing a probe may have created, safely: a regular file or a link is unlinked; a
|
|
1054
|
+
* directory is left untouched, never removed recursively, so a `.git` directory the probe did not
|
|
1055
|
+
* create, or repository metadata a concurrent process made, is never deleted (review C2). Missing is
|
|
1056
|
+
* nothing to do.
|
|
1057
|
+
*/
|
|
1058
|
+
export function removeProbeArtifact(p) {
|
|
1059
|
+
const st = fs.lstatSync(p, { throwIfNoEntry: false });
|
|
1060
|
+
if (!st)
|
|
1061
|
+
return;
|
|
1062
|
+
if (st.isDirectory()) {
|
|
1063
|
+
// Only a directory the probe itself made (empty, named with its tag) is removed, and never recursively.
|
|
1064
|
+
try {
|
|
1065
|
+
fs.rmdirSync(p);
|
|
1066
|
+
}
|
|
1067
|
+
catch {
|
|
1068
|
+
// Not empty, or not ours: leave it.
|
|
1069
|
+
}
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
try {
|
|
1073
|
+
fs.unlinkSync(p);
|
|
1074
|
+
}
|
|
1075
|
+
catch {
|
|
1076
|
+
// Already gone.
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
/** Removes a config-probe artifact only when it is a regular file whose whole content is the probe's marker: never a project's own file, whatever the path. */
|
|
1080
|
+
export function removeProbeMarker(p, marker) {
|
|
1081
|
+
const st = fs.lstatSync(p, { throwIfNoEntry: false });
|
|
1082
|
+
if (!st || !st.isFile() || st.size !== Buffer.byteLength(marker))
|
|
1083
|
+
return;
|
|
1084
|
+
try {
|
|
1085
|
+
if (fs.readFileSync(p, "utf8") === marker)
|
|
1086
|
+
fs.unlinkSync(p);
|
|
1087
|
+
}
|
|
1088
|
+
catch {
|
|
1089
|
+
// Gone, or unreadable: leave it.
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
/** Whether launchd has a job by this label (asked from outside the sandbox). */
|
|
1093
|
+
function launchdListed(label) {
|
|
1094
|
+
try {
|
|
1095
|
+
execFileSync("/bin/launchctl", ["list", label], { stdio: "ignore" });
|
|
1096
|
+
return true;
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
return false;
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
/** Throws ConfinementRefused naming the first failed probe. */
|
|
1103
|
+
export function assertProbes(report) {
|
|
1104
|
+
const f = report.failed;
|
|
1105
|
+
if (!f)
|
|
1106
|
+
return;
|
|
1107
|
+
const what = f.expect === "deny" ? (f.got.startsWith("allowed") ? `escaped (${f.got})` : `was not shown to be refused by the sandbox (${f.got})`) : `was refused (${f.got})`;
|
|
1108
|
+
throw new ConfinementRefused(f.name, `relay will not launch the harness: boundary probe ${f.name} ${what}; expected ${f.expect}`, report);
|
|
1109
|
+
}
|