@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.
Files changed (136) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +93 -2
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +285 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +12 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/sandbox/credential-decode.d.ts +87 -0
  12. package/dist/sandbox/credential-decode.d.ts.map +1 -0
  13. package/dist/sandbox/credential-decode.js +143 -0
  14. package/dist/sandbox/credential-decode.js.map +1 -0
  15. package/dist/sandbox/credential-extract.d.ts +67 -0
  16. package/dist/sandbox/credential-extract.d.ts.map +1 -0
  17. package/dist/sandbox/credential-extract.js +122 -0
  18. package/dist/sandbox/credential-extract.js.map +1 -0
  19. package/dist/sandbox/credential-mask-env.d.ts +33 -0
  20. package/dist/sandbox/credential-mask-env.d.ts.map +1 -0
  21. package/dist/sandbox/credential-mask-env.js +155 -0
  22. package/dist/sandbox/credential-mask-env.js.map +1 -0
  23. package/dist/sandbox/credential-mask-files.d.ts +120 -0
  24. package/dist/sandbox/credential-mask-files.d.ts.map +1 -0
  25. package/dist/sandbox/credential-mask-files.js +285 -0
  26. package/dist/sandbox/credential-mask-files.js.map +1 -0
  27. package/dist/sandbox/credential-sentinel.d.ts +88 -0
  28. package/dist/sandbox/credential-sentinel.d.ts.map +1 -0
  29. package/dist/sandbox/credential-sentinel.js +177 -0
  30. package/dist/sandbox/credential-sentinel.js.map +1 -0
  31. package/dist/sandbox/domain-pattern.d.ts +36 -0
  32. package/dist/sandbox/domain-pattern.d.ts.map +1 -0
  33. package/dist/sandbox/domain-pattern.js +60 -0
  34. package/dist/sandbox/domain-pattern.js.map +1 -0
  35. package/dist/sandbox/generate-seccomp-filter.d.ts +20 -0
  36. package/dist/sandbox/generate-seccomp-filter.d.ts.map +1 -0
  37. package/dist/sandbox/generate-seccomp-filter.js +168 -0
  38. package/dist/sandbox/generate-seccomp-filter.js.map +1 -0
  39. package/dist/sandbox/http-proxy.d.ts +85 -0
  40. package/dist/sandbox/http-proxy.d.ts.map +1 -0
  41. package/dist/sandbox/http-proxy.js +379 -0
  42. package/dist/sandbox/http-proxy.js.map +1 -0
  43. package/dist/sandbox/linux-sandbox-utils.d.ts +162 -0
  44. package/dist/sandbox/linux-sandbox-utils.d.ts.map +1 -0
  45. package/dist/sandbox/linux-sandbox-utils.js +1179 -0
  46. package/dist/sandbox/linux-sandbox-utils.js.map +1 -0
  47. package/dist/sandbox/linux-violation-monitor.d.ts +48 -0
  48. package/dist/sandbox/linux-violation-monitor.d.ts.map +1 -0
  49. package/dist/sandbox/linux-violation-monitor.js +168 -0
  50. package/dist/sandbox/linux-violation-monitor.js.map +1 -0
  51. package/dist/sandbox/listen-in-range.d.ts +12 -0
  52. package/dist/sandbox/listen-in-range.d.ts.map +1 -0
  53. package/dist/sandbox/listen-in-range.js +43 -0
  54. package/dist/sandbox/listen-in-range.js.map +1 -0
  55. package/dist/sandbox/macos-sandbox-utils.d.ts +57 -0
  56. package/dist/sandbox/macos-sandbox-utils.d.ts.map +1 -0
  57. package/dist/sandbox/macos-sandbox-utils.js +810 -0
  58. package/dist/sandbox/macos-sandbox-utils.js.map +1 -0
  59. package/dist/sandbox/mitm-ca.d.ts +112 -0
  60. package/dist/sandbox/mitm-ca.d.ts.map +1 -0
  61. package/dist/sandbox/mitm-ca.js +380 -0
  62. package/dist/sandbox/mitm-ca.js.map +1 -0
  63. package/dist/sandbox/mitm-leaf.d.ts +28 -0
  64. package/dist/sandbox/mitm-leaf.d.ts.map +1 -0
  65. package/dist/sandbox/mitm-leaf.js +132 -0
  66. package/dist/sandbox/mitm-leaf.js.map +1 -0
  67. package/dist/sandbox/mux-proxy.d.ts +59 -0
  68. package/dist/sandbox/mux-proxy.d.ts.map +1 -0
  69. package/dist/sandbox/mux-proxy.js +161 -0
  70. package/dist/sandbox/mux-proxy.js.map +1 -0
  71. package/dist/sandbox/parent-proxy.d.ts +118 -0
  72. package/dist/sandbox/parent-proxy.d.ts.map +1 -0
  73. package/dist/sandbox/parent-proxy.js +469 -0
  74. package/dist/sandbox/parent-proxy.js.map +1 -0
  75. package/dist/sandbox/request-filter.d.ts +56 -0
  76. package/dist/sandbox/request-filter.d.ts.map +1 -0
  77. package/dist/sandbox/request-filter.js +109 -0
  78. package/dist/sandbox/request-filter.js.map +1 -0
  79. package/dist/sandbox/sandbox-config.d.ts +1347 -0
  80. package/dist/sandbox/sandbox-config.d.ts.map +1 -0
  81. package/dist/sandbox/sandbox-config.js +917 -0
  82. package/dist/sandbox/sandbox-config.js.map +1 -0
  83. package/dist/sandbox/sandbox-manager.d.ts +48 -0
  84. package/dist/sandbox/sandbox-manager.d.ts.map +1 -0
  85. package/dist/sandbox/sandbox-manager.js +1498 -0
  86. package/dist/sandbox/sandbox-manager.js.map +1 -0
  87. package/dist/sandbox/sandbox-schemas.d.ts +90 -0
  88. package/dist/sandbox/sandbox-schemas.d.ts.map +1 -0
  89. package/dist/sandbox/sandbox-schemas.js +3 -0
  90. package/dist/sandbox/sandbox-schemas.js.map +1 -0
  91. package/dist/sandbox/sandbox-temp-dir.d.ts +9 -0
  92. package/dist/sandbox/sandbox-temp-dir.d.ts.map +1 -0
  93. package/dist/sandbox/sandbox-temp-dir.js +73 -0
  94. package/dist/sandbox/sandbox-temp-dir.js.map +1 -0
  95. package/dist/sandbox/sandbox-utils.d.ts +121 -0
  96. package/dist/sandbox/sandbox-utils.d.ts.map +1 -0
  97. package/dist/sandbox/sandbox-utils.js +642 -0
  98. package/dist/sandbox/sandbox-utils.js.map +1 -0
  99. package/dist/sandbox/sandbox-violation-store.d.ts +19 -0
  100. package/dist/sandbox/sandbox-violation-store.d.ts.map +1 -0
  101. package/dist/sandbox/sandbox-violation-store.js +57 -0
  102. package/dist/sandbox/sandbox-violation-store.js.map +1 -0
  103. package/dist/sandbox/socks-proxy.d.ts +38 -0
  104. package/dist/sandbox/socks-proxy.d.ts.map +1 -0
  105. package/dist/sandbox/socks-proxy.js +123 -0
  106. package/dist/sandbox/socks-proxy.js.map +1 -0
  107. package/dist/sandbox/tls-terminate-proxy.d.ts +63 -0
  108. package/dist/sandbox/tls-terminate-proxy.d.ts.map +1 -0
  109. package/dist/sandbox/tls-terminate-proxy.js +332 -0
  110. package/dist/sandbox/tls-terminate-proxy.js.map +1 -0
  111. package/dist/sandbox/windows-sandbox-utils.d.ts +625 -0
  112. package/dist/sandbox/windows-sandbox-utils.d.ts.map +1 -0
  113. package/dist/sandbox/windows-sandbox-utils.js +982 -0
  114. package/dist/sandbox/windows-sandbox-utils.js.map +1 -0
  115. package/dist/utils/config-loader.d.ts +24 -0
  116. package/dist/utils/config-loader.d.ts.map +1 -0
  117. package/dist/utils/config-loader.js +65 -0
  118. package/dist/utils/config-loader.js.map +1 -0
  119. package/dist/utils/debug.d.ts +7 -0
  120. package/dist/utils/debug.d.ts.map +1 -0
  121. package/dist/utils/debug.js +25 -0
  122. package/dist/utils/debug.js.map +1 -0
  123. package/dist/utils/platform.d.ts +15 -0
  124. package/dist/utils/platform.d.ts.map +1 -0
  125. package/dist/utils/platform.js +52 -0
  126. package/dist/utils/platform.js.map +1 -0
  127. package/dist/utils/shell-quote.d.ts +27 -0
  128. package/dist/utils/shell-quote.d.ts.map +1 -0
  129. package/dist/utils/shell-quote.js +47 -0
  130. package/dist/utils/shell-quote.js.map +1 -0
  131. package/dist/utils/which.d.ts +9 -0
  132. package/dist/utils/which.d.ts.map +1 -0
  133. package/dist/utils/which.js +28 -0
  134. package/dist/utils/which.js.map +1 -0
  135. package/package.json +85 -4
  136. package/vendor/seccomp/x64/apply-seccomp +0 -0
