@bramvanoploo/sandbox-runtime 0.0.0-stage → 0.5.0
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 +201 -0
- package/README.md +93 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +285 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/sandbox/credential-decode.d.ts +87 -0
- package/dist/sandbox/credential-decode.d.ts.map +1 -0
- package/dist/sandbox/credential-decode.js +143 -0
- package/dist/sandbox/credential-decode.js.map +1 -0
- package/dist/sandbox/credential-extract.d.ts +67 -0
- package/dist/sandbox/credential-extract.d.ts.map +1 -0
- package/dist/sandbox/credential-extract.js +122 -0
- package/dist/sandbox/credential-extract.js.map +1 -0
- package/dist/sandbox/credential-mask-env.d.ts +33 -0
- package/dist/sandbox/credential-mask-env.d.ts.map +1 -0
- package/dist/sandbox/credential-mask-env.js +155 -0
- package/dist/sandbox/credential-mask-env.js.map +1 -0
- package/dist/sandbox/credential-mask-files.d.ts +120 -0
- package/dist/sandbox/credential-mask-files.d.ts.map +1 -0
- package/dist/sandbox/credential-mask-files.js +285 -0
- package/dist/sandbox/credential-mask-files.js.map +1 -0
- package/dist/sandbox/credential-sentinel.d.ts +88 -0
- package/dist/sandbox/credential-sentinel.d.ts.map +1 -0
- package/dist/sandbox/credential-sentinel.js +177 -0
- package/dist/sandbox/credential-sentinel.js.map +1 -0
- package/dist/sandbox/domain-pattern.d.ts +36 -0
- package/dist/sandbox/domain-pattern.d.ts.map +1 -0
- package/dist/sandbox/domain-pattern.js +60 -0
- package/dist/sandbox/domain-pattern.js.map +1 -0
- package/dist/sandbox/generate-seccomp-filter.d.ts +20 -0
- package/dist/sandbox/generate-seccomp-filter.d.ts.map +1 -0
- package/dist/sandbox/generate-seccomp-filter.js +168 -0
- package/dist/sandbox/generate-seccomp-filter.js.map +1 -0
- package/dist/sandbox/http-proxy.d.ts +85 -0
- package/dist/sandbox/http-proxy.d.ts.map +1 -0
- package/dist/sandbox/http-proxy.js +379 -0
- package/dist/sandbox/http-proxy.js.map +1 -0
- package/dist/sandbox/linux-sandbox-utils.d.ts +162 -0
- package/dist/sandbox/linux-sandbox-utils.d.ts.map +1 -0
- package/dist/sandbox/linux-sandbox-utils.js +1179 -0
- package/dist/sandbox/linux-sandbox-utils.js.map +1 -0
- package/dist/sandbox/linux-violation-monitor.d.ts +48 -0
- package/dist/sandbox/linux-violation-monitor.d.ts.map +1 -0
- package/dist/sandbox/linux-violation-monitor.js +168 -0
- package/dist/sandbox/linux-violation-monitor.js.map +1 -0
- package/dist/sandbox/listen-in-range.d.ts +12 -0
- package/dist/sandbox/listen-in-range.d.ts.map +1 -0
- package/dist/sandbox/listen-in-range.js +43 -0
- package/dist/sandbox/listen-in-range.js.map +1 -0
- package/dist/sandbox/macos-sandbox-utils.d.ts +57 -0
- package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
- package/dist/sandbox/macos-sandbox-utils.js +810 -0
- package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
- package/dist/sandbox/mitm-ca.d.ts +112 -0
- package/dist/sandbox/mitm-ca.d.ts.map +1 -0
- package/dist/sandbox/mitm-ca.js +380 -0
- package/dist/sandbox/mitm-ca.js.map +1 -0
- package/dist/sandbox/mitm-leaf.d.ts +28 -0
- package/dist/sandbox/mitm-leaf.d.ts.map +1 -0
- package/dist/sandbox/mitm-leaf.js +132 -0
- package/dist/sandbox/mitm-leaf.js.map +1 -0
- package/dist/sandbox/mux-proxy.d.ts +59 -0
- package/dist/sandbox/mux-proxy.d.ts.map +1 -0
- package/dist/sandbox/mux-proxy.js +161 -0
- package/dist/sandbox/mux-proxy.js.map +1 -0
- package/dist/sandbox/parent-proxy.d.ts +118 -0
- package/dist/sandbox/parent-proxy.d.ts.map +1 -0
- package/dist/sandbox/parent-proxy.js +469 -0
- package/dist/sandbox/parent-proxy.js.map +1 -0
- package/dist/sandbox/request-filter.d.ts +56 -0
- package/dist/sandbox/request-filter.d.ts.map +1 -0
- package/dist/sandbox/request-filter.js +109 -0
- package/dist/sandbox/request-filter.js.map +1 -0
- package/dist/sandbox/sandbox-config.d.ts +1347 -0
- package/dist/sandbox/sandbox-config.d.ts.map +1 -0
- package/dist/sandbox/sandbox-config.js +917 -0
- package/dist/sandbox/sandbox-config.js.map +1 -0
- package/dist/sandbox/sandbox-manager.d.ts +48 -0
- package/dist/sandbox/sandbox-manager.d.ts.map +1 -0
- package/dist/sandbox/sandbox-manager.js +1498 -0
- package/dist/sandbox/sandbox-manager.js.map +1 -0
- package/dist/sandbox/sandbox-schemas.d.ts +90 -0
- package/dist/sandbox/sandbox-schemas.d.ts.map +1 -0
- package/dist/sandbox/sandbox-schemas.js +3 -0
- package/dist/sandbox/sandbox-schemas.js.map +1 -0
- package/dist/sandbox/sandbox-temp-dir.d.ts +9 -0
- package/dist/sandbox/sandbox-temp-dir.d.ts.map +1 -0
- package/dist/sandbox/sandbox-temp-dir.js +73 -0
- package/dist/sandbox/sandbox-temp-dir.js.map +1 -0
- package/dist/sandbox/sandbox-utils.d.ts +121 -0
- package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
- package/dist/sandbox/sandbox-utils.js +642 -0
- package/dist/sandbox/sandbox-utils.js.map +1 -0
- package/dist/sandbox/sandbox-violation-store.d.ts +19 -0
- package/dist/sandbox/sandbox-violation-store.d.ts.map +1 -0
- package/dist/sandbox/sandbox-violation-store.js +57 -0
- package/dist/sandbox/sandbox-violation-store.js.map +1 -0
- package/dist/sandbox/socks-proxy.d.ts +38 -0
- package/dist/sandbox/socks-proxy.d.ts.map +1 -0
- package/dist/sandbox/socks-proxy.js +123 -0
- package/dist/sandbox/socks-proxy.js.map +1 -0
- package/dist/sandbox/tls-terminate-proxy.d.ts +63 -0
- package/dist/sandbox/tls-terminate-proxy.d.ts.map +1 -0
- package/dist/sandbox/tls-terminate-proxy.js +332 -0
- package/dist/sandbox/tls-terminate-proxy.js.map +1 -0
- package/dist/sandbox/windows-sandbox-utils.d.ts +625 -0
- package/dist/sandbox/windows-sandbox-utils.d.ts.map +1 -0
- package/dist/sandbox/windows-sandbox-utils.js +982 -0
- package/dist/sandbox/windows-sandbox-utils.js.map +1 -0
- package/dist/utils/config-loader.d.ts +24 -0
- package/dist/utils/config-loader.d.ts.map +1 -0
- package/dist/utils/config-loader.js +65 -0
- package/dist/utils/config-loader.js.map +1 -0
- package/dist/utils/debug.d.ts +7 -0
- package/dist/utils/debug.d.ts.map +1 -0
- package/dist/utils/debug.js +25 -0
- package/dist/utils/debug.js.map +1 -0
- package/dist/utils/platform.d.ts +15 -0
- package/dist/utils/platform.d.ts.map +1 -0
- package/dist/utils/platform.js +52 -0
- package/dist/utils/platform.js.map +1 -0
- package/dist/utils/shell-quote.d.ts +27 -0
- package/dist/utils/shell-quote.d.ts.map +1 -0
- package/dist/utils/shell-quote.js +47 -0
- package/dist/utils/shell-quote.js.map +1 -0
- package/dist/utils/which.d.ts +9 -0
- package/dist/utils/which.d.ts.map +1 -0
- package/dist/utils/which.js +28 -0
- package/dist/utils/which.js.map +1 -0
- package/package.json +85 -4
- package/vendor/seccomp/x64/apply-seccomp +0 -0
|
@@ -0,0 +1,1498 @@
|
|
|
1
|
+
import { createHttpProxyServer } from './http-proxy.js';
|
|
2
|
+
import { createSocksProxyServer } from './socks-proxy.js';
|
|
3
|
+
import { createMuxProxyServer } from './mux-proxy.js';
|
|
4
|
+
import { listenInRange } from './listen-in-range.js';
|
|
5
|
+
import { SentinelRegistry } from './credential-sentinel.js';
|
|
6
|
+
import { MaskedFileStore, buildMaskedFileBinds, } from './credential-mask-files.js';
|
|
7
|
+
import { buildMaskedEnvVars } from './credential-mask-env.js';
|
|
8
|
+
import { createMitmCA, CRL_PATH, disposeMitmCASync, } from './mitm-ca.js';
|
|
9
|
+
import { logForDebugging } from '../utils/debug.js';
|
|
10
|
+
import { getPlatform, getWslVersion } from '../utils/platform.js';
|
|
11
|
+
import * as fs from 'fs';
|
|
12
|
+
import { randomBytes, X509Certificate } from 'node:crypto';
|
|
13
|
+
import { wrapCommandWithSandboxLinux, initializeLinuxNetworkBridge, checkLinuxDependencies, cleanupBwrapMountPoints, } from './linux-sandbox-utils.js';
|
|
14
|
+
import { wrapCommandWithSandboxMacOS, startMacOSSandboxLogMonitor, } from './macos-sandbox-utils.js';
|
|
15
|
+
import { startLinuxSandboxViolationMonitor, } from './linux-violation-monitor.js';
|
|
16
|
+
import { checkWindowsDependencies, wrapCommandWithSandboxWindows, parseWindowsBinShell, expandWindowsFsPaths, stampWindowsAcl, restoreWindowsAcl, grantWindowsAcl, revokeWindowsAcl, getWindowsSandboxUserStatus, getWindowsSandboxCaCert, verifyWindowsWfpEgress, resolveSrtWin, DEFAULT_WINDOWS_PROXY_PORT_RANGE, } from './windows-sandbox-utils.js';
|
|
17
|
+
import { getDefaultWritePaths, containsGlobChars, removeTrailingGlobSuffix, expandGlobPattern, normalizePathForSandbox, } from './sandbox-utils.js';
|
|
18
|
+
import { SandboxViolationStore } from './sandbox-violation-store.js';
|
|
19
|
+
import { ensureSandboxTempDirectory, resolveSandboxTmpdir, } from './sandbox-temp-dir.js';
|
|
20
|
+
import { canonicalizeHost, isValidHost, redactUrl, resolveParentProxy, } from './parent-proxy.js';
|
|
21
|
+
import { matchesDomainPattern } from './domain-pattern.js';
|
|
22
|
+
import { EOL } from 'node:os';
|
|
23
|
+
import { dirname } from 'node:path';
|
|
24
|
+
const cleanupHandlers = new Map();
|
|
25
|
+
function cleanupManagers(signal) {
|
|
26
|
+
const pending = runCleanupHandlers([...cleanupHandlers.keys()]);
|
|
27
|
+
if (signal) {
|
|
28
|
+
void Promise.allSettled(pending).then(() => {
|
|
29
|
+
if (process.listenerCount(signal) === 0) {
|
|
30
|
+
process.kill(process.pid, signal);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function cleanupManagersOnExit() {
|
|
36
|
+
// Exit handlers cannot await initialization before releasing resources.
|
|
37
|
+
void runCleanupHandlers([...cleanupHandlers.values()]);
|
|
38
|
+
}
|
|
39
|
+
function runCleanupHandlers(handlers) {
|
|
40
|
+
return handlers.map(cleanup => cleanup().catch(error => {
|
|
41
|
+
logForDebugging(`Sandbox cleanup failed: ${error}`, { level: 'error' });
|
|
42
|
+
}));
|
|
43
|
+
}
|
|
44
|
+
function registerCleanup(cleanup, cleanupOnExit) {
|
|
45
|
+
if (cleanupHandlers.size === 0) {
|
|
46
|
+
process.once('exit', cleanupManagersOnExit);
|
|
47
|
+
process.once('SIGINT', cleanupManagers);
|
|
48
|
+
process.once('SIGTERM', cleanupManagers);
|
|
49
|
+
}
|
|
50
|
+
cleanupHandlers.set(cleanup, cleanupOnExit);
|
|
51
|
+
}
|
|
52
|
+
function unregisterCleanup(cleanup) {
|
|
53
|
+
cleanupHandlers.delete(cleanup);
|
|
54
|
+
if (cleanupHandlers.size === 0) {
|
|
55
|
+
process.removeListener('exit', cleanupManagersOnExit);
|
|
56
|
+
process.removeListener('SIGINT', cleanupManagers);
|
|
57
|
+
process.removeListener('SIGTERM', cleanupManagers);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function createManager(legacySingleton) {
|
|
61
|
+
// ============================================================================
|
|
62
|
+
// Private Session State
|
|
63
|
+
// ============================================================================
|
|
64
|
+
let config;
|
|
65
|
+
let httpProxyServer;
|
|
66
|
+
let socksProxyServer;
|
|
67
|
+
let muxProxyServer;
|
|
68
|
+
let managerContext;
|
|
69
|
+
let initializationPromise;
|
|
70
|
+
let resetPromise;
|
|
71
|
+
let logMonitorShutdown;
|
|
72
|
+
let linuxMonitor;
|
|
73
|
+
let parentProxy;
|
|
74
|
+
let mitmCA;
|
|
75
|
+
const macosSessionSuffix = `_${Math.random().toString(36).slice(2, 11)}_SBX`;
|
|
76
|
+
// Per-session proxy auth token. Generated at proxy start, exported only into
|
|
77
|
+
// the sandbox child env, checked on every CONNECT/request — so a host process
|
|
78
|
+
// dialing 127.0.0.1:<proxyPort> can't reach the filter callback.
|
|
79
|
+
let proxyAuthToken;
|
|
80
|
+
// Windows: the resolved access set that was actually applied at
|
|
81
|
+
// initialize(). `undefined` means no stamp/grant was applied
|
|
82
|
+
// (gates running `acl restore`/`acl revoke` at reset()).
|
|
83
|
+
let windowsFsStampedSet;
|
|
84
|
+
// The sandbox user SID captured at initialize(). reset() uses this
|
|
85
|
+
// so a config change between init and reset can't strand ACEs
|
|
86
|
+
// under a different SID.
|
|
87
|
+
let windowsFsSbUserSid;
|
|
88
|
+
// The RAW config inputs that produced `windowsFsStampedSet`.
|
|
89
|
+
// updateConfig() compares these (not the resolved set) so it never
|
|
90
|
+
// re-expands globs — see `sameWindowsStampSet`.
|
|
91
|
+
let windowsFsRawInputs;
|
|
92
|
+
// `verifyWindowsWfpEgress()` is once per PROCESS (it spawns a
|
|
93
|
+
// CreateProcessWithLogonW runner; first call may create the sandbox
|
|
94
|
+
// user's profile). The WFP fence is install-scoped, not config- or
|
|
95
|
+
// session-scoped — reset() does NOT clear this, so updateConfig()'s
|
|
96
|
+
// reset+reinit and the test suite's per-test reset() don't re-verify.
|
|
97
|
+
let windowsWfpVerified = false;
|
|
98
|
+
// Resolved once at initialize() (`resolveSrtWin` stats the disk).
|
|
99
|
+
// Captured so wrapWithSandboxArgv/reset() don't re-resolve per call
|
|
100
|
+
// and so reset()'s revoke/restore addresses the SAME binary the
|
|
101
|
+
// grants/stamps were applied with even if `config` mutated between.
|
|
102
|
+
let srtWinSpawn;
|
|
103
|
+
const sandboxViolationStore = new SandboxViolationStore();
|
|
104
|
+
// Per-session sentinel↔real-value map for masked credentials. Lives only in
|
|
105
|
+
// process memory; never written to disk or logged. Cleared on reset().
|
|
106
|
+
const sentinelRegistry = new SentinelRegistry();
|
|
107
|
+
// Temp dir holding the sentinel-content fake files for masked credential
|
|
108
|
+
// files. Created lazily on first masked file; removed on reset().
|
|
109
|
+
const maskedFileStore = new MaskedFileStore();
|
|
110
|
+
// ============================================================================
|
|
111
|
+
// Private Helper Functions (not exported)
|
|
112
|
+
// ============================================================================
|
|
113
|
+
async function filterNetworkRequest(port, host, sandboxAskCallback) {
|
|
114
|
+
if (!config) {
|
|
115
|
+
logForDebugging('No config available, denying network request');
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
// Reject hosts containing control characters before pattern matching.
|
|
119
|
+
// `matchesDomainPattern` uses string suffix matching which is trivially
|
|
120
|
+
// fooled by e.g. `evil.com\x00.allowed.com` — the null byte passes
|
|
121
|
+
// `.endsWith()` but truncates at the libc DNS layer. The SOCKS path is the
|
|
122
|
+
// main exposure (DOMAINNAME is unvalidated bytes); HTTP is protected by
|
|
123
|
+
// llhttp/URL parsing, but we check here for defence in depth.
|
|
124
|
+
if (!isValidHost(host)) {
|
|
125
|
+
logForDebugging(`Denying malformed host: ${JSON.stringify(host)}:${port}`, {
|
|
126
|
+
level: 'error',
|
|
127
|
+
});
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
// Canonicalize so string comparisons match what getaddrinfo() will dial.
|
|
131
|
+
// Without this, inet_aton shorthand like `2852039166` (= 169.254.169.254)
|
|
132
|
+
// or `127.1` slips past a denylist entry for the dotted-decimal form.
|
|
133
|
+
const canonicalHost = canonicalizeHost(host) ?? host;
|
|
134
|
+
// Check denied domains first
|
|
135
|
+
for (const deniedDomain of config.network.deniedDomains) {
|
|
136
|
+
if (matchesDomainPattern(canonicalHost, deniedDomain)) {
|
|
137
|
+
logForDebugging(`Denied by config rule: ${host}:${port}`);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// Check allowed domains
|
|
142
|
+
for (const allowedDomain of config.network.allowedDomains) {
|
|
143
|
+
if (matchesDomainPattern(canonicalHost, allowedDomain)) {
|
|
144
|
+
logForDebugging(`Allowed by config rule: ${host}:${port}`);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// No matching rules - ask user or deny. strictAllowlist makes the
|
|
149
|
+
// allowlist deterministic enforcement: never fall through to the callback.
|
|
150
|
+
if (!sandboxAskCallback || config.network.strictAllowlist) {
|
|
151
|
+
logForDebugging(`No matching config rule, denying: ${host}:${port}`);
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
logForDebugging(`No matching config rule, asking user: ${canonicalHost}:${port}`);
|
|
155
|
+
try {
|
|
156
|
+
const userAllowed = await sandboxAskCallback({
|
|
157
|
+
host: canonicalHost,
|
|
158
|
+
port,
|
|
159
|
+
});
|
|
160
|
+
if (userAllowed) {
|
|
161
|
+
logForDebugging(`User allowed: ${host}:${port}`);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
logForDebugging(`User denied: ${host}:${port}`);
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
logForDebugging(`Error in permission callback: ${error}`, {
|
|
171
|
+
level: 'error',
|
|
172
|
+
});
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Get the MITM proxy socket path for a given host, if configured.
|
|
178
|
+
* Returns the socket path if the host matches any MITM domain pattern,
|
|
179
|
+
* otherwise returns undefined.
|
|
180
|
+
*/
|
|
181
|
+
/**
|
|
182
|
+
* Build the header-mutation callback that substitutes sentinel→real for
|
|
183
|
+
* masked credentials. Returns undefined when no `credentials` block is
|
|
184
|
+
* configured — wiring the seam at all is unnecessary then.
|
|
185
|
+
*
|
|
186
|
+
* Per-host gating happens inside the registry: each sentinel carries its
|
|
187
|
+
* own injectHosts list and substitutes independently, so credential A's
|
|
188
|
+
* sentinel cannot be laundered through credential B's allowed host. The
|
|
189
|
+
* returned closure does not log header values; the registry holds the only
|
|
190
|
+
* copy of the real value.
|
|
191
|
+
*/
|
|
192
|
+
function buildCredentialInjector() {
|
|
193
|
+
if (!config?.credentials)
|
|
194
|
+
return undefined;
|
|
195
|
+
return (headers, destHost) => {
|
|
196
|
+
sentinelRegistry.substituteInHeaders(headers, destHost, matchesDomainPattern);
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function getMitmSocketPath(host) {
|
|
200
|
+
if (!config?.network.mitmProxy) {
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
const { socketPath, domains } = config.network.mitmProxy;
|
|
204
|
+
const canonical = canonicalizeHost(host) ?? host;
|
|
205
|
+
for (const pattern of domains) {
|
|
206
|
+
if (matchesDomainPattern(canonical, pattern)) {
|
|
207
|
+
logForDebugging(`Host ${canonical} matches MITM pattern ${pattern}`);
|
|
208
|
+
return socketPath;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Per-host TLS-termination opt-out from network.tlsTerminate.excludeDomains.
|
|
215
|
+
* Only consulted by the HTTP proxy when tlsTerminate is enabled; exempted
|
|
216
|
+
* hosts fall back to the opaque CONNECT tunnel (still allowlist-filtered),
|
|
217
|
+
* so mTLS / cert-pinning clients can complete their own handshake.
|
|
218
|
+
*
|
|
219
|
+
* Matches the canonicalized hostname, like the allow/deny filter
|
|
220
|
+
* (filterNetworkRequest) — otherwise a spelling the allowlist accepts after
|
|
221
|
+
* canonicalization (`127.1`, a trailing-dot FQDN) would dodge the exclusion
|
|
222
|
+
* and get terminated anyway.
|
|
223
|
+
*/
|
|
224
|
+
function shouldTerminateTLSForHost(host) {
|
|
225
|
+
const excludeDomains = config?.network.tlsTerminate?.excludeDomains;
|
|
226
|
+
if (!excludeDomains?.length)
|
|
227
|
+
return true;
|
|
228
|
+
const canonicalHost = canonicalizeHost(host) ?? host;
|
|
229
|
+
for (const pattern of excludeDomains) {
|
|
230
|
+
if (!matchesDomainPattern(canonicalHost, pattern))
|
|
231
|
+
continue;
|
|
232
|
+
logForDebugging(`Host ${host} matches tlsTerminate.excludeDomains pattern ${pattern}; skipping TLS termination`);
|
|
233
|
+
// Masked-credential substitution only happens on the terminated path,
|
|
234
|
+
// so a credential whose injectHosts cover this host can never be
|
|
235
|
+
// injected here — the upstream gets the placeholder. Config validation
|
|
236
|
+
// rejects the fully-contradictory spellings; this flags the partial
|
|
237
|
+
// ones (e.g. default injectHosts = allowedDomains) at the moment they
|
|
238
|
+
// actually bite.
|
|
239
|
+
const masked = sentinelRegistry.namesInjectableAt(canonicalHost, matchesDomainPattern);
|
|
240
|
+
if (masked.length > 0) {
|
|
241
|
+
logForDebugging(`tlsTerminate.excludeDomains: masked credential(s) ${masked.join(', ')} ` +
|
|
242
|
+
`are configured for injection at ${host}, but its connections are ` +
|
|
243
|
+
`not terminated, so the upstream will receive the placeholder`, { level: 'error' });
|
|
244
|
+
}
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
async function startMuxProxyServer(sandboxAskCallback, portRange) {
|
|
250
|
+
httpProxyServer = createHttpProxyServer({
|
|
251
|
+
filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback),
|
|
252
|
+
getMitmSocketPath,
|
|
253
|
+
mitmCA,
|
|
254
|
+
shouldTerminateTLS: shouldTerminateTLSForHost,
|
|
255
|
+
getFilterRequest: () => config?.network.filterRequest,
|
|
256
|
+
// TLS-terminated path always gets the injector; the plain-HTTP path
|
|
257
|
+
// only when explicitly opted in. Without the opt-in, a sentinel sent
|
|
258
|
+
// over plain HTTP reaches the upstream unchanged (fails closed).
|
|
259
|
+
getMutateHeaders: () => buildCredentialInjector(),
|
|
260
|
+
getMutateHeadersPlaintext: () => config?.credentials?.allowPlaintextInject
|
|
261
|
+
? buildCredentialInjector()
|
|
262
|
+
: undefined,
|
|
263
|
+
parentProxy,
|
|
264
|
+
proxyAuthToken,
|
|
265
|
+
});
|
|
266
|
+
socksProxyServer = createSocksProxyServer({
|
|
267
|
+
filter: (port, host) => filterNetworkRequest(port, host, sandboxAskCallback),
|
|
268
|
+
parentProxy,
|
|
269
|
+
proxyAuthToken: config?.network.allowUnauthenticatedSocksProxy
|
|
270
|
+
? undefined
|
|
271
|
+
: proxyAuthToken,
|
|
272
|
+
isBlocked: () => Boolean(config?.network.filterRequest),
|
|
273
|
+
});
|
|
274
|
+
muxProxyServer = createMuxProxyServer({
|
|
275
|
+
httpServer: httpProxyServer,
|
|
276
|
+
handleSocksConnection: s => socksProxyServer.handleConnection(s),
|
|
277
|
+
httpBackendPortRange: portRange,
|
|
278
|
+
});
|
|
279
|
+
const mux = muxProxyServer;
|
|
280
|
+
// Backend first so the front-end never accepts a connection that would
|
|
281
|
+
// dispatch to an unbound backend. On Windows the backend's port is
|
|
282
|
+
// excluded when binding the front-end in the same WFP range.
|
|
283
|
+
const backendPort = await mux.listenHttpBackend();
|
|
284
|
+
await listenInRange(mux.server, p => mux.server.listen(p, '127.0.0.1'), portRange, backendPort !== undefined ? new Set([backendPort]) : new Set());
|
|
285
|
+
const muxPort = mux.getPort();
|
|
286
|
+
if (muxPort === undefined) {
|
|
287
|
+
throw new Error('Failed to get mux proxy server port');
|
|
288
|
+
}
|
|
289
|
+
mux.unref();
|
|
290
|
+
logForDebugging(`Mux proxy (HTTP+SOCKS) listening on localhost:${muxPort}`);
|
|
291
|
+
return muxPort;
|
|
292
|
+
}
|
|
293
|
+
// ============================================================================
|
|
294
|
+
// Public Module Functions (will be exported via namespace)
|
|
295
|
+
// ============================================================================
|
|
296
|
+
async function initialize(runtimeConfig, sandboxAskCallback, enableLogMonitor = false) {
|
|
297
|
+
if (!legacySingleton && getPlatform() === 'windows') {
|
|
298
|
+
throw new Error('Independent sandbox managers are supported on macOS and Linux only. Use SandboxManager on Windows.');
|
|
299
|
+
}
|
|
300
|
+
if (resetPromise)
|
|
301
|
+
await resetPromise;
|
|
302
|
+
// Return if already initializing
|
|
303
|
+
if (initializationPromise) {
|
|
304
|
+
await initializationPromise;
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
initializationPromise = (async () => {
|
|
308
|
+
try {
|
|
309
|
+
config = runtimeConfig;
|
|
310
|
+
parentProxy = resolveParentProxy(runtimeConfig.network.parentProxy);
|
|
311
|
+
if (parentProxy) {
|
|
312
|
+
logForDebugging(`Parent proxy configured: http=${redactUrl(parentProxy.httpUrl)} ` +
|
|
313
|
+
`https=${redactUrl(parentProxy.httpsUrl)}`);
|
|
314
|
+
}
|
|
315
|
+
if (runtimeConfig.network.tlsTerminate &&
|
|
316
|
+
runtimeConfig.network.mitmProxy) {
|
|
317
|
+
throw new Error('network.tlsTerminate and network.mitmProxy are mutually exclusive');
|
|
318
|
+
}
|
|
319
|
+
mitmCA = runtimeConfig.network.tlsTerminate
|
|
320
|
+
? createMitmCA(runtimeConfig.network.tlsTerminate)
|
|
321
|
+
: undefined;
|
|
322
|
+
const deps = checkDependencies();
|
|
323
|
+
if (deps.errors.length > 0) {
|
|
324
|
+
throw new Error(`Sandbox dependencies not available: ${deps.errors.join(', ')}`);
|
|
325
|
+
}
|
|
326
|
+
if (enableLogMonitor && getPlatform() === 'macos') {
|
|
327
|
+
logMonitorShutdown = startMacOSSandboxLogMonitor(sandboxViolationStore.addViolation.bind(sandboxViolationStore), config.ignoreViolations, macosSessionSuffix);
|
|
328
|
+
logForDebugging('Started macOS sandbox log monitor');
|
|
329
|
+
}
|
|
330
|
+
if (enableLogMonitor && getPlatform() === 'linux') {
|
|
331
|
+
linuxMonitor = startLinuxSandboxViolationMonitor(sandboxViolationStore.addViolation.bind(sandboxViolationStore), {
|
|
332
|
+
allowWritePaths: [
|
|
333
|
+
...getDefaultWritePaths(),
|
|
334
|
+
...config.filesystem.allowWrite,
|
|
335
|
+
],
|
|
336
|
+
denyWritePaths: config.filesystem.denyWrite,
|
|
337
|
+
ignoreViolations: config.ignoreViolations,
|
|
338
|
+
});
|
|
339
|
+
await linuxMonitor.ready;
|
|
340
|
+
logForDebugging('Started Linux seccomp violation monitor');
|
|
341
|
+
}
|
|
342
|
+
registerCleanup(reset, resetSession);
|
|
343
|
+
if (getPlatform() === 'windows') {
|
|
344
|
+
srtWinSpawn = resolveSrtWin(runtimeConfig.windows?.srtWin);
|
|
345
|
+
const srtWin = srtWinSpawn;
|
|
346
|
+
const u = getWindowsSandboxUserStatus({ srtWin });
|
|
347
|
+
if (!u.provisioned || !u.credPresent) {
|
|
348
|
+
throw new Error(`Windows sandbox user is not provisioned (user=` +
|
|
349
|
+
`${u.provisioned}, cred=${u.credPresent}). Run \`npx ` +
|
|
350
|
+
`sandbox-runtime windows-install\` (one UAC prompt) to ` +
|
|
351
|
+
`provision it.`);
|
|
352
|
+
}
|
|
353
|
+
if (!windowsWfpVerified) {
|
|
354
|
+
await verifyWindowsWfpEgress({
|
|
355
|
+
proxyPortRange: runtimeConfig.windows?.proxyPortRange,
|
|
356
|
+
srtWin,
|
|
357
|
+
});
|
|
358
|
+
windowsWfpVerified = true;
|
|
359
|
+
}
|
|
360
|
+
if (runtimeConfig.network.tlsTerminate && mitmCA) {
|
|
361
|
+
const installed = getWindowsSandboxCaCert(u);
|
|
362
|
+
const sessionThumb = new X509Certificate(mitmCA.certPem).fingerprint
|
|
363
|
+
.replace(/:/g, '')
|
|
364
|
+
.toUpperCase();
|
|
365
|
+
if (!installed) {
|
|
366
|
+
throw new Error(`tlsTerminate on Windows requires the sandbox to be ` +
|
|
367
|
+
`installed with this CA (thumb=${sessionThumb}): run ` +
|
|
368
|
+
`\`srt-win user trust-ca ${mitmCA.certPath}\`. Per-exec ` +
|
|
369
|
+
`installs into the sandbox user's Root store are not ` +
|
|
370
|
+
`supported.`);
|
|
371
|
+
}
|
|
372
|
+
if (installed.thumb !== sessionThumb) {
|
|
373
|
+
throw new Error(`tlsTerminate on Windows: the sandbox's installed CA ` +
|
|
374
|
+
`(thumb=${installed.thumb}) doesn't match this ` +
|
|
375
|
+
`session's CA (thumb=${sessionThumb}). Run \`srt-win ` +
|
|
376
|
+
`user trust-ca ${mitmCA.certPath}\` to update it.`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
const acc = computeWindowsFsAccessSet(runtimeConfig);
|
|
380
|
+
if (mitmCA) {
|
|
381
|
+
acc.grantRead.push(dirname(mitmCA.trustBundlePath));
|
|
382
|
+
acc.denyRead.push(mitmCA.keyPath);
|
|
383
|
+
}
|
|
384
|
+
if (!u.sid) {
|
|
385
|
+
throw new Error('sandbox user SID missing from `srt-win user status` ' +
|
|
386
|
+
'(provisioned but in an inconsistent state)');
|
|
387
|
+
}
|
|
388
|
+
const sb = u.sid;
|
|
389
|
+
windowsFsSbUserSid = sb;
|
|
390
|
+
if (acc.grantRead.length > 0 || acc.grantWrite.length > 0) {
|
|
391
|
+
grantWindowsAcl({
|
|
392
|
+
sandboxUserSid: sb,
|
|
393
|
+
read: acc.grantRead,
|
|
394
|
+
write: acc.grantWrite,
|
|
395
|
+
srtWin,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
if (acc.denyRead.length > 0 || acc.denyWrite.length > 0) {
|
|
399
|
+
stampWindowsAcl({
|
|
400
|
+
sandboxUserSid: sb,
|
|
401
|
+
denyRead: acc.denyRead,
|
|
402
|
+
denyWrite: acc.denyWrite,
|
|
403
|
+
srtWin,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
const anyApplied = acc.grantRead.length > 0 ||
|
|
407
|
+
acc.grantWrite.length > 0 ||
|
|
408
|
+
acc.denyRead.length > 0 ||
|
|
409
|
+
acc.denyWrite.length > 0;
|
|
410
|
+
if (anyApplied) {
|
|
411
|
+
windowsFsStampedSet = acc;
|
|
412
|
+
logForDebugging(`[Sandbox Windows] fs applied: ` +
|
|
413
|
+
`${acc.grantWrite.length} grantWrite, ` +
|
|
414
|
+
`${acc.grantRead.length} grantRead, ` +
|
|
415
|
+
`${acc.denyRead.length} denyRead, ` +
|
|
416
|
+
`${acc.denyWrite.length} denyWrite`);
|
|
417
|
+
}
|
|
418
|
+
windowsFsRawInputs = rawWindowsFsInputs(runtimeConfig);
|
|
419
|
+
}
|
|
420
|
+
const portRange = getPlatform() === 'windows'
|
|
421
|
+
? (config.windows?.proxyPortRange ??
|
|
422
|
+
DEFAULT_WINDOWS_PROXY_PORT_RANGE)
|
|
423
|
+
: undefined;
|
|
424
|
+
proxyAuthToken =
|
|
425
|
+
config.network.httpProxyPort !== undefined
|
|
426
|
+
? undefined
|
|
427
|
+
: randomBytes(16).toString('hex');
|
|
428
|
+
const needLocalProxy = config.network.httpProxyPort === undefined ||
|
|
429
|
+
config.network.socksProxyPort === undefined;
|
|
430
|
+
const muxPort = needLocalProxy
|
|
431
|
+
? await startMuxProxyServer(sandboxAskCallback, portRange)
|
|
432
|
+
: undefined;
|
|
433
|
+
const httpProxyPort = config.network.httpProxyPort ?? muxPort;
|
|
434
|
+
const socksProxyPort = config.network.socksProxyPort ?? muxPort;
|
|
435
|
+
if (mitmCA && muxPort !== undefined && getPlatform() === 'windows') {
|
|
436
|
+
mitmCA.crlUrl = `http://127.0.0.1:${muxPort}${CRL_PATH}`;
|
|
437
|
+
}
|
|
438
|
+
if (config.network.httpProxyPort !== undefined) {
|
|
439
|
+
logForDebugging(`Using external HTTP proxy on port ${httpProxyPort}`);
|
|
440
|
+
}
|
|
441
|
+
if (config.network.socksProxyPort !== undefined) {
|
|
442
|
+
logForDebugging(`Using external SOCKS proxy on port ${socksProxyPort}`);
|
|
443
|
+
}
|
|
444
|
+
let linuxBridge;
|
|
445
|
+
if (getPlatform() === 'linux') {
|
|
446
|
+
linuxBridge = await initializeLinuxNetworkBridge(httpProxyPort, socksProxyPort, config.socatPath);
|
|
447
|
+
}
|
|
448
|
+
managerContext = {
|
|
449
|
+
httpProxyPort,
|
|
450
|
+
socksProxyPort,
|
|
451
|
+
linuxBridge,
|
|
452
|
+
};
|
|
453
|
+
logForDebugging('Network infrastructure initialized');
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
config = undefined;
|
|
457
|
+
initializationPromise = undefined;
|
|
458
|
+
managerContext = undefined;
|
|
459
|
+
await resetSession().catch(e => {
|
|
460
|
+
logForDebugging(`Cleanup failed in initializationPromise ${e}`, {
|
|
461
|
+
level: 'error',
|
|
462
|
+
});
|
|
463
|
+
});
|
|
464
|
+
throw error;
|
|
465
|
+
}
|
|
466
|
+
})();
|
|
467
|
+
await initializationPromise;
|
|
468
|
+
}
|
|
469
|
+
function isSupportedPlatform() {
|
|
470
|
+
const platform = getPlatform();
|
|
471
|
+
if (platform === 'linux') {
|
|
472
|
+
// WSL1 doesn't support bubblewrap
|
|
473
|
+
return getWslVersion() !== '1';
|
|
474
|
+
}
|
|
475
|
+
return platform === 'macos' || platform === 'windows';
|
|
476
|
+
}
|
|
477
|
+
function isSandboxingEnabled() {
|
|
478
|
+
// Sandboxing is enabled if config has been set (via initialize())
|
|
479
|
+
return config !== undefined;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Check sandbox dependencies for the current platform
|
|
483
|
+
* @returns { warnings, errors } - errors mean sandbox cannot run, warnings mean degraded functionality
|
|
484
|
+
*/
|
|
485
|
+
function checkDependencies() {
|
|
486
|
+
if (!isSupportedPlatform()) {
|
|
487
|
+
return { errors: ['Unsupported platform'], warnings: [] };
|
|
488
|
+
}
|
|
489
|
+
const errors = [];
|
|
490
|
+
const warnings = [];
|
|
491
|
+
const platform = getPlatform();
|
|
492
|
+
if (platform === 'linux') {
|
|
493
|
+
const linuxDeps = checkLinuxDependencies({
|
|
494
|
+
seccompConfig: config?.seccomp,
|
|
495
|
+
bwrapPath: config?.bwrapPath,
|
|
496
|
+
socatPath: config?.socatPath,
|
|
497
|
+
enableWeakerNestedSandbox: config?.enableWeakerNestedSandbox,
|
|
498
|
+
});
|
|
499
|
+
errors.push(...linuxDeps.errors);
|
|
500
|
+
warnings.push(...linuxDeps.warnings);
|
|
501
|
+
}
|
|
502
|
+
else if (platform === 'windows') {
|
|
503
|
+
let srtWin;
|
|
504
|
+
try {
|
|
505
|
+
srtWin = resolveSrtWin(config?.windows?.srtWin);
|
|
506
|
+
}
|
|
507
|
+
catch (e) {
|
|
508
|
+
errors.push(e.message);
|
|
509
|
+
return { errors, warnings };
|
|
510
|
+
}
|
|
511
|
+
const winDeps = checkWindowsDependencies({
|
|
512
|
+
sublayerGuid: config?.windows?.sublayerGuid ?? config?.windows?.wfpSublayerGuid,
|
|
513
|
+
srtWin,
|
|
514
|
+
});
|
|
515
|
+
errors.push(...winDeps.errors);
|
|
516
|
+
warnings.push(...winDeps.warnings);
|
|
517
|
+
}
|
|
518
|
+
return { errors, warnings };
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Build the read-deny / env-unset / env-set maps implied by the
|
|
522
|
+
* `credentials` config.
|
|
523
|
+
*
|
|
524
|
+
* Only explicitly declared sources are restricted: `mode: 'deny'` file
|
|
525
|
+
* entries join the read-deny set, `mode: 'deny'` env vars are unset, and
|
|
526
|
+
* `mode: 'mask'` env vars are set to a fake value (whole-value sentinel,
|
|
527
|
+
* the real value with extract-captured spans swapped for sentinels, or a
|
|
528
|
+
* JWT-shaped fake for `decode: 'jwt'` / `maskClaims` entries) registered
|
|
529
|
+
* in {@link sentinelRegistry} — see {@link buildMaskedEnvVars}.
|
|
530
|
+
*/
|
|
531
|
+
function getCredentialRestrictions(credentials, allowedDomains) {
|
|
532
|
+
if (!credentials) {
|
|
533
|
+
return {
|
|
534
|
+
denyReadPaths: [],
|
|
535
|
+
unsetEnvVars: [],
|
|
536
|
+
setEnvVars: {},
|
|
537
|
+
maskedFileBinds: [],
|
|
538
|
+
maskedFileStoreDir: undefined,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
const isWin = getPlatform() === 'windows';
|
|
542
|
+
const denyReadPaths = getCredentialDenyReadPaths(credentials, isWin);
|
|
543
|
+
const unsetEnvVars = [];
|
|
544
|
+
for (const v of credentials.envVars ?? []) {
|
|
545
|
+
if (v.mode === 'deny')
|
|
546
|
+
unsetEnvVars.push(v.name);
|
|
547
|
+
}
|
|
548
|
+
const { setEnvVars, degradeToUnsetNames } = buildMaskedEnvVars(credentials.envVars ?? [], allowedDomains ?? [], sentinelRegistry);
|
|
549
|
+
unsetEnvVars.push(...degradeToUnsetNames);
|
|
550
|
+
// Windows ACLs cannot redirect reads, so masked files degrade directly to
|
|
551
|
+
// denyRead via getCredentialDenyReadPaths(..., true) without creating
|
|
552
|
+
// unused fake files in MaskedFileStore.
|
|
553
|
+
const files = credentials.files ?? [];
|
|
554
|
+
const { binds: maskedFileBinds, degradeToDenyPaths } = isWin
|
|
555
|
+
? { binds: [], degradeToDenyPaths: [] }
|
|
556
|
+
: buildMaskedFileBinds(files, allowedDomains ?? [], sentinelRegistry, maskedFileStore);
|
|
557
|
+
return {
|
|
558
|
+
denyReadPaths: [...new Set([...denyReadPaths, ...degradeToDenyPaths])],
|
|
559
|
+
unsetEnvVars: [...new Set(unsetEnvVars)],
|
|
560
|
+
setEnvVars,
|
|
561
|
+
maskedFileBinds,
|
|
562
|
+
maskedFileStoreDir: maskedFileStore.dirPath,
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
function getCredentialDenyReadPaths(credentials, includeMask = false) {
|
|
566
|
+
const files = credentials?.files ?? [];
|
|
567
|
+
return [
|
|
568
|
+
...new Set(files
|
|
569
|
+
.filter(f => f.mode === 'deny' || (includeMask && f.mode === 'mask'))
|
|
570
|
+
.map(f => f.path)),
|
|
571
|
+
];
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Union the explicit `filesystem.denyRead` with credential-derived
|
|
575
|
+
* deny paths. The single source of "what files does this config
|
|
576
|
+
* want read-denied" — all platforms route through here so a new
|
|
577
|
+
* credential kind that contributes deny paths reaches every
|
|
578
|
+
* backend.
|
|
579
|
+
*/
|
|
580
|
+
function unionDenyReadPaths(denyRead, credentialRestrictions) {
|
|
581
|
+
return [...new Set([...denyRead, ...credentialRestrictions.denyReadPaths])];
|
|
582
|
+
}
|
|
583
|
+
function expandLinuxReadPaths(paths) {
|
|
584
|
+
const out = [];
|
|
585
|
+
for (const p of paths) {
|
|
586
|
+
const stripped = removeTrailingGlobSuffix(p);
|
|
587
|
+
if (getPlatform() === 'linux' && containsGlobChars(stripped)) {
|
|
588
|
+
out.push(...expandGlobPattern(p));
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
out.push(stripped);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return out;
|
|
595
|
+
}
|
|
596
|
+
function stripLinuxWriteGlobs(paths) {
|
|
597
|
+
return paths
|
|
598
|
+
.map(p => removeTrailingGlobSuffix(p))
|
|
599
|
+
.filter(p => {
|
|
600
|
+
if (getPlatform() === 'linux' && containsGlobChars(p)) {
|
|
601
|
+
logForDebugging(`Skipping glob pattern on Linux/WSL: ${p}`);
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
return true;
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
function getFsReadConfig() {
|
|
608
|
+
if (!config || config.filesystem.disabled) {
|
|
609
|
+
return { denyOnly: [], allowWithinDeny: [] };
|
|
610
|
+
}
|
|
611
|
+
const rawDenyRead = unionDenyReadPaths(config.filesystem.denyRead, {
|
|
612
|
+
denyReadPaths: getCredentialDenyReadPaths(config.credentials, getPlatform() === 'windows'),
|
|
613
|
+
unsetEnvVars: [],
|
|
614
|
+
setEnvVars: {},
|
|
615
|
+
maskedFileBinds: [],
|
|
616
|
+
maskedFileStoreDir: undefined,
|
|
617
|
+
});
|
|
618
|
+
return {
|
|
619
|
+
denyOnly: expandLinuxReadPaths(rawDenyRead),
|
|
620
|
+
allowWithinDeny: expandLinuxReadPaths(config.filesystem.allowRead ?? []),
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
function getFsWriteConfig() {
|
|
624
|
+
if (!config) {
|
|
625
|
+
return { allowOnly: getDefaultWritePaths(), denyWithinAllow: [] };
|
|
626
|
+
}
|
|
627
|
+
if (config.filesystem.disabled) {
|
|
628
|
+
return { allowOnly: ['/'], denyWithinAllow: [] };
|
|
629
|
+
}
|
|
630
|
+
return {
|
|
631
|
+
allowOnly: [
|
|
632
|
+
...getDefaultWritePaths(),
|
|
633
|
+
...stripLinuxWriteGlobs(config.filesystem.allowWrite),
|
|
634
|
+
],
|
|
635
|
+
denyWithinAllow: stripLinuxWriteGlobs(config.filesystem.denyWrite),
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Build the Windows file-access set (deny stamps + sandbox-user
|
|
640
|
+
* grants) from `runtimeConfig`. Globs are expanded to concrete
|
|
641
|
+
* paths (point-in-time — a path appearing after this returns is NOT
|
|
642
|
+
* covered). Directory targets are accepted (the `(OI)(CI)` ACEs
|
|
643
|
+
* cover the subtree).
|
|
644
|
+
*
|
|
645
|
+
* The sandbox user has no inherent rights on real-user-owned files,
|
|
646
|
+
* so `allowWrite` (the working-tree roots) becomes a per-session
|
|
647
|
+
* `MODIFY_NO_FDC` ALLOW ACE for `<sb-SID>`, `allowRead` a
|
|
648
|
+
* `READ|EXECUTE` ALLOW ACE, and `denyRead`/`denyWrite` become an
|
|
649
|
+
* explicit DENY ACE for `<sb-SID>` on the target plus a
|
|
650
|
+
* `(OI)(CI) FILE_DELETE_CHILD` DENY on its parent.
|
|
651
|
+
*/
|
|
652
|
+
function computeWindowsFsAccessSet(c) {
|
|
653
|
+
const fs = c.filesystem;
|
|
654
|
+
// filesystem.disabled bypasses ALL filesystem rule generation —
|
|
655
|
+
// same as the macOS/Linux wrapWithSandbox path (readConfig /
|
|
656
|
+
// writeConfig left undefined). On Windows this means no ACL
|
|
657
|
+
// stamp/grant; credential FILE denies are dropped along with the
|
|
658
|
+
// rest (credential ENV: mode:'deny' is structural under the
|
|
659
|
+
// fresh srt-sandbox env; mode:'mask' sentinels are passed via
|
|
660
|
+
// the --env overlay).
|
|
661
|
+
if (fs?.disabled) {
|
|
662
|
+
return { grantRead: [], grantWrite: [], denyRead: [], denyWrite: [] };
|
|
663
|
+
}
|
|
664
|
+
const expand = expandWindowsFsPaths;
|
|
665
|
+
const denyRead = expand([
|
|
666
|
+
...new Set([
|
|
667
|
+
...(fs?.denyRead ?? []),
|
|
668
|
+
...getCredentialDenyReadPaths(c.credentials, true),
|
|
669
|
+
]),
|
|
670
|
+
]);
|
|
671
|
+
const denyWrite = expand(fs?.denyWrite ?? []);
|
|
672
|
+
return {
|
|
673
|
+
// `allowRead` also serves as `allowWithinDeny`: a file under a
|
|
674
|
+
// denied dir gets an explicit ALLOW ACE for the sandbox user,
|
|
675
|
+
// and explicit DENY on the parent doesn't override it because
|
|
676
|
+
// the recompose chokepoint orders deny-before-allow per-path.
|
|
677
|
+
grantRead: expand(fs?.allowRead ?? []),
|
|
678
|
+
grantWrite: expand(fs?.allowWrite ?? []),
|
|
679
|
+
denyRead,
|
|
680
|
+
denyWrite,
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Snapshot the raw config fields that feed
|
|
685
|
+
* {@link computeWindowsFsAccessSet}. Used by updateConfig() to
|
|
686
|
+
* short-circuit the resolved-set diff (which re-runs glob
|
|
687
|
+
* expansion) when nothing relevant changed.
|
|
688
|
+
*/
|
|
689
|
+
function rawWindowsFsInputs(c) {
|
|
690
|
+
// Keyed exactly on what {@link computeWindowsFsAccessSet} reads.
|
|
691
|
+
// `network.allowedDomains` does NOT feed file-deny (only mask
|
|
692
|
+
// injectHosts), so a network-only updateConfig hits the cache.
|
|
693
|
+
return {
|
|
694
|
+
disabled: c.filesystem.disabled ?? false,
|
|
695
|
+
denyRead: [...c.filesystem.denyRead],
|
|
696
|
+
denyWrite: [...c.filesystem.denyWrite],
|
|
697
|
+
allowRead: [...(c.filesystem.allowRead ?? [])],
|
|
698
|
+
allowWrite: [...c.filesystem.allowWrite],
|
|
699
|
+
credFiles: getCredentialDenyReadPaths(c.credentials, true),
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
function setEq(a, b) {
|
|
703
|
+
if (a.length !== b.length)
|
|
704
|
+
return false;
|
|
705
|
+
const s = new Set(a);
|
|
706
|
+
return b.every(x => s.has(x));
|
|
707
|
+
}
|
|
708
|
+
function sameRawWindowsFsInputs(a, b) {
|
|
709
|
+
return (a.disabled === b.disabled &&
|
|
710
|
+
setEq(a.denyRead, b.denyRead) &&
|
|
711
|
+
setEq(a.denyWrite, b.denyWrite) &&
|
|
712
|
+
setEq(a.allowRead, b.allowRead) &&
|
|
713
|
+
setEq(a.allowWrite, b.allowWrite) &&
|
|
714
|
+
setEq(a.credFiles, b.credFiles));
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* True when `newConfig`'s file-deny inputs match what was
|
|
718
|
+
* stamped at initialize(). Compares raw inputs only (cheap,
|
|
719
|
+
* order-insensitive); never re-expands globs — updateConfig is
|
|
720
|
+
* warn-only on Windows and the resolved set wouldn't be used.
|
|
721
|
+
*/
|
|
722
|
+
function sameWindowsStampSet(newConfig) {
|
|
723
|
+
return (windowsFsRawInputs !== undefined &&
|
|
724
|
+
sameRawWindowsFsInputs(windowsFsRawInputs, rawWindowsFsInputs(newConfig)));
|
|
725
|
+
}
|
|
726
|
+
function getNetworkRestrictionConfig() {
|
|
727
|
+
if (!config) {
|
|
728
|
+
return {};
|
|
729
|
+
}
|
|
730
|
+
// Preserve an explicitly-empty allowlist: consumers need to distinguish
|
|
731
|
+
// "no network restriction configured" (absent) from "allowlist configured
|
|
732
|
+
// with zero entries" (block-all / ask-only). Stripping the empty array
|
|
733
|
+
// made a host app's restriction-status UI report an airgapped config as
|
|
734
|
+
// unrestricted. deniedHosts keeps the strip — an empty denylist and an
|
|
735
|
+
// absent one are semantically identical.
|
|
736
|
+
const allowedHosts = config.network.allowedDomains;
|
|
737
|
+
const deniedHosts = config.network.deniedDomains;
|
|
738
|
+
return {
|
|
739
|
+
allowedHosts,
|
|
740
|
+
...(deniedHosts.length > 0 && { deniedHosts }),
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
function getAllowUnixSockets() {
|
|
744
|
+
return config?.network?.allowUnixSockets;
|
|
745
|
+
}
|
|
746
|
+
function getAllowAllUnixSockets() {
|
|
747
|
+
return config?.network?.allowAllUnixSockets;
|
|
748
|
+
}
|
|
749
|
+
function getAllowLocalBinding() {
|
|
750
|
+
return config?.network?.allowLocalBinding;
|
|
751
|
+
}
|
|
752
|
+
function getAllowMachLookup() {
|
|
753
|
+
return config?.network?.allowMachLookup;
|
|
754
|
+
}
|
|
755
|
+
function getIgnoreViolations() {
|
|
756
|
+
return config?.ignoreViolations;
|
|
757
|
+
}
|
|
758
|
+
function getEnableWeakerNestedSandbox() {
|
|
759
|
+
return config?.enableWeakerNestedSandbox;
|
|
760
|
+
}
|
|
761
|
+
function getEnableWeakerNetworkIsolation() {
|
|
762
|
+
return config?.enableWeakerNetworkIsolation;
|
|
763
|
+
}
|
|
764
|
+
function getAllowAppleEvents() {
|
|
765
|
+
return config?.allowAppleEvents;
|
|
766
|
+
}
|
|
767
|
+
function getSeccompConfig() {
|
|
768
|
+
return config?.seccomp;
|
|
769
|
+
}
|
|
770
|
+
function getProxyAuthToken() {
|
|
771
|
+
return proxyAuthToken;
|
|
772
|
+
}
|
|
773
|
+
function getProxyPort() {
|
|
774
|
+
return managerContext?.httpProxyPort;
|
|
775
|
+
}
|
|
776
|
+
function getSocksProxyPort() {
|
|
777
|
+
return managerContext?.socksProxyPort;
|
|
778
|
+
}
|
|
779
|
+
function getLinuxHttpSocketPath() {
|
|
780
|
+
return managerContext?.linuxBridge?.httpSocketPath;
|
|
781
|
+
}
|
|
782
|
+
function getLinuxSocksSocketPath() {
|
|
783
|
+
return managerContext?.linuxBridge?.socksSocketPath;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Wait for network initialization to complete if already in progress
|
|
787
|
+
* Returns true if initialized successfully, false otherwise
|
|
788
|
+
*/
|
|
789
|
+
async function waitForNetworkInitialization() {
|
|
790
|
+
if (!config) {
|
|
791
|
+
return false;
|
|
792
|
+
}
|
|
793
|
+
if (initializationPromise) {
|
|
794
|
+
try {
|
|
795
|
+
await initializationPromise;
|
|
796
|
+
return true;
|
|
797
|
+
}
|
|
798
|
+
catch {
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
return managerContext !== undefined;
|
|
803
|
+
}
|
|
804
|
+
async function wrapWithSandbox(command, binShell, customConfig, abortSignal) {
|
|
805
|
+
abortSignal?.throwIfAborted();
|
|
806
|
+
const platform = getPlatform();
|
|
807
|
+
// filesystem.disabled bypasses ALL filesystem rule generation. Both
|
|
808
|
+
// platform wrappers treat readConfig/writeConfig === undefined as "no
|
|
809
|
+
// filesystem restrictions" (seatbelt emits `(allow file-write*)`; bwrap
|
|
810
|
+
// skips the `--ro-bind / /` root and all path binds).
|
|
811
|
+
//
|
|
812
|
+
// Precedence: when a caller passes a per-call filesystem override at all,
|
|
813
|
+
// its `disabled` (defaulting to false) wins outright. A global
|
|
814
|
+
// disabled=true must not silently discard a per-call tightening that
|
|
815
|
+
// omits the new key.
|
|
816
|
+
const fsDisabled = customConfig?.filesystem !== undefined
|
|
817
|
+
? (customConfig.filesystem.disabled ?? false)
|
|
818
|
+
: (config?.filesystem.disabled ?? false);
|
|
819
|
+
if (!fsDisabled && (platform === 'macos' || platform === 'linux')) {
|
|
820
|
+
ensureSandboxTempDirectory(resolveSandboxTmpdir());
|
|
821
|
+
}
|
|
822
|
+
// Credential env handling is independent of filesystem policy: unsetEnvVars /
|
|
823
|
+
// setEnvVars must be applied even when fsDisabled (the credential file
|
|
824
|
+
// deny-reads are dropped, but env scrubbing still happens).
|
|
825
|
+
const credentialRestrictions = getCredentialRestrictions(customConfig?.credentials ?? config?.credentials, customConfig?.network?.allowedDomains ?? config?.network?.allowedDomains);
|
|
826
|
+
// Get configs - use custom if provided, otherwise fall back to main config
|
|
827
|
+
// If neither exists, defaults to empty arrays (most restrictive)
|
|
828
|
+
// Always include default system write paths (like /dev/null, /tmp/agents)
|
|
829
|
+
//
|
|
830
|
+
// Strip trailing /** and filter remaining globs on Linux (bwrap needs
|
|
831
|
+
// real paths, not globs; macOS subpath matching is also recursive so
|
|
832
|
+
// stripping is harmless there).
|
|
833
|
+
let writeConfig;
|
|
834
|
+
let readConfig;
|
|
835
|
+
if (!fsDisabled) {
|
|
836
|
+
const userAllowWrite = stripLinuxWriteGlobs(customConfig?.filesystem?.allowWrite ??
|
|
837
|
+
config?.filesystem.allowWrite ??
|
|
838
|
+
[]);
|
|
839
|
+
writeConfig = {
|
|
840
|
+
allowOnly: [...getDefaultWritePaths(), ...userAllowWrite],
|
|
841
|
+
denyWithinAllow: stripLinuxWriteGlobs(customConfig?.filesystem?.denyWrite ??
|
|
842
|
+
config?.filesystem.denyWrite ??
|
|
843
|
+
[]),
|
|
844
|
+
};
|
|
845
|
+
const rawDenyRead = unionDenyReadPaths(customConfig?.filesystem?.denyRead ?? config?.filesystem.denyRead ?? [], credentialRestrictions);
|
|
846
|
+
const expandedDenyRead = expandLinuxReadPaths(rawDenyRead);
|
|
847
|
+
const expandedAllowRead = expandLinuxReadPaths(customConfig?.filesystem?.allowRead ??
|
|
848
|
+
config?.filesystem.allowRead ??
|
|
849
|
+
[]);
|
|
850
|
+
// Keep the MITM CA private key unreadable from inside the sandbox even
|
|
851
|
+
// when its parent temp dir or user-supplied location is otherwise readable.
|
|
852
|
+
if (mitmCA) {
|
|
853
|
+
expandedDenyRead.push(mitmCA.keyPath);
|
|
854
|
+
if (mitmCA.ephemeral) {
|
|
855
|
+
expandedDenyRead.push(dirname(mitmCA.keyPath));
|
|
856
|
+
}
|
|
857
|
+
expandedAllowRead.push(mitmCA.certPath, mitmCA.trustBundlePath);
|
|
858
|
+
}
|
|
859
|
+
readConfig = {
|
|
860
|
+
denyOnly: expandedDenyRead,
|
|
861
|
+
allowWithinDeny: expandedAllowRead,
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
// Check if network config is specified - this determines if we need network restrictions
|
|
865
|
+
// Network restriction is needed when:
|
|
866
|
+
// 1. customConfig has network.allowedDomains defined (even if empty array = block all)
|
|
867
|
+
// 2. OR config has network.allowedDomains defined (even if empty array = block all)
|
|
868
|
+
// An empty allowedDomains array means "no domains allowed" = block all network access
|
|
869
|
+
const hasNetworkConfig = customConfig?.network?.allowedDomains !== undefined ||
|
|
870
|
+
config?.network?.allowedDomains !== undefined;
|
|
871
|
+
// Network RESTRICTION is needed whenever network config is specified
|
|
872
|
+
// This includes empty allowedDomains which means "block all network"
|
|
873
|
+
const needsNetworkRestriction = hasNetworkConfig;
|
|
874
|
+
// Network PROXY is needed whenever network config is specified
|
|
875
|
+
// Even with empty allowedDomains, we route through proxy so that:
|
|
876
|
+
// 1. updateConfig() can enable network access for already-running processes
|
|
877
|
+
// 2. The proxy blocks all requests when allowlist is empty
|
|
878
|
+
const needsNetworkProxy = hasNetworkConfig;
|
|
879
|
+
// Wait for network initialization only if proxy is actually needed
|
|
880
|
+
if (needsNetworkProxy) {
|
|
881
|
+
if (!(await waitForNetworkInitialization()) || !managerContext) {
|
|
882
|
+
throw new Error('Sandbox network proxy is not initialized. Initialize the sandbox before running commands.');
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
// Check custom config to allow pseudo-terminal (can be applied dynamically)
|
|
886
|
+
const allowPty = customConfig?.allowPty ?? config?.allowPty;
|
|
887
|
+
// Check custom config to allow browser process operations (Chrome/Chromium)
|
|
888
|
+
const allowBrowserProcess = customConfig?.allowBrowserProcess ?? config?.allowBrowserProcess;
|
|
889
|
+
switch (platform) {
|
|
890
|
+
case 'macos':
|
|
891
|
+
// macOS sandbox profiles support glob patterns directly.
|
|
892
|
+
return wrapCommandWithSandboxMacOS({
|
|
893
|
+
command,
|
|
894
|
+
needsNetworkRestriction,
|
|
895
|
+
// Only pass proxy ports if proxy is running (when there are domains to filter)
|
|
896
|
+
httpProxyPort: needsNetworkProxy ? getProxyPort() : undefined,
|
|
897
|
+
socksProxyPort: needsNetworkProxy ? getSocksProxyPort() : undefined,
|
|
898
|
+
proxyAuthToken: needsNetworkProxy ? proxyAuthToken : undefined,
|
|
899
|
+
caCertPath: mitmCA?.trustBundlePath,
|
|
900
|
+
readConfig,
|
|
901
|
+
writeConfig,
|
|
902
|
+
unsetEnvVars: credentialRestrictions.unsetEnvVars,
|
|
903
|
+
setEnvVars: credentialRestrictions.setEnvVars,
|
|
904
|
+
maskedFileBinds: credentialRestrictions.maskedFileBinds,
|
|
905
|
+
allowUnixSockets: getAllowUnixSockets(),
|
|
906
|
+
allowAllUnixSockets: getAllowAllUnixSockets(),
|
|
907
|
+
allowLocalBinding: getAllowLocalBinding(),
|
|
908
|
+
allowMachLookup: getAllowMachLookup(),
|
|
909
|
+
ignoreViolations: getIgnoreViolations(),
|
|
910
|
+
allowPty,
|
|
911
|
+
allowBrowserProcess,
|
|
912
|
+
allowProcessSignals: customConfig?.allowProcessSignals ?? config?.allowProcessSignals,
|
|
913
|
+
enableWeakerNetworkIsolation: getEnableWeakerNetworkIsolation(),
|
|
914
|
+
allowAppleEvents: getAllowAppleEvents(),
|
|
915
|
+
binShell,
|
|
916
|
+
sessionSuffix: macosSessionSuffix,
|
|
917
|
+
});
|
|
918
|
+
case 'linux':
|
|
919
|
+
return wrapCommandWithSandboxLinux({
|
|
920
|
+
command,
|
|
921
|
+
needsNetworkRestriction,
|
|
922
|
+
// Only pass socket paths if proxy is running (when there are domains to filter)
|
|
923
|
+
httpSocketPath: needsNetworkProxy
|
|
924
|
+
? getLinuxHttpSocketPath()
|
|
925
|
+
: undefined,
|
|
926
|
+
socksSocketPath: needsNetworkProxy
|
|
927
|
+
? getLinuxSocksSocketPath()
|
|
928
|
+
: undefined,
|
|
929
|
+
httpProxyPort: needsNetworkProxy
|
|
930
|
+
? managerContext?.httpProxyPort
|
|
931
|
+
: undefined,
|
|
932
|
+
socksProxyPort: needsNetworkProxy
|
|
933
|
+
? managerContext?.socksProxyPort
|
|
934
|
+
: undefined,
|
|
935
|
+
proxyAuthToken: needsNetworkProxy ? proxyAuthToken : undefined,
|
|
936
|
+
caCertPath: mitmCA?.trustBundlePath,
|
|
937
|
+
readConfig,
|
|
938
|
+
writeConfig,
|
|
939
|
+
unsetEnvVars: credentialRestrictions.unsetEnvVars,
|
|
940
|
+
setEnvVars: credentialRestrictions.setEnvVars,
|
|
941
|
+
maskedFileBinds: credentialRestrictions.maskedFileBinds,
|
|
942
|
+
maskedFileStoreDir: credentialRestrictions.maskedFileStoreDir,
|
|
943
|
+
enableWeakerNestedSandbox: getEnableWeakerNestedSandbox(),
|
|
944
|
+
allowAllUnixSockets: getAllowAllUnixSockets(),
|
|
945
|
+
binShell,
|
|
946
|
+
seccompConfig: getSeccompConfig(),
|
|
947
|
+
bwrapPath: config?.bwrapPath,
|
|
948
|
+
socatPath: config?.socatPath,
|
|
949
|
+
observeSocketPath: linuxMonitor?.observeSocketPath,
|
|
950
|
+
});
|
|
951
|
+
case 'windows':
|
|
952
|
+
// Windows wraps to an argv array, not a shell string. Forcing
|
|
953
|
+
// callers through wrapWithSandboxArgv() means they spawn with
|
|
954
|
+
// {shell:false}, which is the security boundary that keeps the
|
|
955
|
+
// user's command bytes off the HOST shell.
|
|
956
|
+
throw new Error('wrapWithSandbox() returns a shell string and is not supported ' +
|
|
957
|
+
'on Windows. Use SandboxManager.wrapWithSandboxArgv() and ' +
|
|
958
|
+
'spawn the result with {shell: false}.');
|
|
959
|
+
default:
|
|
960
|
+
// Unsupported platform - this should not happen since isSandboxingEnabled() checks platform support
|
|
961
|
+
throw new Error(`Sandbox configuration is not supported on platform: ${platform}`);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Wrap `command` for the sandbox and return a spawn descriptor:
|
|
966
|
+
* `{ argv, env }`, suitable for
|
|
967
|
+
* `spawn(argv[0], argv.slice(1), {shell: false, env})`.
|
|
968
|
+
*
|
|
969
|
+
* On Windows this is the ONLY supported wrap method (see
|
|
970
|
+
* {@link wrapWithSandbox}); `env` is the broker process's spawn env
|
|
971
|
+
* — the sandboxed child gets a fresh `srt-sandbox` profile env with
|
|
972
|
+
* only the `--env` overlay baked into `argv` (see
|
|
973
|
+
* {@link wrapCommandWithSandboxWindows}). On
|
|
974
|
+
* macOS/Linux `argv` is `[binShell, '-c', <wrapWithSandbox result>]`
|
|
975
|
+
* (proxy env is baked into that command) and `env` is the unchanged
|
|
976
|
+
* `process.env`, so callers can spawn uniformly across platforms.
|
|
977
|
+
*
|
|
978
|
+
* @param cwd the working directory the caller will spawn the result
|
|
979
|
+
* with. On Windows the child's cwd is whatever the caller passes
|
|
980
|
+
* as the spawn `{cwd:}` option (there is no `--cwd` flag), and
|
|
981
|
+
* the `safe.directory` git-config injection derives from this — so
|
|
982
|
+
* pass the same value here as to `spawn({cwd})`. Defaults to
|
|
983
|
+
* `process.cwd()`. Currently unused on macOS/Linux.
|
|
984
|
+
*/
|
|
985
|
+
async function wrapWithSandboxArgv(command, binShell, customConfig, abortSignal, cwd) {
|
|
986
|
+
abortSignal?.throwIfAborted();
|
|
987
|
+
const platform = getPlatform();
|
|
988
|
+
if (platform === 'windows') {
|
|
989
|
+
const hasNetworkConfig = customConfig?.network?.allowedDomains !== undefined ||
|
|
990
|
+
config?.network?.allowedDomains !== undefined;
|
|
991
|
+
if (hasNetworkConfig) {
|
|
992
|
+
if (!(await waitForNetworkInitialization()) || !managerContext) {
|
|
993
|
+
throw new Error('Sandbox network proxy is not initialized. Initialize the sandbox before running commands.');
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const credentialRestrictions = getCredentialRestrictions(customConfig?.credentials ?? config?.credentials, customConfig?.network?.allowedDomains ??
|
|
997
|
+
config?.network?.allowedDomains);
|
|
998
|
+
// Per-exec FILE denies (customConfig only — the session-level
|
|
999
|
+
// config's denies were already stamped at initialize()).
|
|
1000
|
+
// Paths go through `expandWindowsFsPaths` — the SAME
|
|
1001
|
+
// chokepoint the session-level set uses (point-in-time glob
|
|
1002
|
+
// expand, normalize, missing→drop) — so a per-exec entry
|
|
1003
|
+
// resolves identically to its session-level equivalent.
|
|
1004
|
+
// macOS/Linux per-exec already reuses session-level expansion;
|
|
1005
|
+
// Windows now matches.
|
|
1006
|
+
//
|
|
1007
|
+
// The dedup against `windowsFsStampedSet` is an OPTIMIZATION,
|
|
1008
|
+
// not a correctness gate: re-stamping a session-held path
|
|
1009
|
+
// under the exec's distinct holder is refcount-safe but wastes
|
|
1010
|
+
// a SetSecurityInfo round-trip.
|
|
1011
|
+
//
|
|
1012
|
+
// filesystem.disabled bypasses ALL filesystem rule generation
|
|
1013
|
+
// — including credential-derived file denies — same ordering
|
|
1014
|
+
// as session-level `computeWindowsFsAccessSet` (credential
|
|
1015
|
+
// ENV: mode:'deny' is structural under the fresh srt-sandbox
|
|
1016
|
+
// env; mode:'mask' sentinels are passed via the --env
|
|
1017
|
+
// overlay).
|
|
1018
|
+
// Per-exec allowRead/allowWrite throw — `srt-win exec` only
|
|
1019
|
+
// exposes `--deny-*`; per-exec grants are not implemented.
|
|
1020
|
+
const fsCfg = customConfig?.filesystem;
|
|
1021
|
+
let perExecDenyRead = [];
|
|
1022
|
+
let perExecDenyWrite = [];
|
|
1023
|
+
if (!fsCfg?.disabled) {
|
|
1024
|
+
if (fsCfg?.allowRead?.length || fsCfg?.allowWrite?.length) {
|
|
1025
|
+
throw new Error(`Per-exec filesystem.allowRead/allowWrite is not supported ` +
|
|
1026
|
+
`on Windows — \`srt-win exec\` only exposes per-exec ` +
|
|
1027
|
+
`denies. Set them at the session level (initialize()).`);
|
|
1028
|
+
}
|
|
1029
|
+
const rawRead = [
|
|
1030
|
+
...(fsCfg?.denyRead ?? []),
|
|
1031
|
+
...getCredentialDenyReadPaths(customConfig?.credentials, true),
|
|
1032
|
+
];
|
|
1033
|
+
const rawWrite = fsCfg?.denyWrite ?? [];
|
|
1034
|
+
// Skip on the dominant path (no per-exec fs or
|
|
1035
|
+
// credential-file deny).
|
|
1036
|
+
if (rawRead.length > 0 || rawWrite.length > 0) {
|
|
1037
|
+
const sessRead = new Set(windowsFsStampedSet?.denyRead ?? []);
|
|
1038
|
+
const sessWrite = new Set(windowsFsStampedSet?.denyWrite ?? []);
|
|
1039
|
+
const expand = expandWindowsFsPaths;
|
|
1040
|
+
perExecDenyRead = expand(rawRead).filter(p => !sessRead.has(p));
|
|
1041
|
+
perExecDenyWrite = expand(rawWrite).filter(p => !sessRead.has(p) && !sessWrite.has(p));
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
// Per-exec deny rides on argv (`acl stamp` reads stdin, but
|
|
1045
|
+
// exec's stdin belongs to the child). The CreateProcessW
|
|
1046
|
+
// length check lives in `wrapCommandWithSandboxWindows`
|
|
1047
|
+
// where the full argv (incl. shell + user command) is known.
|
|
1048
|
+
//
|
|
1049
|
+
// The `denyReadPaths` half of the SESSION-level credentials
|
|
1050
|
+
// is already unioned into the stamp set at initialize() time
|
|
1051
|
+
// via `computeWindowsFsAccessSet`.
|
|
1052
|
+
return wrapCommandWithSandboxWindows({
|
|
1053
|
+
command,
|
|
1054
|
+
httpProxyPort: hasNetworkConfig ? getProxyPort() : undefined,
|
|
1055
|
+
socksProxyPort: hasNetworkConfig ? getSocksProxyPort() : undefined,
|
|
1056
|
+
proxyAuthToken: hasNetworkConfig ? proxyAuthToken : undefined,
|
|
1057
|
+
// mode:'deny' env vars are structurally absent (fresh
|
|
1058
|
+
// srt-sandbox profile env). mode:'mask' sentinels are
|
|
1059
|
+
// passed via the --env overlay so the sandboxed child sees
|
|
1060
|
+
// the sentinel value, same as macOS/Linux.
|
|
1061
|
+
setEnvVars: credentialRestrictions.setEnvVars,
|
|
1062
|
+
denyRead: perExecDenyRead,
|
|
1063
|
+
denyWrite: perExecDenyWrite,
|
|
1064
|
+
// safe.directory: cwd + the resolved session-level write
|
|
1065
|
+
// grants — exactly the working-tree roots the sandbox user
|
|
1066
|
+
// has MODIFY on and where git will see real-user-owned files.
|
|
1067
|
+
cwd,
|
|
1068
|
+
allowWrite: windowsFsStampedSet?.grantWrite,
|
|
1069
|
+
caCertPath: mitmCA?.trustBundlePath,
|
|
1070
|
+
binShell: parseWindowsBinShell(binShell),
|
|
1071
|
+
srtWin: customConfig?.windows?.srtWin
|
|
1072
|
+
? resolveSrtWin(customConfig.windows.srtWin)
|
|
1073
|
+
: (srtWinSpawn ?? resolveSrtWin(config?.windows?.srtWin)),
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
// macOS/Linux: delegate to the existing string wrapper, then put
|
|
1077
|
+
// the result behind `<shell> -c` so the caller's argv-spawn works.
|
|
1078
|
+
if (typeof binShell === 'object') {
|
|
1079
|
+
throw new Error('binShell object form is Windows-only; pass a shell path string ' +
|
|
1080
|
+
'on macOS/Linux');
|
|
1081
|
+
}
|
|
1082
|
+
const wrapped = await wrapWithSandbox(command, binShell, customConfig, abortSignal);
|
|
1083
|
+
const shell = binShell ?? '/bin/bash';
|
|
1084
|
+
return { argv: [shell, '-c', wrapped], env: process.env };
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Get the current sandbox configuration
|
|
1088
|
+
* @returns The current configuration, or undefined if not initialized
|
|
1089
|
+
*/
|
|
1090
|
+
function getConfig() {
|
|
1091
|
+
return config;
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Update the sandbox configuration in place.
|
|
1095
|
+
*
|
|
1096
|
+
* **Network/allowlist changes are a live swap**: the running
|
|
1097
|
+
* mux proxy reads `config.network.allowedDomains` /
|
|
1098
|
+
* `deniedDomains` per-request (via `filterNetworkRequest`), so
|
|
1099
|
+
* reassigning `config` here takes effect on the next connection
|
|
1100
|
+
* with no proxy rebind and no port change — on every platform,
|
|
1101
|
+
* including Windows. This is what lets a host enable/deny domains
|
|
1102
|
+
* for already-running sandboxed children.
|
|
1103
|
+
*
|
|
1104
|
+
* On macOS/Linux, new commands pick up filesystem changes when
|
|
1105
|
+
* their seatbelt profile / bwrap argv is generated. Already-running
|
|
1106
|
+
* processes keep their existing filesystem restrictions. Resetting
|
|
1107
|
+
* does not change those restrictions and disconnects their proxies.
|
|
1108
|
+
* Windows filesystem permissions are session-wide: call reset() +
|
|
1109
|
+
* initialize() to apply a new filesystem config there.
|
|
1110
|
+
*
|
|
1111
|
+
* @param newConfig - The new configuration to use
|
|
1112
|
+
*/
|
|
1113
|
+
function updateConfig(newConfig) {
|
|
1114
|
+
if (getPlatform() === 'windows' &&
|
|
1115
|
+
config &&
|
|
1116
|
+
!sameWindowsStampSet(newConfig)) {
|
|
1117
|
+
logForDebugging(`[Sandbox Windows] updateConfig: the resolved file-access set ` +
|
|
1118
|
+
`(filesystem.* ∪ credentials.files) changed but the ACL ` +
|
|
1119
|
+
`stamp/grant is session-wide — call reset() then initialize() ` +
|
|
1120
|
+
`to apply. The previously-applied set stays in effect.`, { level: 'warn' });
|
|
1121
|
+
}
|
|
1122
|
+
// Deep clone the config to avoid mutations. structuredClone cannot clone
|
|
1123
|
+
// functions, so pull filterRequest out, clone the rest, and put it back —
|
|
1124
|
+
// a function reference is immutable in the sense that matters here.
|
|
1125
|
+
const { filterRequest, ...rest } = newConfig.network;
|
|
1126
|
+
config = structuredClone({ ...newConfig, network: rest });
|
|
1127
|
+
config.network.filterRequest = filterRequest;
|
|
1128
|
+
// Prune removed/downgraded credentials so revoked sentinels cannot
|
|
1129
|
+
// continue substituting on egress after updateConfig().
|
|
1130
|
+
if (!newConfig.credentials) {
|
|
1131
|
+
sentinelRegistry.clear();
|
|
1132
|
+
}
|
|
1133
|
+
else {
|
|
1134
|
+
const envNames = new Set((newConfig.credentials.envVars ?? [])
|
|
1135
|
+
.filter(v => v.mode === 'mask')
|
|
1136
|
+
.map(v => v.name));
|
|
1137
|
+
const filePaths = new Set((newConfig.credentials.files ?? [])
|
|
1138
|
+
.filter(f => f.mode === 'mask')
|
|
1139
|
+
.map(f => normalizePathForSandbox(f.path)));
|
|
1140
|
+
sentinelRegistry.prune(entryName => {
|
|
1141
|
+
if (entryName.startsWith('env:')) {
|
|
1142
|
+
const base = entryName.slice(4).split('#')[0];
|
|
1143
|
+
return envNames.has(base);
|
|
1144
|
+
}
|
|
1145
|
+
if (entryName.startsWith('file:')) {
|
|
1146
|
+
const base = entryName.slice(5).split('#')[0];
|
|
1147
|
+
return filePaths.has(base);
|
|
1148
|
+
}
|
|
1149
|
+
return envNames.has(entryName);
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
// Re-resolve parent proxy so hot-reload picks up changes. Note: the proxy
|
|
1153
|
+
// servers capture `parentProxy` by value at creation, so changes here take
|
|
1154
|
+
// effect only on re-initialize. This keeps the state consistent for the
|
|
1155
|
+
// next initialize() call.
|
|
1156
|
+
parentProxy = resolveParentProxy(newConfig.network.parentProxy);
|
|
1157
|
+
logForDebugging('Sandbox configuration updated');
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Lightweight cleanup to call after each sandboxed command completes.
|
|
1161
|
+
*
|
|
1162
|
+
* On Linux, bwrap creates empty files on the host filesystem as mount points
|
|
1163
|
+
* when protecting non-existent deny paths (e.g. ~/.bashrc, ~/.gitconfig).
|
|
1164
|
+
* These persist after bwrap exits. This function removes them.
|
|
1165
|
+
*
|
|
1166
|
+
* Safe to call on any platform — it's a no-op on macOS.
|
|
1167
|
+
* Also called automatically by reset() and on process exit as safety nets.
|
|
1168
|
+
*/
|
|
1169
|
+
function cleanupAfterCommand() {
|
|
1170
|
+
cleanupBwrapMountPoints();
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* How long to wait for a bridge process to exit after SIGTERM before
|
|
1174
|
+
* escalating to SIGKILL.
|
|
1175
|
+
*
|
|
1176
|
+
* socat exits within ~10ms of SIGTERM; this is purely a safety margin.
|
|
1177
|
+
* Keep it well below bun's default 5s test/hook timeout: when a bridge's
|
|
1178
|
+
* `'exit'` event is missed entirely (a Linux-only Bun pidfd notification
|
|
1179
|
+
* bug, oven-sh/bun#30301), this timer is the only thing that lets `reset()`
|
|
1180
|
+
* make progress, and a 5000ms value here loses the race against the hook
|
|
1181
|
+
* timer by a couple of milliseconds — that race was the dominant CI flake.
|
|
1182
|
+
*/
|
|
1183
|
+
const BRIDGE_EXIT_TIMEOUT_MS = 1500;
|
|
1184
|
+
/**
|
|
1185
|
+
* SIGTERM a bridge process and resolve once it has exited.
|
|
1186
|
+
*
|
|
1187
|
+
* Returns immediately if the process has already exited (`.exitCode` /
|
|
1188
|
+
* `.signalCode` set) — registering `.once('exit')` after the event has
|
|
1189
|
+
* already been emitted produces a listener that never fires.
|
|
1190
|
+
*
|
|
1191
|
+
* Falls back to SIGKILL after {@link BRIDGE_EXIT_TIMEOUT_MS}.
|
|
1192
|
+
*/
|
|
1193
|
+
function killBridgeProcess(proc, label) {
|
|
1194
|
+
// Already exited → 'exit' already emitted → a fresh once('exit') would
|
|
1195
|
+
// never fire. Don't wait on it.
|
|
1196
|
+
if (!proc.pid || proc.exitCode !== null || proc.signalCode !== null) {
|
|
1197
|
+
return Promise.resolve();
|
|
1198
|
+
}
|
|
1199
|
+
try {
|
|
1200
|
+
process.kill(proc.pid, 'SIGTERM');
|
|
1201
|
+
logForDebugging(`Sent SIGTERM to ${label} bridge process`);
|
|
1202
|
+
}
|
|
1203
|
+
catch (err) {
|
|
1204
|
+
if (err.code !== 'ESRCH') {
|
|
1205
|
+
logForDebugging(`Error killing ${label} bridge: ${err}`, {
|
|
1206
|
+
level: 'error',
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
// ESRCH = process already gone; nothing to wait for either way.
|
|
1210
|
+
return Promise.resolve();
|
|
1211
|
+
}
|
|
1212
|
+
return new Promise(resolve => {
|
|
1213
|
+
let settled = false;
|
|
1214
|
+
const done = () => {
|
|
1215
|
+
if (settled)
|
|
1216
|
+
return;
|
|
1217
|
+
settled = true;
|
|
1218
|
+
clearTimeout(timer);
|
|
1219
|
+
resolve();
|
|
1220
|
+
};
|
|
1221
|
+
proc.once('exit', () => {
|
|
1222
|
+
logForDebugging(`${label} bridge process exited`);
|
|
1223
|
+
done();
|
|
1224
|
+
});
|
|
1225
|
+
const timer = setTimeout(() => {
|
|
1226
|
+
// Re-check liveness — the 'exit' may have raced us.
|
|
1227
|
+
if (proc.exitCode === null && proc.signalCode === null) {
|
|
1228
|
+
logForDebugging(`${label} bridge did not exit, forcing SIGKILL`, {
|
|
1229
|
+
level: 'warn',
|
|
1230
|
+
});
|
|
1231
|
+
try {
|
|
1232
|
+
if (proc.pid)
|
|
1233
|
+
process.kill(proc.pid, 'SIGKILL');
|
|
1234
|
+
}
|
|
1235
|
+
catch {
|
|
1236
|
+
// Process may have already exited
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
done();
|
|
1240
|
+
}, BRIDGE_EXIT_TIMEOUT_MS);
|
|
1241
|
+
// The bridge process is being torn down; this timer must not be the
|
|
1242
|
+
// only thing keeping the event loop alive.
|
|
1243
|
+
timer.unref?.();
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Forcibly close an http.Server, including any in-flight requests.
|
|
1248
|
+
*
|
|
1249
|
+
* Plain `server.close()` waits for every active request to finish.
|
|
1250
|
+
* The proxy may be mid-upstream-request when reset() runs (e.g. a test's
|
|
1251
|
+
* curl was killed by --max-time while the proxy was still dialing the
|
|
1252
|
+
* real example.com / api.github.com), and `dialDirect()` allows up to
|
|
1253
|
+
* 30s before giving up. Combined with a socat fork that hasn't yet seen
|
|
1254
|
+
* its unix-socket EOF, that leaves a fully-open inbound connection and
|
|
1255
|
+
* `server.close()` never calls back. `closeAllConnections()` (Node 18.2+,
|
|
1256
|
+
* also implemented in Bun) tears down those sockets so `close()` resolves
|
|
1257
|
+
* immediately.
|
|
1258
|
+
*/
|
|
1259
|
+
function forceCloseHttpServer(server) {
|
|
1260
|
+
return new Promise(resolve => {
|
|
1261
|
+
// Must run *before* close(): in Bun, close() also detaches the
|
|
1262
|
+
// underlying handle, so a closeAllConnections() called afterwards
|
|
1263
|
+
// becomes a no-op and the close callback waits for the in-flight
|
|
1264
|
+
// request to drain — defeating the purpose. With closeAllConnections()
|
|
1265
|
+
// first, the connections are gone by the time close() runs and its
|
|
1266
|
+
// callback fires immediately (Bun reports "Server is not running.",
|
|
1267
|
+
// Node reports no error). Verified against both orderings.
|
|
1268
|
+
if (typeof server.closeAllConnections === 'function') {
|
|
1269
|
+
server.closeAllConnections();
|
|
1270
|
+
}
|
|
1271
|
+
server.close(error => {
|
|
1272
|
+
if (error && error.message !== 'Server is not running.') {
|
|
1273
|
+
logForDebugging(`Error closing HTTP proxy server: ${error.message}`, {
|
|
1274
|
+
level: 'error',
|
|
1275
|
+
});
|
|
1276
|
+
}
|
|
1277
|
+
resolve();
|
|
1278
|
+
});
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
function reset() {
|
|
1282
|
+
if (resetPromise)
|
|
1283
|
+
return resetPromise;
|
|
1284
|
+
const pendingInitialization = initializationPromise;
|
|
1285
|
+
resetPromise = (async () => {
|
|
1286
|
+
await pendingInitialization?.catch(() => { });
|
|
1287
|
+
await resetSession();
|
|
1288
|
+
})().finally(() => {
|
|
1289
|
+
resetPromise = undefined;
|
|
1290
|
+
});
|
|
1291
|
+
return resetPromise;
|
|
1292
|
+
}
|
|
1293
|
+
async function resetSession() {
|
|
1294
|
+
unregisterCleanup(reset);
|
|
1295
|
+
// Windows: release this session's sandbox-user ACEs. Best-effort
|
|
1296
|
+
// — log anomalies rather than throw, so teardown always
|
|
1297
|
+
// completes. Leftover ACEs are recoverable later via
|
|
1298
|
+
// `srt-win acl recover` (which sweeps by trustee SID).
|
|
1299
|
+
if (windowsFsStampedSet && windowsFsSbUserSid) {
|
|
1300
|
+
const sb = windowsFsSbUserSid;
|
|
1301
|
+
// Captured at initialize() — the SAME binary the grants/stamps
|
|
1302
|
+
// were applied with, immune to `config` mutation between.
|
|
1303
|
+
const srtWin = srtWinSpawn;
|
|
1304
|
+
// 'restored'/'alreadyOriginal' are the pre- same-user-removal
|
|
1305
|
+
// srt-win's success vocabulary; 'revoked'/'stillHeld' are the
|
|
1306
|
+
// post-. Either is non-anomalous.
|
|
1307
|
+
const ok = new Set([
|
|
1308
|
+
'revoked',
|
|
1309
|
+
'stillHeld',
|
|
1310
|
+
'restored',
|
|
1311
|
+
'alreadyOriginal',
|
|
1312
|
+
]);
|
|
1313
|
+
const log = (kind, e) => {
|
|
1314
|
+
if (!ok.has(e.status)) {
|
|
1315
|
+
logForDebugging(`[Sandbox Windows] ${kind}: '${e.path}' ${e.status} — ` +
|
|
1316
|
+
`ACE may be left in place; resolve and run ` +
|
|
1317
|
+
`\`srt-win acl recover\` to clear`, { level: 'warn' });
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
for (const e of revokeWindowsAcl({ sandboxUserSid: sb, srtWin }) ?? []) {
|
|
1321
|
+
log('grant revoke', e);
|
|
1322
|
+
}
|
|
1323
|
+
for (const e of restoreWindowsAcl({ sandboxUserSid: sb, srtWin }) ?? []) {
|
|
1324
|
+
log('deny restore', e);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
windowsFsStampedSet = undefined;
|
|
1328
|
+
windowsFsSbUserSid = undefined;
|
|
1329
|
+
windowsFsRawInputs = undefined;
|
|
1330
|
+
srtWinSpawn = undefined;
|
|
1331
|
+
// windowsWfpVerified is NOT cleared — per-process, not per-session.
|
|
1332
|
+
// Other managers may still have commands using these process-wide mounts.
|
|
1333
|
+
cleanupBwrapMountPoints({ completed: false });
|
|
1334
|
+
// Stop log monitors and dispose ephemeral temp stores synchronously before
|
|
1335
|
+
// any awaits so process exit handlers still clean up secrets on disk.
|
|
1336
|
+
sentinelRegistry.clear();
|
|
1337
|
+
maskedFileStore.dispose();
|
|
1338
|
+
if (mitmCA) {
|
|
1339
|
+
disposeMitmCASync(mitmCA);
|
|
1340
|
+
mitmCA = undefined;
|
|
1341
|
+
}
|
|
1342
|
+
if (logMonitorShutdown) {
|
|
1343
|
+
logMonitorShutdown();
|
|
1344
|
+
logMonitorShutdown = undefined;
|
|
1345
|
+
}
|
|
1346
|
+
if (linuxMonitor) {
|
|
1347
|
+
linuxMonitor.stop();
|
|
1348
|
+
linuxMonitor = undefined;
|
|
1349
|
+
}
|
|
1350
|
+
if (managerContext?.linuxBridge) {
|
|
1351
|
+
const { httpSocketPath, socksSocketPath, httpBridgeProcess, socksBridgeProcess, } = managerContext.linuxBridge;
|
|
1352
|
+
await Promise.all([
|
|
1353
|
+
killBridgeProcess(httpBridgeProcess, 'HTTP'),
|
|
1354
|
+
killBridgeProcess(socksBridgeProcess, 'SOCKS'),
|
|
1355
|
+
]);
|
|
1356
|
+
if (httpSocketPath) {
|
|
1357
|
+
try {
|
|
1358
|
+
fs.rmSync(httpSocketPath, { force: true });
|
|
1359
|
+
logForDebugging('Cleaned up HTTP socket');
|
|
1360
|
+
}
|
|
1361
|
+
catch (err) {
|
|
1362
|
+
logForDebugging(`HTTP socket cleanup error: ${err}`, {
|
|
1363
|
+
level: 'error',
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
if (socksSocketPath) {
|
|
1368
|
+
try {
|
|
1369
|
+
fs.rmSync(socksSocketPath, { force: true });
|
|
1370
|
+
logForDebugging('Cleaned up SOCKS socket');
|
|
1371
|
+
}
|
|
1372
|
+
catch (err) {
|
|
1373
|
+
logForDebugging(`SOCKS socket cleanup error: ${err}`, {
|
|
1374
|
+
level: 'error',
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
// Close servers in parallel (only if they exist, i.e., were started by us)
|
|
1380
|
+
const closePromises = [];
|
|
1381
|
+
if (muxProxyServer) {
|
|
1382
|
+
closePromises.push(muxProxyServer.close().catch((error) => {
|
|
1383
|
+
logForDebugging(`Error closing mux proxy server: ${error.message}`, {
|
|
1384
|
+
level: 'error',
|
|
1385
|
+
});
|
|
1386
|
+
}));
|
|
1387
|
+
}
|
|
1388
|
+
if (httpProxyServer) {
|
|
1389
|
+
closePromises.push(forceCloseHttpServer(httpProxyServer));
|
|
1390
|
+
}
|
|
1391
|
+
if (socksProxyServer) {
|
|
1392
|
+
const socksClose = socksProxyServer.close().catch((error) => {
|
|
1393
|
+
logForDebugging(`Error closing SOCKS proxy server: ${error.message}`, {
|
|
1394
|
+
level: 'error',
|
|
1395
|
+
});
|
|
1396
|
+
});
|
|
1397
|
+
closePromises.push(socksClose);
|
|
1398
|
+
}
|
|
1399
|
+
// Wait for all servers to close
|
|
1400
|
+
await Promise.all(closePromises);
|
|
1401
|
+
// Clear references
|
|
1402
|
+
muxProxyServer = undefined;
|
|
1403
|
+
httpProxyServer = undefined;
|
|
1404
|
+
proxyAuthToken = undefined;
|
|
1405
|
+
socksProxyServer = undefined;
|
|
1406
|
+
managerContext = undefined;
|
|
1407
|
+
initializationPromise = undefined;
|
|
1408
|
+
parentProxy = undefined;
|
|
1409
|
+
}
|
|
1410
|
+
function getSandboxViolationStore() {
|
|
1411
|
+
return sandboxViolationStore;
|
|
1412
|
+
}
|
|
1413
|
+
function annotateStderrWithSandboxFailures(command, stderr) {
|
|
1414
|
+
if (!config) {
|
|
1415
|
+
return stderr;
|
|
1416
|
+
}
|
|
1417
|
+
const violations = sandboxViolationStore.getViolationsForCommand(command);
|
|
1418
|
+
if (violations.length === 0) {
|
|
1419
|
+
return stderr;
|
|
1420
|
+
}
|
|
1421
|
+
let annotated = stderr;
|
|
1422
|
+
annotated += EOL + '<sandbox_violations>' + EOL;
|
|
1423
|
+
for (const violation of violations) {
|
|
1424
|
+
annotated += violation.line + EOL;
|
|
1425
|
+
}
|
|
1426
|
+
annotated += '</sandbox_violations>';
|
|
1427
|
+
return annotated;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Returns glob patterns from Edit/Read permission rules that are not
|
|
1431
|
+
* fully supported on Linux. Returns empty array on macOS or when
|
|
1432
|
+
* sandboxing is disabled.
|
|
1433
|
+
*
|
|
1434
|
+
* Patterns ending with /** are excluded since they work as subpaths.
|
|
1435
|
+
*/
|
|
1436
|
+
function getLinuxGlobPatternWarnings() {
|
|
1437
|
+
// Only warn on Linux/WSL (bubblewrap doesn't support globs)
|
|
1438
|
+
// macOS supports glob patterns via regex conversion
|
|
1439
|
+
if (getPlatform() !== 'linux' || !config || config.filesystem.disabled) {
|
|
1440
|
+
return [];
|
|
1441
|
+
}
|
|
1442
|
+
const globPatterns = [];
|
|
1443
|
+
// Check filesystem paths for glob patterns
|
|
1444
|
+
// Note: denyRead is excluded because globs are now expanded to concrete paths on Linux
|
|
1445
|
+
const allPaths = [
|
|
1446
|
+
...config.filesystem.allowWrite,
|
|
1447
|
+
...config.filesystem.denyWrite,
|
|
1448
|
+
];
|
|
1449
|
+
for (const path of allPaths) {
|
|
1450
|
+
// Strip trailing /** since that's just a subpath (directory and everything under it)
|
|
1451
|
+
const pathWithoutTrailingStar = removeTrailingGlobSuffix(path);
|
|
1452
|
+
// Only warn if there are still glob characters after removing trailing /**
|
|
1453
|
+
if (containsGlobChars(pathWithoutTrailingStar)) {
|
|
1454
|
+
globPatterns.push(path);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
return globPatterns;
|
|
1458
|
+
}
|
|
1459
|
+
return {
|
|
1460
|
+
initialize,
|
|
1461
|
+
isSupportedPlatform,
|
|
1462
|
+
isSandboxingEnabled,
|
|
1463
|
+
checkDependencies,
|
|
1464
|
+
getFsReadConfig,
|
|
1465
|
+
getFsWriteConfig,
|
|
1466
|
+
getNetworkRestrictionConfig,
|
|
1467
|
+
getAllowUnixSockets,
|
|
1468
|
+
getAllowLocalBinding,
|
|
1469
|
+
getAllowMachLookup,
|
|
1470
|
+
getIgnoreViolations,
|
|
1471
|
+
getEnableWeakerNestedSandbox,
|
|
1472
|
+
getProxyPort,
|
|
1473
|
+
getProxyAuthToken,
|
|
1474
|
+
getSocksProxyPort,
|
|
1475
|
+
getLinuxHttpSocketPath,
|
|
1476
|
+
getLinuxSocksSocketPath,
|
|
1477
|
+
waitForNetworkInitialization,
|
|
1478
|
+
wrapWithSandbox,
|
|
1479
|
+
wrapWithSandboxArgv,
|
|
1480
|
+
cleanupAfterCommand,
|
|
1481
|
+
reset,
|
|
1482
|
+
getMitmCA: () => mitmCA,
|
|
1483
|
+
getSentinelRegistry: () => sentinelRegistry,
|
|
1484
|
+
getMaskedFileStore: () => maskedFileStore,
|
|
1485
|
+
getSandboxViolationStore,
|
|
1486
|
+
annotateStderrWithSandboxFailures,
|
|
1487
|
+
getLinuxGlobPatternWarnings,
|
|
1488
|
+
getConfig,
|
|
1489
|
+
updateConfig,
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
/** Create an independent macOS/Linux sandbox session with its own policy and proxies. */
|
|
1493
|
+
export function createSandboxManager() {
|
|
1494
|
+
return createManager(false);
|
|
1495
|
+
}
|
|
1496
|
+
/** Backwards-compatible process-wide manager, including Windows support. */
|
|
1497
|
+
export const SandboxManager = createManager(true);
|
|
1498
|
+
//# sourceMappingURL=sandbox-manager.js.map
|