Fix Command Injection in Sanic
Command injection in Sanic occurs when untrusted user input is passed directly to system shells. Because Sanic is often used for high-performance microservices, an RCE (Remote Code Execution) vulnerability here can lead to full container or host compromise. The core issue is the use of functions like os.system or subprocess.Popen with shell=True, which allows attackers to chain commands using metacharacters like ;, &, or |.
The Vulnerable Pattern
from sanic import Sanic, response import osapp = Sanic(‘VulnerableApp’)
@app.get(‘/lookup’) async def lookup(request): domain = request.args.get(‘domain’) # CRITICAL VULNERABILITY: Shell concatenation # Attacker can send: ?domain=google.com;cat /etc/passwd stream = os.popen(f’nslookup {domain}’) result = stream.read() return response.text(result)
The Secure Implementation
To fix command injection, you must break the shell's ability to interpret input as code. First, avoid os.system, os.popen, or subprocess.run(..., shell=True). Instead, pass commands as a list of arguments; this ensures the operating system treats the input as a literal string rather than a command sequence. Second, implement strict input validation using regular expressions or type-specific parsers to ensure the data conforms to expected patterns before it ever touches a sub-process.
from sanic import Sanic, response
import subprocess
import re
app = Sanic(‘SecureApp’)
@app.get(‘/lookup’)
async def lookup(request):
domain = request.args.get(‘domain’)
# 1. Strict Input Validation (Allow-list approach)
if not domain or not re.match(r'^[a-zA-Z0-9.-]+$', domain):
return response.text('Invalid domain format', status=400)
# 2. Use subprocess with argument lists and shell=False
# This prevents the shell from interpreting metacharacters
try:
process = subprocess.run(
['nslookup', domain],
capture_output=True,
text=True,
check=True,
timeout=5
)
return response.text(process.stdout)
except subprocess.CalledProcessError as e:
return response.text(f'Lookup failed: {e.stderr}', status=500)</code></pre>
Your Sanic API
might be exposed to Command Injection
74% of Sanic 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.