Server-side eval injection

Server-side eval injection

Description

Passing user input to eval() can let an attacker execute unintended code. Because eval() interprets strings as JavaScript, crafted input may lead to operating-system command execution, data exposure, or service disruption.

Potential impact

  • Malicious JavaScript or system commands executed on the server
  • Exposure of internal data or environment variables
  • Application crashes or other disruption caused by malicious code

Remediation

  • Use JSON.parse() instead of eval() to process JSON data. Function also executes strings as code and is not a safe substitute.
  • Do not execute user input as code.
  • If input selects an operation, let it choose only from an allow-list of operations implemented in advance.

Examples

Before

javascript
app.get("/vuln", function (req, res) {
  const userCode = req.query.code;
  // Execute user input as code
  eval(userCode);
  res.send("Done");
});

After

javascript
app.get("/safe", function (req, res) {
  const userJson = req.query.data;
  // Parse the input only as JSON
  try {
    const parsed = JSON.parse(userJson);
    res.json(parsed);
  } catch (e) {
    res.status(400).send("Invalid input");
  }
});

Explanation:

  • Before: req.query.code is executed directly by eval(), allowing malicious JavaScript that may compromise the server or expose data.
  • After: JSON.parse() treats the input as data, removing code execution from this path. Validate the data's structure, size, and permissions separately for its intended use.

References