Command injection

How to keep request data out of shell commands when running external programs in Node.js.

Description

Node.js runs child_process.spawn() and spawnSync() through a shell when you set {shell: true} or {shell: '/bin/sh'}. Passing arguments in an array still lets the shell interpret special characters as command syntax. If a request supplies part of the command or its arguments, a caller may be able to run unintended commands with the server process's permissions.

Potential impact

  • Commands can read, alter, or delete sensitive files that the server process can access.
  • Commands that consume resources or stop processes can interrupt service.

Remediation

  • Use fs.readdir to list a directory. When an external program is necessary, choose the executable in application code and pass its arguments in an array with {shell: false}.
  • Validate each argument for its intended use. Even with the shell disabled, the program can interpret input as an option or a file path.
  • If an operation requires a shell, accept a name from a fixed allow-list and map it to a command and arguments defined on the server.

Examples

Before

javascript
const { spawn } = require("child_process");
const app = require("express")();

app.get("/list", (req, res) => {
  // Request input becomes an argument interpreted by the shell.
  const userInput = req.query.path;
  const p = spawn("ls", ["-lh", userInput], { shell: true });
});

After

javascript
const { readdir } = require("node:fs/promises");
const path = require("node:path");
const app = require("express")();

const reportsDirectory = path.join(__dirname, "public", "reports");
const manualsDirectory = path.join(__dirname, "public", "manuals");

app.get("/list", async (req, res) => {
  try {
    switch (req.query.path) {
      case "reports":
        return res.json(await readdir(reportsDirectory));
      case "manuals":
        return res.json(await readdir(manualsDirectory));
      default:
        return res.sendStatus(400);
    }
  } catch {
    return res.sendStatus(500);
  }
});

Explanation:

  • Before: /list passes the request's path value to ls. With {shell: true}, the shell can interpret special characters in that value as command syntax. The handler starts the child process and never sends an HTTP response.
  • After: reports and manuals each name a directory chosen by the server. The handler reads its entries with readdir and returns their names as JSON. It returns HTTP 400 for an unknown name and HTTP 500 if it cannot read the directory.

References