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.
Imaginez demander à un assistant de bureau d'imprimer un document nommé 'rapport.pdf'. L'injection de commande se produit lorsque quelqu'un fournit le nom 'rapport.pdf; whoami', et l'assistant transmet aveuglément le billet au terminal, imprimant le rapport et lisant le badge d'administrateur.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthL'application reçoit des noms d'hôte de diagnostic ou des noms de fichiers directement à partir d'une requête HTTP.
Le backend assemble une commande shell par simple concaténation de chaînes au lieu d'utiliser un tableau d'arguments isolé.
L'attaquant injecte des métacaractères shell comme ';', '&&', '|' ou des accents graves (ex. '127.0.0.1; id') pour échapper au contexte initial.
Le shell du système d'exploitation exécute la commande injectée avec tous les privilèges du processus du serveur web.
# 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().