flawopen.com/command-injection/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.
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.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthAplikasi menerima input nama host diagnostik atau nama file langsung dari permintaan HTTP.
Backend merangkai perintah shell menggunakan penggabungan string mentah alih-alih vektor argumen terisolasi.
Penyerang menyisipkan karakter meta shell seperti ';', '&&', '|', atau backticks (misal: '127.0.0.1; id') untuk keluar dari konteks perintah.
Shell sistem operasi menjalankan perintah yang disuntikkan dengan hak akses penuh proses web server.
# 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)
# 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)
shell=False (the default in subprocess).os.system() and os.popen().