Command Injection Lab

Overview

Demonstrates how unsanitized user input in a system command can lead to arbitrary command execution.

Vulnerable Code


// vuln_cmd.php
if (isset($_GET['cmd'])) {
    $command = "ls " . $_GET['cmd'];
    system($command);
}
      

Exploit Demo

Command Injection Demo

Example URL: ?cmd=-l; cat /etc/passwd

Secure Code


// sec_cmd_escape.php (escaping)
$userInput = escapeshellcmd($_GET['cmd'] ?? '-l');
system("ls " . $userInput);

// Or sec_cmd_whitelist.php (whitelist)
$allowed = ['-l','-la','-a'];
$opt = in_array($_GET['cmd'] ?? '', $allowed) ? $_GET['cmd'] : '-l';
system("ls " . $opt);
      

Remediation & Lessons