OS Command Injection

ID

javascript.command_injection

Severity

critical

Resource

Injection

Language

JavaScript

Tags

CWE:77, CWE:78, NIST.SP.800-53, OWASP:2021:A3, PCI-DSS:6.5.1

Description

Improper neutralization of special elements used in a command ('Command Injection').

Command injection vulnerabilities occur when an application passes untrusted input to a system shell command without proper validation or sanitization.

Such vulnerabilities allow attackers to execute arbitrary shell commands with the privileges of the user running the application, which may result in complete system compromise.

Attackers exploiting the vulnerability can then install a reverse shell, download and install malware or ransomware, cryptocurrency miners, run database clients for data exfiltration, etc.

Understanding and mitigating this risk is crucial, as it can facilitate data breaches, unauthorized data manipulation, or any type of attack that could be crafted via system commands.

Rationale

With Node, the child_process.exec() is a dangerous function that can be used to execute arbitrary shell commands.

var port = process.argv[2];

var childProc = require('child_process');

// VULNERABLE to OS command injection
childProc.exec('netstat -an | grep LISTENING | grep :' + port,
  function (error, stdout, stderr) { console.log(stdout); }
);

In this example, the attacker can inject additional, unexpected commands into the second argument of the command that supposedly should be an integer, into the port variable, which is blindly concatenated with netstat -an | grep LISTENING | grep : and executed as a shell command. Attackers controlling the input will wreak havoc using something like 123 ; evil_command.

child_process.exec() and child_process.shell() are, among many others, dangerous functions that should be avoided when possible.

Remediation

To safeguard against command injection, it is essential to adopt a series of preventive measures:

  1. Avoid Direct Command Execution with Untrusted Input: Avoid using functions for executing shell commands with untrusted inputs. Where command execution is necessary, parameterize inputs as separate command-line arguments, and do not concatenate untrusted inputs into shell commands.

  2. Input Validation and Whitelisting: Perform rigorous input validation to ensure that the input conforms to expected and safe formats. Whitelisting valid input patterns is preferable over blacklisting potentially harmful inputs.

  3. Escape Shell Metacharacters: If the input must be included in a command, ensure any shell metacharacters are properly blacklisted, escaped or sanitized using a dedicated library.

    Characters in { } ( ) < > & * ‘ | = ? ; [ ] ^ $ – # ~ ! . ” % / \ : + , \` are shell metacharacters for most OSes and shells.

    This is difficult to do well, and attackers have many ways of bypassing them so it is not recommended. You have been warned !

By implementing these practices, you can significantly minimize the potential for command injection vulnerabilities, enhancing the application’s resistance to this type of attack.

To fix the vulnerable example above, you can use the following code instead:

const { execFile } = require('child_process');

const port = process.argv[2];

// Validate port input
if (!/^\d+$/.test(port)) {
  console.error('Invalid port number');
  process.exit(1);
}

// Use execFile with fixed command and arguments
execFile('netstat', ['-an'], (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error}`);
    return;
  }

  // Filter results safely using JavaScript
  const listeningPorts = stdout
    .split('\n')
    .filter(line =>
      line.includes('LISTENING') &&
      line.includes(`:${port} `)
    );

  console.log(listeningPorts.join('\n'));
});

In this example, using child_process.spawn() or child_process.execFule() instead of child_process.exec() to run a command with will prevent the injection attack as it does not execute the command in a shell.

Configuration

The detector has the following configurable parameters:

  • sources, that indicates the source kinds to check.

  • neutralizations, that indicates the neutralization kinds to check.

Unless you need to change the default behavior, you typically do not need to configure this detector.

References