--- title: detect-eval-with-expression description: Detects eval(variable) which can allow an attacker to run arbitrary code inside your process tags: ['security', 'node'] category: security severity: critical cwe: CWE-95 owasp: 'A03:2021' autofix: false --- > **Keywords:** eval, code injection, CWE-95, security, ESLint rule, remote code execution, RCE, arbitrary code execution, Function constructor, auto-fix, LLM-optimized, code security > **CWE:** [CWE-95](https://cwe.mitre.org/data/definitions/95.html) > **OWASP Mobile:** [OWASP Mobile Top 10](https://owasp.org/www-project-mobile-top-10/) Detects eval(variable) which can allow an attacker to run arbitrary code inside your process Detects `eval(variable)` which can allow an attacker to run arbitrary code inside your process. This rule is part of [`eslint-plugin-node-security`](https://www.npmjs.com/package/eslint-plugin-node-security) and provides LLM-optimized error messages with fix suggestions. **🚨 Security rule** | **πŸ’‘ Provides LLM-optimized guidance** | **⚠️ Set to error in `recommended`** ## Quick Summary | Aspect | Details | | ----------------- | ------------------------------------------------------------------------- | | **CWE Reference** | [CWE-95](https://cwe.mitre.org/data/definitions/95.html) (Code Injection) | | **Severity** | Critical (security vulnerability) | | **Auto-Fix** | ⚠️ Suggests fixes (manual application) | | **Category** | Security | | **ESLint MCP** | βœ… Optimized for ESLint MCP integration | | **Best For** | All applications, especially those handling user input | ## Value & investment case > Why this rule pays for itself. Framework: [`cicd-impact/philosophy.md`](../../../../cicd-impact/philosophy.md). | Dimension | Value | | :--------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **CWE** | [CWE-95](https://cwe.mitre.org/data/definitions/95.html) β€” Improper Neutralization of Directives in Dynamically Evaluated Code (eval injection) | | **Feedback-loop tier** | Editor / pre-commit (sub-second) β€” cheapest layer per the [feedback-loop hierarchy](../../../../cicd-impact/philosophy.md#the-feedback-loop-hierarchy--why-a-high-end-static-analyzer-is-the-highest-leverage-investment) | | **Defensive-layer leverage** | ~10Γ— cheaper than unit-test Β· ~1,000Γ— cheaper than production rollback Β· **10,000+Γ— cheaper than disclosure** β€” `eval`-injection is a Remote Code Execution class ([cost-ratio anchors](../../../../cicd-impact/philosophy.md#deliverability-axis--quality-risk-and-ma-diligence)) | | **Niche relevance** | **Critical:** infra/devtools (downstream consumers of compromised tooling), fintech, cybersecurity Β· **High:** B2B SaaS, healthtech Β· **Medium:** B2C, marketplaces | | **Investor-frame impact** | Dynamic `eval` of user input β†’ RCE. Single bug class that gives an attacker full process control. The single highest-payoff rule for any codebase parsing untrusted text; lint-time catch is the cheapest possible defense against the highest-cost defect class. | **Read also:** [`philosophy.md` Β§investor-frame](../../../../cicd-impact/philosophy.md#the-investor-frame--engineering-efficiency-as-a-portfolio-metric) Β· [`niche-presets.json`](../../../../cicd-impact/data/niche-presets.json) Β· [`analyzer-evaluation-framework.md`](../../../../cicd-impact/analyzer-evaluation-framework.md) ## Vulnerability and Risk **Vulnerability:** The use of `eval()` or similar functions (like `setTimeout`, `setInterval`, `new Function`) with dynamic arguments allows for the execution of arbitrary code derived from strings. **Risk:** If the string passed to `eval()` contains user-controlled input, an attacker can execute malicious JavaScript code within the context of the application. This can lead to data theft, session hijacking, or server-side remote code execution (RCE). > `new Function('s', 'return import(s)')` is not reported: the idiom that keeps a build from turning `import()` into `require()`. One parameter, and a body that is exactly `return import()`. ## Rule Details This rule detects dangerous use of `eval()` and `Function()` constructor with dynamic expressions that can lead to remote code execution (RCE) vulnerabilities. ```mermaid %%{init: { 'theme': 'base', 'themeVariables': { 'primaryColor': '#f8fafc', 'primaryTextColor': '#1e293b', 'primaryBorderColor': '#334155', 'lineColor': '#475569', 'c0': '#f8fafc', 'c1': '#f1f5f9', 'c2': '#e2e8f0', 'c3': '#cbd5e1' } }}%% flowchart TD A["πŸ“ Detect eval() Call"] --> B{Contains Dynamic Expression?} B -->|Yes| C[πŸ” Analyze Pattern] B -->|No| D[βœ… Safe - Skip] C --> E{Recognized Pattern?} E -->|JSON| F[πŸ’‘ Suggest JSON.parse] E -->|Math| G[πŸ’‘ Suggest Math functions] E -->|Template| H[πŸ’‘ Suggest Template literals] E -->|Object| I[πŸ’‘ Suggest Map/Object validation] E -->|Unknown| J[πŸ’‘ Suggest removal] F --> K[🚨 Report with LLM guidance] G --> K H --> K I --> K J --> K ``` ## Error Message Format The rule provides **LLM-optimized error messages** (Compact 2-line format) with actionable security guidance: ```text πŸ”’ CWE-95 OWASP:A05 CVSS:9.8 | Eval Injection detected | CRITICAL [SOC2,PCI-DSS,ISO27001] Fix: Review and apply the recommended fix | https://owasp.org/Top10/A05_2021/ ``` ### Message Components | Component | Purpose | Example | | :------------------------ | :--------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Risk Standards** | Security benchmarks | [CWE-95](https://cwe.mitre.org/data/definitions/95.html) [OWASP:A05](https://owasp.org/Top10/A05_2021-Injection/) [CVSS:9.8](https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator?vector=AV%3AN%2FAC%3AL%2FPR%3AN%2FUI%3AN%2FS%3AU%2FC%3AH%2FI%3AH%2FA%3AH) | | **Issue Description** | Specific vulnerability | `Eval Injection detected` | | **Severity & Compliance** | Impact assessment | `CRITICAL [SOC2,PCI-DSS,ISO27001]` | | **Fix Instruction** | Actionable remediation | `Follow the remediation steps below` | | **Technical Truth** | Official reference | [OWASP Top 10](https://owasp.org/Top10/A05_2021-Injection/) | ## Configuration | Option | Type | Default | Description | | ------------------------- | ---------- | ------- | -------------------------------------------------------------- | | `allowLiteralStrings` | `boolean` | `false` | Allow every eval-like sink with a program the author wrote out | | `additionalEvalFunctions` | `string[]` | `[]` | Additional functions to treat as eval-like | `eval('…')` with a string literal is never reported: there is nothing dynamic in it to inject. With the default `allowLiteralStrings: false`, every _other_ author-written program is still reported β€” `new Function('price', 'total = price * 2')`, a string `setTimeout('…')`, and `eval(SCRIPT)` through a constant. `allowLiteralStrings: true` exempts all of them: a literal argument, or one hop of single-write constant (`const SCRIPT = '…'; eval(SCRIPT)`), for every eval-like sink, `new Function` included. ## Examples ### ❌ Incorrect ```typescript // Dynamic eval - CRITICAL risk const result = eval(userInput); // Function constructor - HIGH risk const func = new Function('param', userCode); // Template evaluation - HIGH risk const output = eval(`Hello ${userName}!`); // Object property access - MEDIUM risk const value = eval(`obj.${property}`); // Math operations - MEDIUM risk const calc = eval(`${num1} ${operator} ${num2}`); ``` ### βœ… Correct ```typescript // JSON parsing const data = JSON.parse(userInput); // Template literals (safe) const greeting = `Hello ${userName}!`; // Whitelisted object access const ALLOWED_PROPS = ['name', 'age', 'email']; if (ALLOWED_PROPS.includes(property)) { const value = obj[property]; } // Math with validation const result = calculate(num1, operator, num2); // Map for dynamic storage const config = new Map(); config.set(userKey, value); ``` ## Pattern Recognition The rule automatically detects common eval patterns and provides targeted fixes: ### JSON Parsing Pattern ``` ❌ eval('{"key": "' + value + '"}') βœ… JSON.parse('{"key": "' + value + '"}') ``` ### Object Access Pattern ``` ❌ eval('obj.' + property) βœ… const ALLOWED = ['name', 'age']; if (ALLOWED.includes(property)) obj[property] ``` ### Template Pattern ``` ❌ eval('Hello ' + name + '!') βœ… `Hello ${name}!` ``` ### Math Operations Pattern ``` ❌ eval(num1 + ' + ' + num2) βœ… const mathOps = { '+': (a, b) => a + b }; mathOps[op](num1, num2) ``` ## Security Impact | Vulnerability | CWE | OWASP | CVSS | Impact | | ------------------- | --- | -------- | ------------ | -------------------------- | | Code Injection | 95 | A03:2021 | 9.8 Critical | Complete server compromise | | Command Injection | 78 | A03:2021 | 9.8 Critical | System command execution | | Prototype Pollution | 915 | A01:2021 | 8.1 High | Object manipulation | ### Why This Matters | Issue | Impact | Solution | | ---------------------- | ----------------------------------- | ------------------------------------------------------------ | | πŸš€ **Remote Code Ex.** | Full server/client takeover | Remove `eval()` entirely; use `JSON.parse` or object logic | | πŸ•΅οΈ **Data Injection** | Manipulated business logic | Validate input against a strict whitelist of allowed values | | πŸ”’ **Compliance** | Failure to prevent script injection | Implement Content Security Policy (CSP) and static templates | ## Migration Guide ### Phase 1: Discovery ```javascript // Enable rule with warnings first { rules: { 'node-security/detect-eval-with-expression': 'warn' } } ``` ### Phase 2: Pattern Replacement ```javascript // Replace common patterns eval(`obj.${prop}`) β†’ obj[prop] with validation eval(jsonString) β†’ JSON.parse(jsonString) eval(mathExpr) β†’ Safe math functions ``` ### Phase 3: Enforcement ```javascript // Strict enforcement { rules: { 'node-security/detect-eval-with-expression': 'error' } } ``` ## Comparison with Alternatives | Feature | detect-eval-with-expression | eslint-plugin-security | eslint-plugin-sonarjs | | ---------------------------- | --------------------------- | ---------------------- | --------------------- | | **Code Injection Detection** | βœ… Yes | ⚠️ Limited | ⚠️ Limited | | **CWE Reference** | βœ… CWE-95 included | ⚠️ Limited | ⚠️ Limited | | **LLM-Optimized** | βœ… Yes | ❌ No | ❌ No | | **ESLint MCP** | βœ… Optimized | ❌ No | ❌ No | | **Fix Suggestions** | βœ… Detailed | ⚠️ Basic | ⚠️ Basic | ## The `vm` and `vm2` sinks (CWE-94) `eval` is not the only way a string becomes running code. The same rule covers the module sinks that do it β€” they are grouped here rather than split into their own rule because the defect, the question you have to answer, and the fix are identical. ### `vm` is not a sandbox ```javascript const vm = require('vm'); const value = vm.runInNewContext(req.query.expr, { Math }); // ❌ vmCodeExecution ``` The context object makes this _look_ contained, and Node's own documentation says plainly that the module is not a security mechanism. Every object handed into the context carries its own constructor chain, and `this.constructor.constructor('return process')()` is the one-liner that walks back out to the host. All four entry points take the source at argument 0 and are covered: `runInNewContext`, `runInThisContext`, `runInContext`, `compileFunction` β€” plus `new vm.Script(...)` and `new vm.SourceTextModule(...)`, which compile now and run later. ### `vm2` is abandoned ```javascript const { NodeVM } = require('vm2'); const sandbox = new NodeVM({ console: 'inherit' }); const result = sandbox.run(req.body.code, 'plugin.js'); // ❌ vm2CodeExecution ``` vm2 was retired by its maintainer after sandbox escapes it could not fix (CVE-2023-37903, CVE-2023-37466). Running caller-supplied source in it is arbitrary code execution on the host. `VM`/`NodeVM` instances (`.run()`) and `new VMScript(...)` are covered; the classes are only recognised when they are actually bound to the `vm2` module, so an unrelated local class named `VM` is not a finding. ### What stays silent A program the author wrote out is not a finding, including one hop of constant resolution: ```javascript const vm = require('vm'); const SCRIPT = 'total = price * quantity * (1 - discount)'; // βœ… not reported vm.runInNewContext( SCRIPT, { price, quantity, discount, total: 0 }, { timeout: 50 }, ); ``` The single-write requirement is load-bearing. A binding assigned more than once could hold anything by the time the call runs, so proving its initializer constant proves nothing β€” those report. ## Related Rules - [`detect-child-process`](./detect-child-process.md) - Prevents command injection - [`detect-non-literal-fs-filename`](./detect-non-literal-fs-filename.md) - Prevents path traversal - [`detect-object-injection`](./detect-object-injection.md) - Prevents prototype pollution - [`detect-non-literal-regexp`](./detect-non-literal-regexp.md) - Prevents ReDoS attacks ## Known False Negatives The following patterns are **not detected** due to static analysis limitations: ### Aliased Functions **Why**: `const` aliases are followed to any depth (`const execute = eval; const run = execute; run(userInput)` is reported, and a cycle of aliases stops), but a reassignable binding has no single value to follow. ```typescript // ❌ NOT DETECTED - a `let` alias let execute = eval; execute(userInput); ``` **Mitigation**: Never alias dangerous functions. The vm sinks are bound by export name however the import spells it: `const { 'runInNewContext': run } = require('vm')`, a constant computed key, and an ES2022 string export name (`import { 'runInNewContext' as run } from 'vm'`) are all `vm.runInNewContext`. ### Dynamic Invocation **Why**: Dynamic method calls not analyzed. ```typescript // ❌ NOT DETECTED - Dynamic call window['eval'](userInput); ``` **Mitigation**: Avoid dynamic method access. ### Wrapper Functions **Why**: Wrappers not recognized. ```typescript // ❌ NOT DETECTED - Wrapper myEval(userInput); // Uses eval internally ``` **Mitigation**: Apply rule to wrapper implementations. ### The vm Module Bound Through A Wrapper **Why**: the `vm` / `vm2` sinks are resolved through the file's own import and require bindings. A sink reached through a re-export or a helper module is a different file's problem. ```typescript // ❌ NOT DETECTED β€” the binding is not traced across files const { runScript } = require('./sandbox-helper'); runScript(req.body.code); ``` **Mitigation**: apply the rule to the helper implementation too. ## Further Reading - **[OWASP Code Injection Prevention](https://owasp.org/www-community/attacks/Code_Injection)** - Code injection attack guide - **[Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/)** - Node.js security guidelines - **[CWE-95: Code Injection](https://cwe.mitre.org/data/definitions/95.html)** - Official CWE entry - **[ESLint MCP Setup](https://eslint.org/docs/latest/use/mcp)** - Enable AI assistant integration ## βš™οΈ Options | Option | Type | Default | Description | | ------------------------- | ------------------------------------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `allowLiteralStrings` | `boolean` | `false` | Allow every eval-like sink, `new Function` included, with a literal or single-write-constant program. `eval('literal')` is silent either way (false = stricter) | | `additionalEvalFunctions` | `string[]` | `[]` | Additional functions to treat as eval-like | | `strategy` | `"remove"` \| `"refactor"` \| `"validate"` \| `"auto"` | `"auto"` | Strategy for fixing eval usage (auto = smart detection) |