flawopen.com/command-injection/Python

● CWE-918 · Kritis
Riset Keamanan · FlawOpen

Command Injection in Python

Learn how to fix Command Injection (CWE-78) in Python. Side-by-side vulnerable vs secure code examples for subprocess.run(), shlex.quote(), and os.system avoidance.

💡 Penjelasan Sederhana (ELI5)

Bayangkan meminta asisten kantor untuk mencetak dokumen bernama 'laporan.pdf'. Injeksi perintah terjadi saat seseorang memberikan nama 'laporan.pdf; whoami', dan asisten menyerahkan seluruh catatan tersebut ke terminal loket, mencetak dokumen sekaligus membaca lencana administrator.

Konsep Kunci & Istilah

Web Application Security
Komponen arsitektur utama yang terpengaruh oleh CWE-918.
CWE-918
Klasifikasi standar Common Weakness Enumeration (CWE) untuk command-injection-python.
Defense-in-Depth
Verifikasi rekayasa berlapis dan isolasi batas waktu proses (runtime).

Alur Serangan Langkah demi Langkah

Step 1

Penerimaan Parameter Tidak Tepercaya

Aplikasi menerima input nama host diagnostik atau nama file langsung dari permintaan HTTP.

Step 2

Penggabungan String Shell Tidak Aman

Backend merangkai perintah shell menggunakan penggabungan string mentah alih-alih vektor argumen terisolasi.

Step 3

Injeksi Pemisah Perintah

Penyerang menyisipkan karakter meta shell seperti ';', '&&', '|', atau backticks (misal: '127.0.0.1; id') untuk keluar dari konteks perintah.

Step 4

Eksekusi Subshell & Kompromi Host

Shell sistem operasi menjalankan perintah yang disuntikkan dengan hak akses penuh proses web server.

Kode Sumber: Rentan vs Aman

✕ IMPLEMENTASI RENTAN
# shell=True spawns /bin/sh to interpret the string
import subprocess

def ping_host(host):
    # Attacker input: "8.8.8.8; cat /etc/passwd"
    cmd = f"ping -c 1 {host}"
    return subprocess.run(cmd, shell=True, capture_output=True)
✓ PERBAIKAN AMAN & KUAT
# shell=False (default): passes arguments directly to the binary
import subprocess

def ping_host(host):
    # host is treated strictly as a single argument to ping
    cmd = ["ping", "-c", "1", host]
    return subprocess.run(cmd, shell=False, capture_output=True, check=True)

Daftar Periksa Penguatan Sistem Rekayasa

References