just-bash 3.4.1 → 3.4.2
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/CHANGELOG.md +6 -0
- package/dist/security/blocked-globals.d.ts +60 -0
- package/dist/security/defense-context.d.ts +13 -0
- package/dist/security/defense-in-depth-box.d.ts +354 -0
- package/dist/security/index.d.ts +33 -0
- package/dist/security/safe-timestamp.d.ts +1 -0
- package/dist/security/security-violation-logger.d.ts +99 -0
- package/dist/security/trusted-globals.d.ts +17 -0
- package/dist/security/types.d.ts +151 -0
- package/dist/security/violation-error-message.d.ts +3 -0
- package/dist/security/wasm-callback.d.ts +6 -0
- package/dist/security/worker-defense-in-depth.d.ts +228 -0
- package/dist/transform/pipeline.d.ts +8 -0
- package/dist/transform/plugins/command-collector.d.ts +15 -0
- package/dist/transform/plugins/tee-plugin.d.ts +40 -0
- package/dist/transform/serialize.d.ts +4 -0
- package/dist/transform/types.d.ts +18 -0
- package/package.json +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# just-bash
|
|
2
2
|
|
|
3
|
+
## 3.4.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#381](https://github.com/vercel-labs/just-bash/pull/381) [`d40a42d`](https://github.com/vercel-labs/just-bash/commit/d40a42d514b22da4ed023635d747c8b3f029a6c5) Thanks [@cramforce](https://github.com/cramforce)! - Include the security and transform declaration trees referenced by the package entrypoints and worker declarations in published packages.
|
|
8
|
+
|
|
3
9
|
## 3.4.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Blocked Globals for Defense-in-Depth Box
|
|
3
|
+
*
|
|
4
|
+
* This module defines which JavaScript globals should be blocked during
|
|
5
|
+
* bash script execution to prevent code execution escape vectors.
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: This is a SECONDARY defense layer. The primary security comes
|
|
8
|
+
* from proper sandboxing and architectural constraints.
|
|
9
|
+
*
|
|
10
|
+
* NOTE: Dynamic import() is handled separately in defense-in-depth-box.ts via
|
|
11
|
+
* ESM loader hooks. This module only defines global/property patching.
|
|
12
|
+
*/
|
|
13
|
+
import type { SecurityViolationType } from "./types.js";
|
|
14
|
+
/**
|
|
15
|
+
* Strategy for handling a blocked global.
|
|
16
|
+
* - "throw": Replace with a proxy that throws on access/call
|
|
17
|
+
* - "freeze": Freeze the object to prevent modification
|
|
18
|
+
*/
|
|
19
|
+
export type BlockStrategy = "throw" | "freeze";
|
|
20
|
+
/**
|
|
21
|
+
* Configuration for a blocked global.
|
|
22
|
+
*/
|
|
23
|
+
export interface BlockedGlobal {
|
|
24
|
+
/**
|
|
25
|
+
* The property name on the target object (e.g., "Function", "eval").
|
|
26
|
+
*/
|
|
27
|
+
prop: string;
|
|
28
|
+
/**
|
|
29
|
+
* The target object containing the property.
|
|
30
|
+
* Usually globalThis, but can be other objects like Object.prototype.
|
|
31
|
+
*/
|
|
32
|
+
target: object;
|
|
33
|
+
/**
|
|
34
|
+
* Type of violation to record when this global is accessed.
|
|
35
|
+
*/
|
|
36
|
+
violationType: SecurityViolationType;
|
|
37
|
+
/**
|
|
38
|
+
* Strategy for blocking this global.
|
|
39
|
+
*/
|
|
40
|
+
strategy: BlockStrategy;
|
|
41
|
+
/**
|
|
42
|
+
* Human-readable description of why this is blocked.
|
|
43
|
+
*/
|
|
44
|
+
reason: string;
|
|
45
|
+
/**
|
|
46
|
+
* For object proxies (strategy: "throw" on objects): allow reads of these
|
|
47
|
+
* specific property names even inside the sandbox context. Node.js internals
|
|
48
|
+
* read certain properties (e.g., process.env keys) during module loading
|
|
49
|
+
* within the AsyncLocalStorage context, so they must be allowed through.
|
|
50
|
+
*/
|
|
51
|
+
allowedKeys?: Set<string>;
|
|
52
|
+
}
|
|
53
|
+
export declare function getBlockedGlobalViolationTypes(): ReadonlySet<SecurityViolationType>;
|
|
54
|
+
/**
|
|
55
|
+
* Get the list of globals to block during script execution.
|
|
56
|
+
*
|
|
57
|
+
* Note: This function must be called at runtime (not module load time)
|
|
58
|
+
* because some globals may not exist in all environments.
|
|
59
|
+
*/
|
|
60
|
+
export declare function getBlockedGlobals(): BlockedGlobal[];
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fail closed when execution is expected to run inside defense async context.
|
|
3
|
+
*/
|
|
4
|
+
export declare function assertDefenseContext(requireDefenseContext: boolean | undefined, component: string, phase: string): void;
|
|
5
|
+
/**
|
|
6
|
+
* Guard an async boundary by checking context both before and after await.
|
|
7
|
+
*/
|
|
8
|
+
export declare function awaitWithDefenseContext<T>(requireDefenseContext: boolean | undefined, component: string, phase: string, op: () => Promise<T>): Promise<T>;
|
|
9
|
+
/**
|
|
10
|
+
* Bind a callback to the current defense async context and assert defense
|
|
11
|
+
* invariants on callback entry.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bindDefenseContextCallback<TArgs extends unknown[], TResult>(requireDefenseContext: boolean | undefined, component: string, phase: string, callback: (...args: TArgs) => TResult): (...args: TArgs) => TResult;
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Defense-in-Depth Box
|
|
3
|
+
*
|
|
4
|
+
* A security layer that monkey-patches dangerous JavaScript globals during
|
|
5
|
+
* bash script execution. Uses AsyncLocalStorage to track execution context,
|
|
6
|
+
* so blocks only apply to code running within bash.exec() - not to concurrent
|
|
7
|
+
* operations in the same process.
|
|
8
|
+
*
|
|
9
|
+
* IMPORTANT: This is a SECONDARY defense layer. It should never be relied upon
|
|
10
|
+
* as the primary security mechanism. The primary security comes from proper
|
|
11
|
+
* sandboxing, input validation, and architectural constraints.
|
|
12
|
+
*
|
|
13
|
+
* Key design decisions:
|
|
14
|
+
* - AsyncLocalStorage for context tracking (blocks only affect sandboxed code)
|
|
15
|
+
* - Reference counting for nested exec() calls
|
|
16
|
+
* - Patches are process-wide but checks are context-aware
|
|
17
|
+
* - Violations are recorded even in audit mode
|
|
18
|
+
*
|
|
19
|
+
* Dynamic import() mitigation (three layers):
|
|
20
|
+
* 1. ESM loader hooks (module.register/registerHooks):
|
|
21
|
+
* - block data:/blob: URLs only in the untrusted async context
|
|
22
|
+
* - block Node.js builtin specifiers in untrusted sandbox context
|
|
23
|
+
* 2. Module._resolveFilename blocked — catches file-based specifiers
|
|
24
|
+
* 3. Filesystem restrictions — OverlayFs writes to memory only
|
|
25
|
+
*
|
|
26
|
+
* Runtimes with only module.register() (no registerHooks) resolve auto mode as
|
|
27
|
+
* unsupported and reject explicitly enabled activation. Their separate loader
|
|
28
|
+
* thread cannot observe AsyncLocalStorage, so installing a partial or
|
|
29
|
+
* process-global fallback would either be misleading or break unrelated host
|
|
30
|
+
* imports.
|
|
31
|
+
*/
|
|
32
|
+
import type { DefenseInDepthConfig, DefenseInDepthHandle, DefenseInDepthStats, DefenseInDepthStatus, SecurityViolation } from "./types.js";
|
|
33
|
+
/**
|
|
34
|
+
* Error thrown when a security violation is detected and blocking is enabled.
|
|
35
|
+
*/
|
|
36
|
+
export declare class SecurityViolationError extends Error {
|
|
37
|
+
readonly violation: SecurityViolation;
|
|
38
|
+
constructor(message: string, violation: SecurityViolation);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Defense-in-Depth Box
|
|
42
|
+
*
|
|
43
|
+
* Singleton class that manages security patches during bash execution.
|
|
44
|
+
* Use getInstance() to get or create the instance.
|
|
45
|
+
*/
|
|
46
|
+
export declare class DefenseInDepthBox {
|
|
47
|
+
private static instance;
|
|
48
|
+
private static importHooksRegistered;
|
|
49
|
+
/**
|
|
50
|
+
* Tracks active trusted scopes per executionId.
|
|
51
|
+
* Needed for async machinery that may not preserve `store.trusted` all the
|
|
52
|
+
* way into Node.js internals (e.g. dynamic import resolution hooks).
|
|
53
|
+
*/
|
|
54
|
+
private static trustedExecutionDepth;
|
|
55
|
+
private config;
|
|
56
|
+
private refCount;
|
|
57
|
+
private patchFailures;
|
|
58
|
+
private activeExecutionIds;
|
|
59
|
+
/** Reusable DefenseContext objects keyed by executionId (avoids per-.then() allocation). */
|
|
60
|
+
private contextCache;
|
|
61
|
+
private originalDescriptors;
|
|
62
|
+
/**
|
|
63
|
+
* Descriptors made temporarily read-only while the shared host realm is
|
|
64
|
+
* protected. Unlike process-lifetime hardening, every entry remains
|
|
65
|
+
* configurable and is restored exactly when the last handle deactivates.
|
|
66
|
+
*/
|
|
67
|
+
private temporaryIntrinsicDescriptors;
|
|
68
|
+
private violations;
|
|
69
|
+
private activationTime;
|
|
70
|
+
private totalActiveTimeMs;
|
|
71
|
+
private constructor();
|
|
72
|
+
/**
|
|
73
|
+
* Get or create the singleton instance.
|
|
74
|
+
*
|
|
75
|
+
* @param config - Configuration for the defense box.
|
|
76
|
+
* @throws Error if called with a config that conflicts with the existing instance's
|
|
77
|
+
* security-relevant settings (enabled, auditMode). This prevents a weaker
|
|
78
|
+
* first caller from silently downgrading protection for later callers.
|
|
79
|
+
*/
|
|
80
|
+
static getInstance(config?: DefenseInDepthConfig | boolean): DefenseInDepthBox;
|
|
81
|
+
/**
|
|
82
|
+
* Reset the singleton instance. Only use in tests.
|
|
83
|
+
*/
|
|
84
|
+
static resetInstance(): void;
|
|
85
|
+
/**
|
|
86
|
+
* Check if the current async context is within sandboxed execution.
|
|
87
|
+
*/
|
|
88
|
+
static isInSandboxedContext(): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Get the current execution ID if in a sandboxed context.
|
|
91
|
+
*/
|
|
92
|
+
static getCurrentExecutionId(): string | undefined;
|
|
93
|
+
private static enterTrustedScope;
|
|
94
|
+
private static leaveTrustedScope;
|
|
95
|
+
private static isTrustedScopeActive;
|
|
96
|
+
private static isTrustedContext;
|
|
97
|
+
/**
|
|
98
|
+
* Check if a defense execution ID is still live (its handle is not deactivated).
|
|
99
|
+
*/
|
|
100
|
+
private isExecutionIdActive;
|
|
101
|
+
/**
|
|
102
|
+
* Get or create a cached DefenseContext for an executionId.
|
|
103
|
+
* Avoids allocating a new {sandboxActive, executionId} object on every
|
|
104
|
+
* Promise.then / timer call.
|
|
105
|
+
*/
|
|
106
|
+
private getCachedContext;
|
|
107
|
+
/**
|
|
108
|
+
* Bind a callback to the current defense AsyncLocalStorage context.
|
|
109
|
+
*
|
|
110
|
+
* Useful for infrastructure callbacks that may execute later via pre-captured
|
|
111
|
+
* timer references, while still needing executionId/trace continuity.
|
|
112
|
+
*
|
|
113
|
+
* Note: this intentionally does NOT preserve `trusted` mode. Trusted execution
|
|
114
|
+
* is meant to stay tightly scoped to the immediate infrastructure operation.
|
|
115
|
+
*/
|
|
116
|
+
static bindCurrentContext<TArgs extends unknown[], TResult>(fn: (...args: TArgs) => TResult): (...args: TArgs) => TResult;
|
|
117
|
+
/**
|
|
118
|
+
* Check if defense-in-depth is enabled and functional.
|
|
119
|
+
* Returns false if AsyncLocalStorage is unavailable or config.enabled is false.
|
|
120
|
+
*/
|
|
121
|
+
isEnabled(): boolean;
|
|
122
|
+
/** Return the resolved runtime capability without activating protection. */
|
|
123
|
+
getStatus(): DefenseInDepthStatus;
|
|
124
|
+
/**
|
|
125
|
+
* Update configuration. Only affects future activations.
|
|
126
|
+
*/
|
|
127
|
+
updateConfig(config: Partial<DefenseInDepthConfig>): void;
|
|
128
|
+
/**
|
|
129
|
+
* Activate the defense box. Returns a handle for scoped execution.
|
|
130
|
+
*
|
|
131
|
+
* Usage:
|
|
132
|
+
* ```
|
|
133
|
+
* const { run, deactivate } = box.activate();
|
|
134
|
+
* try {
|
|
135
|
+
* await run(async () => {
|
|
136
|
+
* // Code here is protected
|
|
137
|
+
* });
|
|
138
|
+
* } finally {
|
|
139
|
+
* deactivate();
|
|
140
|
+
* }
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
activate(): DefenseInDepthHandle;
|
|
144
|
+
/**
|
|
145
|
+
* Force deactivation, restoring all patches regardless of ref count.
|
|
146
|
+
* Use for error recovery only.
|
|
147
|
+
*/
|
|
148
|
+
forceDeactivate(): void;
|
|
149
|
+
/**
|
|
150
|
+
* Check if patches are currently applied.
|
|
151
|
+
*/
|
|
152
|
+
isActive(): boolean;
|
|
153
|
+
/**
|
|
154
|
+
* Get statistics about the defense box.
|
|
155
|
+
*/
|
|
156
|
+
getStats(): DefenseInDepthStats;
|
|
157
|
+
/**
|
|
158
|
+
* Get the list of patch paths that failed during the last activation.
|
|
159
|
+
*/
|
|
160
|
+
getPatchFailures(): string[];
|
|
161
|
+
/**
|
|
162
|
+
* Clear stored violations. Useful for testing.
|
|
163
|
+
*/
|
|
164
|
+
clearViolations(): void;
|
|
165
|
+
/**
|
|
166
|
+
* Get a human-readable path for a target object and property.
|
|
167
|
+
*/
|
|
168
|
+
private getPathForTarget;
|
|
169
|
+
/**
|
|
170
|
+
* Run a function as trusted infrastructure code.
|
|
171
|
+
* Blocking is suspended for the current async context only — other
|
|
172
|
+
* concurrent exec() calls remain protected.
|
|
173
|
+
*
|
|
174
|
+
* Uses AsyncLocalStorage to scope the trust, so async operations
|
|
175
|
+
* spawned inside the callback inherit the trusted state.
|
|
176
|
+
*/
|
|
177
|
+
static runTrusted<T>(fn: () => T): T;
|
|
178
|
+
/**
|
|
179
|
+
* Async version of runTrusted.
|
|
180
|
+
*/
|
|
181
|
+
static runTrustedAsync<T>(fn: () => Promise<T>): Promise<T>;
|
|
182
|
+
/**
|
|
183
|
+
* Restore blocking for an untrusted operation nested inside trusted host code.
|
|
184
|
+
*/
|
|
185
|
+
static runUntrustedAsync<T>(fn: () => Promise<T>): Promise<T>;
|
|
186
|
+
/**
|
|
187
|
+
* Check if current context should be blocked.
|
|
188
|
+
* Returns false in audit mode, browser environment, outside sandboxed context,
|
|
189
|
+
* inside runTrusted(), or when the immediate caller is a Node.js bundled dep.
|
|
190
|
+
*/
|
|
191
|
+
private shouldBlock;
|
|
192
|
+
/** Record audit events only for untrusted sandbox work. */
|
|
193
|
+
private shouldAudit;
|
|
194
|
+
/**
|
|
195
|
+
* Record a violation and optionally invoke the callback.
|
|
196
|
+
*/
|
|
197
|
+
private recordViolation;
|
|
198
|
+
/**
|
|
199
|
+
* Create a blocking proxy for a function.
|
|
200
|
+
*/
|
|
201
|
+
private createBlockingProxy;
|
|
202
|
+
/**
|
|
203
|
+
* Create a blocking proxy for an object (blocks all property access).
|
|
204
|
+
*/
|
|
205
|
+
private createBlockingObjectProxy;
|
|
206
|
+
/** Preserve read access while denying mutation only in sandbox context. */
|
|
207
|
+
private createReadonlyObjectProxy;
|
|
208
|
+
/**
|
|
209
|
+
* Apply security patches to dangerous globals.
|
|
210
|
+
*/
|
|
211
|
+
private applyPatches;
|
|
212
|
+
/**
|
|
213
|
+
* Close the cached-reference assignment path without permanently freezing
|
|
214
|
+
* host globals. The global proxies protect references obtained after
|
|
215
|
+
* activation; these temporary descriptor changes protect references cached
|
|
216
|
+
* before activation. Configurability is deliberately retained so teardown
|
|
217
|
+
* can restore the host realm byte-for-byte.
|
|
218
|
+
*/
|
|
219
|
+
private protectReversibleIntrinsics;
|
|
220
|
+
/**
|
|
221
|
+
* Protect against .constructor.constructor escape vector.
|
|
222
|
+
*
|
|
223
|
+
* The pattern `{}.constructor.constructor` accesses Function via:
|
|
224
|
+
* - {}.constructor → Object (via Object.prototype.constructor)
|
|
225
|
+
* - Object.constructor → Function (via Function.prototype.constructor)
|
|
226
|
+
*
|
|
227
|
+
* By patching Function.prototype.constructor to return our blocked proxy,
|
|
228
|
+
* we block the escape vector without breaking normal .constructor access.
|
|
229
|
+
*/
|
|
230
|
+
private protectConstructorChain;
|
|
231
|
+
/**
|
|
232
|
+
* Protect Error.prepareStackTrace from being set in sandbox context.
|
|
233
|
+
*
|
|
234
|
+
* The attack vector is:
|
|
235
|
+
* ```
|
|
236
|
+
* Error.prepareStackTrace = (err, stack) => {
|
|
237
|
+
* return stack[0].getFunction().constructor; // Gets Function
|
|
238
|
+
* };
|
|
239
|
+
* const F = new Error().stack;
|
|
240
|
+
* F("return process")();
|
|
241
|
+
* ```
|
|
242
|
+
*
|
|
243
|
+
* We only block SETTING, not reading, because V8 reads it internally
|
|
244
|
+
* when creating error stack traces.
|
|
245
|
+
*/
|
|
246
|
+
private protectErrorPrepareStackTrace;
|
|
247
|
+
/**
|
|
248
|
+
* Protect Promise.then callback lifetime across deactivate boundaries.
|
|
249
|
+
*
|
|
250
|
+
* Callbacks registered in sandbox context are wrapped with an execution-id
|
|
251
|
+
* liveness check. If they run after the originating handle is deactivated,
|
|
252
|
+
* they are blocked even if global patches have already been restored.
|
|
253
|
+
*/
|
|
254
|
+
private protectPromiseThen;
|
|
255
|
+
/**
|
|
256
|
+
* Patch a prototype's constructor property to block access in sandbox context.
|
|
257
|
+
*/
|
|
258
|
+
private patchPrototypeConstructor;
|
|
259
|
+
/**
|
|
260
|
+
* Protect process.mainModule from being accessed or set in sandbox context.
|
|
261
|
+
*
|
|
262
|
+
* The attack vector is:
|
|
263
|
+
* ```
|
|
264
|
+
* process.mainModule.require('child_process').execSync('whoami')
|
|
265
|
+
* process.mainModule.constructor._load('vm')
|
|
266
|
+
* ```
|
|
267
|
+
*
|
|
268
|
+
* process.mainModule may be undefined in ESM contexts but could exist in
|
|
269
|
+
* CommonJS workers. We block both reading and setting.
|
|
270
|
+
*/
|
|
271
|
+
private protectProcessMainModule;
|
|
272
|
+
/**
|
|
273
|
+
* Protect process.execPath from being read or set in sandbox context.
|
|
274
|
+
*
|
|
275
|
+
* process.execPath is a string primitive (not an object), so it cannot be
|
|
276
|
+
* proxied via the normal blocked globals mechanism. We use Object.defineProperty
|
|
277
|
+
* with getter/setter (same pattern as protectProcessMainModule).
|
|
278
|
+
*/
|
|
279
|
+
private protectProcessExecPath;
|
|
280
|
+
/**
|
|
281
|
+
* Lock well-known Symbol properties on built-in constructors/prototypes.
|
|
282
|
+
*
|
|
283
|
+
* Instead of freezing entire prototypes (which breaks Node.js internals),
|
|
284
|
+
* we make specific Symbol properties non-configurable so they can't be
|
|
285
|
+
* replaced. This prevents:
|
|
286
|
+
* - Symbol.species hijacking (controls .map/.filter/.slice return types)
|
|
287
|
+
* - Symbol.iterator hijacking (controls for...of and spread)
|
|
288
|
+
* - Symbol.toPrimitive hijacking (controls type coercion)
|
|
289
|
+
*/
|
|
290
|
+
private lockWellKnownSymbols;
|
|
291
|
+
/**
|
|
292
|
+
* Block Proxy.revocable to prevent bypassing Proxy constructor blocking.
|
|
293
|
+
*
|
|
294
|
+
* Proxy.revocable internally uses the real Proxy constructor, so it bypasses
|
|
295
|
+
* our blocking proxy on globalThis.Proxy. We replace it with a wrapper that
|
|
296
|
+
* checks the sandbox context before delegating to the original.
|
|
297
|
+
*/
|
|
298
|
+
private protectProxyRevocable;
|
|
299
|
+
/**
|
|
300
|
+
* Block dynamic import() escape vectors via ESM loader hooks.
|
|
301
|
+
*
|
|
302
|
+
* Uses Node.js module.registerHooks() (23.5+, synchronous) to install ESM
|
|
303
|
+
* loader hooks that reject dangerous specifiers.
|
|
304
|
+
*
|
|
305
|
+
* registerHooks() runs in-thread and can read AsyncLocalStorage. We use it
|
|
306
|
+
* to block Node.js builtin specifiers (node:* and bare builtins) only in
|
|
307
|
+
* untrusted sandbox context while still allowing trusted infrastructure
|
|
308
|
+
* imports (runTrusted/runTrustedAsync).
|
|
309
|
+
*
|
|
310
|
+
* module.register() is deliberately not used as a fallback: those hooks run
|
|
311
|
+
* in a separate loader thread and cannot read AsyncLocalStorage.
|
|
312
|
+
*
|
|
313
|
+
* This is process-wide and permanent (hooks cannot be unregistered).
|
|
314
|
+
* Only applied once per process regardless of how many DefenseInDepthBox
|
|
315
|
+
* instances are created.
|
|
316
|
+
*
|
|
317
|
+
* Combined with Module._resolveFilename blocking (file-based specifiers),
|
|
318
|
+
* this closes the import() escape vector except for specifiers that bypass
|
|
319
|
+
* both the ESM loader and CJS resolution (none known).
|
|
320
|
+
*/
|
|
321
|
+
private protectDynamicImport;
|
|
322
|
+
/**
|
|
323
|
+
* Protect Module._load from being called in sandbox context.
|
|
324
|
+
*
|
|
325
|
+
* The attack vector is:
|
|
326
|
+
* ```
|
|
327
|
+
* module.constructor._load('child_process')
|
|
328
|
+
* require.main.constructor._load('vm')
|
|
329
|
+
* ```
|
|
330
|
+
*
|
|
331
|
+
* We access the Module class and replace _load with a blocking proxy.
|
|
332
|
+
*/
|
|
333
|
+
private protectModuleLoad;
|
|
334
|
+
/**
|
|
335
|
+
* Protect Module._resolveFilename from being called in sandbox context.
|
|
336
|
+
*
|
|
337
|
+
* Module._resolveFilename is called for both require() and import() resolution.
|
|
338
|
+
* Blocking it catches file-based import() specifiers:
|
|
339
|
+
* import('./malicious.js') // _resolveFilename is called to resolve the path
|
|
340
|
+
*
|
|
341
|
+
* data: and blob: URLs are handled separately by protectDynamicImport()
|
|
342
|
+
* via ESM loader hooks.
|
|
343
|
+
*/
|
|
344
|
+
private protectModuleResolveFilename;
|
|
345
|
+
private protectModuleMethod;
|
|
346
|
+
/**
|
|
347
|
+
* Apply a single patch to a blocked global.
|
|
348
|
+
*/
|
|
349
|
+
private applyPatch;
|
|
350
|
+
/**
|
|
351
|
+
* Restore all original values.
|
|
352
|
+
*/
|
|
353
|
+
private restorePatches;
|
|
354
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security Module - Defense-in-Depth Box
|
|
3
|
+
*
|
|
4
|
+
* This module provides a secondary defense layer that monkey-patches
|
|
5
|
+
* dangerous JavaScript globals during bash script execution.
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: This is a SECONDARY defense layer. It should never be relied upon
|
|
8
|
+
* as the primary security mechanism. The primary security comes from proper
|
|
9
|
+
* sandboxing, input validation, and architectural constraints.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* ```typescript
|
|
13
|
+
* import { Bash } from 'just-bash';
|
|
14
|
+
*
|
|
15
|
+
* // Capability-detect defense-in-depth (the Bash default)
|
|
16
|
+
* const bash = new Bash({
|
|
17
|
+
* defenseInDepth: { enabled: "auto" },
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // Or with custom configuration
|
|
21
|
+
* const bash = new Bash({
|
|
22
|
+
* defenseInDepth: {
|
|
23
|
+
* enabled: true,
|
|
24
|
+
* auditMode: false,
|
|
25
|
+
* onViolation: (v) => console.warn('Violation:', v),
|
|
26
|
+
* },
|
|
27
|
+
* });
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export { DefenseInDepthBox, SecurityViolationError, } from "./defense-in-depth-box.js";
|
|
31
|
+
export { createConsoleViolationCallback, SecurityViolationLogger, type SecurityViolationLoggerOptions, type ViolationSummary, } from "./security-violation-logger.js";
|
|
32
|
+
export type { DefenseInDepthConfig, DefenseInDepthHandle, DefenseInDepthStats, DefenseInDepthStatus, SecurityViolation, SecurityViolationType, } from "./types.js";
|
|
33
|
+
export { WorkerDefenseInDepth, type WorkerDefenseStats, } from "./worker-defense-in-depth.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getSafeTimestamp(): number;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security Violation Logger
|
|
3
|
+
*
|
|
4
|
+
* Utility for tracking and reporting security violations from the
|
|
5
|
+
* defense-in-depth box. Useful for monitoring, alerting, and debugging.
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: This is for monitoring a SECONDARY defense layer.
|
|
8
|
+
* Violations indicate potential escape attempts but the primary
|
|
9
|
+
* security should prevent these from being exploitable.
|
|
10
|
+
*/
|
|
11
|
+
import type { SecurityViolation, SecurityViolationType } from "./types.js";
|
|
12
|
+
/**
|
|
13
|
+
* Options for the security violation logger.
|
|
14
|
+
*/
|
|
15
|
+
export interface SecurityViolationLoggerOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Maximum number of violations to store per type.
|
|
18
|
+
* Default: 100
|
|
19
|
+
*/
|
|
20
|
+
maxViolationsPerType?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Maximum total violations to retain across all types.
|
|
23
|
+
* Oldest violations are dropped when this limit is reached.
|
|
24
|
+
* Default: 1000
|
|
25
|
+
*/
|
|
26
|
+
maxViolationsTotal?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Whether to include stack traces in logged violations.
|
|
29
|
+
* Default: true
|
|
30
|
+
*/
|
|
31
|
+
includeStackTraces?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Custom handler called for each violation.
|
|
34
|
+
*/
|
|
35
|
+
onViolation?: (violation: SecurityViolation) => void;
|
|
36
|
+
/**
|
|
37
|
+
* Whether to log violations to console (for debugging).
|
|
38
|
+
* Default: false
|
|
39
|
+
*/
|
|
40
|
+
logToConsole?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Summary of violations by type.
|
|
44
|
+
*/
|
|
45
|
+
export interface ViolationSummary {
|
|
46
|
+
type: SecurityViolationType;
|
|
47
|
+
count: number;
|
|
48
|
+
firstSeen: number;
|
|
49
|
+
lastSeen: number;
|
|
50
|
+
paths: string[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Security Violation Logger
|
|
54
|
+
*
|
|
55
|
+
* Collects and summarizes security violations for analysis.
|
|
56
|
+
*/
|
|
57
|
+
export declare class SecurityViolationLogger {
|
|
58
|
+
private violations;
|
|
59
|
+
private violationsByType;
|
|
60
|
+
private options;
|
|
61
|
+
constructor(options?: SecurityViolationLoggerOptions);
|
|
62
|
+
/**
|
|
63
|
+
* Record a security violation.
|
|
64
|
+
* This method is designed to be passed as the onViolation callback.
|
|
65
|
+
*/
|
|
66
|
+
record(violation: SecurityViolation): void;
|
|
67
|
+
/**
|
|
68
|
+
* Get all recorded violations.
|
|
69
|
+
*/
|
|
70
|
+
getViolations(): SecurityViolation[];
|
|
71
|
+
/**
|
|
72
|
+
* Get violations of a specific type.
|
|
73
|
+
*/
|
|
74
|
+
getViolationsByType(type: SecurityViolationType): SecurityViolation[];
|
|
75
|
+
/**
|
|
76
|
+
* Get a summary of all violations by type.
|
|
77
|
+
*/
|
|
78
|
+
getSummary(): ViolationSummary[];
|
|
79
|
+
/**
|
|
80
|
+
* Get total violation count.
|
|
81
|
+
*/
|
|
82
|
+
getTotalCount(): number;
|
|
83
|
+
/**
|
|
84
|
+
* Check if any violations have been recorded.
|
|
85
|
+
*/
|
|
86
|
+
hasViolations(): boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Clear all recorded violations.
|
|
89
|
+
*/
|
|
90
|
+
clear(): void;
|
|
91
|
+
/**
|
|
92
|
+
* Create a callback function suitable for DefenseInDepthConfig.onViolation.
|
|
93
|
+
*/
|
|
94
|
+
createCallback(): (violation: SecurityViolation) => void;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Create a simple violation callback that logs to console.
|
|
98
|
+
*/
|
|
99
|
+
export declare function createConsoleViolationCallback(): (violation: SecurityViolation) => void;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SECURITY: Pre-captured references to dangerous globals.
|
|
3
|
+
*
|
|
4
|
+
* These are captured at module load time (before defense-in-depth patches)
|
|
5
|
+
* so that just-bash infrastructure can use them. They bypass all defense
|
|
6
|
+
* protections.
|
|
7
|
+
*
|
|
8
|
+
* DO NOT import these from command implementations unless absolutely
|
|
9
|
+
* necessary (e.g., Python WASM worker IPC). Any import from this module
|
|
10
|
+
* should be reviewed for security implications.
|
|
11
|
+
*/
|
|
12
|
+
export declare const _SharedArrayBuffer: typeof globalThis.SharedArrayBuffer;
|
|
13
|
+
export declare const _Atomics: typeof globalThis.Atomics;
|
|
14
|
+
export declare const _performanceNow: () => number;
|
|
15
|
+
export declare const _Headers: typeof globalThis.Headers;
|
|
16
|
+
/** Internal capability revocation; never expose this constructor to commands. */
|
|
17
|
+
export declare const _Proxy: ProxyConstructor;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security Types for Defense-in-Depth Box
|
|
3
|
+
*
|
|
4
|
+
* These types define the configuration and behavior of the defense-in-depth
|
|
5
|
+
* security layer that protects against code execution escape vectors.
|
|
6
|
+
*
|
|
7
|
+
* IMPORTANT: This is a SECONDARY defense layer. It should never be relied upon
|
|
8
|
+
* as the primary security mechanism. The primary security comes from proper
|
|
9
|
+
* sandboxing, input validation, and architectural constraints.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Configuration for the defense-in-depth box.
|
|
13
|
+
*/
|
|
14
|
+
export interface DefenseInDepthConfig {
|
|
15
|
+
/**
|
|
16
|
+
* Enable, disable, or capability-detect the defense layer.
|
|
17
|
+
*
|
|
18
|
+
* `true` (the default used by `Bash`) and `"auto"` both enable the strongest
|
|
19
|
+
* protection supported by the current runtime. Inspect `getStatus()` when a
|
|
20
|
+
* host requires the full contextual dynamic-import boundary.
|
|
21
|
+
*/
|
|
22
|
+
enabled?: boolean | "auto";
|
|
23
|
+
/**
|
|
24
|
+
* Permanently freeze selected host intrinsics and lock well-known Symbol
|
|
25
|
+
* descriptors. This cannot be undone by `deactivate()` and is therefore
|
|
26
|
+
* disabled by default. Only use in a dedicated, process-lifetime realm.
|
|
27
|
+
*/
|
|
28
|
+
processLifetimeIntrinsicHardening?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Audit mode: log violations but don't block them.
|
|
31
|
+
* Useful for debugging and testing without breaking execution.
|
|
32
|
+
* Default: false
|
|
33
|
+
*/
|
|
34
|
+
auditMode?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Callback invoked when a security violation is detected.
|
|
37
|
+
* Called regardless of auditMode setting.
|
|
38
|
+
*/
|
|
39
|
+
onViolation?: (violation: SecurityViolation) => void;
|
|
40
|
+
/**
|
|
41
|
+
* Violation types to exclude from blocking.
|
|
42
|
+
* Use this when certain globals are required for legitimate purposes
|
|
43
|
+
* (e.g., WebAssembly for sql.js in sqlite3 worker).
|
|
44
|
+
* Constructor-execution protections are non-excludable.
|
|
45
|
+
*/
|
|
46
|
+
excludeViolationTypes?: SecurityViolationType[];
|
|
47
|
+
}
|
|
48
|
+
export interface DefenseInDepthStatus {
|
|
49
|
+
requested: "auto" | "enabled" | "disabled";
|
|
50
|
+
state: "enabled" | "unsupported" | "disabled";
|
|
51
|
+
/**
|
|
52
|
+
* Overall effective enforcement strength without changing the legacy
|
|
53
|
+
* `state` contract. Audit mode always reports `"none"` because it records
|
|
54
|
+
* violations without blocking them.
|
|
55
|
+
*/
|
|
56
|
+
level: "full" | "best-effort" | "none";
|
|
57
|
+
contextualDynamicImportProtection: boolean;
|
|
58
|
+
processLifetimeIntrinsicHardening: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Scoped gates are reversible but cannot revoke mutation functions or
|
|
61
|
+
* intrinsic references cached before activation. Complete protection
|
|
62
|
+
* requires the explicitly irreversible process-lifetime mode or isolation.
|
|
63
|
+
*/
|
|
64
|
+
intrinsicProtection: "scoped-best-effort" | "process-lifetime";
|
|
65
|
+
reason?: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Types of security violations that can be detected.
|
|
69
|
+
*/
|
|
70
|
+
/**
|
|
71
|
+
* Types of security violations that can be detected.
|
|
72
|
+
*
|
|
73
|
+
* Note: We focus on code execution vectors. We don't block:
|
|
74
|
+
* - process: Needed for Node.js operation (process.nextTick, etc.)
|
|
75
|
+
* - require: May not exist in ESM, and import() can't be blocked this way
|
|
76
|
+
*/
|
|
77
|
+
export type SecurityViolationType = "function_constructor" | "eval" | "setTimeout" | "setInterval" | "setImmediate" | "async_function_constructor" | "generator_function_constructor" | "async_generator_function_constructor" | "weak_ref" | "finalization_registry" | "reflect" | "proxy" | "process_env" | "process_binding" | "process_dlopen" | "process_main_module" | "process_exit" | "process_kill" | "process_setuid" | "process_umask" | "process_argv" | "process_exec_path" | "process_chdir" | "process_connected" | "process_send" | "process_channel" | "process_timing" | "module_load" | "webassembly" | "shared_array_buffer" | "atomics" | "process_get_builtin_module" | "error_prepare_stack_trace" | "performance_timing" | "process_stdout" | "process_stderr" | "module_resolve_filename" | "dynamic_import_builtin" | "missing_defense_context" | "promise_then_after_deactivate" | "bound_callback_after_deactivate" | "prototype_mutation" | "json_mutation" | "math_mutation" | "process_report" | "process_exception_handler";
|
|
78
|
+
/**
|
|
79
|
+
* Information about a detected security violation.
|
|
80
|
+
*/
|
|
81
|
+
export interface SecurityViolation {
|
|
82
|
+
/**
|
|
83
|
+
* Timestamp when the violation occurred (milliseconds since epoch).
|
|
84
|
+
*/
|
|
85
|
+
timestamp: number;
|
|
86
|
+
/**
|
|
87
|
+
* Type of violation detected.
|
|
88
|
+
*/
|
|
89
|
+
type: SecurityViolationType;
|
|
90
|
+
/**
|
|
91
|
+
* Human-readable message describing the violation.
|
|
92
|
+
*/
|
|
93
|
+
message: string;
|
|
94
|
+
/**
|
|
95
|
+
* Path to the blocked global (e.g., "globalThis.Function").
|
|
96
|
+
*/
|
|
97
|
+
path: string;
|
|
98
|
+
/**
|
|
99
|
+
* Stack trace at the point of violation, if available.
|
|
100
|
+
*/
|
|
101
|
+
stack?: string;
|
|
102
|
+
/**
|
|
103
|
+
* Execution ID from AsyncLocalStorage context, for correlation.
|
|
104
|
+
*/
|
|
105
|
+
executionId?: string;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Statistics about defense-in-depth box activity.
|
|
109
|
+
*/
|
|
110
|
+
export interface DefenseInDepthStats {
|
|
111
|
+
/**
|
|
112
|
+
* Total number of violations blocked.
|
|
113
|
+
*/
|
|
114
|
+
violationsBlocked: number;
|
|
115
|
+
/**
|
|
116
|
+
* List of all violations detected (capped to prevent memory issues).
|
|
117
|
+
*/
|
|
118
|
+
violations: SecurityViolation[];
|
|
119
|
+
/**
|
|
120
|
+
* Total time the defense layer has been active in milliseconds.
|
|
121
|
+
*/
|
|
122
|
+
activeTimeMs: number;
|
|
123
|
+
/**
|
|
124
|
+
* Current reference count (number of nested activations).
|
|
125
|
+
*/
|
|
126
|
+
refCount: number;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Handle returned by activate() for scoped execution.
|
|
130
|
+
* Use the run() method to execute code within the protected context.
|
|
131
|
+
*/
|
|
132
|
+
export interface DefenseInDepthHandle {
|
|
133
|
+
/**
|
|
134
|
+
* Run code within the protected AsyncLocalStorage context.
|
|
135
|
+
* All async descendants of the provided function will be tracked.
|
|
136
|
+
*
|
|
137
|
+
* @param fn - Async function to execute in the protected context
|
|
138
|
+
* @returns Promise resolving to the function's return value
|
|
139
|
+
*/
|
|
140
|
+
run: <T>(fn: () => Promise<T>) => Promise<T>;
|
|
141
|
+
/**
|
|
142
|
+
* Deactivate the defense layer. Must be called in a finally block.
|
|
143
|
+
* Decrements ref count; patches are restored when count hits 0.
|
|
144
|
+
*/
|
|
145
|
+
deactivate: () => void;
|
|
146
|
+
/**
|
|
147
|
+
* Unique identifier for this execution context.
|
|
148
|
+
* Useful for correlating violations with specific exec() calls.
|
|
149
|
+
*/
|
|
150
|
+
executionId: string;
|
|
151
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { SecurityViolationType } from "./types.js";
|
|
2
|
+
export declare function assertExcludableViolationTypes(violationTypes: readonly SecurityViolationType[] | undefined): void;
|
|
3
|
+
export declare function formatViolationErrorMessage(message: string, violationType: SecurityViolationType, canExclude: boolean): string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function sanitizeUnknownError(error: unknown): string;
|
|
2
|
+
/**
|
|
3
|
+
* Wrap WASM-to-JS callbacks so callback failures are surfaced as sanitized
|
|
4
|
+
* internal errors without leaking host/internal paths.
|
|
5
|
+
*/
|
|
6
|
+
export declare function wrapWasmCallback<TArgs extends unknown[], TResult>(component: string, phase: string, callback: (...args: TArgs) => TResult): (...args: TArgs) => TResult;
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker Defense-in-Depth
|
|
3
|
+
*
|
|
4
|
+
* A simplified version of DefenseInDepthBox designed for use in Worker threads.
|
|
5
|
+
* Since workers have their own isolated V8 context, we don't need AsyncLocalStorage
|
|
6
|
+
* to track execution context - the entire worker IS the sandboxed context.
|
|
7
|
+
*
|
|
8
|
+
* Key differences from DefenseInDepthBox:
|
|
9
|
+
* - No AsyncLocalStorage (always blocks, no context tracking needed)
|
|
10
|
+
* - Single activation model (apply patches once at worker startup)
|
|
11
|
+
* - Violations reported via callback (typically postMessage to parent)
|
|
12
|
+
*
|
|
13
|
+
* Usage in a worker:
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { parentPort } from 'node:worker_threads';
|
|
16
|
+
* import { WorkerDefenseInDepth } from '../security/worker-defense-in-depth.js';
|
|
17
|
+
*
|
|
18
|
+
* // Apply patches at worker startup
|
|
19
|
+
* const defense = new WorkerDefenseInDepth({
|
|
20
|
+
* onViolation: (v) => parentPort?.postMessage({ type: 'security-violation', violation: v }),
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // All code in the worker is now protected
|
|
24
|
+
* // Attempting Function, eval, etc. will throw SecurityViolationError
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* Constructor Protection:
|
|
28
|
+
* Function.prototype.constructor returns a proxy that allows property reads
|
|
29
|
+
* (e.g., `.constructor.name` for type introspection) but blocks invocation
|
|
30
|
+
* (e.g., `.constructor("code")` for dynamic code execution).
|
|
31
|
+
*
|
|
32
|
+
* IMPORTANT: This is a SECONDARY defense layer. It should never be relied upon
|
|
33
|
+
* as the primary security mechanism. The primary security comes from proper
|
|
34
|
+
* sandboxing, input validation, and architectural constraints.
|
|
35
|
+
*
|
|
36
|
+
* Dynamic import() mitigation (three layers):
|
|
37
|
+
* 1. Module._resolveFilename blocked — catches file-based specifiers
|
|
38
|
+
* 2. Main-thread ESM loader hooks block data:/blob: URLs (not in workers)
|
|
39
|
+
* 3. Filesystem restrictions — OverlayFs writes to memory only
|
|
40
|
+
*
|
|
41
|
+
* Note: ESM loader hooks are registered by DefenseInDepthBox in the main
|
|
42
|
+
* thread. Workers inherit the hooks automatically. Worker-level registration
|
|
43
|
+
* is not needed (and would require require('node:module') which is blocked).
|
|
44
|
+
*/
|
|
45
|
+
import type { DefenseInDepthConfig, SecurityViolation } from "./types.js";
|
|
46
|
+
/**
|
|
47
|
+
* Error thrown when a security violation is detected.
|
|
48
|
+
*/
|
|
49
|
+
export declare class WorkerSecurityViolationError extends Error {
|
|
50
|
+
readonly violation: SecurityViolation;
|
|
51
|
+
constructor(message: string, violation: SecurityViolation);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Statistics about the worker defense layer.
|
|
55
|
+
*/
|
|
56
|
+
export interface WorkerDefenseStats {
|
|
57
|
+
/** Total number of violations detected */
|
|
58
|
+
violationsBlocked: number;
|
|
59
|
+
/** List of all violations detected (capped to prevent memory issues) */
|
|
60
|
+
violations: SecurityViolation[];
|
|
61
|
+
/** Whether patches are currently active */
|
|
62
|
+
isActive: boolean;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Worker Defense-in-Depth
|
|
66
|
+
*
|
|
67
|
+
* Applies security patches to dangerous JavaScript globals in a worker context.
|
|
68
|
+
* Unlike DefenseInDepthBox, this is designed for workers where the entire
|
|
69
|
+
* execution context is sandboxed.
|
|
70
|
+
*/
|
|
71
|
+
export declare class WorkerDefenseInDepth {
|
|
72
|
+
private config;
|
|
73
|
+
private isActivated;
|
|
74
|
+
private originalDescriptors;
|
|
75
|
+
private patchFailures;
|
|
76
|
+
private violations;
|
|
77
|
+
private executionId;
|
|
78
|
+
/**
|
|
79
|
+
* Original Proxy constructor, captured before patching.
|
|
80
|
+
* This is captured at instance creation time to ensure we get the unpatched version.
|
|
81
|
+
*/
|
|
82
|
+
private originalProxy;
|
|
83
|
+
/**
|
|
84
|
+
* Recursion guard to prevent infinite loops when proxy traps trigger
|
|
85
|
+
* code that accesses the same proxied object (e.g., process.env).
|
|
86
|
+
*/
|
|
87
|
+
private inTrap;
|
|
88
|
+
/**
|
|
89
|
+
* Create and activate the worker defense layer.
|
|
90
|
+
*
|
|
91
|
+
* @param config - Configuration for the defense layer
|
|
92
|
+
*/
|
|
93
|
+
constructor(config: DefenseInDepthConfig);
|
|
94
|
+
/**
|
|
95
|
+
* Get statistics about the defense layer.
|
|
96
|
+
*/
|
|
97
|
+
getStats(): WorkerDefenseStats;
|
|
98
|
+
/**
|
|
99
|
+
* Clear stored violations. Useful for testing.
|
|
100
|
+
*/
|
|
101
|
+
clearViolations(): void;
|
|
102
|
+
/**
|
|
103
|
+
* Get the execution ID for this worker.
|
|
104
|
+
*/
|
|
105
|
+
getExecutionId(): string;
|
|
106
|
+
/**
|
|
107
|
+
* Deactivate the defense layer and restore original globals.
|
|
108
|
+
* Typically only needed for testing.
|
|
109
|
+
*/
|
|
110
|
+
deactivate(): void;
|
|
111
|
+
/**
|
|
112
|
+
* Activate the defense layer by applying patches.
|
|
113
|
+
*/
|
|
114
|
+
private activate;
|
|
115
|
+
/**
|
|
116
|
+
* Get a human-readable path for a target object and property.
|
|
117
|
+
*/
|
|
118
|
+
private getPathForTarget;
|
|
119
|
+
/**
|
|
120
|
+
* Record a violation and invoke the callback.
|
|
121
|
+
* In worker context, blocking always happens (no audit mode context check).
|
|
122
|
+
*/
|
|
123
|
+
private recordViolation;
|
|
124
|
+
/**
|
|
125
|
+
* Create a blocking proxy for a function.
|
|
126
|
+
* In worker context, always blocks (no context check needed).
|
|
127
|
+
*/
|
|
128
|
+
private createBlockingProxy;
|
|
129
|
+
/**
|
|
130
|
+
* Create a blocking proxy for an object (blocks all property access).
|
|
131
|
+
*/
|
|
132
|
+
private createBlockingObjectProxy;
|
|
133
|
+
private createReadonlyObjectProxy;
|
|
134
|
+
/**
|
|
135
|
+
* Apply security patches to dangerous globals.
|
|
136
|
+
*/
|
|
137
|
+
private applyPatches;
|
|
138
|
+
/**
|
|
139
|
+
* Lock well-known Symbol properties on built-in constructors/prototypes.
|
|
140
|
+
*/
|
|
141
|
+
private lockWellKnownSymbols;
|
|
142
|
+
/**
|
|
143
|
+
* Block Proxy.revocable to prevent bypassing Proxy constructor blocking.
|
|
144
|
+
*
|
|
145
|
+
* Proxy.revocable internally uses the real Proxy constructor, so it bypasses
|
|
146
|
+
* our blocking proxy on globalThis.Proxy. We replace it with a wrapper that
|
|
147
|
+
* always blocks in worker context.
|
|
148
|
+
*/
|
|
149
|
+
private protectProxyRevocable;
|
|
150
|
+
/**
|
|
151
|
+
* Protect against .constructor.constructor escape vector.
|
|
152
|
+
* @param excludeTypes - Set of violation types to skip
|
|
153
|
+
*/
|
|
154
|
+
private protectConstructorChain;
|
|
155
|
+
/**
|
|
156
|
+
* Protect Error.prepareStackTrace from being set.
|
|
157
|
+
*/
|
|
158
|
+
private protectErrorPrepareStackTrace;
|
|
159
|
+
/**
|
|
160
|
+
* Patch a prototype's constructor property.
|
|
161
|
+
*
|
|
162
|
+
* Returns a proxy that allows reading properties (like .name) but blocks
|
|
163
|
+
* calling the constructor as a function (which would allow code execution).
|
|
164
|
+
*/
|
|
165
|
+
private patchPrototypeConstructor;
|
|
166
|
+
/**
|
|
167
|
+
* Protect process.mainModule from being accessed or set.
|
|
168
|
+
*
|
|
169
|
+
* The attack vector is:
|
|
170
|
+
* ```
|
|
171
|
+
* process.mainModule.require('child_process').execSync('whoami')
|
|
172
|
+
* process.mainModule.constructor._load('vm')
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* process.mainModule may be undefined in ESM contexts but could exist in
|
|
176
|
+
* CommonJS workers. We block both reading and setting.
|
|
177
|
+
*/
|
|
178
|
+
private protectProcessMainModule;
|
|
179
|
+
/**
|
|
180
|
+
* Protect process.execPath from being read or set in worker context.
|
|
181
|
+
*
|
|
182
|
+
* process.execPath is a string primitive (not an object), so it cannot be
|
|
183
|
+
* proxied via the normal blocked globals mechanism. We use Object.defineProperty
|
|
184
|
+
* with getter/setter (same pattern as protectProcessMainModule).
|
|
185
|
+
*/
|
|
186
|
+
private protectProcessExecPath;
|
|
187
|
+
/**
|
|
188
|
+
* Protect process.connected from being read or set in worker context.
|
|
189
|
+
*
|
|
190
|
+
* process.connected is a boolean primitive (not an object), so it cannot be
|
|
191
|
+
* proxied via the normal blocked globals mechanism. We use Object.defineProperty
|
|
192
|
+
* with getter/setter (same pattern as protectProcessExecPath).
|
|
193
|
+
*
|
|
194
|
+
* Only protects if process.connected exists (IPC contexts).
|
|
195
|
+
*/
|
|
196
|
+
private protectProcessConnected;
|
|
197
|
+
/**
|
|
198
|
+
* Protect Module._load from being called.
|
|
199
|
+
*
|
|
200
|
+
* The attack vector is:
|
|
201
|
+
* ```
|
|
202
|
+
* module.constructor._load('child_process')
|
|
203
|
+
* require.main.constructor._load('vm')
|
|
204
|
+
* ```
|
|
205
|
+
*
|
|
206
|
+
* We access the Module class and replace _load with a blocking proxy.
|
|
207
|
+
*/
|
|
208
|
+
private protectModuleLoad;
|
|
209
|
+
/**
|
|
210
|
+
* Protect Module._resolveFilename from being called in worker context.
|
|
211
|
+
*
|
|
212
|
+
* Module._resolveFilename is called for both require() and import() resolution.
|
|
213
|
+
* Blocking it catches file-based import() specifiers.
|
|
214
|
+
*
|
|
215
|
+
* data: and blob: URLs are handled by ESM loader hooks registered
|
|
216
|
+
* in the main thread (DefenseInDepthBox.protectDynamicImport).
|
|
217
|
+
*/
|
|
218
|
+
private protectModuleResolveFilename;
|
|
219
|
+
private protectModuleMethod;
|
|
220
|
+
/**
|
|
221
|
+
* Apply a single patch to a blocked global.
|
|
222
|
+
*/
|
|
223
|
+
private applyPatch;
|
|
224
|
+
/**
|
|
225
|
+
* Restore all original values.
|
|
226
|
+
*/
|
|
227
|
+
private restorePatches;
|
|
228
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { BashTransformResult, TransformPlugin } from "./types.js";
|
|
2
|
+
export declare class BashTransformPipeline<TMetadata extends object = Record<string, never>> {
|
|
3
|
+
private readonly maxSourceBytes;
|
|
4
|
+
private plugins;
|
|
5
|
+
constructor(maxSourceBytes?: number);
|
|
6
|
+
use<M extends object>(plugin: TransformPlugin<M>): BashTransformPipeline<TMetadata & M>;
|
|
7
|
+
transform(script: string): BashTransformResult<TMetadata>;
|
|
8
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { TransformContext, TransformPlugin, TransformResult } from "../types.js";
|
|
2
|
+
export interface CommandCollectorMetadata {
|
|
3
|
+
commands: string[];
|
|
4
|
+
}
|
|
5
|
+
export declare class CommandCollectorPlugin implements TransformPlugin<CommandCollectorMetadata> {
|
|
6
|
+
readonly name = "command-collector";
|
|
7
|
+
transform(context: TransformContext): TransformResult<CommandCollectorMetadata>;
|
|
8
|
+
private walkScript;
|
|
9
|
+
private walkStatement;
|
|
10
|
+
private walkPipeline;
|
|
11
|
+
private walkCommand;
|
|
12
|
+
private walkWordParts;
|
|
13
|
+
private walkParameterOp;
|
|
14
|
+
private extractName;
|
|
15
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { TransformContext, TransformPlugin, TransformResult } from "../types.js";
|
|
2
|
+
export interface TeePluginOptions {
|
|
3
|
+
outputDir: string;
|
|
4
|
+
targetCommandPattern?: {
|
|
5
|
+
test(input: string): boolean;
|
|
6
|
+
};
|
|
7
|
+
timestamp?: Date;
|
|
8
|
+
}
|
|
9
|
+
export interface TeeFileInfo {
|
|
10
|
+
commandIndex: number;
|
|
11
|
+
commandName: string;
|
|
12
|
+
/** The full command string (name + arguments) before tee wrapping */
|
|
13
|
+
command: string;
|
|
14
|
+
stdoutFile: string;
|
|
15
|
+
}
|
|
16
|
+
export interface TeePluginMetadata {
|
|
17
|
+
teeFiles: TeeFileInfo[];
|
|
18
|
+
}
|
|
19
|
+
export declare class TeePlugin implements TransformPlugin<TeePluginMetadata> {
|
|
20
|
+
readonly name = "tee";
|
|
21
|
+
private options;
|
|
22
|
+
private counter;
|
|
23
|
+
constructor(options: TeePluginOptions);
|
|
24
|
+
transform(context: TransformContext): TransformResult<TeePluginMetadata>;
|
|
25
|
+
private formatTimestamp;
|
|
26
|
+
private generateStdoutPath;
|
|
27
|
+
private encodeCommandName;
|
|
28
|
+
private transformScript;
|
|
29
|
+
private transformStatement;
|
|
30
|
+
private transformPipeline;
|
|
31
|
+
/**
|
|
32
|
+
* Restore PIPESTATUS and exit code without user-visible variables.
|
|
33
|
+
* Produces: `builtin __just_bash_tee_restore ${PIPESTATUS[i]} ...`
|
|
34
|
+
*/
|
|
35
|
+
private makePipestatusRestore;
|
|
36
|
+
private shouldTarget;
|
|
37
|
+
private getCommandName;
|
|
38
|
+
private serializeCommand;
|
|
39
|
+
private makeTeeCommand;
|
|
40
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ScriptNode } from "../ast/types.js";
|
|
2
|
+
export interface TransformPlugin<TMetadata extends object = Record<string, unknown>> {
|
|
3
|
+
name: string;
|
|
4
|
+
transform(context: TransformContext): TransformResult<TMetadata>;
|
|
5
|
+
}
|
|
6
|
+
export interface TransformContext {
|
|
7
|
+
ast: ScriptNode;
|
|
8
|
+
metadata: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface TransformResult<TMetadata extends object = Record<string, unknown>> {
|
|
11
|
+
ast: ScriptNode;
|
|
12
|
+
metadata?: TMetadata;
|
|
13
|
+
}
|
|
14
|
+
export interface BashTransformResult<TMetadata extends object = Record<string, unknown>> {
|
|
15
|
+
script: string;
|
|
16
|
+
ast: ScriptNode;
|
|
17
|
+
metadata: TMetadata;
|
|
18
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "just-bash",
|
|
3
|
-
"version": "3.4.
|
|
3
|
+
"version": "3.4.2",
|
|
4
4
|
"description": "A simulated bash environment with virtual filesystem",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -46,6 +46,8 @@
|
|
|
46
46
|
"dist/network/**/*.d.ts",
|
|
47
47
|
"dist/parser/*.d.ts",
|
|
48
48
|
"dist/sandbox/*.d.ts",
|
|
49
|
+
"dist/security/*.d.ts",
|
|
50
|
+
"dist/transform/**/*.d.ts",
|
|
49
51
|
"dist/utils/*.d.ts",
|
|
50
52
|
"vendor/cpython-emscripten/",
|
|
51
53
|
"README.md",
|
|
@@ -117,7 +119,7 @@
|
|
|
117
119
|
"knip": "knip",
|
|
118
120
|
"test": "vitest",
|
|
119
121
|
"test:run": "vitest run --exclude src/security/fuzzing/ --exclude src/commands/python3/ --exclude src/commands/sqlite3/ --exclude src/commands/js-exec/ --exclude src/agent-examples/python-scripting.test.ts",
|
|
120
|
-
"test:dist": "vitest run src/cli/just-bash.bundle.test.ts",
|
|
122
|
+
"test:dist": "vitest run src/cli/just-bash.bundle.test.ts src/package-contents.test.ts",
|
|
121
123
|
"test:unit": "vitest run --config vitest.unit.config.ts",
|
|
122
124
|
"test:wasm": "vitest run --config vitest.wasm.config.ts",
|
|
123
125
|
"test:comparison": "vitest run --config vitest.comparison.config.ts",
|