Fix Command Injection in FastAPI
Command Injection (CWE-78) in FastAPI is a critical remote code execution (RCE) vector. It occurs when untrusted user input flows into OS shell executors like os.system() or subprocess calls with shell=True. To mitigate, we must eliminate shell spawning and enforce strict input validation.
The Vulnerable Pattern
from fastapi import FastAPI import subprocessapp = FastAPI()
@app.get(“/ping”) def ping(host: str): # CRITICAL VULNERABILITY: shell=True with string formatting # Attacker can send: /ping?host=127.0.0.1;cat /etc/passwd cmd = f”ping -c 1 {host}” output = subprocess.check_output(cmd, shell=True) return {“output”: output.decode()}
The Secure Implementation
The vulnerability stems from the shell interpreting control characters when 'shell=True' is used. An attacker can break out of the intended command using semicolons or pipes. The fix is two-fold: First, use a list of arguments in subprocess.run() which bypasses the shell interpreter entirely, treating the input as a literal string. Second, implement strict input validation (like the ipaddress module) to ensure the data matches the expected schema before it ever reaches the system layer.
from fastapi import FastAPI, HTTPException
import subprocess
import ipaddress
app = FastAPI()
@app.get(“/ping”)
def ping(host: str):
# 1. Strict Input Validation (Type-specific)
try:
ipaddress.ip_address(host)
except ValueError:
raise HTTPException(status_code=400, detail=“Invalid IP address format”)
# 2. Use Argument Lists and shell=False (Default)
# This prevents the shell from interpreting meta-characters like ';', '&', or '|'
result = subprocess.run(
["ping", "-c", "1", host],
capture_output=True,
text=True,
check=True
)
return {"output": result.stdout}</code></pre>
Your FastAPI API
might be exposed to Command Injection
74% of FastAPI apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.