Command injection

Command injection

Description

Passing user input into an OS command through APIs such as shell_exec, exec, system, passthru, or proc_open can allow command injection.

Potential impact

This may lead to arbitrary command execution, file disclosure, privilege escalation, or compromise of the service.

Remediation

Avoid shell calls where possible. If a shell call is necessary, combine allow-list validation with escapeshellarg.

Examples

Before

php
<?php
$target = $_REQUEST['ip'];
shell_exec('ping -c 4 ' . $target);

After

php
<?php
$target = $_REQUEST['ip'] ?? '';
if (filter_var($target, FILTER_VALIDATE_IP) === false) {
    http_response_code(400);
    exit;
}

shell_exec('ping -c 4 -- ' . escapeshellarg($target));

Explanation:

  • Before: Concatenating input into the shell_exec command string lets shell metacharacters such as ;, &&, or backticks introduce additional commands.
  • After: Validate the input as an IP address, use -- to end option parsing, and quote the argument with escapeshellarg. Quoting alone does not prevent a value such as -f from being interpreted as a program option.

References