Rustelo/book/configuration/security.md

605 lines
13 KiB
Markdown
Raw Normal View History

# Security Configuration
Rustelo provides comprehensive security features to protect your application and user data. This chapter covers how to configure authentication, authorization, encryption, and other security measures to ensure your application meets security best practices.
## Overview
Rustelo's security system includes:
- **Authentication**: User identity verification and session management
- **Authorization**: Role-based access control (RBAC) and permissions
- **Encryption**: Data protection at rest and in transit
- **Input Validation**: Protection against injection attacks
- **Security Headers**: HTTP security headers and CSP
- **Rate Limiting**: Protection against abuse and DoS attacks
- **Audit Logging**: Security event tracking and monitoring
## Authentication Configuration
### Basic Authentication Settings
```toml
[auth]
enabled = true
require_authentication = true
default_session_timeout = 1800 # 30 minutes
max_session_duration = 28800 # 8 hours
session_cleanup_interval = 300 # 5 minutes
[auth.password]
min_length = 12
max_length = 128
require_uppercase = true
require_lowercase = true
require_numbers = true
require_special_chars = true
forbidden_passwords = [
"password", "123456", "admin", "root"
]
password_history_count = 5
password_expiry_days = 90
```
### JWT Configuration
```toml
[auth.jwt]
secret = "${JWT_SECRET}"
algorithm = "HS256"
issuer = "rustelo-app"
audience = ["rustelo-users"]
access_token_expiry = 900 # 15 minutes
refresh_token_expiry = 86400 # 24 hours
require_exp = true
require_iat = true
require_nbf = true
clock_skew = 60 # Allow 60 seconds clock skew
```
### Session Management
```toml
[auth.sessions]
cookie_name = "rustelo_session"
cookie_secure = true # HTTPS only
cookie_http_only = true # No JavaScript access
cookie_same_site = "Strict"
cookie_path = "/"
cookie_domain = "" # Current domain only
session_regeneration = true # Regenerate session ID on login
concurrent_sessions = 3 # Max concurrent sessions per user
```
### Account Security
```toml
[auth.security]
max_login_attempts = 5
lockout_duration = 900 # 15 minutes
progressive_lockout = true # Increase lockout time on repeated failures
require_email_verification = true
email_verification_expiry = 86400 # 24 hours
password_reset_expiry = 3600 # 1 hour
```
## Two-Factor Authentication
### TOTP Configuration
```toml
[auth.two_factor]
enabled = true
required_for_admin = true
backup_codes_count = 10
backup_codes_length = 8
[auth.two_factor.totp]
issuer = "Rustelo App"
algorithm = "SHA1"
digits = 6
period = 30
window = 1 # Allow 1 step before/after current time
```
### SMS Configuration
```toml
[auth.two_factor.sms]
enabled = false
provider = "twilio" # twilio, aws_sns
verification_code_length = 6
verification_code_expiry = 300 # 5 minutes
rate_limit = 5 # Max 5 SMS per hour per user
[auth.two_factor.sms.twilio]
account_sid = "${TWILIO_ACCOUNT_SID}"
auth_token = "${TWILIO_AUTH_TOKEN}"
from_number = "${TWILIO_FROM_NUMBER}"
```
## Authorization & RBAC
### Role-Based Access Control
```toml
[rbac]
enabled = true
default_role = "user"
admin_role = "admin"
super_admin_role = "super_admin"
guest_role = "guest"
[rbac.permissions]
hierarchical = true # Roles inherit permissions from parent roles
cache_enabled = true
cache_ttl = 300 # 5 minutes
audit_enabled = true
[rbac.roles]
user = {
permissions = ["read_own_profile", "update_own_profile"],
inherits_from = ["guest"]
}
moderator = {
permissions = ["moderate_content", "view_reports"],
inherits_from = ["user"]
}
admin = {
permissions = ["manage_users", "manage_content", "view_logs"],
inherits_from = ["moderator"]
}
super_admin = {
permissions = ["*"],
inherits_from = []
}
```
### Resource-Based Permissions
```toml
[rbac.resources]
users = ["create", "read", "update", "delete"]
content = ["create", "read", "update", "delete", "publish"]
reports = ["create", "read", "update", "delete", "resolve"]
logs = ["read", "export"]
settings = ["read", "update"]
```
## Encryption Configuration
### Data Encryption
```toml
[encryption]
enabled = true
algorithm = "AES-256-GCM"
key_derivation = "PBKDF2"
key_derivation_iterations = 100000
salt_length = 32
[encryption.at_rest]
enabled = true
encrypt_sensitive_fields = true
sensitive_fields = [
"password", "email", "phone", "ssn", "credit_card"
]
[encryption.in_transit]
min_tls_version = "1.2"
cipher_suites = [
"TLS_AES_256_GCM_SHA384",
"TLS_CHACHA20_POLY1305_SHA256",
"TLS_AES_128_GCM_SHA256"
]
```
### Key Management
```toml
[encryption.keys]
rotation_enabled = true
rotation_interval = 2592000 # 30 days
key_backup_enabled = true
key_backup_location = "${KEY_BACKUP_PATH}"
master_key = "${MASTER_ENCRYPTION_KEY}"
```
## Input Validation & Sanitization
### General Validation
```toml
[security.validation]
enabled = true
strict_mode = true
max_request_size = 10485760 # 10MB
max_field_length = 1000
max_array_length = 100
max_nesting_depth = 10
[security.validation.email]
allow_plus_addressing = true
allow_internationalized = true
require_verification = true
blocked_domains = ["tempmail.com", "10minutemail.com"]
```
### SQL Injection Prevention
```toml
[security.sql_injection]
use_prepared_statements = true
validate_input_types = true
escape_special_characters = true
log_suspicious_queries = true
```
### XSS Prevention
```toml
[security.xss]
enabled = true
auto_escape_html = true
content_security_policy = true
sanitize_user_input = true
allowed_html_tags = ["b", "i", "u", "em", "strong", "a"]
allowed_attributes = ["href", "title", "alt"]
```
## Security Headers
### HTTP Security Headers
```toml
[security.headers]
enabled = true
[security.headers.hsts]
enabled = true
max_age = 31536000 # 1 year
include_subdomains = true
preload = true
[security.headers.csp]
enabled = true
default_src = ["'self'"]
script_src = ["'self'", "'unsafe-inline'"]
style_src = ["'self'", "'unsafe-inline'"]
img_src = ["'self'", "data:", "https:"]
connect_src = ["'self'"]
font_src = ["'self'"]
object_src = ["'none'"]
frame_ancestors = ["'none'"]
base_uri = ["'self'"]
form_action = ["'self'"]
[security.headers.other]
x_content_type_options = "nosniff"
x_frame_options = "DENY"
x_xss_protection = "1; mode=block"
referrer_policy = "strict-origin-when-cross-origin"
permissions_policy = "geolocation=(), microphone=(), camera=()"
```
## Rate Limiting
### API Rate Limiting
```toml
[security.rate_limiting]
enabled = true
storage = "memory" # memory, redis, database
cleanup_interval = 3600 # 1 hour
[security.rate_limiting.global]
requests_per_minute = 100
burst_limit = 10
[security.rate_limiting.per_user]
requests_per_minute = 60
burst_limit = 5
[security.rate_limiting.endpoints]
"/api/auth/login" = { requests_per_minute = 5, burst_limit = 2 }
"/api/auth/register" = { requests_per_minute = 3, burst_limit = 1 }
"/api/password/reset" = { requests_per_minute = 2, burst_limit = 1 }
"/api/upload" = { requests_per_minute = 10, burst_limit = 3 }
```
### DDoS Protection
```toml
[security.ddos]
enabled = true
max_connections_per_ip = 10
connection_timeout = 30
slow_loris_protection = true
```
## CSRF Protection
```toml
[security.csrf]
enabled = true
token_name = "csrf_token"
header_name = "X-CSRF-Token"
cookie_name = "csrf_cookie"
token_length = 32
double_submit_cookie = true
same_site_cookie = "Strict"
```
## File Upload Security
```toml
[security.uploads]
enabled = true
max_file_size = 10485760 # 10MB
max_files_per_request = 5
allowed_extensions = [
"jpg", "jpeg", "png", "gif", "webp",
"pdf", "doc", "docx", "txt", "csv"
]
scan_for_viruses = true
quarantine_suspicious_files = true
```
## Audit Logging
### Security Event Logging
```toml
[security.audit]
enabled = true
log_level = "info"
log_format = "json"
log_file = "/var/log/rustelo/security.log"
max_log_size = 104857600 # 100MB
max_log_files = 10
log_retention_days = 90
[security.audit.events]
login_success = true
login_failure = true
logout = true
password_change = true
password_reset = true
account_lockout = true
permission_denied = true
data_access = true
data_modification = true
admin_actions = true
```
### Compliance Logging
```toml
[security.compliance]
gdpr_logging = true
hipaa_logging = false
pci_logging = false
sox_logging = false
```
## Environment-Specific Security
### Development Environment
```toml
[security.development]
relaxed_cors = true
debug_headers = true
disable_https_redirect = true
allow_http_cookies = true
verbose_error_messages = true
```
### Production Environment
```toml
[security.production]
strict_mode = true
hide_server_info = true
disable_debug_endpoints = true
require_https = true
enable_monitoring = true
```
## SSL/TLS Configuration
### Certificate Management
```toml
[security.tls]
enabled = true
cert_file = "${TLS_CERT_FILE}"
key_file = "${TLS_KEY_FILE}"
ca_file = "${TLS_CA_FILE}"
protocols = ["TLSv1.2", "TLSv1.3"]
prefer_server_ciphers = true
[security.tls.auto_renewal]
enabled = true
provider = "lets_encrypt"
renewal_threshold = 2592000 # 30 days
notification_email = "${ADMIN_EMAIL}"
```
## Security Monitoring
### Intrusion Detection
```toml
[security.monitoring]
enabled = true
failed_login_threshold = 10
suspicious_activity_threshold = 5
alert_admin = true
auto_block_suspicious_ips = true
block_duration = 3600 # 1 hour
```
### Security Metrics
```toml
[security.metrics]
enabled = true
track_login_attempts = true
track_permission_denials = true
track_rate_limit_hits = true
track_security_violations = true
```
## Best Practices Configuration
### Password Security
```toml
[security.passwords]
use_bcrypt = true
bcrypt_cost = 12
require_password_confirmation = true
prevent_password_reuse = true
password_strength_meter = true
```
### API Security
```toml
[security.api]
require_authentication = true
require_https = true
validate_content_type = true
rate_limit_enabled = true
cors_enabled = true
cors_allow_credentials = false
```
## Security Testing
### Penetration Testing
```toml
[security.testing]
enable_security_tests = true
sql_injection_tests = true
xss_tests = true
csrf_tests = true
authentication_tests = true
authorization_tests = true
```
## Incident Response
### Security Incident Configuration
```toml
[security.incident_response]
enabled = true
auto_lockout_on_breach = true
notify_admin_on_incident = true
incident_log_file = "/var/log/rustelo/incidents.log"
emergency_contact = "${SECURITY_CONTACT}"
```
## Compliance Frameworks
### GDPR Compliance
```toml
[security.gdpr]
enabled = true
data_retention_days = 2555 # 7 years
anonymize_on_deletion = true
consent_tracking = true
data_export_enabled = true
```
### OWASP Configuration
```toml
[security.owasp]
top_10_protection = true
injection_prevention = true
broken_authentication_prevention = true
sensitive_data_exposure_prevention = true
xml_external_entities_prevention = true
broken_access_control_prevention = true
security_misconfiguration_prevention = true
cross_site_scripting_prevention = true
insecure_deserialization_prevention = true
known_vulnerabilities_prevention = true
insufficient_logging_prevention = true
```
## Security Checklist
### Pre-Deployment Security Checks
- [ ] Strong authentication configured
- [ ] HTTPS enabled and enforced
- [ ] Security headers implemented
- [ ] Input validation enabled
- [ ] Rate limiting configured
- [ ] Audit logging enabled
- [ ] File upload restrictions in place
- [ ] Database security configured
- [ ] Regular security updates scheduled
- [ ] Backup and recovery procedures tested
- [ ] Incident response plan documented
- [ ] Security monitoring enabled
- [ ] Penetration testing completed
- [ ] Compliance requirements met
## Troubleshooting
### Common Security Issues
1. **Authentication Failures**
- Check password policies
- Verify JWT configuration
- Review session settings
2. **Authorization Issues**
- Validate RBAC configuration
- Check permission inheritance
- Review role assignments
3. **SSL/TLS Problems**
- Verify certificate validity
- Check cipher suite compatibility
- Validate TLS version settings
4. **Rate Limiting Issues**
- Monitor rate limit logs
- Adjust limits based on usage
- Check for IP blocking
### Security Debugging
```bash
# Enable security debug logging
RUST_LOG=rustelo::security=debug ./rustelo-server
# Check security headers
curl -I https://yourapp.com
# Test authentication
curl -X POST https://yourapp.com/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"test","password":"test"}'
```
## Security Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework)
- [Mozilla Security Guidelines](https://infosec.mozilla.org/guidelines/)
- [Rust Security Guidelines](https://doc.rust-lang.org/nomicon/security.html)
## Next Steps
- [Authentication System](../developers/components/auth.md)
- [Performance Optimization](../performance/overview.md)
- [Monitoring & Logging](../deployment/monitoring.md)
- [Security Best Practices](../security/best-practices.md)