Fix Command Injection in Bottle
Command injection in Bottle occurs when untrusted user input from 'request.params' or 'request.json' is passed directly to system shells. This typically involves functions like os.system, os.popen, or subprocess.run with shell=True. To fix it, you must bypass the shell entirely and pass arguments as a list.
The Vulnerable Pattern
from bottle import route, request import os
@route(‘/check-host’) def check_host(): target = request.query.get(‘ip’) # DANGEROUS: f-string concatenation allows command chaining (e.g., ?ip=8.8.8.8;rm -rf /) response = os.popen(f’ping -c 1 {target}‘).read() return {‘output’: response}
The Secure Implementation
The exploit vector exists because the shell interprets characters like semicolon (;), pipe (|), and ampersand (&) as command separators. When using os.popen or subprocess.Popen(..., shell=True), the input is parsed by /bin/sh. The fix involves passing a list of strings to the subprocess module. This ensures that the operating system treats the user input as a literal argument to the executable, not as a command to be executed by the shell. Always avoid shell=True and implement strict input validation using regex or allow-lists for added defense-in-depth.
from bottle import route, request
import subprocess
import shlex
@route(‘/check-host’)
def check_host():
target = request.query.get(‘ip’)
if not target:
return {‘error’: ‘No IP provided’}
# SECURE: Use a list of arguments and shell=False (default)
# This prevents the shell from interpreting metacharacters like ; or &
try:
result = subprocess.run(['ping', '-c', '1', target],
capture_output=True,
text=True,
timeout=5,
check=True)
return {'output': result.stdout}
except subprocess.CalledProcessError as e:
return {'error': 'Ping failed', 'details': e.stderr}
except Exception as e:
return {'error': str(e)}</code></pre>
Your Bottle API
might be exposed to Command Injection
74% of Bottle 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.