@@ -0,0 +1,1179 @@
1
+ import { quote } from '../utils/shell-quote.js';
2
+ import { logForDebugging } from '../utils/debug.js';
3
+ import { whichSync } from '../utils/which.js';
4
+ import { randomBytes } from 'node:crypto';
5
+ import * as fs from 'fs';
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import { tmpdir } from 'node:os';
8
+ import path, { join } from 'node:path';
9
+ import { generateProxyEnvVars, normalizePathForSandbox, isSymlinkOutsideBoundary, encodeSandboxedCommand, } from './sandbox-utils.js';
10
+ import { getApplySeccompBinaryPath } from './generate-seccomp-filter.js';
11
+ /**
12
+ * Find if any component of the path is a symlink within the allowed write paths.
13
+ * Returns the symlink path if found, or null if no symlinks.
14
+ *
15
+ * This is used to detect and block symlink replacement attacks where an attacker
16
+ * could delete a symlink and create a real directory with malicious content.
17
+ */
18
+ function findSymlinkInPath(targetPath, allowedWritePaths) {
19
+ const parts = targetPath.split(path.sep);
20
+ let currentPath = '';
21
+ for (const part of parts) {
22
+ if (!part)
23
+ continue; // Skip empty parts (leading /)
24
+ const nextPath = currentPath + path.sep + part;
25
+ try {
26
+ const stats = fs.lstatSync(nextPath);
27
+ if (stats.isSymbolicLink()) {
28
+ // Check if this symlink is within an allowed write path
29
+ const isWithinAllowedPath = allowedWritePaths.some(allowedPath => nextPath.startsWith(allowedPath + '/') || nextPath === allowedPath);
30
+ if (isWithinAllowedPath) {
31
+ return nextPath;
32
+ }
33
+ }
34
+ }
35
+ catch {
36
+ // Path doesn't exist - no symlink issue here
37
+ break;
38
+ }
39
+ currentPath = nextPath;
40
+ }
41
+ return null;
42
+ }
43
+ /** Bounded depth for chasing dangling symlink chains (kernel ELOOP limit). */
44
+ const MAX_SYMLINK_RESOLUTION_DEPTH = 40;
45
+ /**
46
+ * Canonicalize a deny path through symlinks before any mask or bind is
47
+ * computed (resolve-before-mask). Deny paths regularly contain symlinked
48
+ * ancestors — the common dotfiles setup symlinks .claude (or the parent of
49
+ * .mcp.json) to a real directory — and masking the raw symlink with
50
+ * `--ro-bind /dev/null <symlink>` makes bwrap abort at startup: "Is a
51
+ * directory" for relative link targets, ENOENT for absolute ones.
52
+ *
53
+ * Resolution: realpath when the full path exists; otherwise canonicalize the
54
+ * deepest existing ancestor and re-join the missing components. A dangling
55
+ * symlink along the way is chain-walked (bounded) so the deny lands where a
56
+ * write through the link would actually create the file. Returns null when
57
+ * the path cannot be canonicalized (e.g. a symlink cycle); callers should
58
+ * skip such paths rather than emit a mask bwrap will reject.
59
+ *
60
+ * Unlike normalizePathForSandbox, this intentionally applies no
61
+ * isSymlinkOutsideBoundary check: that check exists so allow paths can't
62
+ * silently widen write access through a symlink, but a deny path only ever
63
+ * removes access, and the mask must land on the inode that writes through
64
+ * the symlink actually reach.
65
+ */
66
+ function resolveSymlinkedDenyPath(targetPath) {
67
+ let current = targetPath;
68
+ for (let i = 0; i < MAX_SYMLINK_RESOLUTION_DEPTH; i++) {
69
+ try {
70
+ return fs.realpathSync(current);
71
+ }
72
+ catch {
73
+ // Some component is missing or dangling — canonicalize manually below.
74
+ }
75
+ // Find the deepest ancestor that fully resolves, collecting the missing
76
+ // suffix components (leaf first, so unshift keeps them in path order).
77
+ let ancestor = current;
78
+ const remainder = [];
79
+ let resolvedAncestor = null;
80
+ while (resolvedAncestor === null) {
81
+ const parent = path.dirname(ancestor);
82
+ if (parent === ancestor) {
83
+ return null; // reached the root without resolving anything
84
+ }
85
+ remainder.unshift(path.basename(ancestor));
86
+ ancestor = parent;
87
+ try {
88
+ resolvedAncestor = fs.realpathSync(ancestor);
89
+ }
90
+ catch {
91
+ // Keep walking up.
92
+ }
93
+ }
94
+ // The first missing component may be a dangling symlink (lstat succeeds,
95
+ // realpath fails). Follow it and loop to re-canonicalize; otherwise the
96
+ // remainder is genuinely non-existent and the re-joined path is final.
97
+ const firstMissing = path.join(resolvedAncestor, remainder[0]);
98
+ let linkTarget = null;
99
+ try {
100
+ linkTarget = fs.readlinkSync(firstMissing);
101
+ }
102
+ catch {
103
+ // Not a symlink — nothing left to resolve.
104
+ }
105
+ if (linkTarget === null) {
106
+ return path.join(resolvedAncestor, ...remainder);
107
+ }
108
+ current = path.join(path.resolve(path.dirname(firstMissing), linkTarget), ...remainder.slice(1));
109
+ }
110
+ return null; // symlink chain too long or cyclic
111
+ }
112
+ /**
113
+ * Check if any existing component in the path is a file (not a directory).
114
+ * If so, the target path can never be created because you can't mkdir under a file.
115
+ *
116
+ * This handles the git worktree case: .git is a file, so .git/hooks can never
117
+ * exist and there's nothing to deny.
118
+ */
119
+ function hasFileAncestor(targetPath) {
120
+ const parts = targetPath.split(path.sep);
121
+ let currentPath = '';
122
+ for (const part of parts) {
123
+ if (!part)
124
+ continue; // Skip empty parts (leading /)
125
+ const nextPath = currentPath + path.sep + part;
126
+ try {
127
+ const stat = fs.statSync(nextPath);
128
+ if (!stat.isDirectory()) {
129
+ // Not a directory (file, FIFO, socket, etc.) — nothing below it can be created
130
+ return true;
131
+ }
132
+ }
133
+ catch {
134
+ // Path doesn't exist — stop checking
135
+ break;
136
+ }
137
+ currentPath = nextPath;
138
+ }
139
+ return false;
140
+ }
141
+ /**
142
+ * Find the first non-existent path component.
143
+ * E.g., for "/existing/parent/nonexistent/child/file.txt" where /existing/parent exists,
144
+ * returns "/existing/parent/nonexistent"
145
+ *
146
+ * This is used to block creation of non-existent deny paths by mounting /dev/null
147
+ * at the first missing component, preventing mkdir from creating the parent directories.
148
+ */
149
+ function findFirstNonExistentComponent(targetPath) {
150
+ const parts = targetPath.split(path.sep);
151
+ let currentPath = '';
152
+ for (const part of parts) {
153
+ if (!part)
154
+ continue; // Skip empty parts (leading /)
155
+ const nextPath = currentPath + path.sep + part;
156
+ if (!fs.existsSync(nextPath)) {
157
+ return nextPath;
158
+ }
159
+ currentPath = nextPath;
160
+ }
161
+ return targetPath; // Shouldn't reach here if called correctly
162
+ }
163
+ // Track mount points created by bwrap for non-existent deny paths.
164
+ // When bwrap does --ro-bind /dev/null /nonexistent/path, it creates an empty
165
+ // file on the host as a mount point. These persist after bwrap exits and must
166
+ // be cleaned up explicitly.
167
+ const bwrapMountPoints = new Set();
168
+ // Shared empty read-only directory used as source for non-existent intermediate
169
+ // denyWrite mount points. Reused across wraps and removed on teardown when
170
+ // activeSandboxCount reaches zero (or on process exit).
171
+ let emptyReadOnlyDir;
172
+ function getEmptyReadOnlyDir() {
173
+ if (emptyReadOnlyDir && fs.existsSync(emptyReadOnlyDir)) {
174
+ return emptyReadOnlyDir;
175
+ }
176
+ const dir = fs.mkdtempSync(path.join(tmpdir(), 'claude-empty-'));
177
+ fs.chmodSync(dir, 0o500);
178
+ emptyReadOnlyDir = dir;
179
+ registerExitCleanupHandler();
180
+ return dir;
181
+ }
182
+ // Number of wrapped commands that have been generated but whose cleanup has
183
+ // not yet run. cleanupBwrapMountPoints() defers file deletion while this is
184
+ // positive, because deleting a mount point file on the host while another
185
+ // bwrap instance is still running detaches that instance's bind mount and
186
+ // the deny rule stops applying inside it.
187
+ let activeSandboxCount = 0;
188
+ // Forced cleanups so far. One zeroes the count under a wrap still in flight,
189
+ // which from then on has nothing in it to give back.
190
+ let forcedCleanups = 0;
191
+ let exitHandlerRegistered = false;
192
+ /**
193
+ * Register cleanup handler for bwrap mount points
194
+ */
195
+ function registerExitCleanupHandler() {
196
+ if (exitHandlerRegistered) {
197
+ return;
198
+ }
199
+ process.on('exit', () => {
200
+ cleanupBwrapMountPoints({ force: true });
201
+ });
202
+ exitHandlerRegistered = true;
203
+ }
204
+ /**
205
+ * Clean up mount point files created by bwrap for non-existent deny paths.
206
+ *
207
+ * When protecting non-existent deny paths, bwrap creates empty files on the
208
+ * host filesystem as mount points for --ro-bind. These files persist after
209
+ * bwrap exits. This function removes them.
210
+ *
211
+ * This should be called after each sandboxed command completes to prevent
212
+ * ghost dotfiles (e.g. .bashrc, .gitconfig) from appearing in the working
213
+ * directory. It is also called automatically on process exit as a safety net.
214
+ *
215
+ * Each command-completion call decrements the active-sandbox counter incremented by
216
+ * wrapCommandWithSandboxLinux(). File deletion is deferred until the counter
217
+ * reaches zero. Deleting a mount point file on the host while another bwrap
218
+ * instance is still running detaches that instance's bind mount (the dentry
219
+ * is unhashed, so path lookup no longer finds the mount) and the deny rule
220
+ * stops applying inside that sandbox.
221
+ *
222
+ * Pass `{ completed: false }` during manager teardown to leave other commands'
223
+ * counts untouched. `{ force: true }` is reserved for process exit.
224
+ */
225
+ export function cleanupBwrapMountPoints(opts) {
226
+ if (!opts?.force) {
227
+ if (opts?.completed !== false && activeSandboxCount > 0) {
228
+ activeSandboxCount--;
229
+ }
230
+ if (activeSandboxCount > 0) {
231
+ logForDebugging(`[Sandbox Linux] Deferring mount point cleanup — ${activeSandboxCount} sandbox(es) still active`);
232
+ return;
233
+ }
234
+ }
235
+ else {
236
+ activeSandboxCount = 0;
237
+ forcedCleanups++;
238
+ }
239
+ // Deepest first: a sandbox wrapped while another's directory mount point is
240
+ // there gets its own inside it, and a directory goes only when it is empty.
241
+ const deepestFirst = [...bwrapMountPoints].sort((a, b) => b.length - a.length);
242
+ for (const mountPoint of deepestFirst) {
243
+ try {
244
+ // Only remove if it's still the empty file/directory bwrap created.
245
+ // Use lstatSync so symlinks are never followed.
246
+ const stat = fs.lstatSync(mountPoint);
247
+ if (stat.isFile() && stat.size === 0) {
248
+ fs.unlinkSync(mountPoint);
249
+ logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${mountPoint}`);
250
+ }
251
+ else if (stat.isDirectory()) {
252
+ // Empty directory mount points are created for intermediate
253
+ // components (Fix 2). Only remove if still empty.
254
+ const entries = fs.readdirSync(mountPoint);
255
+ if (entries.length === 0) {
256
+ fs.rmdirSync(mountPoint);
257
+ logForDebugging(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${mountPoint}`);
258
+ }
259
+ }
260
+ }
261
+ catch {
262
+ // Ignore cleanup errors — the file may have already been removed
263
+ }
264
+ }
265
+ bwrapMountPoints.clear();
266
+ if (emptyReadOnlyDir) {
267
+ try {
268
+ fs.rmSync(emptyReadOnlyDir, { recursive: true, force: true });
269
+ }
270
+ catch {
271
+ // Best effort
272
+ }
273
+ emptyReadOnlyDir = undefined;
274
+ }
275
+ }
276
+ // Probing spawns bwrap, so cache the result per resolved binary for the
277
+ // lifetime of the process.
278
+ const procMountProbeCache = new Map();
279
+ /**
280
+ * Probe whether bwrap can mount a private /proc with the same namespace flags
281
+ * the secure path uses (`--unshare-user --cap-drop ALL --unshare-pid --proc
282
+ * /proc`). Returns true when the mount succeeds. In unprivileged containers
283
+ * this fails with "Can't mount proc on /newroot/proc: Operation not
284
+ * permitted", which otherwise surfaces cryptically on every command.
285
+ */
286
+ function canMountPrivateProc(bwrapPath) {
287
+ const bwrap = bwrapPath ?? 'bwrap';
288
+ const cached = procMountProbeCache.get(bwrap);
289
+ if (cached !== undefined)
290
+ return cached;
291
+ const trueBin = whichSync('true') ?? '/bin/true';
292
+ const result = spawnSync(bwrap, [
293
+ '--ro-bind',
294
+ '/',
295
+ '/',
296
+ '--unshare-user',
297
+ '--cap-drop',
298
+ 'ALL',
299
+ '--unshare-pid',
300
+ '--proc',
301
+ '/proc',
302
+ '--',
303
+ trueBin,
304
+ ], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 5000, encoding: 'utf8' });
305
+ // On spawn failure (e.g. bwrap missing) don't claim a proc-mount problem;
306
+ // the missing-binary check reports that separately.
307
+ const ok = result.error !== undefined
308
+ ? true
309
+ : result.status === 0 ||
310
+ !/Operation not permitted|Can't mount proc/i.test(result.stderr ?? '');
311
+ procMountProbeCache.set(bwrap, ok);
312
+ return ok;
313
+ }
314
+ function isExecutable(p) {
315
+ try {
316
+ fs.accessSync(p, fs.constants.X_OK);
317
+ return true;
318
+ }
319
+ catch {
320
+ return false;
321
+ }
322
+ }
323
+ /**
324
+ * Check sandbox dependencies and return structured result
325
+ */
326
+ export function checkLinuxDependencies(opts) {
327
+ const { seccompConfig, bwrapPath, socatPath } = opts ?? {};
328
+ const errors = [];
329
+ const warnings = [];
330
+ // An explicit override is a directive, not a hint — if it doesn't exist,
331
+ // surface that rather than silently falling back to PATH.
332
+ if (bwrapPath) {
333
+ if (!isExecutable(bwrapPath))
334
+ errors.push(`bubblewrap (bwrap) not executable at ${bwrapPath}`);
335
+ }
336
+ else if (whichSync('bwrap') === null) {
337
+ errors.push('bubblewrap (bwrap) not installed');
338
+ }
339
+ if (socatPath) {
340
+ if (!isExecutable(socatPath))
341
+ errors.push(`socat not executable at ${socatPath}`);
342
+ }
343
+ else if (whichSync('socat') === null) {
344
+ errors.push('socat not installed');
345
+ }
346
+ if (!seccompConfig?.argv0 &&
347
+ getApplySeccompBinaryPath(seccompConfig?.applyPath) === null) {
348
+ warnings.push('seccomp not available - unix socket access not restricted');
349
+ }
350
+ // Secure mode mounts a private /proc (--proc /proc). In unprivileged
351
+ // containers that EPERMs, and every sandboxed command then fails with an
352
+ // opaque "bwrap: Can't mount proc on /newroot/proc". Probe once and point
353
+ // at the fix instead. Only when bwrap is actually present.
354
+ if (!opts?.enableWeakerNestedSandbox &&
355
+ errors.length === 0 &&
356
+ !canMountPrivateProc(bwrapPath)) {
357
+ errors.push('bubblewrap cannot mount a private /proc, which is expected in ' +
358
+ "unprivileged containers (e.g. Docker's default). Set " +
359
+ '"enableWeakerNestedSandbox": true in the sandbox config to run here ' +
360
+ '(note: this weakens isolation), or grant the container the required ' +
361
+ 'namespace privileges.');
362
+ }
363
+ return { warnings, errors };
364
+ }
365
+ /**
366
+ * Initialize the Linux network bridge for sandbox networking
367
+ *
368
+ * ARCHITECTURE NOTE:
369
+ * Linux network sandboxing uses bwrap --unshare-net which creates a completely isolated
370
+ * network namespace with NO network access. To enable network access, we:
371
+ *
372
+ * 1. Host side: Run socat bridges that listen on Unix sockets and forward to host proxy servers
373
+ * - HTTP bridge: Unix socket -> host HTTP proxy (for HTTP/HTTPS traffic)
374
+ * - SOCKS bridge: Unix socket -> host SOCKS5 proxy (for SSH/git traffic)
375
+ *
376
+ * 2. Sandbox side: Bind the Unix sockets into the isolated namespace and run socat listeners
377
+ * - HTTP listener on port 3128 -> HTTP Unix socket -> host HTTP proxy
378
+ * - SOCKS listener on port 1080 -> SOCKS Unix socket -> host SOCKS5 proxy
379
+ *
380
+ * 3. Configure environment:
381
+ * - HTTP_PROXY=http://localhost:3128 for HTTP/HTTPS tools
382
+ * - GIT_SSH_COMMAND with socat for SSH through SOCKS5
383
+ *
384
+ * LIMITATION: Unlike macOS sandbox which can enforce domain-based allowlists at the kernel level,
385
+ * Linux's --unshare-net provides only all-or-nothing network isolation. Domain filtering happens
386
+ * at the host proxy level, not the sandbox boundary. This means network restrictions on Linux
387
+ * depend on the proxy's filtering capabilities.
388
+ *
389
+ * DEPENDENCIES: Requires bwrap (bubblewrap) and socat
390
+ */
391
+ function escapeSocatAddr(addr) {
392
+ return addr.replace(/([\\,:])/g, '\\$1');
393
+ }
394
+ function cleanupFailedBridge(procs, paths) {
395
+ for (const proc of procs) {
396
+ if (proc?.pid && proc.exitCode === null && proc.signalCode === null) {
397
+ try {
398
+ process.kill(proc.pid, 'SIGTERM');
399
+ }
400
+ catch {
401
+ // Ignore
402
+ }
403
+ }
404
+ }
405
+ for (const p of paths) {
406
+ try {
407
+ fs.rmSync(p, { force: true });
408
+ }
409
+ catch {
410
+ // Ignore
411
+ }
412
+ }
413
+ }
414
+ export async function initializeLinuxNetworkBridge(httpProxyPort, socksProxyPort, socatPath) {
415
+ const socat = socatPath ?? 'socat';
416
+ const socketId = randomBytes(8).toString('hex');
417
+ const httpSocketPath = join(tmpdir(), `claude-http-${socketId}.sock`);
418
+ // Only allocated when ports differ; in the mux case the SOCKS side
419
+ // reuses httpSocketPath.
420
+ const socksSocketPath = join(tmpdir(), `claude-socks-${socketId}.sock`);
421
+ // Start HTTP bridge
422
+ const httpSocatArgs = [
423
+ `UNIX-LISTEN:${escapeSocatAddr(httpSocketPath)},fork,reuseaddr`,
424
+ `TCP:localhost:${httpProxyPort},nodelay,keepalive,keepidle=10,keepintvl=5,keepcnt=3`,
425
+ ];
426
+ logForDebugging(`Starting HTTP bridge: ${socat} ${httpSocatArgs.join(' ')}`);
427
+ const httpBridgeProcess = spawn(socat, httpSocatArgs, {
428
+ stdio: 'ignore',
429
+ });
430
+ // Add error and exit handlers to monitor bridge health. These must be
431
+ // registered before the !pid check: when spawn fails (e.g. socat is
432
+ // missing or not executable), the ChildProcess emits an asynchronous
433
+ // 'error' event, and throwing first would leave that event without a
434
+ // listener — surfacing as an uncaughtException instead of the rejection
435
+ // below.
436
+ httpBridgeProcess.on('error', err => {
437
+ logForDebugging(`HTTP bridge process error: ${err}`, { level: 'error' });
438
+ });
439
+ httpBridgeProcess.on('exit', (code, signal) => {
440
+ logForDebugging(`HTTP bridge process exited with code ${code}, signal ${signal}`, { level: code === 0 ? 'info' : 'error' });
441
+ });
442
+ if (!httpBridgeProcess.pid) {
443
+ throw new Error('Failed to start HTTP bridge process');
444
+ }
445
+ // SOCKS bridge: when the host serves both protocols on one port (the mux),
446
+ // a second socat to the same TCP target is redundant — reuse the HTTP
447
+ // bridge's process and socket path. Downstream consumers
448
+ // (LinuxNetworkBridgeContext, in-sandbox socat, cleanup) treat duplicate
449
+ // refs idempotently. A separate bridge is only spawned when the ports
450
+ // differ (external proxy override).
451
+ let socksBridgeProcess;
452
+ let socksSockPath;
453
+ if (socksProxyPort === httpProxyPort) {
454
+ socksBridgeProcess = httpBridgeProcess;
455
+ socksSockPath = httpSocketPath;
456
+ }
457
+ else {
458
+ socksSockPath = socksSocketPath;
459
+ const socksSocatArgs = [
460
+ `UNIX-LISTEN:${escapeSocatAddr(socksSocketPath)},fork,reuseaddr`,
461
+ `TCP:localhost:${socksProxyPort},nodelay,keepalive,keepidle=10,keepintvl=5,keepcnt=3`,
462
+ ];
463
+ logForDebugging(`Starting SOCKS bridge: ${socat} ${socksSocatArgs.join(' ')}`);
464
+ socksBridgeProcess = spawn(socat, socksSocatArgs, {
465
+ stdio: 'ignore',
466
+ });
467
+ // Add error and exit handlers to monitor bridge health — registered
468
+ // before the !pid check for the same reason as the HTTP bridge above.
469
+ socksBridgeProcess.on('error', err => {
470
+ logForDebugging(`SOCKS bridge process error: ${err}`, { level: 'error' });
471
+ });
472
+ socksBridgeProcess.on('exit', (code, signal) => {
473
+ logForDebugging(`SOCKS bridge process exited with code ${code}, signal ${signal}`, { level: code === 0 ? 'info' : 'error' });
474
+ });
475
+ if (!socksBridgeProcess.pid) {
476
+ cleanupFailedBridge([httpBridgeProcess, socksBridgeProcess], [httpSocketPath, socksSockPath]);
477
+ throw new Error('Failed to start SOCKS bridge process');
478
+ }
479
+ }
480
+ // Wait for both sockets to be ready
481
+ const maxAttempts = 5;
482
+ for (let i = 0; i < maxAttempts; i++) {
483
+ const httpDead = !httpBridgeProcess.pid ||
484
+ httpBridgeProcess.exitCode !== null ||
485
+ httpBridgeProcess.signalCode !== null;
486
+ const socksDead = !socksBridgeProcess.pid ||
487
+ socksBridgeProcess.exitCode !== null ||
488
+ socksBridgeProcess.signalCode !== null;
489
+ if (httpDead || socksDead) {
490
+ cleanupFailedBridge([httpBridgeProcess, socksBridgeProcess], [httpSocketPath, socksSockPath]);
491
+ throw new Error('Linux bridge process died unexpectedly');
492
+ }
493
+ try {
494
+ // fs already imported
495
+ if (fs.existsSync(httpSocketPath) && fs.existsSync(socksSockPath)) {
496
+ logForDebugging(`Linux bridges ready after ${i + 1} attempts`);
497
+ break;
498
+ }
499
+ }
500
+ catch (err) {
501
+ logForDebugging(`Error checking sockets (attempt ${i + 1}): ${err}`, {
502
+ level: 'error',
503
+ });
504
+ }
505
+ if (i === maxAttempts - 1) {
506
+ cleanupFailedBridge([httpBridgeProcess, socksBridgeProcess], [httpSocketPath, socksSockPath]);
507
+ throw new Error(`Failed to create bridge sockets after ${maxAttempts} attempts`);
508
+ }
509
+ await new Promise(resolve => setTimeout(resolve, i * 100));
510
+ }
511
+ return {
512
+ httpSocketPath,
513
+ socksSocketPath: socksSockPath,
514
+ httpBridgeProcess,
515
+ socksBridgeProcess,
516
+ httpProxyPort,
517
+ socksProxyPort,
518
+ };
519
+ }
520
+ /**
521
+ * Resolve how to invoke apply-seccomp: either a standalone binary path, or a
522
+ * multicall-binary prefix that dispatches on the ARGV0 env var.
523
+ *
524
+ * Returns a shell-ready string ending in a trailing space — callers append
525
+ * quote([shell, '-c', cmd]). Returns undefined when seccomp is
526
+ * unavailable (no argv0, no binary found).
527
+ *
528
+ * When argv0 is set, applyPath is used verbatim (no existence check); the
529
+ * caller is responsible for ensuring it resolves inside the bwrap namespace.
530
+ */
531
+ function resolveApplySeccompPrefix(applyPath, argv0) {
532
+ if (argv0) {
533
+ if (!applyPath) {
534
+ throw new Error('seccompConfig.argv0 requires seccompConfig.applyPath');
535
+ }
536
+ return `ARGV0=${quote([argv0])} ${quote([applyPath])} `;
537
+ }
538
+ const binary = getApplySeccompBinaryPath(applyPath);
539
+ return binary ? `${quote([binary])} ` : undefined;
540
+ }
541
+ /**
542
+ * Build the command that runs inside the sandbox.
543
+ * Sets up HTTP proxy on port 3128 and SOCKS proxy on port 1080
544
+ */
545
+ function buildSandboxCommand(httpSocketPath, socksSocketPath, userCommand, applySeccompPrefix, shell, socatPath) {
546
+ const shellPath = shell || 'bash';
547
+ const quotedShell = quote([shellPath]);
548
+ // Host filesystem is bind-mounted into the sandbox, so an explicit
549
+ // socatPath resolves to the same binary inside bwrap.
550
+ const socat = quote([socatPath ?? 'socat']);
551
+ const httpConnectArg = quote([
552
+ `UNIX-CONNECT:${escapeSocatAddr(httpSocketPath)}`,
553
+ ]);
554
+ const socksConnectArg = quote([
555
+ `UNIX-CONNECT:${escapeSocatAddr(socksSocketPath)}`,
556
+ ]);
557
+ const socatCommands = [
558
+ `${socat} TCP-LISTEN:3128,fork,reuseaddr,nodelay ${httpConnectArg} >/dev/null 2>&1 &`,
559
+ `${socat} TCP-LISTEN:1080,fork,reuseaddr,nodelay ${socksConnectArg} >/dev/null 2>&1 &`,
560
+ // Save and re-exit with the script's status: under zsh a bare `exit` in
561
+ // an EXIT trap takes the kill's status, so failures reported 0.
562
+ "trap 'rc=$?; kill %1 %2 2>/dev/null; exit $rc' EXIT",
563
+ ];
564
+ // apply-seccomp runs after socat so socat can still create Unix sockets.
565
+ if (applySeccompPrefix) {
566
+ const applySeccompCmd = applySeccompPrefix + quote([shellPath, '-c', userCommand]);
567
+ const innerScript = [...socatCommands, applySeccompCmd].join('\n');
568
+ return `${quotedShell} -c ${quote([innerScript])}`;
569
+ }
570
+ else {
571
+ const innerScript = [...socatCommands, `eval ${quote([userCommand])}`].join('\n');
572
+ return `${quotedShell} -c ${quote([innerScript])}`;
573
+ }
574
+ }
575
+ /**
576
+ * bwrap cannot create a file bind mount point over a destination that is
577
+ * itself a symlink — `--ro-bind /dev/null <symlink>` fails with "Can't create
578
+ * file at <path>" and the whole command refuses to start. File read-deny
579
+ * binds therefore target the symlink's resolved target instead: reads
580
+ * through the symlink resolve to that target inside the mount namespace, so
581
+ * the denied content stays covered. This matters for credential dotfiles
582
+ * (~/.netrc, ~/.npmrc, …) that are commonly symlinks into a dotfile
583
+ * manager's directory. Directory denies (`--tmpfs`) are left on the original
584
+ * path: bwrap accepts those, and rewriting them would break allowRead
585
+ * carve-outs expressed against the symlink path (e.g. /bin on usr-merged
586
+ * systems).
587
+ */
588
+ function isSymlink(p) {
589
+ try {
590
+ return fs.lstatSync(p).isSymbolicLink();
591
+ }
592
+ catch {
593
+ return false;
594
+ }
595
+ }
596
+ function resolveDenyDest(normalizedPath) {
597
+ return resolveSymlinkedDenyPath(normalizedPath) ?? normalizedPath;
598
+ }
599
+ /**
600
+ * Mount a tmpfs over a read-denied directory, then restore the allowRead
601
+ * paths and the allowed write paths the tmpfs just wiped. Used by the
602
+ * denyRead loop in generateFilesystemArgs and again when a late denyWrite
603
+ * ro-bind re-exposes a read-denied directory and the tmpfs must be
604
+ * re-applied on top.
605
+ *
606
+ * Order matters: bwrap applies binds in order, so the write re-binds are
607
+ * emitted AFTER the allowRead re-binds. An allowRead path can be an
608
+ * ancestor of an allowed-write path (e.g. allowRead: [~/src],
609
+ * allowWrite: [~/src/repo]); emitting the ancestor's ro-bind last would
610
+ * silently cover the descendant's rw bind and leave the write path —
611
+ * often the cwd — read-only again.
612
+ */
613
+ function pushReadDenyDirMounts(args, normalizedPath, allowedWritePaths, readAllowPaths) {
614
+ const denySep = normalizedPath === '/' ? '/' : normalizedPath + '/';
615
+ args.push('--tmpfs', normalizedPath);
616
+ // Re-allow specific paths within the denied directory (allowRead overrides denyRead).
617
+ // After mounting tmpfs over the denied dir, bind back the allowed subdirectories
618
+ // so they are readable again.
619
+ for (const allowPath of readAllowPaths) {
620
+ if (allowPath.startsWith(denySep) || allowPath === normalizedPath) {
621
+ if (!fs.existsSync(allowPath)) {
622
+ logForDebugging(`[Sandbox Linux] Skipping non-existent read allow path: ${allowPath}`);
623
+ continue;
624
+ }
625
+ // Skip only if a write path below will be re-bound AND covers
626
+ // allowPath. A write path that's an ancestor of the deny dir isn't
627
+ // re-bound (it wasn't wiped), so allowPath under it still needs
628
+ // its own ro-bind here.
629
+ if (allowedWritePaths.some(w => w.startsWith(denySep) &&
630
+ (allowPath === w || allowPath.startsWith(w + '/')))) {
631
+ continue;
632
+ }
633
+ // Bind the allowed path back over the tmpfs so it's readable
634
+ args.push('--ro-bind', allowPath, allowPath);
635
+ logForDebugging(`[Sandbox Linux] Re-allowed read access within denied region: ${allowPath}`);
636
+ }
637
+ }
638
+ // tmpfs wiped any earlier write binds strictly under this path — restore them.
639
+ // Exact-match writePath === normalizedPath is intentionally NOT restored,
640
+ // because denyRead must win over allowWrite on the same directory.
641
+ for (const writePath of allowedWritePaths) {
642
+ if (writePath.startsWith(denySep)) {
643
+ args.push('--bind', writePath, writePath);
644
+ logForDebugging(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${writePath}`);
645
+ }
646
+ }
647
+ }
648
+ function collectWriteAndDenyWriteArgs(writeConfig, args) {
649
+ const allowedWritePaths = [];
650
+ const denyWriteArgs = [];
651
+ const denyWriteRawDests = new Map();
652
+ if (!writeConfig) {
653
+ args.push('--bind', '/', '/');
654
+ return { allowedWritePaths, denyWriteArgs, denyWriteRawDests };
655
+ }
656
+ args.push('--ro-bind', '/', '/');
657
+ for (const pathPattern of writeConfig.allowOnly || []) {
658
+ const normalizedPath = normalizePathForSandbox(pathPattern);
659
+ logForDebugging(`[Sandbox Linux] Processing write path: ${pathPattern} -> ${normalizedPath}`);
660
+ if (normalizedPath.startsWith('/dev/')) {
661
+ logForDebugging(`[Sandbox Linux] Skipping /dev path: ${normalizedPath}`);
662
+ continue;
663
+ }
664
+ if (!fs.existsSync(normalizedPath)) {
665
+ logForDebugging(`[Sandbox Linux] Skipping non-existent write path: ${normalizedPath}`);
666
+ continue;
667
+ }
668
+ try {
669
+ const resolvedPath = fs.realpathSync(normalizedPath);
670
+ const normalizedForComparison = normalizedPath.replace(/\/+$/, '');
671
+ if (resolvedPath !== normalizedForComparison &&
672
+ isSymlinkOutsideBoundary(normalizedPath, resolvedPath)) {
673
+ logForDebugging(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${pathPattern} -> ${resolvedPath}`);
674
+ continue;
675
+ }
676
+ }
677
+ catch {
678
+ logForDebugging(`[Sandbox Linux] Skipping write path that could not be resolved: ${normalizedPath}`);
679
+ continue;
680
+ }
681
+ args.push('--bind', normalizedPath, normalizedPath);
682
+ allowedWritePaths.push(normalizedPath);
683
+ }
684
+ const seenDenyWrite = new Set();
685
+ const seenDenyWriteMountDests = new Set();
686
+ for (const pathPattern of writeConfig.denyWithinAllow || []) {
687
+ const rawPath = normalizePathForSandbox(pathPattern);
688
+ if (rawPath.startsWith('/dev/'))
689
+ continue;
690
+ const normalizedPath = resolveSymlinkedDenyPath(rawPath);
691
+ if (normalizedPath === null) {
692
+ const unresolvableSymlink = findSymlinkInPath(rawPath, allowedWritePaths);
693
+ if (unresolvableSymlink &&
694
+ !seenDenyWrite.has(unresolvableSymlink) &&
695
+ !seenDenyWriteMountDests.has(unresolvableSymlink)) {
696
+ seenDenyWrite.add(unresolvableSymlink);
697
+ seenDenyWriteMountDests.add(unresolvableSymlink);
698
+ denyWriteArgs.push('--ro-bind', '/dev/null', unresolvableSymlink);
699
+ denyWriteRawDests.set(unresolvableSymlink, rawPath);
700
+ }
701
+ logForDebugging(`[Sandbox Linux] Deny path could not be resolved through symlinks, failing closed: ${rawPath}`);
702
+ continue;
703
+ }
704
+ if (normalizedPath !== rawPath) {
705
+ logForDebugging(`[Sandbox Linux] Resolved symlinked deny path: ${rawPath} -> ${normalizedPath}`);
706
+ }
707
+ if (normalizedPath.startsWith('/dev/'))
708
+ continue;
709
+ if (seenDenyWrite.has(normalizedPath))
710
+ continue;
711
+ seenDenyWrite.add(normalizedPath);
712
+ const symlinkInPath = findSymlinkInPath(normalizedPath, allowedWritePaths);
713
+ if (symlinkInPath) {
714
+ if (!seenDenyWrite.has(symlinkInPath) &&
715
+ !seenDenyWriteMountDests.has(symlinkInPath)) {
716
+ seenDenyWrite.add(symlinkInPath);
717
+ seenDenyWriteMountDests.add(symlinkInPath);
718
+ denyWriteArgs.push('--ro-bind', '/dev/null', symlinkInPath);
719
+ denyWriteRawDests.set(symlinkInPath, rawPath);
720
+ }
721
+ logForDebugging(`[Sandbox Linux] Mounted /dev/null at symlink ${symlinkInPath} to prevent symlink replacement attack`);
722
+ continue;
723
+ }
724
+ if (!fs.existsSync(normalizedPath)) {
725
+ if (hasFileAncestor(normalizedPath)) {
726
+ logForDebugging(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${normalizedPath}`);
727
+ continue;
728
+ }
729
+ let ancestorPath = path.dirname(normalizedPath);
730
+ while (ancestorPath !== '/' && !fs.existsSync(ancestorPath)) {
731
+ ancestorPath = path.dirname(ancestorPath);
732
+ }
733
+ const ancestorIsWithinAllowedPath = allowedWritePaths.some(allowedPath => ancestorPath.startsWith(allowedPath + '/') ||
734
+ ancestorPath === allowedPath ||
735
+ normalizedPath.startsWith(allowedPath + '/'));
736
+ if (ancestorIsWithinAllowedPath) {
737
+ const firstNonExistent = findFirstNonExistentComponent(normalizedPath);
738
+ if (seenDenyWriteMountDests.has(firstNonExistent)) {
739
+ continue;
740
+ }
741
+ seenDenyWriteMountDests.add(firstNonExistent);
742
+ if (firstNonExistent !== normalizedPath) {
743
+ denyWriteArgs.push('--ro-bind', getEmptyReadOnlyDir(), firstNonExistent);
744
+ denyWriteRawDests.set(firstNonExistent, rawPath);
745
+ bwrapMountPoints.add(firstNonExistent);
746
+ registerExitCleanupHandler();
747
+ logForDebugging(`[Sandbox Linux] Mounted empty dir at ${firstNonExistent} to block creation of ${normalizedPath}`);
748
+ }
749
+ else {
750
+ denyWriteArgs.push('--ro-bind', '/dev/null', firstNonExistent);
751
+ denyWriteRawDests.set(firstNonExistent, rawPath);
752
+ bwrapMountPoints.add(firstNonExistent);
753
+ registerExitCleanupHandler();
754
+ logForDebugging(`[Sandbox Linux] Mounted /dev/null at ${firstNonExistent} to block creation of ${normalizedPath}`);
755
+ }
756
+ }
757
+ else {
758
+ logForDebugging(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${normalizedPath}`);
759
+ }
760
+ continue;
761
+ }
762
+ const isWithinAllowedPath = allowedWritePaths.some(allowedPath => normalizedPath.startsWith(allowedPath + '/') ||
763
+ normalizedPath === allowedPath);
764
+ if (isWithinAllowedPath) {
765
+ if (!seenDenyWriteMountDests.has(normalizedPath)) {
766
+ seenDenyWriteMountDests.add(normalizedPath);
767
+ denyWriteArgs.push('--ro-bind', normalizedPath, normalizedPath);
768
+ denyWriteRawDests.set(normalizedPath, rawPath);
769
+ }
770
+ }
771
+ else {
772
+ logForDebugging(`[Sandbox Linux] Skipping deny path not within allowed paths: ${normalizedPath}`);
773
+ }
774
+ }
775
+ return { allowedWritePaths, denyWriteArgs, denyWriteRawDests };
776
+ }
777
+ function applyReadDenyAndMaskArgs(readConfig, maskedFileBinds, allowedWritePaths, readAllowPaths, args) {
778
+ const readDenyPaths = [];
779
+ const maskedFiles = new Map();
780
+ const tmpfsDirs = [];
781
+ const rootSkip = new Set(['proc', 'dev', 'sys']);
782
+ for (const p of readConfig?.denyOnly || []) {
783
+ if (normalizePathForSandbox(p) === '/') {
784
+ for (const child of fs.readdirSync('/')) {
785
+ if (rootSkip.has(child))
786
+ continue;
787
+ if (isSymlink('/' + child))
788
+ continue;
789
+ readDenyPaths.push('/' + child);
790
+ }
791
+ }
792
+ else {
793
+ readDenyPaths.push(p);
794
+ }
795
+ }
796
+ if (readConfig && fs.existsSync('/etc/ssh/ssh_config.d')) {
797
+ readDenyPaths.push('/etc/ssh/ssh_config.d');
798
+ }
799
+ const depth = (p) => resolveDenyDest(p).split('/').length;
800
+ const normalizedDenyPaths = readDenyPaths
801
+ .map(p => normalizePathForSandbox(p))
802
+ .sort((a, b) => depth(a) - depth(b));
803
+ const tmpfsAliases = new Map();
804
+ for (const denyPath of normalizedDenyPaths) {
805
+ const target = resolveDenyDest(denyPath);
806
+ if (target === denyPath || target === '/')
807
+ continue;
808
+ tmpfsAliases.set(target, [...(tmpfsAliases.get(target) ?? []), denyPath]);
809
+ }
810
+ const throughAliases = (dir, paths) => {
811
+ const aliases = tmpfsAliases.get(dir) ?? [];
812
+ const translated = aliases.flatMap(alias => paths
813
+ .filter(p => p === alias || p.startsWith(alias + '/'))
814
+ .map(p => dir + p.slice(alias.length)));
815
+ return translated.length ? [...new Set([...paths, ...translated])] : paths;
816
+ };
817
+ for (const normalizedPath of normalizedDenyPaths) {
818
+ if (!fs.existsSync(normalizedPath)) {
819
+ logForDebugging(`[Sandbox Linux] Skipping non-existent read deny path: ${normalizedPath}`);
820
+ continue;
821
+ }
822
+ const readDenyStat = fs.statSync(normalizedPath);
823
+ if (readDenyStat.isDirectory()) {
824
+ const resolvedDir = resolveDenyDest(normalizedPath);
825
+ const denyDir = resolvedDir === '/' ? normalizedPath : resolvedDir;
826
+ if (tmpfsDirs.includes(denyDir)) {
827
+ logForDebugging(`[Sandbox Linux] Skipping read deny already masked at ${denyDir}: ${normalizedPath}`);
828
+ continue;
829
+ }
830
+ tmpfsDirs.push(denyDir);
831
+ pushReadDenyDirMounts(args, denyDir, throughAliases(denyDir, allowedWritePaths), throughAliases(denyDir, readAllowPaths));
832
+ }
833
+ else {
834
+ if (readAllowPaths.includes(normalizedPath)) {
835
+ logForDebugging(`[Sandbox Linux] Skipping read deny for re-allowed path: ${normalizedPath}`);
836
+ continue;
837
+ }
838
+ const denyDest = resolveDenyDest(normalizedPath);
839
+ args.push('--ro-bind', '/dev/null', denyDest);
840
+ maskedFiles.set(denyDest, '/dev/null');
841
+ maskedFiles.set(normalizedPath, '/dev/null');
842
+ }
843
+ }
844
+ for (const { realPath, fakePath } of maskedFileBinds ?? []) {
845
+ const dest = resolveDenyDest(realPath);
846
+ args.push('--ro-bind', fakePath, dest);
847
+ maskedFiles.set(dest, fakePath);
848
+ maskedFiles.set(realPath, fakePath);
849
+ }
850
+ return { maskedFiles, tmpfsDirs };
851
+ }
852
+ function layerDenyWriteAndRestackArgs(denyWriteArgs, denyWriteRawDests, allowedWritePaths, readAllowPaths, maskedFiles, tmpfsDirs, args) {
853
+ const isHiddenByTmpfs = (dest) => tmpfsDirs.some(tmpfsDir => {
854
+ const underTmpfs = dest === tmpfsDir || dest.startsWith(tmpfsDir + '/');
855
+ if (!underTmpfs)
856
+ return false;
857
+ const reExposedByWriteBind = allowedWritePaths.some(writePath => (writePath === tmpfsDir || writePath.startsWith(tmpfsDir + '/')) &&
858
+ (dest === writePath || dest.startsWith(writePath + '/')));
859
+ return !reExposedByWriteBind;
860
+ });
861
+ const emittedDenyWriteDests = [];
862
+ for (let i = 0; i < denyWriteArgs.length; i += 3) {
863
+ const dest = denyWriteArgs[i + 2];
864
+ const rawDest = denyWriteRawDests.get(dest) ?? dest;
865
+ if (maskedFiles.has(dest) || maskedFiles.has(rawDest))
866
+ continue;
867
+ if (isHiddenByTmpfs(dest) || isHiddenByTmpfs(rawDest)) {
868
+ logForDebugging(`[Sandbox Linux] Skipping denyWrite bind already hidden by denyRead tmpfs: ${dest}`);
869
+ continue;
870
+ }
871
+ args.push(denyWriteArgs[i], denyWriteArgs[i + 1], dest);
872
+ emittedDenyWriteDests.push(dest);
873
+ if (rawDest !== dest)
874
+ emittedDenyWriteDests.push(rawDest);
875
+ }
876
+ for (const tmpfsDir of tmpfsDirs) {
877
+ if (emittedDenyWriteDests.some(dest => tmpfsDir.startsWith(dest + '/'))) {
878
+ logForDebugging(`[Sandbox Linux] Re-applying denyRead tmpfs re-exposed by denyWrite bind: ${tmpfsDir}`);
879
+ // Do not re-emit write binds underneath a write-denied ancestor.
880
+ pushReadDenyDirMounts(args, tmpfsDir, [], readAllowPaths);
881
+ }
882
+ }
883
+ for (const [maskedFile, source] of maskedFiles) {
884
+ if (emittedDenyWriteDests.some(dest => maskedFile.startsWith(dest + '/'))) {
885
+ if (resolveDenyDest(maskedFile) !== maskedFile)
886
+ continue;
887
+ logForDebugging(`[Sandbox Linux] Re-applying file mask re-exposed by denyWrite bind: ${maskedFile}`);
888
+ args.push('--ro-bind', source, maskedFile);
889
+ }
890
+ }
891
+ }
892
+ /**
893
+ * Generate filesystem bind mount arguments for bwrap
894
+ */
895
+ async function generateFilesystemArgs(readConfig, writeConfig, maskedFileBinds, maskedFileStoreDir) {
896
+ const args = [];
897
+ const { allowedWritePaths, denyWriteArgs, denyWriteRawDests } = collectWriteAndDenyWriteArgs(writeConfig, args);
898
+ const readAllowPaths = (readConfig?.allowWithinDeny || []).map(p => normalizePathForSandbox(p));
899
+ const { maskedFiles, tmpfsDirs } = applyReadDenyAndMaskArgs(readConfig, maskedFileBinds, allowedWritePaths, readAllowPaths, args);
900
+ layerDenyWriteAndRestackArgs(denyWriteArgs, denyWriteRawDests, allowedWritePaths, readAllowPaths, maskedFiles, tmpfsDirs, args);
901
+ if (maskedFileStoreDir !== undefined) {
902
+ args.push('--ro-bind', maskedFileStoreDir, maskedFileStoreDir);
903
+ }
904
+ return args;
905
+ }
906
+ /**
907
+ * Wrap a command with sandbox restrictions on Linux
908
+ *
909
+ * UNIX SOCKET BLOCKING (APPLY-SECCOMP):
910
+ * This implementation uses a custom apply-seccomp binary to block Unix domain socket
911
+ * creation for user commands while allowing network infrastructure:
912
+ *
913
+ * Stage 1: Outer bwrap - Network and filesystem isolation (NO seccomp)
914
+ * - Bubblewrap starts with isolated network namespace (--unshare-net)
915
+ * - Bubblewrap applies PID namespace isolation (--unshare-pid and --proc)
916
+ * - Filesystem restrictions are applied (read-only mounts, bind mounts, etc.)
917
+ * - Socat processes start and connect to Unix socket bridges (can use socket(AF_UNIX, ...))
918
+ *
919
+ * Stage 2: apply-seccomp - Nested PID namespace + seccomp filter
920
+ * - apply-seccomp creates a nested user+PID+mount namespace and remounts /proc
921
+ * - Inside, apply-seccomp becomes PID 1 (non-dumpable init/reaper)
922
+ * - Forks, sets PR_SET_NO_NEW_PRIVS, applies seccomp via prctl(PR_SET_SECCOMP)
923
+ * - Execs user command with seccomp active (cannot create new Unix sockets)
924
+ * - User command cannot see or ptrace bwrap/bash/socat (separate PID namespace)
925
+ *
926
+ * This solves the conflict between:
927
+ * - Security: Blocking arbitrary Unix socket creation in user commands
928
+ * - Functionality: Network sandboxing requires socat to call socket(AF_UNIX, ...) for bridge connections
929
+ *
930
+ * The seccomp-bpf filter blocks socket(AF_UNIX, ...) syscalls, preventing:
931
+ * - Creating new Unix domain socket file descriptors
932
+ *
933
+ * It also blocks socket(AF_VSOCK, ...): the network namespace does not fence
934
+ * VM sockets, so one would reach out of the sandbox past the proxies.
935
+ *
936
+ * Security limitations:
937
+ * - Does NOT block operations (bind, connect, sendto, etc.) on inherited Unix socket FDs
938
+ * - Does NOT prevent passing Unix socket FDs via SCM_RIGHTS
939
+ * - For most sandboxing use cases, blocking socket creation is sufficient
940
+ *
941
+ * The filter allows:
942
+ * - All TCP/UDP sockets (AF_INET, AF_INET6) for normal network operations
943
+ * - All other syscalls
944
+ *
945
+ * PLATFORM NOTE:
946
+ * The allowUnixSockets configuration is not path-based on Linux (unlike macOS)
947
+ * because seccomp-bpf cannot inspect user-space memory to read socket paths.
948
+ *
949
+ * Requirements for seccomp filtering:
950
+ * - Pre-built apply-seccomp binaries are included for x64 and ARM64
951
+ * - Pre-generated BPF filters are included for x64 and ARM64
952
+ * - Other architectures are not currently supported (no apply-seccomp binary available)
953
+ * - To use sandboxing without Unix socket blocking on unsupported architectures,
954
+ * set allowAllUnixSockets: true in your configuration
955
+ * Dependencies are checked by checkLinuxDependencies() before enabling the sandbox.
956
+ */
957
+ export async function wrapCommandWithSandboxLinux(params) {
958
+ const { command, needsNetworkRestriction, httpSocketPath, socksSocketPath, httpProxyPort, socksProxyPort, proxyAuthToken, caCertPath, readConfig, writeConfig, unsetEnvVars, setEnvVars, maskedFileBinds, maskedFileStoreDir, enableWeakerNestedSandbox, allowAllUnixSockets, binShell, seccompConfig, bwrapPath, socatPath, observeSocketPath, } = params;
959
+ // Determine if we have restrictions to apply
960
+ // Read: denyOnly pattern - empty array means no restrictions
961
+ // Write: allowOnly pattern - undefined means no restrictions, any config means restrictions
962
+ const hasReadRestrictions = (readConfig && readConfig.denyOnly.length > 0) ||
963
+ (maskedFileBinds !== undefined && maskedFileBinds.length > 0);
964
+ const hasWriteRestrictions = writeConfig !== undefined;
965
+ const hasEnvRestrictions = (unsetEnvVars !== undefined && unsetEnvVars.length > 0) ||
966
+ (setEnvVars !== undefined && Object.keys(setEnvVars).length > 0);
967
+ // Check if we need any sandboxing
968
+ if (!needsNetworkRestriction &&
969
+ !hasReadRestrictions &&
970
+ !hasWriteRestrictions &&
971
+ !hasEnvRestrictions) {
972
+ return command;
973
+ }
974
+ // Mark this sandbox invocation as active. cleanupBwrapMountPoints() will
975
+ // defer file deletion until this (and every other concurrent) invocation
976
+ // has been cleaned up. The matching decrement happens in
977
+ // cleanupBwrapMountPoints(), which the caller must invoke after the
978
+ // spawned command exits. If wrapping fails below, the catch block
979
+ // decrements so the count does not leak.
980
+ activeSandboxCount++;
981
+ const countedAfter = forcedCleanups;
982
+ const bwrapArgs = ['--new-session', '--die-with-parent'];
983
+ let applySeccompPrefix;
984
+ try {
985
+ // ========== SECCOMP FILTER (Unix Socket Blocking) ==========
986
+ // apply-seccomp wraps the workload and applies the baked-in BPF filter
987
+ // that blocks socket(AF_UNIX, ...). Skipped when allowAllUnixSockets is true.
988
+ if (!allowAllUnixSockets) {
989
+ applySeccompPrefix = resolveApplySeccompPrefix(seccompConfig?.applyPath, seccompConfig?.argv0);
990
+ if (!applySeccompPrefix) {
991
+ logForDebugging('[Sandbox Linux] apply-seccomp binary not available - unix socket blocking disabled. ' +
992
+ 'Install @anthropic-ai/sandbox-runtime globally for full protection.', { level: 'warn' });
993
+ }
994
+ else {
995
+ logForDebugging('[Sandbox Linux] Applying seccomp filter for Unix socket blocking');
996
+ }
997
+ }
998
+ else {
999
+ logForDebugging('[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled');
1000
+ }
1001
+ // ========== VIOLATION OBSERVATION (best-effort) ==========
1002
+ // Only meaningful when apply-seccomp will run — it is the binary that
1003
+ // installs the USER_NOTIF filter and ships the listener fd. The --bind
1004
+ // mount is emitted AFTER fsArgs so denyRead: ['/'] or ['/tmp'] does not
1005
+ // wipe it with a tmpfs.
1006
+ let observeBindPath;
1007
+ if (observeSocketPath && applySeccompPrefix) {
1008
+ if (fs.existsSync(observeSocketPath)) {
1009
+ observeBindPath = observeSocketPath;
1010
+ bwrapArgs.push('--setenv', 'SRT_OBSERVE_SOCK', observeSocketPath);
1011
+ // Tag events with the encoded command so the violation store can
1012
+ // associate them with this invocation (parity with macOS log tag).
1013
+ bwrapArgs.push('--setenv', 'SRT_ENCODED_CMD', encodeSandboxedCommand(command));
1014
+ }
1015
+ else {
1016
+ logForDebugging('[Sandbox Linux] observe socket missing — supervisor not running; ' +
1017
+ 'continuing without violation monitoring');
1018
+ }
1019
+ }
1020
+ // ========== ENV RESTRICTIONS ==========
1021
+ // Drop denied credential env vars from the inherited environment. Emitted
1022
+ // before the proxy --setenv flags below: bwrap applies env operations in
1023
+ // argument order, so SRT's own proxy plumbing vars survive even if a
1024
+ // caller lists one of them as a denied credential.
1025
+ if (hasEnvRestrictions) {
1026
+ for (const name of unsetEnvVars ?? []) {
1027
+ bwrapArgs.push('--unsetenv', name);
1028
+ }
1029
+ // Masked credentials override the inherited real value with a
1030
+ // sentinel; bwrap --setenv replaces any inherited value of NAME.
1031
+ for (const [name, value] of Object.entries(setEnvVars ?? {})) {
1032
+ bwrapArgs.push('--setenv', name, value);
1033
+ }
1034
+ }
1035
+ // ========== NETWORK RESTRICTIONS ==========
1036
+ let bindNetworkSockets = false;
1037
+ if (needsNetworkRestriction) {
1038
+ // Always unshare network namespace to isolate network access
1039
+ // This removes all network interfaces, effectively blocking all network
1040
+ bwrapArgs.push('--unshare-net');
1041
+ // If proxy sockets are provided, verify they exist now and bind them
1042
+ // AFTER fsArgs so denyRead: ['/'] or ['/tmp'] does not wipe them.
1043
+ if (httpSocketPath && socksSocketPath) {
1044
+ // Verify socket files still exist before trying to bind them
1045
+ if (!fs.existsSync(httpSocketPath)) {
1046
+ throw new Error(`Linux HTTP bridge socket does not exist: ${httpSocketPath}. ` +
1047
+ 'The bridge process may have died. Try reinitializing the sandbox.');
1048
+ }
1049
+ if (!fs.existsSync(socksSocketPath)) {
1050
+ throw new Error(`Linux SOCKS bridge socket does not exist: ${socksSocketPath}. ` +
1051
+ 'The bridge process may have died. Try reinitializing the sandbox.');
1052
+ }
1053
+ bindNetworkSockets = true;
1054
+ // Add proxy environment variables
1055
+ // HTTP_PROXY points to the socat listener inside the sandbox (port 3128)
1056
+ // which forwards to the Unix socket that bridges to the host's proxy server
1057
+ const proxyEnv = generateProxyEnvVars(3128, // Internal HTTP listener port
1058
+ 1080, // Internal SOCKS listener port
1059
+ caCertPath, proxyAuthToken, writeConfig === undefined);
1060
+ bwrapArgs.push(...proxyEnv.flatMap((env) => {
1061
+ const firstEq = env.indexOf('=');
1062
+ const key = env.slice(0, firstEq);
1063
+ const value = env.slice(firstEq + 1);
1064
+ return ['--setenv', key, value];
1065
+ }));
1066
+ // Add host proxy port environment variables for debugging/transparency
1067
+ // These show which host ports the Unix socket bridges connect to
1068
+ if (httpProxyPort !== undefined) {
1069
+ bwrapArgs.push('--setenv', 'CLAUDE_CODE_HOST_HTTP_PROXY_PORT', String(httpProxyPort));
1070
+ }
1071
+ if (socksProxyPort !== undefined) {
1072
+ bwrapArgs.push('--setenv', 'CLAUDE_CODE_HOST_SOCKS_PROXY_PORT', String(socksProxyPort));
1073
+ }
1074
+ }
1075
+ // If no sockets provided, network is completely blocked (--unshare-net without proxy)
1076
+ }
1077
+ // ========== FILESYSTEM RESTRICTIONS ==========
1078
+ const fsArgs = await generateFilesystemArgs(readConfig, writeConfig, maskedFileBinds, maskedFileStoreDir);
1079
+ bwrapArgs.push(...fsArgs);
1080
+ // Bind observe & network bridge sockets AFTER fsArgs so denyRead: ['/']
1081
+ // or ['/tmp'] tmpfs mounts do not wipe them out.
1082
+ if (observeBindPath) {
1083
+ bwrapArgs.push('--bind', observeBindPath, observeBindPath);
1084
+ }
1085
+ if (bindNetworkSockets && httpSocketPath && socksSocketPath) {
1086
+ bwrapArgs.push('--bind', httpSocketPath, httpSocketPath);
1087
+ if (socksSocketPath !== httpSocketPath) {
1088
+ bwrapArgs.push('--bind', socksSocketPath, socksSocketPath);
1089
+ }
1090
+ }
1091
+ // Always bind /dev
1092
+ bwrapArgs.push('--dev', '/dev');
1093
+ // ========== PID NAMESPACE ISOLATION ==========
1094
+ // IMPORTANT: These must come AFTER filesystem binds for nested bwrap to work
1095
+ // By default, always unshare PID namespace and mount fresh /proc.
1096
+ // If we don't have --unshare-pid, it is possible to escape the sandbox.
1097
+ // If we don't have --proc, it is possible to read host /proc and leak information about code running
1098
+ // outside the sandbox. But, --proc is not available when running in unprivileged docker containers
1099
+ // so we support running without it if explicitly requested.
1100
+ bwrapArgs.push('--unshare-pid');
1101
+ if (!enableWeakerNestedSandbox) {
1102
+ // Mount fresh /proc if PID namespace is isolated (secure mode).
1103
+ // --unshare-user + --cap-drop ALL: bwrap only auto-creates a userns
1104
+ // when EUID != 0, so a root parent would otherwise leave the sandboxed
1105
+ // command with full caps in the initial userns (CAP_SYS_ADMIN → remount
1106
+ // rw over --ro-bind / /). Force the userns and explicitly drop caps so
1107
+ // the sandboxed process cannot remount regardless of parent EUID.
1108
+ // apply-seccomp does not need caps here — it creates its own nested
1109
+ // userns to obtain CAP_SYS_ADMIN for its PID+mount unshare (see below).
1110
+ bwrapArgs.push('--unshare-user', '--cap-drop', 'ALL', '--proc', '/proc');
1111
+ }
1112
+ else {
1113
+ // --unshare-user: bwrap only auto-adds this when EUID != 0. In an
1114
+ // unprivileged container (Docker's default: EUID=0 without
1115
+ // CAP_SYS_ADMIN), bwrap assumes it has caps, tries direct clone,
1116
+ // and EPERMs. Force the userns path so bwrap starts at all.
1117
+ //
1118
+ // --bind /proc /proc: apply-seccomp's nested-userns path writes
1119
+ // /proc/self/setgroups and uid_map. Without --proc above, the
1120
+ // --ro-bind / / leaves /proc read-only and those writes EROFS.
1121
+ bwrapArgs.push('--unshare-user', '--cap-drop', 'ALL', '--bind', '/proc', '/proc');
1122
+ }
1123
+ // apply-seccomp obtains CAP_SYS_ADMIN for its nested PID+mount unshare
1124
+ // by creating a nested user namespace. This requires the host to permit
1125
+ // capability-bearing unprivileged user namespaces (the same requirement
1126
+ // bwrap itself has when not installed setuid). See README for the
1127
+ // Ubuntu 24.04 sysctl if AppArmor restricts this.
1128
+ // ========== COMMAND ==========
1129
+ // Use the user's shell (zsh, bash, etc.) to ensure aliases/snapshots work
1130
+ // Resolve the full path to the shell binary since bwrap doesn't use $PATH
1131
+ const shellName = binShell || 'bash';
1132
+ const shell = whichSync(shellName);
1133
+ if (!shell) {
1134
+ throw new Error(`Shell '${shellName}' not found in PATH`);
1135
+ }
1136
+ bwrapArgs.push('--', shell, '-c');
1137
+ // With network restrictions, route the command through buildSandboxCommand
1138
+ // so socat starts before seccomp is applied. Otherwise invoke apply-seccomp
1139
+ // directly if we have a binary.
1140
+ if (needsNetworkRestriction && httpSocketPath && socksSocketPath) {
1141
+ const sandboxCommand = buildSandboxCommand(httpSocketPath, socksSocketPath, command, applySeccompPrefix, shell, socatPath);
1142
+ bwrapArgs.push(sandboxCommand);
1143
+ }
1144
+ else if (applySeccompPrefix) {
1145
+ const applySeccompCmd = applySeccompPrefix + quote([shell, '-c', command]);
1146
+ bwrapArgs.push(applySeccompCmd);
1147
+ }
1148
+ else {
1149
+ bwrapArgs.push(command);
1150
+ }
1151
+ const wrappedCommand = quote([bwrapPath ?? 'bwrap', ...bwrapArgs]);
1152
+ const restrictions = [];
1153
+ if (needsNetworkRestriction)
1154
+ restrictions.push('network');
1155
+ if (hasReadRestrictions || hasWriteRestrictions)
1156
+ restrictions.push('filesystem');
1157
+ if (hasEnvRestrictions)
1158
+ restrictions.push('env');
1159
+ if (applySeccompPrefix)
1160
+ restrictions.push('seccomp(unix-block)');
1161
+ logForDebugging(`[Sandbox Linux] Wrapped command with bwrap (${restrictions.join(', ')} restrictions)`);
1162
+ // INVARIANT: a wrap that hands out a command is in the count when it does,
1163
+ // whatever a forced cleanup did meanwhile: its caller gives one back.
1164
+ if (forcedCleanups !== countedAfter)
1165
+ activeSandboxCount++;
1166
+ return wrappedCommand;
1167
+ }
1168
+ catch (error) {
1169
+ // Undo the activeSandboxCount increment — the caller won't call
1170
+ // cleanupBwrapMountPoints() for a wrap that threw. A command that ended
1171
+ // meanwhile deferred its removal to this wrap, so it runs here. After a
1172
+ // forced cleanup the count is of other sandboxes only: one taken from it
1173
+ // has their mount points removed while they run.
1174
+ if (forcedCleanups === countedAfter)
1175
+ cleanupBwrapMountPoints();
1176
+ throw error;
1177
+ }
1178
+ }
1179
+ //# sourceMappingURL=linux-sandbox-utils.js.map