Security rules

NGB004: Dynamic code execution

Reports untrusted data reaching string-based JavaScript execution: eval(), Function() / new Function(), and setTimeout() / setInterval() with a string argument.

Property Value
Rule ID NGB004
Category Angular security & XSS
Default severity critical
CWE CWE-95
Built-in presets recommended: error, strict: error

Confidence is reported per finding (high, medium, low) and is independent of severity. See Reading findings.

What it checks

Reports untrusted data reaching string-based JavaScript execution: eval(), Function() / new Function(), and setTimeout() / setInterval() with a string argument. Constant code strings are not reported; dynamic code of unknown origin is reported with low confidence.

Why it matters

These APIs compile strings into code that runs with the full privileges of your application. Attacker-controlled input reaching them is direct script injection, regardless of Angular sanitization. They also require unsafe-eval in a Content Security Policy.

Detection behavior and supported patterns

  • eval(code), window.eval(code), globalThis.eval(code) resolved to the global eval
  • new Function(...args) and Function(...args) (every argument is traced)
  • setTimeout(code, …) / setInterval(code, …) when code is not a function
  • A local function that shadows eval is not reported (symbols are resolved, not matched by name)

Example

TypeScript
const formula = this.route.snapshot.queryParams['f'];const result = eval(formula);

Safer alternative

TypeScript
const OPS = { sum: (a: number, b: number) => a + b } as const;const op = OPS[this.route.snapshot.queryParams['op'] as keyof typeof OPS];const result = op ? op(1, 2) : undefined;

Remediation

Remove string-based code execution. Use a lookup table of functions, JSON.parse() for data, or a purpose-built expression parser that does not execute JavaScript.

False-positive considerations

  • Expressions built only from developer-controlled configuration can still be reported when that configuration is loaded at runtime (HTTP / storage).

Known limitations

  • Indirect references (const e = eval; e(x)) are not followed.
  • Execution through third-party template engines or vm-like libraries is not modeled.

References

Run it

Shell
ngbastion explain NGB004