Log in Join

OS Command Injection

User input reaching a shell command unescaped, letting an attacker append a second command of their own.

What it is

OS command injection happens when user input reaches a shell command unescaped, letting an attacker append their own commands to the one the application meant to run.

How it works

$output = shell_exec("ping -c 1 " . $_GET['host']);

Shell metacharacters in $_GET['host'], such as ; whoami, don't get interpreted as part of the hostname; the shell reads them as command syntax, so 8.8.8.8; whoami runs the ping and then whoami as a second, independent command.

Real-world impact

Full remote code execution as whatever user the web server runs as, one shell metacharacter away.

How to prevent it

$output = shell_exec('ping -c 1 ' . escapeshellarg($host));
// better still: validate the expected shape before it goes anywhere near a shell
$output = shell_exec('ping -c 1 ' . filter_var($host, FILTER_VALIDATE_IP));

Escape shell arguments properly, or better, avoid invoking a shell at all when a direct system call or library can do the job, and validate the input's actual expected shape before it goes anywhere near a command.

Labs in this topic

Medium

ArchiveIt tar wildcard injection

A personal backup tool. The folder name is properly escaped; the files inside it aren't.

0 solves