Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ coverage
node_modules
tests
shared
!**/dist/shared/
!**/dist/shared/**

# Exclude docs, those can be accessed online
docs
Expand Down
79 changes: 72 additions & 7 deletions docs/bug-detectors.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ using Jest in `.jazzerjsrc.json`:
Hooks all relevant functions of the built-in modules `fs` and `path` and reports
a finding if the fuzzer could pass a special path to any of the functions.

The Path Traversal bug detector can be configured in the
[custom hooks](./fuzz-settings.md#customhooks--arraystring) file.

- `ignore(rule)` - suppresses findings from callsites matching the shown stack
excerpt.
- `stackPattern` accepts either a string or a `RegExp` and is matched against
the shown stack excerpt after removing the leading `Error` line and Jazzer.js
frames. The remaining stack text is matched as shown, including path
separators and column numbers.

Here is an example configuration in the
[custom hooks](./fuzz-settings.md#customhooks--arraystring) file:

```javascript
const { getBugDetectorConfiguration } = require("@jazzer.js/bug-detectors");

getBugDetectorConfiguration("path-traversal")?.ignore({
stackPattern: "safe-path-wrapper.js:41",
});
```

Findings also print a generic example suppression snippet. Copy/paste it and
adapt `stackPattern` to the shown stack excerpt.

_Disable with:_ `--disableBugDetectors=path-traversal` in CLI mode; or when
using Jest in `.jazzerjsrc.json`:

Expand Down Expand Up @@ -98,17 +122,58 @@ using Jest in `.jazzerjsrc.json`:
{ "disableBugDetectors": ["prototype-pollution"] }
```

## Remote Code Execution
## Code Injection

Installs a canary on `globalThis` and hooks the `eval` and `Function` functions.
The before-hooks guide the fuzzer toward injecting the active canary identifier
into code strings. The detector reports two fatal stages by default:

Hooks the `eval` and `Function` functions and reports a finding if the fuzzer
was able to pass a special string to `eval` and to the function body of
`Function`.
- `Potential Code Injection (Canary Accessed)` - some code resolved the canary.
This high-recall heuristic catches cases where dynamically produced code reads
or stores the canary before executing it later.
- `Confirmed Code Injection (Canary Invoked)` - the callable canary returned by
the getter was invoked.

_Disable with:_ `--disableBugDetectors=remote-code-execution` in CLI mode; or
when using Jest in `.jazzerjsrc.json`:
The detector can be configured in the
[custom hooks](./fuzz-settings.md#customhooks--arraystring) file.

- `disableAccessReporting` - disables the stage-1 access finding while keeping
invocation reporting active.
- `disableInvocationReporting` - disables the stage-2 invocation finding.
- `ignoreAccess(rule)` - suppresses stage-1 findings matching the shown stack
excerpt.
- `ignoreInvocation(rule)` - suppresses stage-2 findings matching the shown
stack excerpt.
- `stackPattern` accepts either a string or a `RegExp` and is matched against
the shown stack excerpt after removing the leading `Error` line and Jazzer.js
frames. The remaining stack text is matched as shown, including path
separators and column numbers.

The detector must be able to install a canary on at least one active global
object. Locked-down environments that forbid this should disable the detector
explicitly.

Here is an example configuration in the
[custom hooks](./fuzz-settings.md#customhooks--arraystring) file:

```javascript
const { getBugDetectorConfiguration } = require("@jazzer.js/bug-detectors");

getBugDetectorConfiguration("code-injection")
?.ignoreAccess({
stackPattern: "handlebars/runtime.js:87",
})
?.disableInvocationReporting();
```

Findings print a generic example suppression snippet. Copy/paste it and adapt
`stackPattern` to a stable substring or `RegExp` from the shown stack.

_Disable with:_ `--disableBugDetectors=code-injection` in CLI mode; or when
using Jest in `.jazzerjsrc.json`:

```json
{ "disableBugDetectors": ["remote-code-execution"] }
{ "disableBugDetectors": ["code-injection"] }
```

## Server-Side Request Forgery (SSRF)
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ module.exports = {
"^.+\\.tsx?$": [
"ts-jest",
{
tsconfig: "<rootDir>/tsconfig.jest.json",
// ts-jest does not support composite project references.
// It compiles workspace .ts sources in one flat program,
// which breaks cross-package type resolution. Disabling
Expand Down
258 changes: 258 additions & 0 deletions packages/bug-detectors/internal/code-injection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
/*
* Copyright 2026 Code Intelligence GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Context } from "vm";

import {
getJazzerJsGlobal,
guideTowardsContainment,
registerAfterEachCallback,
reportAndThrowFinding,
reportFinding,
} from "@jazzer.js/core";
import { registerBeforeHook } from "@jazzer.js/hooking";

import { bugDetectorConfigurations } from "../configuration";
import { ensureCanary } from "../shared/code-injection-canary";
import {
buildGenericSuppressionSnippet,
captureStack,
getUserFacingStackLines,
IgnoreList,
type IgnoreRule,
} from "../shared/finding-suppression";

export type { IgnoreRule } from "../shared/finding-suppression";

type PendingAccess = {
canaryName: string;
stack: string;
invoked: boolean;
};

/**
* Configuration for the Code Injection bug detector.
* Controls the reporting and suppression of dynamic code evaluation findings.
*/
export interface CodeInjectionConfig {
/**
* Disables Stage 1 (Access) reporting entirely.
* The detector will no longer report when the canary is merely read.
*/
disableAccessReporting(): this;
/**
* Disables Stage 2 (Invocation) reporting entirely.
* The detector will no longer report when the canary is actually executed.
*/
disableInvocationReporting(): this;
/**
* Suppresses Stage 1 (Access) findings that match the provided rule.
* Use this to silence safe heuristic reads such as template lookups.
*/
ignoreAccess(rule: IgnoreRule): this;
/**
* Suppresses Stage 2 (Invocation) findings that match the provided rule.
* Use this only for known-safe execution sinks in test environments.
*/
ignoreInvocation(rule: IgnoreRule): this;
}

