@capybara-hq/device 0.1.0-rc.18 → 0.1.0-rc.19
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/README.md +65 -33
- package/dist/api.d.ts +3 -3
- package/dist/args.d.ts +8 -3
- package/dist/args.js +27 -14
- package/dist/cli.js +1 -1
- package/dist/client.js +1 -1
- package/dist/commands/ceiling.d.ts +3 -2
- package/dist/commands/ceiling.js +39 -21
- package/dist/commands/login.d.ts +15 -11
- package/dist/commands/login.js +46 -33
- package/dist/commands/policy.js +16 -10
- package/dist/commands/start.d.ts +11 -3
- package/dist/commands/start.js +25 -9
- package/dist/commands/status.js +10 -6
- package/dist/exec/docker-operations.d.ts +14 -2
- package/dist/exec/docker-operations.js +32 -5
- package/dist/exec/linux-agent.d.ts +13 -3
- package/dist/exec/linux-agent.js +450 -43
- package/dist/exec/linux-operation-backend.d.ts +27 -6
- package/dist/exec/linux-operation-backend.js +30 -9
- package/dist/exec/linux-operation-worker.d.ts +51 -3
- package/dist/exec/linux-operation-worker.js +55 -3
- package/dist/exec/linux-runtime.d.ts +3 -2
- package/dist/exec/linux-runtime.js +4 -2
- package/dist/exec/mac-operation-backend.d.ts +7 -2
- package/dist/exec/mac-operation-backend.js +18 -10
- package/dist/exec/mac-write-policy.d.ts +2 -0
- package/dist/exec/mac-write-policy.js +1 -1
- package/dist/exec/operation-types.d.ts +35 -5
- package/dist/exec/operation-types.js +73 -23
- package/dist/exec/operation-worker.d.ts +80 -1
- package/dist/exec/operation-worker.js +197 -14
- package/dist/exec/protected-targets.d.ts +16 -0
- package/dist/exec/protected-targets.js +53 -0
- package/dist/exec/shared.d.ts +7 -3
- package/dist/exec/shared.js +7 -5
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/CAPYBARA-MODIFICATIONS.patch +343 -7
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/resolved-address-guard.js +220 -6
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js +17 -0
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js +11 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.d.ts +77 -46
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +206 -83
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +3 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +3 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.d.ts +98 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/network-classes.js +291 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-linux-runtime-source.js +460 -28
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-native-runtime-source.js +143 -3
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.d.ts +36 -4
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.js +21 -4
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-runtime-source.js +2 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.d.ts +87 -8
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-write-denies.js +249 -10
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox.d.ts +11 -22
- package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
- package/dist/owner-report.d.ts +1 -1
- package/dist/owner-report.js +5 -4
- package/dist/policy-store.d.ts +2 -1
- package/dist/policy-store.js +2 -1
- package/dist/policy.d.ts +23 -14
- package/dist/policy.js +28 -21
- package/dist/runtime-manifest.json +1 -1
- package/dist/server-ops.d.ts +30 -5
- package/dist/server-ops.js +105 -85
- package/dist/staged-connect.d.ts +1 -1
- package/dist/staged-connect.js +1 -1
- package/dist/staged-device.d.ts +1 -1
- package/dist/staged-device.js +7 -5
- package/dist/staged-session.d.ts +1 -1
- package/dist/state.d.ts +41 -21
- package/dist/state.js +102 -45
- package/package.json +2 -2
|
@@ -2,9 +2,9 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { basename, dirname, join, resolve } from "node:path";
|
|
5
|
-
import { SandboxScopeDeniedError, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
5
|
+
import { SandboxScopeDeniedError, sandboxRuntimeDirectoryOf, validateAllowHost, } from "@capybara-hq/plugin-sdk";
|
|
6
6
|
import { covers, deniedSecretPaths, effectiveEgress } from "../policy.js";
|
|
7
|
-
import { policyPath, readPolicyFile
|
|
7
|
+
import { policyPath, readPolicyFile } from "../state.js";
|
|
8
8
|
import { osRoots } from "./shared.js";
|
|
9
9
|
export function within(path, root) {
|
|
10
10
|
return root === "/" || path === root || path.startsWith(`${root}/`);
|
|
@@ -18,7 +18,7 @@ export async function readStrictOwnerCeiling(input) {
|
|
|
18
18
|
}
|
|
19
19
|
/**
|
|
20
20
|
* {@link readStrictOwnerCeiling}, synchronously (the owner report issues it under the policy lock).
|
|
21
|
-
* Only a version-
|
|
21
|
+
* Only a version-3 policy file is authority: an old format is refused until it is converted.
|
|
22
22
|
*/
|
|
23
23
|
export function readStrictOwnerCeilingSync(input) {
|
|
24
24
|
const file = policyPath(input.stateDir);
|
|
@@ -38,16 +38,16 @@ export function readStrictOwnerCeilingSync(input) {
|
|
|
38
38
|
const roots = Object.freeze(osRoots(resolve(input.dir)));
|
|
39
39
|
return Object.freeze({
|
|
40
40
|
revision: digest({ generation: version(after), policy, roots, deviceId: input.deviceId }),
|
|
41
|
-
|
|
41
|
+
outsideSandbox: policy.ownerCeiling.outsideSandbox,
|
|
42
|
+
network: policy.ownerCeiling.network,
|
|
43
|
+
allowedDomains: Object.freeze([...policy.allowedDomains]),
|
|
42
44
|
roots,
|
|
43
45
|
restrictedProjectReach: policy.ownerCeiling.restrictedProjectReach,
|
|
44
|
-
restrictedAllowedDomains: Object.freeze([...policy.allowedDomains]),
|
|
45
46
|
restrictedDeniedReadRoots: Object.freeze(withCanonicalForms([...deniedSecretPaths(input.home ?? homedir()), resolve(input.stateDir)])),
|
|
46
47
|
preparation: Object.freeze({
|
|
47
48
|
skillsRoot: roots.skills,
|
|
48
49
|
attachmentsBase: join(roots.workspace, "attachments"),
|
|
49
50
|
}),
|
|
50
|
-
fullNetwork: "environment",
|
|
51
51
|
});
|
|
52
52
|
}
|
|
53
53
|
/**
|
|
@@ -87,6 +87,14 @@ export function checkRoots(read, write, ceiling, preparation = false) {
|
|
|
87
87
|
if (ceiling.restrictedDeniedReadRoots.some((r) => within(root, r)))
|
|
88
88
|
throw new SandboxScopeDeniedError("Root is denied by the owner");
|
|
89
89
|
}
|
|
90
|
+
// the kernel's candidate builder and admission refuse the same roots: another process's socket
|
|
91
|
+
// there would let a sandboxed command act outside the sandbox. Checked before the skills rule so
|
|
92
|
+
// the refusal names the real reason wherever the skills root lives (under /tmp on Linux)
|
|
93
|
+
for (const root of write) {
|
|
94
|
+
const runtime = sandboxRuntimeDirectoryOf(root);
|
|
95
|
+
if (runtime !== null)
|
|
96
|
+
throw new SandboxScopeDeniedError(`Write root ${root} is a system runtime or socket directory (${runtime}), where other programs keep their sockets; grant a directory of its own (such as /tmp/<name>) or one inside the project instead`);
|
|
97
|
+
}
|
|
90
98
|
if (!preparation &&
|
|
91
99
|
write.some((r) => within(r, ceiling.roots.skills) || within(ceiling.roots.skills, r)))
|
|
92
100
|
throw new SandboxScopeDeniedError("Skills remain read only");
|
|
@@ -118,13 +126,23 @@ export function freezeAuthority(a) {
|
|
|
118
126
|
: {}),
|
|
119
127
|
});
|
|
120
128
|
}
|
|
129
|
+
/** The refusal of an escalated call the owner ceiling does not allow. */
|
|
130
|
+
export const OUTSIDE_SANDBOX_REFUSAL = "Running outside the sandbox is outside the current owner ceiling; the owner allows it on " +
|
|
131
|
+
"this machine with capybara-device ceiling set --outside-sandbox on";
|
|
132
|
+
/**
|
|
133
|
+
* One operation's scope intersected with the owner ceiling now (approval-only profiles design).
|
|
134
|
+
* Every profile's ordinary call is sandboxed: scoped roots, the owner's denied read roots and the
|
|
135
|
+
* sandbox network. Only an escalated call (`filesystem: device` with `network: environment`) runs
|
|
136
|
+
* outside the sandbox, and only while the owner ceiling allows `outsideSandbox`. The profile in the
|
|
137
|
+
* scope is audit only: it never widens anything here.
|
|
138
|
+
*/
|
|
121
139
|
export function intersectOperation(scope, ceiling, authority, native = false) {
|
|
122
140
|
if (authority && authority.operationId !== scope.operationId)
|
|
123
141
|
throw new SandboxScopeDeniedError("Execution authority operation ID mismatch");
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
126
|
-
if (!ceiling.
|
|
127
|
-
throw new SandboxScopeDeniedError(
|
|
142
|
+
const escalated = scope.filesystem.kind === "device" && scope.network.kind === "environment";
|
|
143
|
+
if (escalated) {
|
|
144
|
+
if (!ceiling.outsideSandbox)
|
|
145
|
+
throw new SandboxScopeDeniedError(OUTSIDE_SANDBOX_REFUSAL);
|
|
128
146
|
return Object.freeze({
|
|
129
147
|
full: true,
|
|
130
148
|
readRoots: Object.freeze(["/"]),
|
|
@@ -135,26 +153,43 @@ export function intersectOperation(scope, ceiling, authority, native = false) {
|
|
|
135
153
|
});
|
|
136
154
|
}
|
|
137
155
|
if (scope.filesystem.kind !== "scoped" || scope.network.kind === "environment")
|
|
138
|
-
throw new SandboxScopeDeniedError("
|
|
156
|
+
throw new SandboxScopeDeniedError("The device filesystem and the environment network come only together, as one escalated call");
|
|
139
157
|
checkRoots(scope.filesystem.readRoots, scope.filesystem.writeRoots, ceiling);
|
|
140
158
|
if (!native && !authority)
|
|
141
159
|
throw new SandboxScopeDeniedError("Restricted execution requires authenticated authority");
|
|
160
|
+
let openNetwork = false;
|
|
142
161
|
const hosts = new Set();
|
|
143
|
-
if (authority && !native
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
162
|
+
if (authority && !native) {
|
|
163
|
+
const egress = effectiveEgress({ ownerCeiling: { network: ceiling.network }, allowedDomains: [...ceiling.allowedDomains] }, authority.orgNetwork, authority.grants);
|
|
164
|
+
if (scope.network.kind === "open-public") {
|
|
165
|
+
// asked for the open network: open only where the owner and the kernel both allow it,
|
|
166
|
+
// otherwise narrowed to the allowlist they do allow
|
|
167
|
+
if (egress.kind === "open-public")
|
|
168
|
+
openNetwork = true;
|
|
169
|
+
else
|
|
170
|
+
for (const h of egress.hosts)
|
|
171
|
+
hosts.add(h);
|
|
172
|
+
}
|
|
173
|
+
else if (scope.network.kind !== "allowlist") {
|
|
174
|
+
// `none`: no network at all
|
|
175
|
+
}
|
|
176
|
+
else if (egress.kind === "open-public") {
|
|
177
|
+
for (const h of scope.network.hosts)
|
|
178
|
+
hosts.add(h.toLowerCase());
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
for (const a of egress.hosts)
|
|
182
|
+
for (const b of scope.network.hosts) {
|
|
183
|
+
if (covers(a, b))
|
|
184
|
+
hosts.add(b);
|
|
185
|
+
else if (covers(b, a))
|
|
186
|
+
hosts.add(a);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
155
189
|
}
|
|
156
190
|
return Object.freeze({
|
|
157
191
|
full: false,
|
|
192
|
+
...(openNetwork && { openNetwork: true }),
|
|
158
193
|
readRoots: Object.freeze([...scope.filesystem.readRoots]),
|
|
159
194
|
writeRoots: Object.freeze([...scope.filesystem.writeRoots]),
|
|
160
195
|
hosts: Object.freeze([...hosts]),
|
|
@@ -162,3 +197,18 @@ export function intersectOperation(scope, ceiling, authority, native = false) {
|
|
|
162
197
|
revision: ceiling.revision,
|
|
163
198
|
});
|
|
164
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Whether a live operation's grant still holds against the grant the fresh owner ceiling gives the
|
|
202
|
+
* same scope (owner reconcile): a full grant only while the next one is full; a sandboxed grant
|
|
203
|
+
* only while every host, the open network if it had one, and exactly the same denied read roots
|
|
204
|
+
* remain. Anything narrower revokes the operation.
|
|
205
|
+
*/
|
|
206
|
+
export function grantStillHolds(grant, next) {
|
|
207
|
+
if (grant.full)
|
|
208
|
+
return next.full;
|
|
209
|
+
return (!next.full &&
|
|
210
|
+
(!grant.openNetwork || next.openNetwork === true) &&
|
|
211
|
+
grant.hosts.every((h) => next.hosts.includes(h)) &&
|
|
212
|
+
grant.deniedReadRoots.every((r) => next.deniedReadRoots.includes(r)) &&
|
|
213
|
+
next.deniedReadRoots.every((r) => grant.deniedReadRoots.includes(r)));
|
|
214
|
+
}
|
|
@@ -55,6 +55,12 @@ interface Common {
|
|
|
55
55
|
home: string;
|
|
56
56
|
env: Record<string, string | undefined>;
|
|
57
57
|
};
|
|
58
|
+
/**
|
|
59
|
+
* A test seam (trusted construction, like the Linux forwarder's `allow_private`): the proxy's
|
|
60
|
+
* address rules are lifted so a fixture listening on loopback can be granted. Never set in
|
|
61
|
+
* production.
|
|
62
|
+
*/
|
|
63
|
+
allowPrivateProxyTargets?: boolean;
|
|
58
64
|
}
|
|
59
65
|
export type MacWorkerRequest = Common & ({
|
|
60
66
|
kind: "exec";
|
|
@@ -83,6 +89,76 @@ export declare function createCancellationAttempt(attempt: (graceMs: number) =>
|
|
|
83
89
|
* beneath it and break ordinary git work.
|
|
84
90
|
*/
|
|
85
91
|
export declare function mandatoryDenyPatterns(root: string): string[];
|
|
92
|
+
/**
|
|
93
|
+
* The sandbox runtime's network configuration for one restricted grant (approval-only profiles
|
|
94
|
+
* design, "Open network"), and whether the worker answers the runtime's ask callback with allow.
|
|
95
|
+
*
|
|
96
|
+
* Both networks decide every connection on the resolved address in the operation's own proxy,
|
|
97
|
+
* which dials the address it checked (no second resolution: DNS rebinding cannot swap it).
|
|
98
|
+
* `deniedResolvedAddresses` is the SDK's whole closed set ({@link OPEN_PUBLIC_DENIED_CIDRS}:
|
|
99
|
+
* private, CGNAT, ULA, link-local, metadata, loopback, NAT64, multicast, reserved, embedded forms
|
|
100
|
+
* expanded); the runtime adds loopback, link-local, the cloud metadata endpoints and this host's
|
|
101
|
+
* own interface addresses itself. The patched runtime's `resolvedAddressStrict` judges an IP
|
|
102
|
+
* literal by the same rules (upstream skips literals), gives `localhost` no loopback carve-out and
|
|
103
|
+
* an allow-listed literal none over the closed classes: a private destination needs the
|
|
104
|
+
* escalation, never a host grant.
|
|
105
|
+
*
|
|
106
|
+
* - The allowlist (no `openNetwork`): exactly the grant's hosts, by the runtime's own matching.
|
|
107
|
+
* - The open network: no host list and an allow-all ask callback, so the address rules alone
|
|
108
|
+
* decide. The grant's hosts are not used.
|
|
109
|
+
*
|
|
110
|
+
* In both networks a name the system resolver answers with a fake-IP address
|
|
111
|
+
* ({@link SANDBOX_FAKE_IP_DNS}: 198.18.0.0/15, an OpenClash-style router) is re-resolved through
|
|
112
|
+
* DNS-over-HTTPS at the SDK's IP-literal endpoints (the patched runtime's `fakeIpDoh`; the SDK's
|
|
113
|
+
* timeout is the whole lookup, shared among the endpoints) and the real answer judged and dialed as
|
|
114
|
+
* above; when that lookup fails the connection is refused with a reason naming the fake-IP
|
|
115
|
+
* resolver, never dialed to the fake address.
|
|
116
|
+
*
|
|
117
|
+
* Listening stays refused (`allowLocalBinding: false`) under every profile: Seatbelt cannot limit a
|
|
118
|
+
* bind to loopback (spec "Known limitations"), and with it the command could reach every local
|
|
119
|
+
* port. `allowPrivate` is a trusted test seam (like the Linux forwarder's): it lifts the address
|
|
120
|
+
* rules so a fixture on loopback can be granted; nothing in production sets it.
|
|
121
|
+
*
|
|
122
|
+
* TLS trust needs one Mach service, `com.apple.TrustEvaluationAgent` (the per-user agent, not its
|
|
123
|
+
* `.system` sibling): Apple's LibreSSL in `/usr/bin/curl`, `/usr/bin/openssl` and the Command
|
|
124
|
+
* Line Tools' `python3` checks a chain against `/etc/ssl/cert.pem` (readable) and, when that
|
|
125
|
+
* bundle lacks the anchor (a newer root, such as example.com's SSL.com 2022 chain), asks this
|
|
126
|
+
* agent, which evaluates it against the system keychain and the admin's trust settings. Without
|
|
127
|
+
* it such a site fails with "unable to get local issuer certificate". The agent only evaluates
|
|
128
|
+
* the chain the client hands it: it fetched no issuer named in a certificate (checked on macOS
|
|
129
|
+
* 26 with a leaf whose AIA URL pointed at a local listener). `trustd` stays closed.
|
|
130
|
+
*/
|
|
131
|
+
export declare function macNetworkConfig(grant: Pick<LocalOperationGrant, "hosts" | "openNetwork">, options?: {
|
|
132
|
+
allowPrivate?: boolean;
|
|
133
|
+
}): {
|
|
134
|
+
askAll: boolean;
|
|
135
|
+
network: Record<string, unknown>;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Absolute write denies a restricted macOS operation gets besides each write root's policy:
|
|
139
|
+
*
|
|
140
|
+
* - `subtrees`, denied with everything beneath them: the system persistence paths
|
|
141
|
+
* ({@link SANDBOX_SYSTEM_WRITE_DENIES}: the crontab and at spools) in each spelling Seatbelt may
|
|
142
|
+
* see, and the final target of every protected location under `home` (the
|
|
143
|
+
* {@link SANDBOX_MANDATORY_WRITE_DENIES} entries: `~/Library/LaunchAgents`, `~/.config/systemd`,
|
|
144
|
+
* the shell startup files, …) reached through a symbolic link, and each
|
|
145
|
+
* {@link SANDBOX_HOME_WRITE_DENIES} entry (`~/bin`) always, with the target of its link;
|
|
146
|
+
* - `links`, denied exactly (the link itself cannot be removed, renamed or replaced): every
|
|
147
|
+
* symbolic link on the way to such a location. A dotfile manager links `~/.zshrc` to
|
|
148
|
+
* `~/code/dotfiles-current/zshrc`, and `dotfiles-current` may itself be a link inside a write
|
|
149
|
+
* root; swapping any hop for a real directory would redirect the protected location into
|
|
150
|
+
* writable space (SDK `sandbox-write-denies.ts`, constraint on consumers).
|
|
151
|
+
*
|
|
152
|
+
* Resolved at operation start: a link changed later is seen by the next operation. A hard link to
|
|
153
|
+
* a protected file that already exists inside a write root is not caught (it is the same file,
|
|
154
|
+
* under an ordinary name).
|
|
155
|
+
*/
|
|
156
|
+
export declare function macProtectedWriteDenies(home: string): {
|
|
157
|
+
subtrees: string[];
|
|
158
|
+
links: string[];
|
|
159
|
+
};
|
|
160
|
+
/** The environment of an escalated call: the device program's, minus every `CAPYBARA_` variable. */
|
|
161
|
+
export declare function escalatedEnvironment(env: NodeJS.ProcessEnv, own: Record<string, string> | undefined): Record<string, string>;
|
|
86
162
|
/** The JVM proxy agent the sandbox runtime points sandboxed JVMs at, inside its package. */
|
|
87
163
|
export declare const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-agent.jar";
|
|
88
164
|
/**
|
|
@@ -95,8 +171,11 @@ export declare const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-a
|
|
|
95
171
|
* Darwin answers a group signal with EPERM (not ESRCH) while the group holds only dead members
|
|
96
172
|
* (zombies not yet reaped, or processes exiting), so `signalGroup` counts EPERM as gone when a
|
|
97
173
|
* process snapshot shows no live member of the group; EPERM with a live member still fails.
|
|
174
|
+
* A runtime without the network patch (`resolvedAddressStrict`, `fakeIpDoh` in its schema) is
|
|
175
|
+
* refused before it starts: its proxy would skip the address rules, so the bind self-check fails
|
|
176
|
+
* and the device reports no restricted support (and so no open network).
|
|
98
177
|
*/
|
|
99
|
-
export declare const WORKER = "import {pathToFileURL} from 'node:url';\nimport {spawn,spawnSync} from 'node:child_process';\nimport {randomUUID} from 'node:crypto';\nlet manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false,exited=false,forced=false,settling=false,settleTimer;\nconst owned=new Map(),signaled=new Set();\nlet credit,sequence=0,outputFailed=false,outputDone=Promise.resolve();\nasync function collect(stream){\n try{for await(const chunk of stream){\n for(let offset=0;offset<chunk.length;offset+=65536){\n if(outputFailed)continue;\n const data=chunk.subarray(offset,offset+65536);const seq=sequence++;\n const bufferedBytes=chunk.length+stream.readableLength;if(bufferedBytes>262144)throw Error('Managed producer buffer exceeded bound');\n send({event:'output-flow',frameBytes:data.length,bufferedBytes,producerLimit:262144});\n await new Promise((resolve,reject)=>{credit={seq,resolve,reject};send({event:'output',stream:'stdout',seq,data:data.toString('base64')});});\n }\n }}catch(error){if(forced)return;const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}\n}\nconst send=value=>{if(process.connected)process.send(value,()=>{});};\nfunction stopTree(){\n if(!child?.pid||child.exitCode!==null||child.signalCode!==null)return [];\n try{process.kill(child.pid,'SIGSTOP');}catch{return [];}\n const tree=new Set([child.pid]);\n for(let round=0;round<64;round++){\n const ps=spawnSync('/bin/ps',['-axo','pid=,ppid='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0){send({event:'diagnostic',text:'Descendant snapshot failed'});break;}\n const found=[];\n for(const line of ps.stdout.split('\\n')){const [pid,ppid]=line.trim().split(/\\s+/).map(Number);if(pid>1&&tree.has(ppid)&&!tree.has(pid))found.push(pid);}\n if(!found.length)break;\n for(const pid of found)try{process.kill(pid,'SIGSTOP');tree.add(pid);}catch{}\n }\n return [...tree];\n}\nfunction deadGroup(pgid){\n const ps=spawnSync('/bin/ps',['-axo','pgid=,stat='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0)return false;\n for(const line of ps.stdout.split('\\n')){const [group,stat='']=line.trim().split(/\\s+/);if(Number(group)===pgid&&!stat.startsWith('Z')&&!stat.includes('E'))return false;}\n return true;\n}\nfunction signalGroup(pgid,signal){try{process.kill(-pgid,signal);return true;}catch(error){if(error.code==='ESRCH'||(error.code==='EPERM'&&deadGroup(pgid)))return false;throw error;}}\nfunction signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;if(!signalGroup(pid,signal)||signal==='SIGKILL')signaled.add(pid);}}\nfunction settle(){\n if(!child||settling||!exited||!(killed||timedOut||closing))return;settling=true;\n const started=Date.now();let goneAt=0;\n const tick=()=>{\n let gone=false;try{gone=!signalGroup(child.pid,0);}catch{}\n const now=Date.now();if(gone&&!goneAt)goneAt=now;\n if((goneAt&&now-goneAt>=250)||now-started>=5000){\n forced=true;if(credit){const pending=credit;credit=undefined;pending.reject(Error('Owned output closed after cancellation'));}\n child.stdout.destroy();child.stderr.destroy();return;\n }\n settleTimer=setTimeout(tick,50);\n };\n settleTimer=setTimeout(tick,50);\n}\nasync function stop(){\n if(closing)return;closing=true;\n if(credit){outputFailed=true;const pending=credit;credit=undefined;pending.reject(Error('Owned output channel closed'));child?.stdout.resume();}\n try{signalOwned();}catch(error){closing=false;send({event:'error',message:'Owned cancellation remains pending: '+error.code});return;}\n settle();await childClosed;owned.clear();await manager?.reset();process.disconnect?.();\n}\nprocess.on('disconnect',stop);process.on('SIGTERM',stop);\nprocess.on('message',async message=>{try{\n if(message.type==='output-ack'){\n if(credit && credit.seq===message.seq){const pending=credit;credit=undefined;if(message.ok)pending.resolve();else{outputFailed=true;pending.reject(Error('Managed sink failed'));child?.stdout.resume();}}\n }else if(message.type==='init'){\n if(initialized)throw Error('Worker initialization is immutable');initialized=true;full=message.full;\n if(!full){({SandboxManager:manager}=await import(pathToFileURL(message.runtime)));const deps=manager.checkDependencies();if(!manager.isSupportedPlatform()||deps.errors?.length)throw Error('Unsupported macOS sandbox runtime');await manager.initialize(message.config,undefined,false);}\n send({event:'ready',proxyUrl:full?'':'http://srt:'+manager.getProxyAuthToken()+'@127.0.0.1:'+manager.getProxyPort()});\n }else if(message.type==='wrap'){\n if(!initialized||wrapped)throw Error('One command per worker');wrapped=true;\n const script=full?message.script:await manager.wrapWithSandbox(message.script,'/bin/bash');send({event:'wrapped',script});\n }else if(message.type==='execute'){\n if(!wrapped||child||closing)throw Error('Immutable worker already consumed');\n child=spawn('/bin/bash',['-c',message.script],{cwd:message.cwd,env:message.env,detached:true,stdio:['ignore','pipe','pipe']});\n const identity={pid:child.pid,token:randomUUID()};if(!identity.pid)throw Error('Missing trusted launch identity');\n owned.set(identity.pid,identity.token);\n childClosed=new Promise(resolve=>child.once('close',async code=>{clearTimeout(timer);clearTimeout(settleTimer);await outputDone;send({event:'completed',code,timedOut,killed,outputFailed});resolve();}));\n child.once('error',error=>send({event:'error',message:String(error)}));\n child.once('exit',code=>{exited=true;send({event:'process-exit',code,timedOut,killed});try{signalOwned();}catch(error){send({event:'error',message:'Owned group cleanup pending: '+error.code});}settle();});\n if(message.managed){\n if(child.stdout.readableHighWaterMark>65536)throw Error('Unbounded managed producer buffer');\n outputDone=collect(child.stdout);let diagnosticBytes=0;child.stderr.on('data',bytes=>{diagnosticBytes+=bytes.length;if(diagnosticBytes<=65536)send({event:'diagnostic',text:bytes.toString()});});\n }else for(const stream of ['stdout','stderr'])child[stream].on('data',bytes=>{child[stream].pause();if(!process.connected){child[stream].resume();return;}process.send({event:'output',stream,data:bytes.toString('base64')},()=>child[stream].resume());});\n timer=setTimeout(()=>{timedOut=true;try{signalOwned();}catch(error){send({event:'error',message:'Owned timeout cancellation pending: '+error.code});}settle();},message.timeoutMs);\n send({event:'launched',...identity});\n }else if(message.type==='cancel'){\n killed=true;try{if(message.graceMs>0&&child){signalOwned('SIGTERM');const force=setTimeout(()=>{try{signalOwned();}catch(error){send({event:'error',message:'Owned graceful cancellation pending: '+error.code});}},message.graceMs);childClosed.finally(()=>clearTimeout(force));}else signalOwned();send({event:'cancelled',ok:true});}catch(error){send({event:'cancelled',ok:false,message:'Owned cancellation pending: '+error.code});}settle();\n }else if(message.type==='register'){\n if(!Number.isSafeInteger(message.pid)||message.pid<=1||typeof message.token!=='string')throw Error('Invalid trusted launch identity');\n owned.set(message.pid,message.token);send({event:'registered'});\n }else if(message.type==='release'){\n if(owned.get(message.pid)!==message.token)throw Error('Owned launch identity mismatch');owned.delete(message.pid);send({event:'released'});\n }else if(message.type==='stop')await stop();\n}catch(error){send({event:'error',message:String(error)});await stop();}});";
|
|
178
|
+
export declare const WORKER = "import {pathToFileURL} from 'node:url';\nimport {spawn,spawnSync} from 'node:child_process';\nimport {randomUUID} from 'node:crypto';\nlet manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false,exited=false,forced=false,settling=false,settleTimer;\nconst owned=new Map(),signaled=new Set();\nlet credit,sequence=0,outputFailed=false,outputDone=Promise.resolve();\nasync function collect(stream){\n try{for await(const chunk of stream){\n for(let offset=0;offset<chunk.length;offset+=65536){\n if(outputFailed)continue;\n const data=chunk.subarray(offset,offset+65536);const seq=sequence++;\n const bufferedBytes=chunk.length+stream.readableLength;if(bufferedBytes>262144)throw Error('Managed producer buffer exceeded bound');\n send({event:'output-flow',frameBytes:data.length,bufferedBytes,producerLimit:262144});\n await new Promise((resolve,reject)=>{credit={seq,resolve,reject};send({event:'output',stream:'stdout',seq,data:data.toString('base64')});});\n }\n }}catch(error){if(forced)return;const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}\n}\nconst send=value=>{if(process.connected)process.send(value,()=>{});};\nfunction stopTree(){\n if(!child?.pid||child.exitCode!==null||child.signalCode!==null)return [];\n try{process.kill(child.pid,'SIGSTOP');}catch{return [];}\n const tree=new Set([child.pid]);\n for(let round=0;round<64;round++){\n const ps=spawnSync('/bin/ps',['-axo','pid=,ppid='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0){send({event:'diagnostic',text:'Descendant snapshot failed'});break;}\n const found=[];\n for(const line of ps.stdout.split('\\n')){const [pid,ppid]=line.trim().split(/\\s+/).map(Number);if(pid>1&&tree.has(ppid)&&!tree.has(pid))found.push(pid);}\n if(!found.length)break;\n for(const pid of found)try{process.kill(pid,'SIGSTOP');tree.add(pid);}catch{}\n }\n return [...tree];\n}\nfunction deadGroup(pgid){\n const ps=spawnSync('/bin/ps',['-axo','pgid=,stat='],{encoding:'utf8',timeout:5000});\n if(ps.status!==0)return false;\n for(const line of ps.stdout.split('\\n')){const [group,stat='']=line.trim().split(/\\s+/);if(Number(group)===pgid&&!stat.startsWith('Z')&&!stat.includes('E'))return false;}\n return true;\n}\nfunction signalGroup(pgid,signal){try{process.kill(-pgid,signal);return true;}catch(error){if(error.code==='ESRCH'||(error.code==='EPERM'&&deadGroup(pgid)))return false;throw error;}}\nfunction signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;if(!signalGroup(pid,signal)||signal==='SIGKILL')signaled.add(pid);}}\nfunction settle(){\n if(!child||settling||!exited||!(killed||timedOut||closing))return;settling=true;\n const started=Date.now();let goneAt=0;\n const tick=()=>{\n let gone=false;try{gone=!signalGroup(child.pid,0);}catch{}\n const now=Date.now();if(gone&&!goneAt)goneAt=now;\n if((goneAt&&now-goneAt>=250)||now-started>=5000){\n forced=true;if(credit){const pending=credit;credit=undefined;pending.reject(Error('Owned output closed after cancellation'));}\n child.stdout.destroy();child.stderr.destroy();return;\n }\n settleTimer=setTimeout(tick,50);\n };\n settleTimer=setTimeout(tick,50);\n}\nasync function stop(){\n if(closing)return;closing=true;\n if(credit){outputFailed=true;const pending=credit;credit=undefined;pending.reject(Error('Owned output channel closed'));child?.stdout.resume();}\n try{signalOwned();}catch(error){closing=false;send({event:'error',message:'Owned cancellation remains pending: '+error.code});return;}\n settle();await childClosed;owned.clear();await manager?.reset();process.disconnect?.();\n}\nprocess.on('disconnect',stop);process.on('SIGTERM',stop);\nprocess.on('message',async message=>{try{\n if(message.type==='output-ack'){\n if(credit && credit.seq===message.seq){const pending=credit;credit=undefined;if(message.ok)pending.resolve();else{outputFailed=true;pending.reject(Error('Managed sink failed'));child?.stdout.resume();}}\n }else if(message.type==='init'){\n if(initialized)throw Error('Worker initialization is immutable');initialized=true;full=message.full;\n if(!full){let schema;({SandboxManager:manager,NetworkConfigSchema:schema}=await import(pathToFileURL(message.runtime)));const net=message.config.network;if((net.resolvedAddressStrict||net.fakeIpDoh)&&!(schema?.shape?.resolvedAddressStrict&&schema?.shape?.fakeIpDoh))throw Error('The sandbox runtime lacks the network patch');const deps=manager.checkDependencies();if(!manager.isSupportedPlatform()||deps.errors?.length)throw Error('Unsupported macOS sandbox runtime');await manager.initialize(message.config,message.askAll?async()=>true:undefined,false);}\n send({event:'ready',proxyUrl:full?'':'http://srt:'+manager.getProxyAuthToken()+'@127.0.0.1:'+manager.getProxyPort()});\n }else if(message.type==='wrap'){\n if(!initialized||wrapped)throw Error('One command per worker');wrapped=true;\n const script=full?message.script:await manager.wrapWithSandbox(message.script,'/bin/bash');send({event:'wrapped',script});\n }else if(message.type==='execute'){\n if(!wrapped||child||closing)throw Error('Immutable worker already consumed');\n child=spawn('/bin/bash',['-c',message.script],{cwd:message.cwd,env:message.env,detached:true,stdio:['ignore','pipe','pipe']});\n const identity={pid:child.pid,token:randomUUID()};if(!identity.pid)throw Error('Missing trusted launch identity');\n owned.set(identity.pid,identity.token);\n childClosed=new Promise(resolve=>child.once('close',async code=>{clearTimeout(timer);clearTimeout(settleTimer);await outputDone;send({event:'completed',code,timedOut,killed,outputFailed});resolve();}));\n child.once('error',error=>send({event:'error',message:String(error)}));\n child.once('exit',code=>{exited=true;send({event:'process-exit',code,timedOut,killed});try{signalOwned();}catch(error){send({event:'error',message:'Owned group cleanup pending: '+error.code});}settle();});\n if(message.managed){\n if(child.stdout.readableHighWaterMark>65536)throw Error('Unbounded managed producer buffer');\n outputDone=collect(child.stdout);let diagnosticBytes=0;child.stderr.on('data',bytes=>{diagnosticBytes+=bytes.length;if(diagnosticBytes<=65536)send({event:'diagnostic',text:bytes.toString()});});\n }else for(const stream of ['stdout','stderr'])child[stream].on('data',bytes=>{child[stream].pause();if(!process.connected){child[stream].resume();return;}process.send({event:'output',stream,data:bytes.toString('base64')},()=>child[stream].resume());});\n timer=setTimeout(()=>{timedOut=true;try{signalOwned();}catch(error){send({event:'error',message:'Owned timeout cancellation pending: '+error.code});}settle();},message.timeoutMs);\n send({event:'launched',...identity});\n }else if(message.type==='cancel'){\n killed=true;try{if(message.graceMs>0&&child){signalOwned('SIGTERM');const force=setTimeout(()=>{try{signalOwned();}catch(error){send({event:'error',message:'Owned graceful cancellation pending: '+error.code});}},message.graceMs);childClosed.finally(()=>clearTimeout(force));}else signalOwned();send({event:'cancelled',ok:true});}catch(error){send({event:'cancelled',ok:false,message:'Owned cancellation pending: '+error.code});}settle();\n }else if(message.type==='register'){\n if(!Number.isSafeInteger(message.pid)||message.pid<=1||typeof message.token!=='string')throw Error('Invalid trusted launch identity');\n owned.set(message.pid,message.token);send({event:'registered'});\n }else if(message.type==='release'){\n if(owned.get(message.pid)!==message.token)throw Error('Owned launch identity mismatch');owned.delete(message.pid);send({event:'released'});\n }else if(message.type==='stop')await stop();\n}catch(error){send({event:'error',message:String(error)});await stop();}});";
|
|
100
179
|
/** A separate process owns each immutable SRT manager; Full never enters that process. */
|
|
101
180
|
export declare function startMacOperationWorker(request: MacWorkerRequest, signal: AbortSignal): Promise<MacWorkerHandle>;
|
|
102
181
|
export {};
|
|
@@ -4,12 +4,13 @@ import { constants, realpathSync } from "node:fs";
|
|
|
4
4
|
import { mkdtemp, open, readdir, realpath, rm, stat } from "node:fs/promises";
|
|
5
5
|
import { homedir, tmpdir } from "node:os";
|
|
6
6
|
import { basename, dirname, join } from "node:path";
|
|
7
|
-
import { SANDBOX_GIT_DENIED_INTERNALS, SANDBOX_MANDATORY_WRITE_DENIES, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
7
|
+
import { OPEN_PUBLIC_DENIED_CIDRS, SANDBOX_FAKE_IP_DNS, SANDBOX_GIT_DENIED_INTERNALS, SANDBOX_HOME_WRITE_DENIES, SANDBOX_MANDATORY_WRITE_DENIES, SANDBOX_RESERVED_NAME_PREFIX, SANDBOX_SYSTEM_WRITE_DENIES, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
8
8
|
import { implicitWritePaths } from "../policy.js";
|
|
9
9
|
import { macReadAllows } from "./mac-read-policy.js";
|
|
10
|
-
import { macWriteRegexRules, macWriteRootSpellings } from "./mac-write-policy.js";
|
|
10
|
+
import { ci, macWriteRegexRules, macWriteRootSpellings, } from "./mac-write-policy.js";
|
|
11
11
|
import { runNativeHelper, } from "./native-helper-client.js";
|
|
12
12
|
import { withCanonicalForms } from "./operation-types.js";
|
|
13
|
+
import { onDisk, protectedChain } from "./protected-targets.js";
|
|
13
14
|
import { acquireSealedRuntime, stagePrivateSource, stageRuntimeSource, } from "./runtime-source.js";
|
|
14
15
|
import { ENV_NAME_RE, OutputCap, restrictedToolHomes, shellQuote } from "./shared.js";
|
|
15
16
|
import { recordTransferTiming } from "./transfer-timing.js";
|
|
@@ -50,6 +51,162 @@ export function mandatoryDenyPatterns(root) {
|
|
|
50
51
|
]),
|
|
51
52
|
];
|
|
52
53
|
}
|
|
54
|
+
/** The Mach services a restricted macOS command may look up for TLS trust ({@link macNetworkConfig}). */
|
|
55
|
+
const MAC_TLS_TRUST_SERVICES = Object.freeze(["com.apple.TrustEvaluationAgent"]);
|
|
56
|
+
/**
|
|
57
|
+
* The sandbox runtime's network configuration for one restricted grant (approval-only profiles
|
|
58
|
+
* design, "Open network"), and whether the worker answers the runtime's ask callback with allow.
|
|
59
|
+
*
|
|
60
|
+
* Both networks decide every connection on the resolved address in the operation's own proxy,
|
|
61
|
+
* which dials the address it checked (no second resolution: DNS rebinding cannot swap it).
|
|
62
|
+
* `deniedResolvedAddresses` is the SDK's whole closed set ({@link OPEN_PUBLIC_DENIED_CIDRS}:
|
|
63
|
+
* private, CGNAT, ULA, link-local, metadata, loopback, NAT64, multicast, reserved, embedded forms
|
|
64
|
+
* expanded); the runtime adds loopback, link-local, the cloud metadata endpoints and this host's
|
|
65
|
+
* own interface addresses itself. The patched runtime's `resolvedAddressStrict` judges an IP
|
|
66
|
+
* literal by the same rules (upstream skips literals), gives `localhost` no loopback carve-out and
|
|
67
|
+
* an allow-listed literal none over the closed classes: a private destination needs the
|
|
68
|
+
* escalation, never a host grant.
|
|
69
|
+
*
|
|
70
|
+
* - The allowlist (no `openNetwork`): exactly the grant's hosts, by the runtime's own matching.
|
|
71
|
+
* - The open network: no host list and an allow-all ask callback, so the address rules alone
|
|
72
|
+
* decide. The grant's hosts are not used.
|
|
73
|
+
*
|
|
74
|
+
* In both networks a name the system resolver answers with a fake-IP address
|
|
75
|
+
* ({@link SANDBOX_FAKE_IP_DNS}: 198.18.0.0/15, an OpenClash-style router) is re-resolved through
|
|
76
|
+
* DNS-over-HTTPS at the SDK's IP-literal endpoints (the patched runtime's `fakeIpDoh`; the SDK's
|
|
77
|
+
* timeout is the whole lookup, shared among the endpoints) and the real answer judged and dialed as
|
|
78
|
+
* above; when that lookup fails the connection is refused with a reason naming the fake-IP
|
|
79
|
+
* resolver, never dialed to the fake address.
|
|
80
|
+
*
|
|
81
|
+
* Listening stays refused (`allowLocalBinding: false`) under every profile: Seatbelt cannot limit a
|
|
82
|
+
* bind to loopback (spec "Known limitations"), and with it the command could reach every local
|
|
83
|
+
* port. `allowPrivate` is a trusted test seam (like the Linux forwarder's): it lifts the address
|
|
84
|
+
* rules so a fixture on loopback can be granted; nothing in production sets it.
|
|
85
|
+
*
|
|
86
|
+
* TLS trust needs one Mach service, `com.apple.TrustEvaluationAgent` (the per-user agent, not its
|
|
87
|
+
* `.system` sibling): Apple's LibreSSL in `/usr/bin/curl`, `/usr/bin/openssl` and the Command
|
|
88
|
+
* Line Tools' `python3` checks a chain against `/etc/ssl/cert.pem` (readable) and, when that
|
|
89
|
+
* bundle lacks the anchor (a newer root, such as example.com's SSL.com 2022 chain), asks this
|
|
90
|
+
* agent, which evaluates it against the system keychain and the admin's trust settings. Without
|
|
91
|
+
* it such a site fails with "unable to get local issuer certificate". The agent only evaluates
|
|
92
|
+
* the chain the client hands it: it fetched no issuer named in a certificate (checked on macOS
|
|
93
|
+
* 26 with a leaf whose AIA URL pointed at a local listener). `trustd` stays closed.
|
|
94
|
+
*/
|
|
95
|
+
export function macNetworkConfig(grant, options = {}) {
|
|
96
|
+
const closed = options.allowPrivate
|
|
97
|
+
? {}
|
|
98
|
+
: { deniedResolvedAddresses: [...OPEN_PUBLIC_DENIED_CIDRS], resolvedAddressStrict: true };
|
|
99
|
+
const doh = {
|
|
100
|
+
fakeIpDoh: { ...SANDBOX_FAKE_IP_DNS, endpoints: [...SANDBOX_FAKE_IP_DNS.endpoints] },
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
askAll: grant.openNetwork === true,
|
|
104
|
+
network: {
|
|
105
|
+
allowedDomains: grant.openNetwork ? [] : [...grant.hosts],
|
|
106
|
+
deniedDomains: [],
|
|
107
|
+
...closed,
|
|
108
|
+
...doh,
|
|
109
|
+
allowLocalBinding: false,
|
|
110
|
+
allowMachLookup: [...MAC_TLS_TRUST_SERVICES],
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Absolute write denies a restricted macOS operation gets besides each write root's policy:
|
|
116
|
+
*
|
|
117
|
+
* - `subtrees`, denied with everything beneath them: the system persistence paths
|
|
118
|
+
* ({@link SANDBOX_SYSTEM_WRITE_DENIES}: the crontab and at spools) in each spelling Seatbelt may
|
|
119
|
+
* see, and the final target of every protected location under `home` (the
|
|
120
|
+
* {@link SANDBOX_MANDATORY_WRITE_DENIES} entries: `~/Library/LaunchAgents`, `~/.config/systemd`,
|
|
121
|
+
* the shell startup files, …) reached through a symbolic link, and each
|
|
122
|
+
* {@link SANDBOX_HOME_WRITE_DENIES} entry (`~/bin`) always, with the target of its link;
|
|
123
|
+
* - `links`, denied exactly (the link itself cannot be removed, renamed or replaced): every
|
|
124
|
+
* symbolic link on the way to such a location. A dotfile manager links `~/.zshrc` to
|
|
125
|
+
* `~/code/dotfiles-current/zshrc`, and `dotfiles-current` may itself be a link inside a write
|
|
126
|
+
* root; swapping any hop for a real directory would redirect the protected location into
|
|
127
|
+
* writable space (SDK `sandbox-write-denies.ts`, constraint on consumers).
|
|
128
|
+
*
|
|
129
|
+
* Resolved at operation start: a link changed later is seen by the next operation. A hard link to
|
|
130
|
+
* a protected file that already exists inside a write root is not caught (it is the same file,
|
|
131
|
+
* under an ordinary name).
|
|
132
|
+
*/
|
|
133
|
+
export function macProtectedWriteDenies(home) {
|
|
134
|
+
const subtrees = new Set();
|
|
135
|
+
const links = new Set();
|
|
136
|
+
for (const path of SANDBOX_SYSTEM_WRITE_DENIES)
|
|
137
|
+
for (const spelling of macWriteRootSpellings(path))
|
|
138
|
+
subtrees.add(spelling);
|
|
139
|
+
const add = (location, always) => {
|
|
140
|
+
const chain = protectedChain(location);
|
|
141
|
+
if (always)
|
|
142
|
+
subtrees.add(location);
|
|
143
|
+
if (!always && !chain.links.length)
|
|
144
|
+
return;
|
|
145
|
+
subtrees.add(chain.target);
|
|
146
|
+
for (const link of chain.links) {
|
|
147
|
+
links.add(link);
|
|
148
|
+
// the link's location with its parent in on-disk form
|
|
149
|
+
links.add(join(onDisk(dirname(link)), basename(link)));
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
for (const entry of SANDBOX_MANDATORY_WRITE_DENIES)
|
|
153
|
+
add(join(home, ...entry), false);
|
|
154
|
+
// the home-anchored entries (`~/bin`) exist nowhere else in the policy: always denied here
|
|
155
|
+
for (const entry of SANDBOX_HOME_WRITE_DENIES)
|
|
156
|
+
add(join(home, ...entry), true);
|
|
157
|
+
return { subtrees: [...subtrees], links: [...links] };
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* {@link macProtectedWriteDenies} as ordered write rules the patched runtime appends after every
|
|
161
|
+
* other rule, so they decide last (over the per-root git allowlist too), case-insensitively: each
|
|
162
|
+
* subtree with everything beneath it, each link exactly, and the removal or move of any of their
|
|
163
|
+
* ancestors. Fails closed when a path cannot be
|
|
164
|
+
* expressed (a control character, or too long for a Seatbelt rule).
|
|
165
|
+
*/
|
|
166
|
+
function protectedWriteRules(denies) {
|
|
167
|
+
const rule = (path, beneath) => {
|
|
168
|
+
if ([...path].some((ch) => ch.codePointAt(0) < 0x20 || ch === "\u007f"))
|
|
169
|
+
throw new Error("A protected path with a control character cannot be expressed as a policy");
|
|
170
|
+
const regex = `^${ci(path)}${beneath ? "(/.*)?" : ""}$`;
|
|
171
|
+
if (regex.length > 1000)
|
|
172
|
+
throw new Error("A protected path is too long for the macOS policy");
|
|
173
|
+
return {
|
|
174
|
+
action: "deny",
|
|
175
|
+
operations: ["file-write*", "file-write-create", "file-write-unlink"],
|
|
176
|
+
regex,
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
// no ancestor of an anchored deny moves away (Seatbelt checks file-write-unlink on a rename's
|
|
180
|
+
// source, and on rmdir): moved, it would take the anchor with it and leave its path free
|
|
181
|
+
const ancestors = new Set();
|
|
182
|
+
for (const path of [...denies.subtrees, ...denies.links])
|
|
183
|
+
for (let up = dirname(path); up !== dirname(up); up = dirname(up))
|
|
184
|
+
ancestors.add(up);
|
|
185
|
+
return [
|
|
186
|
+
// a component starting with the reserved staging prefix (the Linux broker's staging and
|
|
187
|
+
// quarantine names; SDK `sandbox-write-denies.ts` rule 6), with everything beneath it, at any
|
|
188
|
+
// depth and in any case: nothing sandboxed creates, writes, removes or renames one
|
|
189
|
+
{
|
|
190
|
+
action: "deny",
|
|
191
|
+
operations: ["file-write*", "file-write-create", "file-write-unlink"],
|
|
192
|
+
regex: `^/(.*/)?${ci(SANDBOX_RESERVED_NAME_PREFIX)}[^/]*(/.*)?$`,
|
|
193
|
+
},
|
|
194
|
+
...denies.subtrees.map((path) => rule(path, true)),
|
|
195
|
+
...denies.links.map((path) => rule(path, false)),
|
|
196
|
+
...[...ancestors].map((path) => ({
|
|
197
|
+
...rule(path, false),
|
|
198
|
+
operations: ["file-write-unlink"],
|
|
199
|
+
})),
|
|
200
|
+
];
|
|
201
|
+
}
|
|
202
|
+
/** The environment of an escalated call: the device program's, minus every `CAPYBARA_` variable. */
|
|
203
|
+
export function escalatedEnvironment(env, own) {
|
|
204
|
+
const out = {};
|
|
205
|
+
for (const [key, value] of Object.entries(env))
|
|
206
|
+
if (value !== undefined && !/^CAPYBARA_/i.test(key))
|
|
207
|
+
out[key] = value;
|
|
208
|
+
return { ...out, ...own };
|
|
209
|
+
}
|
|
53
210
|
/**
|
|
54
211
|
* Removes empty git sequencer directories (`.git/sequencer`, and those of the gitdirs below
|
|
55
212
|
* `.git/modules`) under each write root, descriptor-relative and never following a link, after a
|
|
@@ -127,6 +284,9 @@ export const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-agent.jar
|
|
|
127
284
|
* Darwin answers a group signal with EPERM (not ESRCH) while the group holds only dead members
|
|
128
285
|
* (zombies not yet reaped, or processes exiting), so `signalGroup` counts EPERM as gone when a
|
|
129
286
|
* process snapshot shows no live member of the group; EPERM with a live member still fails.
|
|
287
|
+
* A runtime without the network patch (`resolvedAddressStrict`, `fakeIpDoh` in its schema) is
|
|
288
|
+
* refused before it starts: its proxy would skip the address rules, so the bind self-check fails
|
|
289
|
+
* and the device reports no restricted support (and so no open network).
|
|
130
290
|
*/
|
|
131
291
|
export const WORKER = `import {pathToFileURL} from 'node:url';
|
|
132
292
|
import {spawn,spawnSync} from 'node:child_process';
|
|
@@ -194,7 +354,7 @@ process.on('message',async message=>{try{
|
|
|
194
354
|
if(credit && credit.seq===message.seq){const pending=credit;credit=undefined;if(message.ok)pending.resolve();else{outputFailed=true;pending.reject(Error('Managed sink failed'));child?.stdout.resume();}}
|
|
195
355
|
}else if(message.type==='init'){
|
|
196
356
|
if(initialized)throw Error('Worker initialization is immutable');initialized=true;full=message.full;
|
|
197
|
-
if(!full){({SandboxManager:manager}=await import(pathToFileURL(message.runtime)));const deps=manager.checkDependencies();if(!manager.isSupportedPlatform()||deps.errors?.length)throw Error('Unsupported macOS sandbox runtime');await manager.initialize(message.config,undefined,false);}
|
|
357
|
+
if(!full){let schema;({SandboxManager:manager,NetworkConfigSchema:schema}=await import(pathToFileURL(message.runtime)));const net=message.config.network;if((net.resolvedAddressStrict||net.fakeIpDoh)&&!(schema?.shape?.resolvedAddressStrict&&schema?.shape?.fakeIpDoh))throw Error('The sandbox runtime lacks the network patch');const deps=manager.checkDependencies();if(!manager.isSupportedPlatform()||deps.errors?.length)throw Error('Unsupported macOS sandbox runtime');await manager.initialize(message.config,message.askAll?async()=>true:undefined,false);}
|
|
198
358
|
send({event:'ready',proxyUrl:full?'':'http://srt:'+manager.getProxyAuthToken()+'@127.0.0.1:'+manager.getProxyPort()});
|
|
199
359
|
}else if(message.type==='wrap'){
|
|
200
360
|
if(!initialized||wrapped)throw Error('One command per worker');wrapped=true;
|
|
@@ -374,6 +534,12 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
374
534
|
const preparedAt = performance.now();
|
|
375
535
|
const completion = (async () => {
|
|
376
536
|
try {
|
|
537
|
+
// only an escalated call (the device filesystem with the environment network) is unwrapped
|
|
538
|
+
if (request.grant.full &&
|
|
539
|
+
!("profile" in request.scope &&
|
|
540
|
+
request.scope.filesystem.kind === "device" &&
|
|
541
|
+
request.scope.network.kind === "environment"))
|
|
542
|
+
throw new SandboxScopeDeniedError("Only an escalated call (the device filesystem with the environment network) runs outside the sandbox");
|
|
377
543
|
// Restricted workers import only the sealed private copy of the verified runtime closure
|
|
378
544
|
// the binding attested; anything else is refused here, before anything is spawned.
|
|
379
545
|
if (!request.grant.full)
|
|
@@ -424,7 +590,8 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
424
590
|
// Version managers (asdf, nvm, pyenv, ...) read their data under the real home, while HOME
|
|
425
591
|
// is the working directory: this trusted process has the real home and the device's own
|
|
426
592
|
// environment (the forked worker runs with a reduced one), so it picks the variables and
|
|
427
|
-
// grants their directories read only.
|
|
593
|
+
// grants their directories read only. An escalated call inherits this process's environment
|
|
594
|
+
// minus every CAPYBARA_ variable (escalatedEnvironment).
|
|
428
595
|
const toolHomes = request.kind === "exec" && !request.grant.full
|
|
429
596
|
? restrictedToolHomes(request.toolHome?.home ?? homedir(), request.toolHome?.env ?? process.env, request.grant.deniedReadRoots)
|
|
430
597
|
: undefined;
|
|
@@ -499,6 +666,13 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
499
666
|
return firstMissing;
|
|
500
667
|
})
|
|
501
668
|
: [];
|
|
669
|
+
// the protected locations as they resolve now, and the system persistence paths
|
|
670
|
+
const protectedDenies = request.grant.full
|
|
671
|
+
? { subtrees: [], links: [] }
|
|
672
|
+
: macProtectedWriteDenies(request.toolHome?.home ?? homedir());
|
|
673
|
+
const network = macNetworkConfig(request.grant, {
|
|
674
|
+
allowPrivate: request.allowPrivateProxyTargets === true,
|
|
675
|
+
});
|
|
502
676
|
const config = {
|
|
503
677
|
filesystem: {
|
|
504
678
|
denyRead: ["/", ...request.grant.deniedReadRoots],
|
|
@@ -516,6 +690,9 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
516
690
|
// approved `cd ~`), and the runtime turns each deny into write, move and creation
|
|
517
691
|
// denies on the path and moves of its ancestors.
|
|
518
692
|
...withCanonicalForms(request.grant.deniedReadRoots),
|
|
693
|
+
// the subtrees only: a link given to the runtime would be resolved to its target
|
|
694
|
+
// (for `/var`, all of `/private/var`); links are exact regex rules below
|
|
695
|
+
...protectedDenies.subtrees,
|
|
519
696
|
// Per-root deny entries pin every ancestor against creation in SRT.
|
|
520
697
|
// The fixed helper has no rename API; retain global Git content denies
|
|
521
698
|
// while it establishes a missing root without those ancestor pins.
|
|
@@ -526,15 +703,14 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
526
703
|
],
|
|
527
704
|
// the shared policy exactly (case-insensitive, gitdir allowlist, HEAD rules), as
|
|
528
705
|
// ordered regex rules the patched runtime appends last (mac-write-policy.ts)
|
|
529
|
-
writeRegexRules:
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
deniedDomains: [],
|
|
536
|
-
allowLocalBinding: false,
|
|
706
|
+
writeRegexRules: [
|
|
707
|
+
...(establishmentRoots.length
|
|
708
|
+
? macWriteRegexRules("")
|
|
709
|
+
: writeRoots.flatMap((r) => macWriteRootSpellings(r).flatMap(macWriteRegexRules))),
|
|
710
|
+
...protectedWriteRules(protectedDenies),
|
|
711
|
+
],
|
|
537
712
|
},
|
|
713
|
+
network: network.network,
|
|
538
714
|
...(javaAgent ? { javaAgentJarPath: javaAgent } : {}),
|
|
539
715
|
};
|
|
540
716
|
const initialized = message(runtime, "ready");
|
|
@@ -543,6 +719,7 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
543
719
|
full: request.grant.full,
|
|
544
720
|
runtime: runtimeEntry,
|
|
545
721
|
config,
|
|
722
|
+
askAll: network.askAll,
|
|
546
723
|
});
|
|
547
724
|
const initializedInfo = await initialized;
|
|
548
725
|
// the worker has imported the runtime: the copy may be pruned from now on
|
|
@@ -628,7 +805,13 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
628
805
|
const exports = Object.entries(args.env ?? {})
|
|
629
806
|
.map(([key, value]) => `export ${key}=${shellQuote(value)}`)
|
|
630
807
|
.join("; ");
|
|
631
|
-
|
|
808
|
+
// The runtime's NO_PROXY sends loopback, link-local and the private ranges direct, where
|
|
809
|
+
// Seatbelt refuses the connect and the client prints only "Couldn't connect to server".
|
|
810
|
+
// Every one of them is closed here (no own listener exists: listening is refused), so a
|
|
811
|
+
// restricted command sends them to the operation's proxy, whose refusal names the reason.
|
|
812
|
+
// The call's own environment comes after, so a NO_PROXY it sets still applies.
|
|
813
|
+
const direct = request.grant.full ? "" : "unset NO_PROXY no_proxy; ";
|
|
814
|
+
const script = await wrap(`${temp}${direct}${!request.grant.full && exports ? `${exports}; ` : ""}exec /bin/bash -c ${shellQuote(args.command)}${request.managedOutput ? " 2>&1" : ""}`);
|
|
632
815
|
await request.beforeLaunch();
|
|
633
816
|
controller.signal.throwIfAborted();
|
|
634
817
|
const cap = new OutputCap(args.maxOutputBytes);
|
|
@@ -689,7 +872,7 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
689
872
|
type: "execute",
|
|
690
873
|
script,
|
|
691
874
|
cwd: args.cwd,
|
|
692
|
-
env: request.grant.full ?
|
|
875
|
+
env: request.grant.full ? escalatedEnvironment(process.env, args.env) : outerEnv,
|
|
693
876
|
timeoutMs: args.timeoutMs,
|
|
694
877
|
managed: request.managedOutput !== undefined,
|
|
695
878
|
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** `path` in on-disk form when it exists (case and Unicode normalization as stored). */
|
|
2
|
+
export declare function onDisk(path: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* How `path` resolves, one component at a time with `lstat` and `readlink`: every symbolic link
|
|
5
|
+
* met on the way (each link's own location, wherever in the chain it sits) and the final target
|
|
6
|
+
* (its existing part in on-disk form, the missing names appended). A dangling link is followed to
|
|
7
|
+
* the location it names. A link loop stops the walk; the links met so far are still returned.
|
|
8
|
+
*
|
|
9
|
+
* Shared by the device workers (macOS and Linux): each link and the target become anchored denies
|
|
10
|
+
* (the SDK `sandbox-write-denies.ts` constraint on consumers), so no hop of a dotfile manager's
|
|
11
|
+
* chain can be swapped for a real directory.
|
|
12
|
+
*/
|
|
13
|
+
export declare function protectedChain(path: string): {
|
|
14
|
+
links: string[];
|
|
15
|
+
target: string;
|
|
16
|
+
};
|