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.
Imagina pedirle a un asistente de oficina que imprima un documento llamado 'informe.pdf'. La inyección de comandos ocurre cuando alguien entrega el nombre 'informe.pdf; whoami', y el asistente entrega toda la nota al empleado del terminal, imprimiendo el informe y leyendo la credencial del administrador.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthLa aplicación acepta nombres de host de diagnóstico, nombres de archivo o parámetros directamente desde una solicitud HTTP.
El backend construye la cadena de comando shell concatenando texto directamente en lugar de usar un vector de argumentos seguro.
El atacante inyecta metacaracteres de shell como ';', '&&', '|' o comillas invertidas (ej. '127.0.0.1; id') para escapar del comando esperado.
El shell del sistema operativo ejecuta la instrucción inyectada con todos los permisos del proceso del servidor 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().