@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,982 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as net from 'node:net';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { once } from 'node:events';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { logForDebugging } from '../utils/debug.js';
|
|
8
|
+
import { generateProxyEnvVars, normalizePathForSandbox, containsGlobCharsWin, expandGlobPattern, removeTrailingGlobSuffix, } from './sandbox-utils.js';
|
|
9
|
+
/**
|
|
10
|
+
* Windows sandbox backend.
|
|
11
|
+
*
|
|
12
|
+
* Network isolation is enforced by `srt-win.exe` — a Rust helper that
|
|
13
|
+
* provisions a dedicated `srt-sandbox` local user account, installs a
|
|
14
|
+
* machine-wide WFP filter set keyed on that account's SID, and
|
|
15
|
+
* provides an `exec` subcommand that spawns the target via a two-hop
|
|
16
|
+
* launch (broker → `CreateProcessWithLogonW(runner)` → runner →
|
|
17
|
+
* restricted-token child) under `srt-sandbox`. The sandboxed child
|
|
18
|
+
* reaches the host only via the JS mux proxy, which the caller
|
|
19
|
+
* passes in via `--env`.
|
|
20
|
+
*
|
|
21
|
+
* The separate-user account structurally closes the surrogate-spawn
|
|
22
|
+
* class (schtasks, `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS`, BITS,
|
|
23
|
+
* RunAs="Interactive User" COM): the child's token carries a
|
|
24
|
+
* different user SID, so it cannot reach real-user processes, tasks
|
|
25
|
+
* register under `srt-sandbox`, and the user-SID WFP filter fences
|
|
26
|
+
* `srt-sandbox` egress regardless of how the child was spawned.
|
|
27
|
+
*
|
|
28
|
+
* This module is a thin wrapper around the `srt-win` CLI; all status
|
|
29
|
+
* comes from live enumeration. There is no marker file.
|
|
30
|
+
*
|
|
31
|
+
* Filesystem rules (`denyRead`/`denyWrite`/`allowRead`/`allowWrite`)
|
|
32
|
+
* are enforced via additive explicit ACEs for `<sb-SID>` — see
|
|
33
|
+
* {@link grantWindowsAcl} / {@link stampWindowsAcl}.
|
|
34
|
+
*/
|
|
35
|
+
// ────────────────────────────────────────────────────────────────────
|
|
36
|
+
// Types
|
|
37
|
+
// ────────────────────────────────────────────────────────────────────
|
|
38
|
+
export const DEFAULT_WINDOWS_PROXY_PORT_RANGE = [
|
|
39
|
+
60080, 60089,
|
|
40
|
+
];
|
|
41
|
+
const PWSH_FLAGS = ['-NoProfile', '-Command'];
|
|
42
|
+
/**
|
|
43
|
+
* Sole normalizer from the cross-platform `binShell?: string |
|
|
44
|
+
* WindowsBinShell` surface ({@link SandboxManager.wrapWithSandboxArgv})
|
|
45
|
+
* to a spawnable `{exe, args}` pair. All validation lives here —
|
|
46
|
+
* {@link wrapCommandWithSandboxWindows} consumes the result verbatim.
|
|
47
|
+
*
|
|
48
|
+
* String form: bare token (`'cmd'|'pwsh'|'powershell'`) resolves to
|
|
49
|
+
* the default install; absolute path to `bash.exe`/`sh.exe`/
|
|
50
|
+
* `pwsh.exe`/`powershell.exe`/`cmd.exe` keeps the caller's path with
|
|
51
|
+
* the matching flag shape. Object form: `exe` must be absolute; `args`
|
|
52
|
+
* pass through unchanged. Throws on anything else — no silent
|
|
53
|
+
* fallback to cmd.exe.
|
|
54
|
+
*
|
|
55
|
+
* Uses `path.win32` explicitly so the function (and its unit test)
|
|
56
|
+
* is platform-independent.
|
|
57
|
+
*/
|
|
58
|
+
export function parseWindowsBinShell(raw) {
|
|
59
|
+
const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
|
|
60
|
+
const cmdDefault = {
|
|
61
|
+
exe: path.win32.join(systemRoot, 'System32', 'cmd.exe'),
|
|
62
|
+
args: ['/d', '/s', '/c'],
|
|
63
|
+
};
|
|
64
|
+
if (raw === undefined || raw === null)
|
|
65
|
+
return cmdDefault;
|
|
66
|
+
if (typeof raw === 'object') {
|
|
67
|
+
if (!path.win32.isAbsolute(raw.exe)) {
|
|
68
|
+
throw new Error(`binShell.exe must be an absolute path ` +
|
|
69
|
+
`(got ${JSON.stringify(raw.exe)})`);
|
|
70
|
+
}
|
|
71
|
+
if (!Array.isArray(raw.args)) {
|
|
72
|
+
throw new Error(`binShell.args must be an array (got ${JSON.stringify(raw.args)})`);
|
|
73
|
+
}
|
|
74
|
+
return raw;
|
|
75
|
+
}
|
|
76
|
+
const rawBase = path.win32.basename(raw);
|
|
77
|
+
const base = rawBase.toLowerCase();
|
|
78
|
+
const isAbs = path.win32.isAbsolute(raw);
|
|
79
|
+
// A relative path with a directory component (`bin\bash.exe`) is
|
|
80
|
+
// neither a token nor a resolved install — never silently degrade.
|
|
81
|
+
if (!isAbs && raw !== rawBase) {
|
|
82
|
+
throw new Error(`binShell string must be a bare token or an absolute path ` +
|
|
83
|
+
`(got ${JSON.stringify(raw)})`);
|
|
84
|
+
}
|
|
85
|
+
switch (base) {
|
|
86
|
+
case 'bash':
|
|
87
|
+
case 'bash.exe':
|
|
88
|
+
case 'sh':
|
|
89
|
+
case 'sh.exe':
|
|
90
|
+
// Bare 'bash' is ambiguous (WSL vs Git Bash) — require the
|
|
91
|
+
// resolved install path.
|
|
92
|
+
if (!isAbs) {
|
|
93
|
+
throw new Error(`binShell bash path must be absolute ` +
|
|
94
|
+
`(got ${JSON.stringify(raw)}); pass the resolved Git Bash ` +
|
|
95
|
+
`install path`);
|
|
96
|
+
}
|
|
97
|
+
return { exe: raw, args: ['-c'] };
|
|
98
|
+
case 'pwsh':
|
|
99
|
+
case 'pwsh.exe':
|
|
100
|
+
return {
|
|
101
|
+
exe: isAbs
|
|
102
|
+
? raw
|
|
103
|
+
: path.win32.join(process.env.ProgramFiles || 'C:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
|
|
104
|
+
args: PWSH_FLAGS,
|
|
105
|
+
};
|
|
106
|
+
case 'powershell':
|
|
107
|
+
case 'powershell.exe':
|
|
108
|
+
return {
|
|
109
|
+
exe: isAbs
|
|
110
|
+
? raw
|
|
111
|
+
: path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
112
|
+
args: PWSH_FLAGS,
|
|
113
|
+
};
|
|
114
|
+
case 'cmd':
|
|
115
|
+
case 'cmd.exe':
|
|
116
|
+
return isAbs ? { exe: raw, args: cmdDefault.args } : cmdDefault;
|
|
117
|
+
default:
|
|
118
|
+
throw new Error(`unrecognised binShell ${JSON.stringify(raw)}: expected ` +
|
|
119
|
+
`'cmd' | 'powershell' | 'pwsh' or an absolute path to ` +
|
|
120
|
+
`bash.exe/sh.exe/pwsh.exe/powershell.exe`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// ────────────────────────────────────────────────────────────────────
|
|
124
|
+
// Binary resolution
|
|
125
|
+
// ────────────────────────────────────────────────────────────────────
|
|
126
|
+
function repoRoot() {
|
|
127
|
+
// src/sandbox/windows-sandbox-utils.ts → repo root (compiled: dist/sandbox/…)
|
|
128
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
129
|
+
return path.resolve(here, '..', '..');
|
|
130
|
+
}
|
|
131
|
+
const nodeArchToDir = { x64: 'x64', arm64: 'arm64' };
|
|
132
|
+
/**
|
|
133
|
+
* Locate the packaged `srt-win.exe`. Resolution order:
|
|
134
|
+
* 1. `<root>/vendor/srt-win/{arch}/srt-win.exe` (prebuilt — published npm
|
|
135
|
+
* package, or after `npm run build:srt-win` locally).
|
|
136
|
+
* 2. `<root>/vendor/srt-win-src/target/release/srt-win.exe` (local
|
|
137
|
+
* `cargo build --release` fallback for development).
|
|
138
|
+
*
|
|
139
|
+
* `<root>` is {@link repoRoot} — `__dirname/../..`, which resolves to the
|
|
140
|
+
* repo root from `src/sandbox/` and `dist/sandbox/` alike, and to the
|
|
141
|
+
* package root when installed under `node_modules`.
|
|
142
|
+
*
|
|
143
|
+
* Callers that ship their own binary (or a multicall binary that
|
|
144
|
+
* routes on `argv[1] == `{@link SRT_WIN_DISPATCH_ARG1}) pass
|
|
145
|
+
* `windows.srtWin` instead of relying on this lookup — see
|
|
146
|
+
* {@link resolveSrtWin}.
|
|
147
|
+
*
|
|
148
|
+
* Resolution via the optional `@anthropic-ai/sandbox-runtime-win32-*`
|
|
149
|
+
* platform packages is added separately.
|
|
150
|
+
*
|
|
151
|
+
* @throws if none exist.
|
|
152
|
+
*/
|
|
153
|
+
export function getSrtWinPath() {
|
|
154
|
+
const root = repoRoot();
|
|
155
|
+
const arch = nodeArchToDir[process.arch];
|
|
156
|
+
const candidates = [];
|
|
157
|
+
if (arch) {
|
|
158
|
+
candidates.push(path.join(root, 'vendor', 'srt-win', arch, 'srt-win.exe'));
|
|
159
|
+
}
|
|
160
|
+
candidates.push(path.join(root, 'vendor', 'srt-win-src', 'target', 'release', 'srt-win.exe'));
|
|
161
|
+
for (const c of candidates) {
|
|
162
|
+
if (fs.existsSync(c))
|
|
163
|
+
return c;
|
|
164
|
+
}
|
|
165
|
+
throw new Error(`srt-win.exe not found. Set windows.srtWin.path or build with ` +
|
|
166
|
+
`\`cargo build --release --manifest-path vendor/srt-win-src/Cargo.toml\`. ` +
|
|
167
|
+
`Looked in: ${candidates.join(', ')}`);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* `argv[1]` sentinel a multicall embedder's dispatcher matches
|
|
171
|
+
* against to route into `srt_win::run_from_args`. Mirrors the Rust
|
|
172
|
+
* `srt_win::SRT_WIN_DISPATCH_ARG1`; the two MUST stay in sync.
|
|
173
|
+
* `run_from_args` strips it before clap, so the standalone binary
|
|
174
|
+
* accepts it harmlessly.
|
|
175
|
+
*/
|
|
176
|
+
export const SRT_WIN_DISPATCH_ARG1 = '--srt-win';
|
|
177
|
+
/**
|
|
178
|
+
* Resolve the `srt-win` spawn target from config. When `cfg.path` is
|
|
179
|
+
* set it is used verbatim (no fallback to the packaged binary — an
|
|
180
|
+
* explicit override is a directive, not a hint) and
|
|
181
|
+
* {@link SRT_WIN_DISPATCH_ARG1} is prepended so a multicall
|
|
182
|
+
* dispatcher routes on `argv[1]`. When unset, falls back to
|
|
183
|
+
* {@link getSrtWinPath} with no sentinel (the packaged binary
|
|
184
|
+
* doesn't need it; `run_from_args` would strip it anyway).
|
|
185
|
+
*/
|
|
186
|
+
export function resolveSrtWin(cfg) {
|
|
187
|
+
if (cfg?.path !== undefined) {
|
|
188
|
+
if (!path.isAbsolute(cfg.path) && !path.win32.isAbsolute(cfg.path)) {
|
|
189
|
+
throw new Error(`windows.srtWin.path must be an absolute path (got ${JSON.stringify(cfg.path)})`);
|
|
190
|
+
}
|
|
191
|
+
const st = fs.statSync(cfg.path, { throwIfNoEntry: false });
|
|
192
|
+
if (!st) {
|
|
193
|
+
throw new Error(`windows.srtWin.path is set to '${cfg.path}' but the file does ` +
|
|
194
|
+
`not exist; remove srtWin.path to fall back to the packaged ` +
|
|
195
|
+
`binary`);
|
|
196
|
+
}
|
|
197
|
+
if (!st.isFile()) {
|
|
198
|
+
throw new Error(`windows.srtWin.path is set to '${cfg.path}' but is not a regular file`);
|
|
199
|
+
}
|
|
200
|
+
return { exe: cfg.path, prependArgs: [SRT_WIN_DISPATCH_ARG1] };
|
|
201
|
+
}
|
|
202
|
+
return { exe: getSrtWinPath(), prependArgs: [] };
|
|
203
|
+
}
|
|
204
|
+
function runSrtWin(args, opts = {}) {
|
|
205
|
+
// Direct callers of the exported helpers may omit `srtWin`
|
|
206
|
+
// (backward-compat) — fall back to the packaged-binary lookup.
|
|
207
|
+
// `SandboxManager` resolves once at `initialize()` and threads the
|
|
208
|
+
// handle, so this per-call resolve is only hit outside a session.
|
|
209
|
+
const { exe, prependArgs } = opts.srtWin ?? resolveSrtWin();
|
|
210
|
+
const r = spawnSync(exe, [...prependArgs, ...args], {
|
|
211
|
+
encoding: 'utf8',
|
|
212
|
+
timeout: opts.timeoutMs ?? 15000,
|
|
213
|
+
...(opts.stdin !== undefined ? { input: opts.stdin } : {}),
|
|
214
|
+
});
|
|
215
|
+
if (r.error) {
|
|
216
|
+
throw new Error(`srt-win ${args[0]}: spawn failed: ${r.error.message}`);
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
status: r.status,
|
|
220
|
+
signal: r.signal,
|
|
221
|
+
stdout: (r.stdout ?? '').trim(),
|
|
222
|
+
stderr: (r.stderr ?? '').trim(),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function runSrtWinJson(args, opts) {
|
|
226
|
+
const r = runSrtWin(args, opts);
|
|
227
|
+
if (r.status !== 0) {
|
|
228
|
+
throw new Error(`srt-win ${args.join(' ')} exited ${r.status}: ${r.stderr || r.stdout}`);
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
return JSON.parse(r.stdout);
|
|
232
|
+
}
|
|
233
|
+
catch (e) {
|
|
234
|
+
throw new Error(`srt-win ${args.join(' ')}: unparseable JSON output ` +
|
|
235
|
+
`${JSON.stringify(r.stdout)}: ${e.message}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* As {@link runSrtWinJson} but parses stdout BEFORE checking the
|
|
240
|
+
* exit code, so a non-zero exit with the per-path JSON intact
|
|
241
|
+
* still surfaces every entry. For best-effort teardown helpers
|
|
242
|
+
* (`acl restore`/`acl revoke`).
|
|
243
|
+
*/
|
|
244
|
+
function runSrtWinJsonAllowFail(args, opts) {
|
|
245
|
+
const r = runSrtWin(args, opts);
|
|
246
|
+
let json;
|
|
247
|
+
try {
|
|
248
|
+
json = JSON.parse(r.stdout);
|
|
249
|
+
}
|
|
250
|
+
catch (e) {
|
|
251
|
+
throw new Error(`srt-win ${args.join(' ')}: unparseable JSON output ` +
|
|
252
|
+
`${JSON.stringify(r.stdout)}: ${e.message}`);
|
|
253
|
+
}
|
|
254
|
+
return { ok: r.status === 0, json, stderr: r.stderr };
|
|
255
|
+
}
|
|
256
|
+
// ────────────────────────────────────────────────────────────────────
|
|
257
|
+
// Status / install API
|
|
258
|
+
// ────────────────────────────────────────────────────────────────────
|
|
259
|
+
/**
|
|
260
|
+
* Query the WFP filter set under the given sublayer via live BFE
|
|
261
|
+
* enumeration. `installed` means at least one srt-win-tagged
|
|
262
|
+
* `block-user` filter is present. Detection is **tag-based**
|
|
263
|
+
* (providerData JSON); filters installed by other tooling without the
|
|
264
|
+
* tag are not counted.
|
|
265
|
+
*
|
|
266
|
+
* BFE enumeration is admin-gated — a non-elevated caller gets
|
|
267
|
+
* `state:"cannot-read"` with a `hint` (not an error). The
|
|
268
|
+
* non-elevated readiness check is {@link verifyWindowsWfpEgress}.
|
|
269
|
+
*/
|
|
270
|
+
export function getWindowsWfpStatus(opts = {}) {
|
|
271
|
+
const args = ['wfp', 'status'];
|
|
272
|
+
if (opts.sublayerGuid)
|
|
273
|
+
args.push('--sublayer-guid', opts.sublayerGuid);
|
|
274
|
+
const raw = runSrtWinJson(args, { srtWin: opts.srtWin });
|
|
275
|
+
return {
|
|
276
|
+
state: raw.state,
|
|
277
|
+
filters: raw.filters,
|
|
278
|
+
...(raw.port_range && { portRange: raw.port_range }),
|
|
279
|
+
...(raw.user_sid && { userSid: raw.user_sid }),
|
|
280
|
+
...(raw.hint && { hint: raw.hint }),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Behavioral proof that the WFP egress fence is active for the
|
|
285
|
+
* sandbox user. Binds a local listener on an ephemeral loopback port
|
|
286
|
+
* outside the WFP loopback-permit range, then spawns `srt-win
|
|
287
|
+
* runner` as the sandbox user (via `CreateProcessWithLogonW`) to
|
|
288
|
+
* attempt a direct TCP connect to it. The WFP block-user filter
|
|
289
|
+
* fires at `ALE_AUTH_CONNECT` — before any packet leaves — so an
|
|
290
|
+
* active fence yields WSAEACCES immediately and a missing fence lets
|
|
291
|
+
* the connect through (the kernel completes the handshake against
|
|
292
|
+
* the listening socket's backlog; no event-loop tick required, so
|
|
293
|
+
* the synchronous `runSrtWin` is safe). Does not require elevation
|
|
294
|
+
* and does not depend on any external host.
|
|
295
|
+
*
|
|
296
|
+
* `initialize()` calls this once per session, so a stale install
|
|
297
|
+
* (sandbox user provisioned but filters since removed) fails closed
|
|
298
|
+
* at session start instead of running every exec with full egress.
|
|
299
|
+
*
|
|
300
|
+
* @param opts.target overrides the probe target (skips the local
|
|
301
|
+
* listener bind).
|
|
302
|
+
* @param opts.proxyPortRange the WFP loopback-permit range the
|
|
303
|
+
* listener must avoid. Default
|
|
304
|
+
* {@link DEFAULT_WINDOWS_PROXY_PORT_RANGE}.
|
|
305
|
+
* @throws on any outcome other than `blocked` (exit 0).
|
|
306
|
+
*/
|
|
307
|
+
export async function verifyWindowsWfpEgress(opts = {}) {
|
|
308
|
+
let target = opts.target;
|
|
309
|
+
let server;
|
|
310
|
+
if (!target) {
|
|
311
|
+
// Bind ephemeral; retry if it lands inside the WFP
|
|
312
|
+
// loopback-permit range (a port in-range would be PERMITted
|
|
313
|
+
// even with the fence active → false `connected`).
|
|
314
|
+
const [lo, hi] = opts.proxyPortRange ?? DEFAULT_WINDOWS_PROXY_PORT_RANGE;
|
|
315
|
+
for (let i = 0; i < 5; i++) {
|
|
316
|
+
const s = net.createServer();
|
|
317
|
+
s.listen(0, '127.0.0.1');
|
|
318
|
+
await once(s, 'listening');
|
|
319
|
+
const p = s.address().port;
|
|
320
|
+
if (p < lo || p > hi) {
|
|
321
|
+
server = s;
|
|
322
|
+
target = `127.0.0.1:${p}`;
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
s.close();
|
|
326
|
+
}
|
|
327
|
+
if (!target) {
|
|
328
|
+
throw new Error(`verifyWindowsWfpEgress: could not bind a loopback ` +
|
|
329
|
+
`listener outside the WFP permit range [${lo},${hi}] in ` +
|
|
330
|
+
`5 attempts`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
// 30s: first call after install may create the sandbox user's
|
|
335
|
+
// profile (LOGON_WITH_PROFILE) via CreateProcessWithLogonW —
|
|
336
|
+
// same budget as windowsTrustCa, plus the runner's own 2s
|
|
337
|
+
// connect timeout.
|
|
338
|
+
const r = runSrtWin(['wfp', 'verify', '--target', target], {
|
|
339
|
+
timeoutMs: 30000,
|
|
340
|
+
srtWin: opts.srtWin,
|
|
341
|
+
});
|
|
342
|
+
logForDebugging(`[Sandbox Windows] wfp verify exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
343
|
+
let raw;
|
|
344
|
+
try {
|
|
345
|
+
raw = JSON.parse(r.stdout);
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
// status=null → spawnSync killed the child (timeout or external
|
|
349
|
+
// signal). Include signal + stderr so the CI log self-explains
|
|
350
|
+
// instead of just `exited null with unparseable output ""`.
|
|
351
|
+
throw new Error(`WFP egress fence could not be verified — \`srt-win wfp ` +
|
|
352
|
+
`verify\` exited ${r.status}` +
|
|
353
|
+
(r.signal ? ` (signal ${r.signal})` : '') +
|
|
354
|
+
` with unparseable output ${JSON.stringify(r.stdout)} ` +
|
|
355
|
+
`(stderr: ${JSON.stringify(r.stderr)})`);
|
|
356
|
+
}
|
|
357
|
+
if (r.status === 3) {
|
|
358
|
+
throw new Error(`WFP egress fence is not active — direct outbound from the ` +
|
|
359
|
+
`sandbox user to ${raw.target} succeeded. Re-run ` +
|
|
360
|
+
`\`srt-win install\` (one UAC prompt). (${r.stderr})`);
|
|
361
|
+
}
|
|
362
|
+
if (r.status !== 0) {
|
|
363
|
+
throw new Error(`WFP egress fence could not be verified — probe to ` +
|
|
364
|
+
`${raw.target} was '${raw.egress_probe}' (exit ` +
|
|
365
|
+
`${r.status}). The fence may be absent. Re-run \`srt-win ` +
|
|
366
|
+
`install\`. (${r.stderr})`);
|
|
367
|
+
}
|
|
368
|
+
return { target: raw.target, stderr: r.stderr };
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
server?.close();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Query the sandbox user account's provisioning state. Each field
|
|
376
|
+
* is independently observed so a half-provisioned install (e.g.
|
|
377
|
+
* user exists but credential file missing) is distinguishable.
|
|
378
|
+
* Does not require elevation.
|
|
379
|
+
*/
|
|
380
|
+
export function getWindowsSandboxUserStatus(opts = {}) {
|
|
381
|
+
const raw = runSrtWinJson(['user', 'status'], { srtWin: opts.srtWin });
|
|
382
|
+
return {
|
|
383
|
+
provisioned: raw.user.exists,
|
|
384
|
+
...(raw.user.sid && { sid: raw.user.sid }),
|
|
385
|
+
groupExists: raw.user.group_exists,
|
|
386
|
+
...(raw.user.group_sid && { groupSid: raw.user.group_sid }),
|
|
387
|
+
inBuiltinUsers: raw.user.in_builtin_users,
|
|
388
|
+
inSandboxGroup: raw.user.in_sandbox_group,
|
|
389
|
+
hiddenFromLogon: raw.user.hidden_from_logon,
|
|
390
|
+
credPresent: raw.cred_present,
|
|
391
|
+
...(typeof raw.marker_version === 'number' && {
|
|
392
|
+
markerVersion: raw.marker_version,
|
|
393
|
+
}),
|
|
394
|
+
realUserSid: raw.real_user_sid,
|
|
395
|
+
...(raw.ca_cert_thumb && { caCertThumb: raw.ca_cert_thumb }),
|
|
396
|
+
...(raw.ca_cert_pem && { caCertPem: raw.ca_cert_pem }),
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Read back the persistent MITM CA the sandbox was installed with
|
|
401
|
+
* (via `srt-win user trust-ca` / {@link windowsTrustCa}).
|
|
402
|
+
* Returns `null` when no CA was installed. The PEM is what `srt-win
|
|
403
|
+
* user status` reconstructs from the DER stored in `state.db`.
|
|
404
|
+
*
|
|
405
|
+
* On Windows, `tlsTerminate` requires this CA to be present in the
|
|
406
|
+
* sandbox user's `CurrentUser\Root` (schannel-level trust is an
|
|
407
|
+
* install-time concern, not per-session); the host calls this from
|
|
408
|
+
* `initialize()` to fail early with an actionable message when it
|
|
409
|
+
* isn't.
|
|
410
|
+
*
|
|
411
|
+
* @param status pass an already-fetched
|
|
412
|
+
* {@link getWindowsSandboxUserStatus} result to avoid a second
|
|
413
|
+
* `srt-win user status` spawn.
|
|
414
|
+
*/
|
|
415
|
+
export function getWindowsSandboxCaCert(status, opts = {}) {
|
|
416
|
+
const u = status ?? getWindowsSandboxUserStatus(opts);
|
|
417
|
+
if (!u.caCertThumb || !u.caCertPem)
|
|
418
|
+
return null;
|
|
419
|
+
return { pem: u.caCertPem, thumb: u.caCertThumb };
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Install (or replace) the MITM CA in the **sandbox user's**
|
|
423
|
+
* `CurrentUser\Root` and record it in `state.db` (so
|
|
424
|
+
* {@link getWindowsSandboxCaCert} surfaces its thumbprint + PEM).
|
|
425
|
+
* Thin wrapper around `srt-win user trust-ca <path>`. Does NOT
|
|
426
|
+
* require elevation. Persistent until {@link uninstallWindowsSandbox}
|
|
427
|
+
* deletes the sandbox user's profile.
|
|
428
|
+
*
|
|
429
|
+
* The CA has a separate lifecycle from {@link installWindowsSandbox}
|
|
430
|
+
* — install provisions the account/filters and never touches the CA;
|
|
431
|
+
* call this AFTER install when `tlsTerminate` will be used.
|
|
432
|
+
*
|
|
433
|
+
* @throws when the sandbox user is not provisioned, the file is not a
|
|
434
|
+
* parseable X.509 certificate, or the registry write into the
|
|
435
|
+
* sandbox user's hive fails.
|
|
436
|
+
*/
|
|
437
|
+
export function windowsTrustCa(caCertPath, opts = {}) {
|
|
438
|
+
// 60s: first call may create the sandbox user's profile
|
|
439
|
+
// (LOGON_WITH_PROFILE) via the one-shot CreateProcessWithLogonW.
|
|
440
|
+
const r = runSrtWin(['user', 'trust-ca', caCertPath], {
|
|
441
|
+
timeoutMs: 60000,
|
|
442
|
+
srtWin: opts.srtWin,
|
|
443
|
+
});
|
|
444
|
+
logForDebugging(`[Sandbox Windows] user trust-ca exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
445
|
+
if (r.status !== 0) {
|
|
446
|
+
throw new Error(`srt-win user trust-ca '${caCertPath}' failed (exit ` +
|
|
447
|
+
`${r.status}): ${r.stderr || r.stdout}`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* One-shot install: provisions the `srt-sandbox` user account and
|
|
452
|
+
* installs the user-SID-keyed WFP filter set — all in a single
|
|
453
|
+
* self-elevating process (one UAC prompt). Idempotent; re-running
|
|
454
|
+
* rotates the sandbox user's password.
|
|
455
|
+
*
|
|
456
|
+
* Network for the calling user is **not disrupted**: the filters key
|
|
457
|
+
* on the `srt-sandbox` user's SID, so the broker, services, and
|
|
458
|
+
* every other principal fall through to default-permit. No logout
|
|
459
|
+
* is required.
|
|
460
|
+
*
|
|
461
|
+
* Returns the post-call WFP + sandbox-user state. If the user
|
|
462
|
+
* cancels the UAC prompt this returns `{cancelled: true, …}` rather
|
|
463
|
+
* than throwing — cancellation is a user choice, not an error.
|
|
464
|
+
*
|
|
465
|
+
* @throws on user/WFP creation failure, or if filters already exist
|
|
466
|
+
* under `sublayerGuid` with a different port range and `force` is
|
|
467
|
+
* not set.
|
|
468
|
+
*/
|
|
469
|
+
export function installWindowsSandbox(opts = {}) {
|
|
470
|
+
const srtWin = opts.srtWin ?? resolveSrtWin();
|
|
471
|
+
const args = ['install'];
|
|
472
|
+
if (opts.sublayerGuid)
|
|
473
|
+
args.push('--sublayer-guid', opts.sublayerGuid);
|
|
474
|
+
if (opts.proxyPortRange) {
|
|
475
|
+
args.push('--proxy-port-range', `${opts.proxyPortRange[0]}-${opts.proxyPortRange[1]}`);
|
|
476
|
+
}
|
|
477
|
+
if (opts.sandboxUser)
|
|
478
|
+
args.push('--sandbox-user', opts.sandboxUser);
|
|
479
|
+
if (opts.force)
|
|
480
|
+
args.push('--force');
|
|
481
|
+
const r = runSrtWin(args, { timeoutMs: 60000, srtWin });
|
|
482
|
+
logForDebugging(`[Sandbox Windows] install exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
483
|
+
// srt-win install exit-code contract:
|
|
484
|
+
// 0 ok
|
|
485
|
+
// 10 user cancelled UAC elevation
|
|
486
|
+
// 12 WFP install failed
|
|
487
|
+
// 13 already installed with different config (use --force)
|
|
488
|
+
// 14 sandbox-user provisioning failed
|
|
489
|
+
// 1 other error (stderr has detail)
|
|
490
|
+
const out = r.stderr || r.stdout;
|
|
491
|
+
const readBack = () => ({
|
|
492
|
+
wfp: getWindowsWfpStatus({ sublayerGuid: opts.sublayerGuid, srtWin }),
|
|
493
|
+
user: getWindowsSandboxUserStatus({ srtWin }),
|
|
494
|
+
});
|
|
495
|
+
switch (r.status) {
|
|
496
|
+
case 0:
|
|
497
|
+
return readBack();
|
|
498
|
+
case 10:
|
|
499
|
+
return { ...readBack(), cancelled: true };
|
|
500
|
+
case 12:
|
|
501
|
+
throw new Error(`srt-win install: WFP filter install failed: ${out}`);
|
|
502
|
+
case 14:
|
|
503
|
+
throw new Error(`srt-win install: sandbox user provisioning failed: ${out}`);
|
|
504
|
+
case 13:
|
|
505
|
+
throw new Error(`srt-win install: filters already exist under this sublayer with ` +
|
|
506
|
+
`a different port range or sandbox-user name. Pass ` +
|
|
507
|
+
`{force: true} to replace, or pick a different sublayerGuid. ` +
|
|
508
|
+
`Output: ${out}`);
|
|
509
|
+
default:
|
|
510
|
+
throw new Error(`srt-win install failed (exit ${r.status}): ${out}`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Remove the WFP filter set under `sublayerGuid` and the
|
|
515
|
+
* `srt-sandbox` account, its credential file, and the setup marker
|
|
516
|
+
* (one UAC prompt). Idempotent.
|
|
517
|
+
*
|
|
518
|
+
* @returns `{cancelled: true}` if the user dismissed UAC.
|
|
519
|
+
*/
|
|
520
|
+
export function uninstallWindowsSandbox(opts = {}) {
|
|
521
|
+
const args = ['uninstall'];
|
|
522
|
+
if (opts.sublayerGuid)
|
|
523
|
+
args.push('--sublayer-guid', opts.sublayerGuid);
|
|
524
|
+
if (opts.keepUser)
|
|
525
|
+
args.push('--keep-user');
|
|
526
|
+
const r = runSrtWin(args, { timeoutMs: 60000, srtWin: opts.srtWin });
|
|
527
|
+
logForDebugging(`[Sandbox Windows] uninstall exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
528
|
+
if (r.status === 10)
|
|
529
|
+
return { cancelled: true };
|
|
530
|
+
if (r.status !== 0) {
|
|
531
|
+
throw new Error(`srt-win uninstall failed (exit ${r.status}): ${r.stderr || r.stdout}`);
|
|
532
|
+
}
|
|
533
|
+
return {};
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Resolve any Windows filesystem-config path list — `allowRead`/
|
|
537
|
+
* `allowWrite` grants and `denyRead`/`denyWrite` stamps — to
|
|
538
|
+
* concrete existing paths via the single platform-aware
|
|
539
|
+
* {@link normalizePathForSandbox} chokepoint (Linux/macOS parity:
|
|
540
|
+
* point-in-time expansion at session initialize, not per-exec).
|
|
541
|
+
* Glob patterns are expanded; non-glob paths are normalized and
|
|
542
|
+
* returned 1:1. Missing paths are dropped (statSync probe).
|
|
543
|
+
* Directory targets are accepted — the additive sandbox-user ACE
|
|
544
|
+
* carries `(OI)(CI)` so it covers the subtree.
|
|
545
|
+
*/
|
|
546
|
+
export function expandWindowsFsPaths(patterns) {
|
|
547
|
+
const out = new Set();
|
|
548
|
+
for (const raw of patterns) {
|
|
549
|
+
const norm = removeTrailingGlobSuffix(normalizePathForSandbox(raw));
|
|
550
|
+
const candidates = containsGlobCharsWin(norm)
|
|
551
|
+
? expandGlobPattern(norm, { caseInsensitive: true })
|
|
552
|
+
: [norm];
|
|
553
|
+
for (const c of candidates) {
|
|
554
|
+
const st = fs.statSync(c, { throwIfNoEntry: false });
|
|
555
|
+
if (!st)
|
|
556
|
+
continue;
|
|
557
|
+
out.add(c);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
return [...out];
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Apply the file-deny ACE set for one host session: an additive
|
|
564
|
+
* `(D;OICI;mask;;;<sb-SID>)` on the target plus a
|
|
565
|
+
* `(D;OICI;FILE_DELETE_CHILD;;;<sb-SID>)` on the parent — no
|
|
566
|
+
* PROTECTED rewrite, no SD snapshot. Idempotent and refcounted via
|
|
567
|
+
* srt-win's `working_aces` table.
|
|
568
|
+
*
|
|
569
|
+
* Inputs are passed verbatim to `srt-win` (which canonicalizes and
|
|
570
|
+
* rejects globs). Callers that accept globs should pre-expand via
|
|
571
|
+
* {@link expandWindowsFsPaths}.
|
|
572
|
+
*
|
|
573
|
+
* @throws on exit ≠ 0 — including exit 2 (one or more inputs
|
|
574
|
+
* skipped). srt-win stamps the resolvable inputs before exiting
|
|
575
|
+
* 2, so on throw the caller should call {@link restoreWindowsAcl}
|
|
576
|
+
* to release whatever WAS stamped.
|
|
577
|
+
*/
|
|
578
|
+
export function stampWindowsAcl(opts) {
|
|
579
|
+
const holder = opts.holderPid ?? process.pid;
|
|
580
|
+
const stdin = JSON.stringify({
|
|
581
|
+
denyRead: opts.denyRead,
|
|
582
|
+
denyWrite: opts.denyWrite,
|
|
583
|
+
});
|
|
584
|
+
const r = runSrtWin([
|
|
585
|
+
'acl',
|
|
586
|
+
'stamp',
|
|
587
|
+
'--holder-pid',
|
|
588
|
+
`${holder}`,
|
|
589
|
+
'--sandbox-user-sid',
|
|
590
|
+
opts.sandboxUserSid,
|
|
591
|
+
], { timeoutMs: 60000, stdin, srtWin: opts.srtWin });
|
|
592
|
+
logForDebugging(`[Sandbox Windows] acl stamp exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
593
|
+
if (r.status !== 0) {
|
|
594
|
+
throw new Error(`srt-win acl stamp exited ${r.status} ` +
|
|
595
|
+
(r.status === 2 ? '(partial — some inputs skipped)' : '(failed)') +
|
|
596
|
+
`: ${r.stderr || r.stdout}`);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Release this holder's deny ACEs and remove the sandbox-user ACE
|
|
601
|
+
* on any path whose refcount falls to zero. Best-effort (does not
|
|
602
|
+
* throw on per-path anomalies); returns per-path outcomes for the
|
|
603
|
+
* caller to surface. Returns `undefined` only when `srt-win`
|
|
604
|
+
* itself failed (no JSON to parse).
|
|
605
|
+
*/
|
|
606
|
+
export function restoreWindowsAcl(opts) {
|
|
607
|
+
const holder = opts.holderPid ?? process.pid;
|
|
608
|
+
// Don't let a teardown helper throw — the caller's reset() must
|
|
609
|
+
// complete. runSrtWinJsonAllowFail parses stdout before checking
|
|
610
|
+
// the exit code, so a non-zero exit with the per-path JSON intact
|
|
611
|
+
// still surfaces every entry to reset()'s loop. Only spawn-fail
|
|
612
|
+
// / unparseable output throws → log and return undefined.
|
|
613
|
+
try {
|
|
614
|
+
const r = runSrtWinJsonAllowFail([
|
|
615
|
+
'acl',
|
|
616
|
+
'restore',
|
|
617
|
+
'--holder-pid',
|
|
618
|
+
`${holder}`,
|
|
619
|
+
'--sandbox-user-sid',
|
|
620
|
+
opts.sandboxUserSid,
|
|
621
|
+
'--json',
|
|
622
|
+
], { timeoutMs: 60000, srtWin: opts.srtWin });
|
|
623
|
+
if (!r.ok) {
|
|
624
|
+
logForDebugging(`[Sandbox Windows] acl restore exited non-zero (per-path ` +
|
|
625
|
+
`outcomes preserved): ${r.stderr}`, { level: 'error' });
|
|
626
|
+
}
|
|
627
|
+
// Pre- same-user-removal builds emit `{paths, parents}`; post-
|
|
628
|
+
// emit a flat array. Flatten either so reset()'s logging loop
|
|
629
|
+
// is shape-agnostic across the transition.
|
|
630
|
+
return Array.isArray(r.json)
|
|
631
|
+
? r.json
|
|
632
|
+
: [...(r.json.paths ?? []), ...(r.json.parents ?? [])];
|
|
633
|
+
}
|
|
634
|
+
catch (e) {
|
|
635
|
+
logForDebugging(`[Sandbox Windows] acl restore: ${e.message}`, {
|
|
636
|
+
level: 'error',
|
|
637
|
+
});
|
|
638
|
+
return undefined;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Apply per-session additive `(OI)(CI)` ALLOW ACEs for the sandbox
|
|
643
|
+
* user on each path. The sandbox user has no inherent rights on
|
|
644
|
+
* real-user-owned files; this is what makes the working tree (and
|
|
645
|
+
* explicit `allowRead`/`allowWrite` paths) reachable from the
|
|
646
|
+
* child. Idempotent and refcounted via srt-win's `working_aces`
|
|
647
|
+
* table.
|
|
648
|
+
*
|
|
649
|
+
* @throws on exit ≠ 0. On throw the caller should call
|
|
650
|
+
* {@link revokeWindowsAcl} to release whatever WAS granted.
|
|
651
|
+
*/
|
|
652
|
+
export function grantWindowsAcl(opts) {
|
|
653
|
+
const holder = opts.holderPid ?? process.pid;
|
|
654
|
+
const stdin = JSON.stringify({ read: opts.read, write: opts.write });
|
|
655
|
+
const r = runSrtWin([
|
|
656
|
+
'acl',
|
|
657
|
+
'grant',
|
|
658
|
+
'--holder-pid',
|
|
659
|
+
`${holder}`,
|
|
660
|
+
'--sandbox-user-sid',
|
|
661
|
+
opts.sandboxUserSid,
|
|
662
|
+
], { timeoutMs: 60000, stdin, srtWin: opts.srtWin });
|
|
663
|
+
logForDebugging(`[Sandbox Windows] acl grant exit=${r.status}: ${r.stderr || r.stdout}`);
|
|
664
|
+
if (r.status !== 0) {
|
|
665
|
+
throw new Error(`srt-win acl grant exited ${r.status}: ${r.stderr || r.stdout}`);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Release this holder's grants and remove the sandbox-user ACE on
|
|
670
|
+
* any path whose refcount falls to zero. Best-effort (does not
|
|
671
|
+
* throw); logs anomalies.
|
|
672
|
+
*/
|
|
673
|
+
export function revokeWindowsAcl(opts) {
|
|
674
|
+
const holder = opts.holderPid ?? process.pid;
|
|
675
|
+
try {
|
|
676
|
+
const r = runSrtWinJsonAllowFail([
|
|
677
|
+
'acl',
|
|
678
|
+
'revoke',
|
|
679
|
+
'--holder-pid',
|
|
680
|
+
`${holder}`,
|
|
681
|
+
'--sandbox-user-sid',
|
|
682
|
+
opts.sandboxUserSid,
|
|
683
|
+
'--json',
|
|
684
|
+
], { timeoutMs: 60000, srtWin: opts.srtWin });
|
|
685
|
+
if (!r.ok) {
|
|
686
|
+
logForDebugging(`[Sandbox Windows] acl revoke exited non-zero: ${r.stderr}`, { level: 'error' });
|
|
687
|
+
}
|
|
688
|
+
return r.json;
|
|
689
|
+
}
|
|
690
|
+
catch (e) {
|
|
691
|
+
logForDebugging(`[Sandbox Windows] acl revoke: ${e.message}`, {
|
|
692
|
+
level: 'error',
|
|
693
|
+
});
|
|
694
|
+
return undefined;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
// ────────────────────────────────────────────────────────────────────
|
|
698
|
+
// Wrap
|
|
699
|
+
// ────────────────────────────────────────────────────────────────────
|
|
700
|
+
/**
|
|
701
|
+
* `safe.directory` entries above this count collapse to a single
|
|
702
|
+
* `safe.directory=*`. Keeps `GIT_CONFIG_COUNT` (and the `--env`
|
|
703
|
+
* argv it rides on) bounded when `allowWrite` is wide.
|
|
704
|
+
*/
|
|
705
|
+
const SAFE_DIRECTORY_WILDCARD_THRESHOLD = 8;
|
|
706
|
+
/**
|
|
707
|
+
* Build the `GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_<n>` /
|
|
708
|
+
* `GIT_CONFIG_VALUE_<n>` env-var set for the sandboxed child.
|
|
709
|
+
*
|
|
710
|
+
* Emits:
|
|
711
|
+
* - `safe.directory=<dir>` for each entry in `safeDirs` (or one
|
|
712
|
+
* `safe.directory=*` when the list is long) — the working tree
|
|
713
|
+
* is owned by the real user, so git running as `srt-sandbox`
|
|
714
|
+
* refuses with "detected dubious ownership" without it.
|
|
715
|
+
* - `http.schannelUseSSLCAInfo=true` and
|
|
716
|
+
* `http.schannelCheckRevoke=false` when `schannelCa` — makes
|
|
717
|
+
* git's default (schannel) backend honor `GIT_SSL_CAINFO`
|
|
718
|
+
* without `-c http.sslBackend=openssl`. Revocation is disabled
|
|
719
|
+
* because CryptoAPI CRL/OCSP fetches ignore proxy env and would
|
|
720
|
+
* be WFP-fenced.
|
|
721
|
+
*
|
|
722
|
+
* Composes with an existing `GIT_CONFIG_COUNT` in `baseEnv` by
|
|
723
|
+
* continuing its numbering; the returned `GIT_CONFIG_COUNT` is the
|
|
724
|
+
* new total. Under the two-hop launch the broker's own environment
|
|
725
|
+
* never reaches the child, so `baseEnv` is the caller-supplied
|
|
726
|
+
* overlay ({@link WindowsSandboxParams.setEnvVars}), not
|
|
727
|
+
* `process.env`.
|
|
728
|
+
*
|
|
729
|
+
* Paths are emitted with forward slashes so the value survives
|
|
730
|
+
* msys2's env conversion untouched and native git accepts it.
|
|
731
|
+
*/
|
|
732
|
+
export function buildGitConfigEnv(opts) {
|
|
733
|
+
// An explicit `GIT_CONFIG_COUNT=0` in baseEnv is an opt-out ("no
|
|
734
|
+
// env-level git config") — respect it rather than overwriting.
|
|
735
|
+
if (opts.baseEnv?.GIT_CONFIG_COUNT === '0')
|
|
736
|
+
return {};
|
|
737
|
+
const parsed = Number.parseInt(opts.baseEnv?.GIT_CONFIG_COUNT ?? '', 10);
|
|
738
|
+
const start = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
|
|
739
|
+
let n = start;
|
|
740
|
+
const out = {};
|
|
741
|
+
const emit = (key, value) => {
|
|
742
|
+
out[`GIT_CONFIG_KEY_${n}`] = key;
|
|
743
|
+
out[`GIT_CONFIG_VALUE_${n}`] = value;
|
|
744
|
+
n++;
|
|
745
|
+
};
|
|
746
|
+
const dirs = [
|
|
747
|
+
...new Set(opts.safeDirs
|
|
748
|
+
.filter((d) => !!d)
|
|
749
|
+
.map(d => {
|
|
750
|
+
const fwd = d.replace(/\\/g, '/');
|
|
751
|
+
const stripped = fwd.replace(/\/+$/, '');
|
|
752
|
+
// Don't strip the trailing slash off a drive root — `C:`
|
|
753
|
+
// is drive-relative-cwd, not the root; git wants `C:/`.
|
|
754
|
+
return /^[A-Za-z]:$/.test(stripped) ? `${stripped}/` : stripped;
|
|
755
|
+
})),
|
|
756
|
+
];
|
|
757
|
+
if (dirs.length > SAFE_DIRECTORY_WILDCARD_THRESHOLD) {
|
|
758
|
+
emit('safe.directory', '*');
|
|
759
|
+
}
|
|
760
|
+
else {
|
|
761
|
+
// git matches safe.directory against the REPO TOP-LEVEL exactly,
|
|
762
|
+
// so a workspace root doesn't cover a nested repo. Emit both the
|
|
763
|
+
// exact path and the `<dir>/*` glob (git ≥2.46) so any repo
|
|
764
|
+
// at-or-under a granted dir is trusted.
|
|
765
|
+
for (const d of dirs) {
|
|
766
|
+
emit('safe.directory', d);
|
|
767
|
+
emit('safe.directory', `${d.endsWith('/') ? d : `${d}/`}*`);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
if (opts.schannelCa) {
|
|
771
|
+
emit('http.schannelUseSSLCAInfo', 'true');
|
|
772
|
+
emit('http.schannelCheckRevoke', 'false');
|
|
773
|
+
}
|
|
774
|
+
if (n === start)
|
|
775
|
+
return {};
|
|
776
|
+
out.GIT_CONFIG_COUNT = String(n);
|
|
777
|
+
return out;
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Build the spawn descriptor for running `command` inside the Windows
|
|
781
|
+
* sandbox: an `argv` array plus the `env` to spawn it with.
|
|
782
|
+
*
|
|
783
|
+
* Caller MUST spawn the result with `{shell: false}` — that is the
|
|
784
|
+
* security boundary that keeps untrusted bytes off the host's shell
|
|
785
|
+
* (the inner `cmd.exe /c` runs INSIDE the sandbox; see
|
|
786
|
+
* `vendor/srt-win-src/src/launch.rs` `build_cmdline` for the passthrough
|
|
787
|
+
* rationale) — AND with the returned `env`.
|
|
788
|
+
*
|
|
789
|
+
* Proxy configuration is single-sourced by {@link generateProxyEnvVars}
|
|
790
|
+
* (the same canonical builder used on macOS/Linux). `srt-win exec`
|
|
791
|
+
* takes no `--http-proxy` / `--socks-proxy` flags and synthesizes no
|
|
792
|
+
* proxy env. The two-hop runner starts with the SANDBOX user's
|
|
793
|
+
* profile env (`USERPROFILE`/`TEMP` isolated) and overlays exactly
|
|
794
|
+
* what we pass as `--env` — built here from the broker's `PATH` plus
|
|
795
|
+
* the generated proxy set.
|
|
796
|
+
*/
|
|
797
|
+
export function wrapCommandWithSandboxWindows(p) {
|
|
798
|
+
const { exe, prependArgs } = p.srtWin ?? resolveSrtWin();
|
|
799
|
+
// Generated proxy + CA-trust env. Single-sourced here so the
|
|
800
|
+
// same object feeds (a) the spawn env merge below and (b) the
|
|
801
|
+
// explicit `--env` overlay for the runner.
|
|
802
|
+
//
|
|
803
|
+
// The CA trust-bundle path is emitted with forward slashes:
|
|
804
|
+
// msys2's POSIX-path conversion leaves `C:/…` alone and every
|
|
805
|
+
// tool we set the var for (curl, git, node, python, …) accepts
|
|
806
|
+
// forward slashes on Windows; backslashes would be mangled if
|
|
807
|
+
// the value passes through a bash command line. Schannel-level
|
|
808
|
+
// trust comes from the registry write `srt-win user trust-ca`
|
|
809
|
+
// did at install time; the env-var layer here covers the
|
|
810
|
+
// OpenSSL-backed tools.
|
|
811
|
+
const generated = envListToObject(generateProxyEnvVars(p.httpProxyPort, p.socksProxyPort, p.caCertPath?.replace(/\\/g, '/'), p.proxyAuthToken));
|
|
812
|
+
// TMPDIR is a POSIX path meant for the macOS/Linux FS sandbox — it
|
|
813
|
+
// serves no purpose on Windows and breaks msys2 tools (mktemp etc.).
|
|
814
|
+
delete generated.TMPDIR;
|
|
815
|
+
// NO_PROXY=localhost,127.0.0.1,… is correct on POSIX where seatbelt/
|
|
816
|
+
// bwrap allow direct loopback: a NO_PROXY match makes the client
|
|
817
|
+
// connect directly and it works. On Windows the WFP fence blocks
|
|
818
|
+
// ALL direct connects from the sandbox user — including loopback
|
|
819
|
+
// outside the proxy-port PERMIT range — so NO_PROXY makes clients
|
|
820
|
+
// bypass the proxy and hit the fence; every localhost/127.0.0.1
|
|
821
|
+
// request fails. Consumers currently work around with
|
|
822
|
+
// `curl --noproxy ""`. Drop NO_PROXY here so localhost goes through
|
|
823
|
+
// the proxy (which connects on the child's behalf, from the broker's
|
|
824
|
+
// SID, and is not fenced).
|
|
825
|
+
delete generated.NO_PROXY;
|
|
826
|
+
delete generated.no_proxy;
|
|
827
|
+
// GIT_CONFIG_* set — safe.directory (dubious-ownership) + the
|
|
828
|
+
// schannel CA knobs. Composed against setEnvVars so a caller
|
|
829
|
+
// that already emits GIT_CONFIG_COUNT keeps its entries.
|
|
830
|
+
const gitCfg = buildGitConfigEnv({
|
|
831
|
+
safeDirs: [p.cwd ?? process.cwd(), ...(p.allowWrite ?? [])],
|
|
832
|
+
schannelCa: p.caCertPath !== undefined,
|
|
833
|
+
baseEnv: p.setEnvVars,
|
|
834
|
+
});
|
|
835
|
+
const argv = [exe, ...prependArgs, 'exec'];
|
|
836
|
+
if (p.quiet !== false)
|
|
837
|
+
argv.push('--quiet');
|
|
838
|
+
for (const d of p.denyRead ?? [])
|
|
839
|
+
argv.push('--deny-read', d);
|
|
840
|
+
for (const d of p.denyWrite ?? [])
|
|
841
|
+
argv.push('--deny-write', d);
|
|
842
|
+
// The two-hop runner starts with the SANDBOX user's profile env
|
|
843
|
+
// (USERPROFILE/TEMP isolated) and overlays exactly what we pass as
|
|
844
|
+
// `--env`. The broker does NOT enumerate its own env — the overlay
|
|
845
|
+
// is built here from the broker's PATH, the mode:'mask' sentinel
|
|
846
|
+
// set, the generated proxy set, and the GIT_CONFIG_* set.
|
|
847
|
+
// Sentinels precede `generated` so a caller masking e.g.
|
|
848
|
+
// `HTTPS_PROXY` cannot break the sandbox's own proxy plumbing —
|
|
849
|
+
// same precedence as the macOS/Linux `env -u … VAR=…
|
|
850
|
+
// sandbox-exec` order. `gitCfg` is last so its GIT_CONFIG_COUNT
|
|
851
|
+
// (which composes against setEnvVars) wins.
|
|
852
|
+
const overlay = {
|
|
853
|
+
PATH: process.env.PATH,
|
|
854
|
+
PATHEXT: process.env.PATHEXT,
|
|
855
|
+
...(p.setEnvVars ?? {}),
|
|
856
|
+
...generated,
|
|
857
|
+
...gitCfg,
|
|
858
|
+
};
|
|
859
|
+
for (const [k, v] of Object.entries(overlay)) {
|
|
860
|
+
if (v !== undefined)
|
|
861
|
+
argv.push('--env', `${k}=${v}`);
|
|
862
|
+
}
|
|
863
|
+
argv.push('--');
|
|
864
|
+
// Inner shell: `{exe, args}` from parseWindowsBinShell — the SOLE
|
|
865
|
+
// normalizer. `p.command` lands as a single argv element; srt-win's
|
|
866
|
+
// `build_cmdline` MSVCRT-quotes it (or wraps in one outer "…" for
|
|
867
|
+
// cmd /s) so the inner shell receives it intact. See launch.rs.
|
|
868
|
+
const sh = p.binShell ?? parseWindowsBinShell(undefined);
|
|
869
|
+
argv.push(sh.exe, ...sh.args, p.command);
|
|
870
|
+
// CreateProcessW's lpCommandLine is capped at 32 767 WCHARs.
|
|
871
|
+
// Node's `shell:false` spawn builds it by MSVCRT-quoting each
|
|
872
|
+
// argv element and joining with spaces; ~30 000 leaves headroom
|
|
873
|
+
// for the quote overhead the estimate doesn't model.
|
|
874
|
+
const cmdlineEstimate = argv.reduce((n, a) => n + a.length + 3, 0);
|
|
875
|
+
if (cmdlineEstimate > 30000) {
|
|
876
|
+
throw new Error(`Windows sandbox argv is ~${cmdlineEstimate} chars ` +
|
|
877
|
+
`(CreateProcessW limit is 32 767). Shorten the command, ` +
|
|
878
|
+
`or move broad globs to session-level filesystem.denyRead.`);
|
|
879
|
+
}
|
|
880
|
+
// The two-hop runner starts with a FRESH `srt-sandbox` profile
|
|
881
|
+
// env (`lpEnvironment = NULL` + `LOGON_WITH_PROFILE`), so the
|
|
882
|
+
// broker process's environment never reaches the child. The
|
|
883
|
+
// returned `env` is the spawn env for the broker (srt-win)
|
|
884
|
+
// process only; the child sees the `--env` overlay built into
|
|
885
|
+
// `argv` above (PATH/PATHEXT + mode:'mask' sentinels + proxy).
|
|
886
|
+
const env = { ...process.env, ...generated };
|
|
887
|
+
return { argv, env };
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* Parse a list of `KEY=VALUE` strings (as produced by
|
|
891
|
+
* {@link generateProxyEnvVars}) into an object. Splits on the FIRST
|
|
892
|
+
* `=` only, so values containing `=` survive intact.
|
|
893
|
+
*/
|
|
894
|
+
function envListToObject(list) {
|
|
895
|
+
const out = {};
|
|
896
|
+
for (const entry of list) {
|
|
897
|
+
const eq = entry.indexOf('=');
|
|
898
|
+
if (eq === -1)
|
|
899
|
+
continue;
|
|
900
|
+
out[entry.slice(0, eq)] = entry.slice(eq + 1);
|
|
901
|
+
}
|
|
902
|
+
return out;
|
|
903
|
+
}
|
|
904
|
+
// ────────────────────────────────────────────────────────────────────
|
|
905
|
+
// Dependency / readiness check
|
|
906
|
+
// ────────────────────────────────────────────────────────────────────
|
|
907
|
+
/**
|
|
908
|
+
* Install instructions, surfaced verbatim in error messages.
|
|
909
|
+
*/
|
|
910
|
+
export function windowsInstallInstructions(sublayerGuid) {
|
|
911
|
+
const sl = sublayerGuid ? ` --sublayer-guid ${sublayerGuid}` : '';
|
|
912
|
+
return (`Windows sandbox needs a one-time install (one UAC prompt):\n` +
|
|
913
|
+
` npx sandbox-runtime windows-install\n` +
|
|
914
|
+
` — or call installWindowsSandbox(), or run ` +
|
|
915
|
+
`\`srt-win.exe install${sl}\` directly.\n` +
|
|
916
|
+
`No logout is needed: the WFP filter keys on the dedicated ` +
|
|
917
|
+
`\`srt-sandbox\` user's SID, so your network is unaffected.`);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Check the Windows backend is ready to sandbox. Errors block
|
|
921
|
+
* `initialize()`; warnings are informational.
|
|
922
|
+
*/
|
|
923
|
+
export function checkWindowsDependencies(opts = {}) {
|
|
924
|
+
const { sublayerGuid } = opts;
|
|
925
|
+
const errors = [];
|
|
926
|
+
const warnings = [];
|
|
927
|
+
// 1. Binary present (`resolveSrtWin` throws on a missing
|
|
928
|
+
// override, `getSrtWinPath` on a missing packaged binary). Resolve
|
|
929
|
+
// once and reuse for the status calls below.
|
|
930
|
+
let srtWin;
|
|
931
|
+
try {
|
|
932
|
+
srtWin = opts.srtWin ?? resolveSrtWin();
|
|
933
|
+
}
|
|
934
|
+
catch (e) {
|
|
935
|
+
return { errors: [e.message], warnings };
|
|
936
|
+
}
|
|
937
|
+
logForDebugging(`[Sandbox Windows] using srt-win at ${srtWin.exe}`);
|
|
938
|
+
// 2. Sandbox user provisioned + credential readable.
|
|
939
|
+
let us;
|
|
940
|
+
try {
|
|
941
|
+
us = getWindowsSandboxUserStatus({ srtWin });
|
|
942
|
+
}
|
|
943
|
+
catch (e) {
|
|
944
|
+
errors.push(`srt-win user status failed: ${e.message}`);
|
|
945
|
+
return { errors, warnings };
|
|
946
|
+
}
|
|
947
|
+
if (!us.provisioned || !us.credPresent) {
|
|
948
|
+
errors.push(`Sandbox user is not provisioned (user=${us.provisioned}, ` +
|
|
949
|
+
`cred=${us.credPresent}). ` +
|
|
950
|
+
windowsInstallInstructions(sublayerGuid));
|
|
951
|
+
}
|
|
952
|
+
// 3. WFP filters installed under the sublayer. BFE enumeration is
|
|
953
|
+
// admin-gated; `cannot-read` is informational only — the
|
|
954
|
+
// BEHAVIORAL check (`verifyWindowsWfpEgress`) runs at
|
|
955
|
+
// `initialize()` and is what actually fails closed.
|
|
956
|
+
let ws;
|
|
957
|
+
try {
|
|
958
|
+
ws = getWindowsWfpStatus({ sublayerGuid, srtWin });
|
|
959
|
+
}
|
|
960
|
+
catch (e) {
|
|
961
|
+
errors.push(`srt-win wfp status failed: ${e.message}`);
|
|
962
|
+
return { errors, warnings };
|
|
963
|
+
}
|
|
964
|
+
if (ws.state === 'cannot-read') {
|
|
965
|
+
logForDebugging(`[Sandbox Windows] wfp status cannot-read (non-elevated): ${ws.hint}`);
|
|
966
|
+
}
|
|
967
|
+
else if (ws.state !== 'installed') {
|
|
968
|
+
// 'absent'. If the user is also not-provisioned, the user-state
|
|
969
|
+
// error above already gave the right instruction; don't repeat.
|
|
970
|
+
if (us.provisioned && us.credPresent) {
|
|
971
|
+
errors.push(`WFP filters not installed under sublayer ` +
|
|
972
|
+
`${sublayerGuid ?? '(default)'}. ` +
|
|
973
|
+
windowsInstallInstructions(sublayerGuid));
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
else if (ws.portRange) {
|
|
977
|
+
logForDebugging(`[Sandbox Windows] WFP installed: ${ws.filters} filters, ` +
|
|
978
|
+
`proxy port range ${ws.portRange[0]}-${ws.portRange[1]}`);
|
|
979
|
+
}
|
|
980
|
+
return { errors, warnings };
|
|
981
|
+
}
|
|
982
|
+
//# sourceMappingURL=windows-sandbox-utils.js.map
|