from flask import Flask, request
@app.route('/execute_code')
def execute_code():
# Vulnerable: exec() with user input allows arbitrary code execution
user_code = request.form.get('code')
try:
# EXTREMELY DANGEROUS: Direct code execution
exec(user_code) # Complete RCE vulnerability
return 'Code executed successfully'
except Exception as e:
return f'Execution error: {str(e)}', 400
@app.route('/dynamic_function')
def dynamic_function():
# Vulnerable: Building and executing function definitions
func_name = request.args.get('name')
func_body = request.args.get('body')
# Dangerous: Creating functions dynamically
code = f'''def {func_name}():
{func_body}
result = {func_name}()'''
local_vars = {}
exec(code, {}, local_vars) # RCE through function creation
return str(local_vars.get('result', 'No result'))
@app.route('/template_exec')
def template_exec():
# Vulnerable: Template-like execution
template = request.form.get('template')
variables = {'user': 'admin', 'role': 'user'}
# Dangerous: exec() for template processing
try:
exec(template, variables) # Can execute arbitrary code
return f'Template processed: {variables}'
except:
return 'Template error', 400
# Vulnerable: Dynamic module execution
def load_plugin(plugin_code):
namespace = {}
exec(plugin_code, namespace) # Arbitrary code execution
return namespace.get('plugin_function', lambda: None)
from flask import Flask, request
import importlib
import json
import re
from types import ModuleType
# Safe function registry
SAFE_FUNCTIONS = {
'greet': lambda name: f'Hello, {name}!' if isinstance(name, str) else 'Hello!',
'add': lambda a, b: a + b if isinstance(a, (int, float)) and isinstance(b, (int, float)) else 0,
'multiply': lambda a, b: a * b if isinstance(a, (int, float)) and isinstance(b, (int, float)) else 0,
'format_text': lambda text: text.strip().title() if isinstance(text, str) else ''
}
@app.route('/execute_code')
def execute_code():
# Secure: Use predefined safe functions instead of exec()
function_name = request.form.get('function', '')
args_json = request.form.get('args', '[]')
if function_name not in SAFE_FUNCTIONS:
return 'Function not allowed', 400
try:
args = json.loads(args_json)
if not isinstance(args, list) or len(args) > 5:
return 'Invalid arguments', 400
result = SAFE_FUNCTIONS[function_name](*args)
return f'Result: {result}'
except (json.JSONDecodeError, TypeError, ValueError) as e:
return f'Error: {str(e)}', 400
@app.route('/dynamic_function')
def dynamic_function():
# Secure: Use configuration-based approach
operation = request.args.get('operation', '')
operand1 = request.args.get('a', '0')
operand2 = request.args.get('b', '0')
# Validate operation
allowed_operations = ['add', 'subtract', 'multiply', 'divide']
if operation not in allowed_operations:
return 'Operation not allowed', 400
try:
a = float(operand1)
b = float(operand2)
# Safe operation mapping
operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y if y != 0 else 'Division by zero'
}
result = operations[operation](a, b)
return f'Result: {result}'
except ValueError:
return 'Invalid numeric input', 400
except ZeroDivisionError:
return 'Division by zero', 400
@app.route('/template_exec')
def template_exec():
# Secure: Use safe template substitution
template = request.form.get('template', '')
# Validate template format (only allow simple variable substitution)
if not re.match(r'^[a-zA-Z0-9 {}_.,-]+$', template):
return 'Invalid template format', 400
# Safe variable substitution
safe_variables = {
'user': 'admin',
'role': 'user',
'timestamp': '2024-01-01',
'version': '1.0.0'
}
try:
# Safe template formatting
result = template.format(**safe_variables)
return f'Template result: {result}'
except (KeyError, ValueError) as e:
return f'Template error: {str(e)}', 400
# Secure: Safe plugin loading using importlib
def load_safe_plugin(plugin_name):
"""Safely load plugins from a trusted directory."""
# Validate plugin name
if not re.match(r'^[a-zA-Z0-9_]+$', plugin_name):
raise ValueError('Invalid plugin name')
try:
# Safe import from trusted location
module_name = f'plugins.{plugin_name}'
module = importlib.import_module(module_name)
# Validate required interface
if not hasattr(module, 'plugin_function'):
raise AttributeError('Plugin missing required interface')
return getattr(module, 'plugin_function')
except ImportError:
raise ImportError(f'Plugin {plugin_name} not found')
@app.route('/load_plugin')
def load_plugin_endpoint():
# Secure: Controlled plugin loading
plugin_name = request.args.get('plugin', '')
# Allowlist of permitted plugins
allowed_plugins = ['math_utils', 'text_processor', 'data_validator']
if plugin_name not in allowed_plugins:
return 'Plugin not allowed', 400
try:
plugin_func = load_safe_plugin(plugin_name)
# Call plugin with safe parameters
result = plugin_func({'safe': True, 'version': '1.0'})
return f'Plugin result: {result}'
except (ImportError, AttributeError, ValueError) as e:
return f'Plugin error: {str(e)}', 400