Security Best Practices
Authentication and Authorization
Implementing Secure Authentication
import secrets
import hashlib
def generate_secure_token():
return secrets.token_hex(16)
def hash_password(password):
return hashlib.sha256(password.encode()).hexdigest()
Preventing Injection Attacks
import re
def validate_input(user_input):
## Sanitize and validate input
pattern = re.compile(r'^[a-zA-Z0-9_-]+$')
if not pattern.match(user_input):
raise ValueError("Invalid input")
Network Security
graph TD
A[Network Security] --> B[HTTPS]
A --> C[Firewall]
A --> D[Rate Limiting]
A --> E[IP Whitelisting]
SSL/TLS Configuration
import ssl
def create_ssl_context():
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile='server.crt', keyfile='server.key')
return context
Security Checklist
Category |
Recommendation |
Implementation |
Authentication |
Use token-based auth |
JWT, OAuth |
Encryption |
Use HTTPS |
SSL/TLS |
Input Handling |
Validate & sanitize |
Regex, whitelist |
Access Control |
Implement least privilege |
Role-based access |
Rate Limiting and Protection
from functools import wraps
from time import time
def rate_limit(max_requests=100, window=3600):
requests = {}
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
current_time = time()
## Implement rate limiting logic
return func(*args, **kwargs)
return wrapper
return decorator
Logging and Monitoring
Secure Logging Practice
import logging
def setup_secure_logging():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='/var/log/server_security.log'
)
logger = logging.getLogger(__name__)
return logger
Key Security Principles
- Principle of Least Privilege
- Defense in Depth
- Regular Security Audits
- Keep Systems Updated
- Implement Comprehensive Logging
Advanced Protection Techniques
- Use Web Application Firewall (WAF)
- Implement CORS policies
- Regular security vulnerability scanning
- Use environment variable management
- Implement multi-factor authentication
By following these security best practices, developers can significantly reduce the risk of potential security breaches and protect their Python HTTP servers from common vulnerabilities.