class CodeInjectionConfigImpl implements CodeInjectionConfig {
private _reportAccess = true;
private _reportInvocation = true;
private readonly _ignoredAccessRules = new IgnoreList();
private readonly _ignoredInvocationRules = new IgnoreList();

disableAccessReporting(): this {
this._reportAccess = false;
return this;
}

disableInvocationReporting(): this {
this._reportInvocation = false;
return this;
}

ignoreAccess(rule: IgnoreRule): this {
this._ignoredAccessRules.add(rule);
return this;
}

ignoreInvocation(rule: IgnoreRule): this {
this._ignoredInvocationRules.add(rule);
return this;
}

shouldReportAccess(stack: string): boolean {
return this._reportAccess && !this._ignoredAccessRules.matches(stack);
}

shouldReportInvocation(stack: string): boolean {
return (
this._reportInvocation && !this._ignoredInvocationRules.matches(stack)
);
}
}

const config = new CodeInjectionConfigImpl();
bugDetectorConfigurations.set("code-injection", config);

const canaryCache = new WeakMap<object, string>();
const pendingAccesses: PendingAccess[] = [];

ensureActiveCanary();
registerAfterEachCallback(flushPendingAccesses);

registerBeforeHook(
"eval",
"",
false,
function beforeEvalHook(
_thisPtr: unknown,
params: unknown[],
hookId: number,
) {
const canaryName = ensureActiveCanary();

const code = params[0];
if (typeof code === "string") {
guideTowardsContainment(code, canaryName, hookId);
}
},
);

registerBeforeHook(
"Function",
"",
false,
function beforeFunctionHook(
_thisPtr: unknown,
params: unknown[],
hookId: number,
) {
const canaryName = ensureActiveCanary();
if (params.length === 0) return;

const functionBody = params[params.length - 1];
if (functionBody == null) return;

let functionBodySource: string;
try {
functionBodySource = String(functionBody);
} catch {
return;
}
// The hook has already performed Function's body coercion; reuse it so
// user-provided toString methods are not invoked a second time.
params[params.length - 1] = functionBodySource;

guideTowardsContainment(functionBodySource, canaryName, hookId);
},
);

function getVmContext(): Context | undefined {
return getJazzerJsGlobal<Context>("vmContext");
}

function ensureActiveCanary(): string {
return ensureCanary(
[
{ label: "vmContext", object: getVmContext() },
{ label: "globalThis", object: globalThis },
],
canaryCache,
createCanaryDescriptor,
);
}

function createCanaryDescriptor(canaryName: string): PropertyDescriptor {
return {
get() {
const accessStack = captureStack();
const pendingAccess = config.shouldReportAccess(accessStack)
? {
canaryName,
stack: accessStack,
invoked: false,
}
: undefined;
if (pendingAccess) {
pendingAccesses.push(pendingAccess);
}

return function canaryCall() {
const invocationStack = captureStack();
if (config.shouldReportInvocation(invocationStack)) {
if (pendingAccess) {
pendingAccess.invoked = true;
}
reportAndThrowFinding(
buildFindingMessage(
"Confirmed Code Injection (Canary Invoked)",
`invoked canary: ${canaryName}`,
invocationStack,
"ignoreInvocation",
"If this execution sink is expected in your test environment, suppress it:",
),
false,
);
}
};
},
enumerable: false,
configurable: false,
};
}

function flushPendingAccesses(): void {
for (const pendingAccess of pendingAccesses.splice(0)) {
if (pendingAccess.invoked) {
continue;
}
reportFinding(
buildFindingMessage(
"Potential Code Injection (Canary Accessed)",
`accessed canary: ${pendingAccess.canaryName}`,
pendingAccess.stack,
"ignoreAccess",
"If this is a safe heuristic read, suppress it to continue fuzzing for code execution. Add this to your custom hooks:",
),
false,
);
}
}

function buildFindingMessage(
title: string,
action: string,
stack: string,
suppressionMethod: "ignoreAccess" | "ignoreInvocation",
hint: string,
): string {
const relevantStackLines = getUserFacingStackLines(stack);
const message = [`${title} -- ${action}`];
if (relevantStackLines.length > 0) {
message.push(...relevantStackLines);
}
message.push(
"",
`[!] ${hint}`,
" Example only: copy/paste it and adapt `stackPattern` to your needs.",
"",
buildGenericSuppressionSnippet("code-injection", suppressionMethod),
);
return message.join("\n");
}
Loading
Loading