import subprocess
from flask import request
@app.route('/execute')
def execute_command():
# Vulnerable: User input directly in shell command
cmd = request.args.get('cmd')
result = subprocess.call(f'ls {cmd}', shell=True)
return f'Command executed: {result}'
@app.route('/ping')
def ping_host():
# Vulnerable: Command injection through hostname
host = request.args.get('host')
command = f'ping -c 1 {host}'
output = subprocess.check_output(command, shell=True)
return output.decode()
@app.route('/backup')
def backup_file():
# Vulnerable: File path not validated
filename = request.args.get('file')
subprocess.run(['tar', '-czf', '/tmp/backup.tar.gz', filename])
return 'Backup created'
# Vulnerable: Direct user input to subprocess
def run_user_script(script_name):
return subprocess.run(f'python {script_name}', shell=True)
import subprocess
import shlex
import os
from flask import request
# Safe command allowlist
ALLOWED_COMMANDS = ['ls', 'pwd', 'date']
ALLOWED_PING_HOSTS = ['google.com', 'github.com']
@app.route('/execute')
def execute_command():
# Secure: Validate against allowlist
cmd = request.args.get('cmd')
if cmd not in ALLOWED_COMMANDS:
return 'Command not allowed', 400
# Secure: Use argument list, no shell
try:
result = subprocess.run([cmd], capture_output=True, text=True, timeout=5)
return f'Output: {result.stdout}'
except subprocess.TimeoutExpired:
return 'Command timeout', 408
@app.route('/ping')
def ping_host():
# Secure: Validate against allowlist
host = request.args.get('host')
if host not in ALLOWED_PING_HOSTS:
return 'Host not allowed', 400
# Secure: Use argument list with validated input
try:
result = subprocess.run(
['ping', '-c', '1', host],
capture_output=True,
text=True,
timeout=10
)
return result.stdout
except subprocess.TimeoutExpired:
return 'Ping timeout', 408
@app.route('/backup')
def backup_file():
# Secure: Validate file path
filename = request.args.get('file')
# Validate filename
if not filename or '..' in filename or filename.startswith('/'):
return 'Invalid filename', 400
# Ensure file exists and is in allowed directory
safe_path = os.path.join('/var/www/uploads', filename)
if not os.path.exists(safe_path):
return 'File not found', 404
# Secure: Use argument list with validated paths
try:
subprocess.run([
'tar', '-czf', '/tmp/backup.tar.gz', safe_path
], timeout=30, check=True)
return 'Backup created'
except subprocess.CalledProcessError:
return 'Backup failed', 500
# Secure: Properly validate and execute scripts
def run_user_script(script_name):
# Validate script name
if not script_name.endswith('.py') or '..' in script_name:
raise ValueError('Invalid script name')
script_path = os.path.join('/var/scripts', script_name)
if not os.path.exists(script_path):
raise FileNotFoundError('Script not found')
# Secure execution with timeout
return subprocess.run(
['python3', script_path],
capture_output=True,
text=True,
timeout=30
)