This document outlines the comprehensive security enhancements implemented for the Python2Cpp project to address critical vulnerabilities.
- Input Size Limits: Maximum 10KB Python code input
- AST Node Limits: Maximum 1000 AST nodes to prevent resource exhaustion
- Pydantic Validation: Server-side input validation with size constraints
- Dangerous Import Detection: Basic heuristic to detect potentially unsafe imports
- File Size Validation: Maximum 50KB file size limit
- Path Validation: Comprehensive file path validation to prevent directory traversal
- Input Sanitization: Secure handling of user input and file paths
- Client-side Validation: Pre-validates input before sending to server
- File Upload Restrictions: Type and size validation for uploads
- Content Size Checking: Validates content size after file reading
- Reduced Limits: Changed from 10/minute to 3/minute for API endpoints
- Per-IP Tracking: Monitors individual IP addresses for abuse patterns
- Progressive Penalties: Implements exponential backoff with temporary bans
- Strike System: 5 strikes before temporary ban
- Ban Duration: 5-minute temporary bans for repeat offenders
- Comprehensive Logging: All security events are logged for monitoring
- Directory Traversal Protection: Validates and resolves file paths securely
- Secure Temporary Files: Uses secure temporary file creation methods
- Output Directory Validation: Ensures output files stay within safe boundaries
- Extension Checking: Only allows .py files for input
- Size Limits: Enforces file size restrictions at multiple levels
- Content Validation: Validates file content after reading
- Information Disclosure Prevention: Removes sensitive information from error messages
- Debug Mode Handling: Provides detailed errors only in debug mode
- Generic Error Messages: Uses safe, generic messages for production
- Comprehensive Logging: All security events are logged with timestamps
- IP Tracking: Logs IP addresses for security monitoring
- Structured Logging: Uses consistent format for easy parsing
- Content Security Policy: Implements strict CSP headers
- XSS Protection: Enables browser XSS protection
- Content Type Protection: Prevents MIME sniffing attacks
- Frame Options: Prevents clickjacking attacks
- Restricted Origins: Changed from wildcard "*" to specific allowed origins
- Method Restrictions: Only allows necessary HTTP methods
- Header Restrictions: Limits allowed headers for security
- Real-time Validation: Validates input as user types
- File Upload Security: Comprehensive file validation for uploads
- Drag and Drop Security: Secure handling of drag and drop operations
- Timeout Handling: 30-second timeout for API requests
- Error Sanitization: Cleans error messages before display
- User-friendly Messages: Provides clear, safe error messages
SECURITY_CONFIG = {
'MAX_INPUT_SIZE': 10 * 1024, # 10KB max Python code
'MAX_AST_NODES': 1000, # Max AST nodes
'MAX_FILE_SIZE': 50 * 1024, # 50KB max file size
'API_RATE_LIMIT': '3/minute', # API rate limit
'CONVERSION_TIMEOUT': 30, # Conversion timeout
'ALLOWED_ORIGINS': [...], # Allowed CORS origins
'CSP_HEADER': "...", # Content Security Policy
}
validate_input_size()
: Validates input size limitsvalidate_ast_complexity()
: Checks AST node count limitssanitize_filename()
: Prevents path traversal attacksvalidate_file_path()
: Comprehensive file path validationsanitize_error_message()
: Removes sensitive information from errors
- Implements timeout mechanisms for long-running operations
- Prevents resource exhaustion from infinite loops or complex operations
- Input size and complexity validation tests
- Path traversal protection tests
- Error message sanitization tests
- CLI security feature tests
- API rate limiting verification
- File upload security tests
- CORS and security header validation
All security enhancements maintain backward compatibility:
- Existing CLI usage patterns continue to work
- API responses maintain same structure (with added security)
- Configuration is additive, not replacing existing functionality
- All security violations are logged to
security.log
- Includes IP addresses, timestamps, and violation details
- Structured format for easy parsing and analysis
- Monitor
security.log
for suspicious patterns - Set up alerts for repeated violations from same IP
- Regularly review file size and complexity limits
- Monitor API response times for performance impact
- Ensure
PROD = True
in constants.py - Set up log rotation for security.log
- Configure firewall rules based on security logs
- Regularly review and update CORS allowed origins
- Input validation adds minimal overhead
- Rate limiting may affect high-volume users
- Security logging has minimal performance impact
- File size limits prevent resource exhaustion
- Integration with Web Application Firewall (WAF)
- Advanced malware scanning for uploaded files
- Machine learning-based anomaly detection
- Integration with security monitoring tools
- Advanced rate limiting with different tiers
- Regularly review security logs for new attack patterns
- Update dangerous import patterns based on threats
- Adjust rate limits based on usage patterns
- Keep security headers updated with latest recommendations