Code Evaluation (Python)
Description
This application is vulnerable to Python code injection, a critical security flaw that occurs when user-supplied input is passed directly into Python's dynamic code evaluation functions (such as eval(), exec(), or compile()) without proper validation or sanitization. This allows attackers to inject and execute arbitrary Python code within the application's runtime environment, potentially gaining complete control over the application and underlying system.
Remediation
Eliminate the use of dynamic code evaluation functions with user input. Follow these remediation steps:
1. Remove Dynamic Evaluation: Avoid using eval(), exec(), compile(), or __import__() with any user-controlled data.
2. Use Safe Alternatives: Replace dynamic evaluation with safer approaches such as predefined function mappings, configuration-based logic, or structured data parsing.
Example - Unsafe Code:
# Vulnerable - DO NOT USE user_input = request.GET['calculation'] result = eval(user_input) # Allows arbitrary code execution
Example - Safe Alternative:
# Safe approach using ast.literal_eval for simple expressions
import ast
try:
user_input = request.GET['calculation']
# Only evaluates literals (strings, numbers, tuples, lists, dicts, booleans, None)
result = ast.literal_eval(user_input)
except (ValueError, SyntaxError):
# Handle invalid input
return error_response()
# Or use a whitelist approach for specific operations
allowed_operations = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y
}
operation = request.GET['operation']
if operation in allowed_operations:
result = allowed_operations[operation](param1, param2)3. Input Validation: If dynamic behavior is absolutely necessary, implement strict input validation using whitelists of allowed values, patterns, or operations.
4. Principle of Least Privilege: Run the application with minimal system permissions to limit the impact of potential exploitation.