criticalCWE-94A03:2021

eval() with User Input

Passing user-controlled data to eval(), new Function(), or similar dynamic code execution functions, enabling arbitrary code execution on your server.

How It Works

eval() executes whatever string you give it as JavaScript. If that string contains user input, the attacker controls what code runs on your server. This is Remote Code Execution (RCE) — the worst possible outcome. new Function(), setTimeout(string), and setInterval(string) have the same problem.

Vulnerable Code
// BAD: user input executed as code
export async function POST(req: Request) {
  const { formula } = await req.json();
  const result = eval(formula); // attacker sends: process.exit(1)
  return Response.json({ result });
}
Secure Code
// GOOD: use a safe expression evaluator
import { evaluate } from 'mathjs';
export async function POST(req: Request) {
  const { formula } = await req.json();
  // mathjs evaluates math only, no code execution
  const result = evaluate(formula);
  return Response.json({ result });
}

Real-World Example

A no-code tool builder let users define 'custom formulas' using a text field wired directly to eval(). A security researcher sent `require('child_process').execSync('cat /etc/passwd')` and received the server's password file in the response.

How to Prevent It

  • Never use eval(), new Function(), or setTimeout/setInterval with a string argument
  • For math expressions, use mathjs or expr-eval — they only evaluate math, not code
  • For template logic, use a sandboxed template engine like Handlebars or Nunjucks
  • If you genuinely need to run user-provided code, use a sandboxed VM (vm2 or isolated-vm)

Affected Technologies

nodejsNext.jsReact

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities