Guide to Setting Up a Web Application Firewall on a Server with Caddy Server
What Does a Web Application Firewall Protect Against?
A WAF protects web applications from various attacks, including: - SQL injection - Cross-site scripting (XSS) - Cross-site request forgery (CSRF) - Remote code execution - Application layer DDoS attacks - Automated bot attacks - Unauthorized access attempts
Why Choose Caddy for Web Application Firewall?
Caddy stands out as an excellent choice for implementing a web application firewall due to: - Automatic HTTPS with Let's Encrypt - Simple, intuitive configuration - Built-in security features - Lightweight and performant - Modern Go-based architecture - Extensive middleware and plugin ecosystem
Prerequisites
Before we begin, ensure you have the following: - A server running Linux (Ubuntu/Debian recommended) - Root or sudo access - Existing web application or service to protect
Step 1: Installing Caddy Server
Install Caddy using the official installation script:
# Download and install Caddy
wget -O- https://get.caddy.sh | bash
# Verify installation
caddy version
Step 2: Comprehensive Security Configuration
Detailed Header Protection
example.com {
header {
# Prevent Clickjacking
X-Frame-Options "DENY"
# Strict Transport Security (HSTS)
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Prevent MIME Type Sniffing
X-Content-Type-Options "nosniff"
# Enhanced Content Security Policy
Content-Security-Policy "default-src 'self';
script-src 'self' 'unsafe-inline' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' https://fonts.googleapis.com;
connect-src 'self';
frame-ancestors 'none';
base-uri 'self'"
# Referrer Policy
Referrer-Policy "strict-origin-when-cross-origin"
# Permissions Policy
Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()"
# XSS Protection
X-XSS-Protection "1; mode=block"
}
}
Security Headers Breakdown:
- X-Frame-Options: Prevents clickjacking by disabling iframe embedding
- HSTS: Forces HTTPS and prevents protocol downgrade attacks
- X-Content-Type-Options: Stops MIME type sniffing attacks
- Content-Security-Policy: Provides granular control over resource loading
- Referrer-Policy: Controls information sent in HTTP referrer header
- Permissions-Policy: Restricts powerful browser APIs
- X-XSS-Protection: Additional cross-site scripting protection
Advanced Rate Limiting Strategies
{
servers {
# Global rate limiting configuration
limits {
# Maximum concurrent connections
max_connections 1000
# Connection timeout
timeout 30s
}
}
}
example.com {
# Sophisticated rate limiting
rate_limit {
# Limit by IP address
zone ip {
# 100 requests per minute per IP
requests 100
burst 50
period 1m
}
# Separate limit for authenticated users
zone authenticated {
requests 500
burst 100
period 1m
}
# API-specific rate limiting
zone api {
requests 50
burst 20
period 1m
}
}
# Geoblocking configuration
filter {
# Block requests from specific countries
country_block {
countries US,CN,RU
}
# Block known malicious IP ranges
ip_block {
ranges 185.220.0.0/16,
91.121.0.0/16
}
}
}
Comprehensive Logging and Monitoring
{
# Global logging configuration
log {
# Centralized logging
output file /var/log/caddy/global_access.log {
# Log rotation
roll_size 100MB
max_age 30
compress
}
# Structured logging format
format json {
fields {
request>remote_ip
request>method
request>uri
request>proto
status
duration
size
}
}
}
}
example.com {
# Specific site logging
log {
output file /var/log/caddy/example_access.log
format json
}
# Advanced request logging
request_log {
# Log potentially malicious requests
capture_errors
log_suspicious_activity
}
}
Proxy and Backend Protection
example.com {
# Reverse proxy with enhanced security
reverse_proxy localhost:8080 {
# Hide original client IP
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
# Health checking
health_check {
path /health
interval 30s
timeout 5s
fail_duration 1m
}
# Circuit breaker for backend failures
circuit_breaker {
failure_threshold 5
recovery_time 30s
}
# Transport layer security
transport http {
tls_insecure_skip_verify
keepalive 30s
keepalive_idle_conns 10
}
}
}
Advanced Security Techniques
Bot and Crawler Protection
example.com {
# Bot detection and mitigation
filter {
bot_protection {
# Challenge-based bot detection
challenge_type captcha
# Block known bot user agents
block_user_agents [
"AhrefsBot",
"MJ12bot",
"DotBot"
]
# Custom bot detection rules
custom_rules {
# Block requests with specific patterns
match_request_pattern "/wp-login.php"
match_header "User-Agent" "^Python-requests"
}
}
}
}
JWT and Authentication Integration
example.com {
# JWT-based authentication middleware
jwt {
# Secret key for token validation
secret env JWT_SECRET
# Token validation rules
validation {
# Token expiration check
max_age 1h
# Require specific claims
require_claims [
"user_id",
"role"
]
}
# Authorization based on JWT claims
authorization {
# Role-based access control
admin_roles ["superadmin", "admin"]
user_roles ["user", "readonly"]
}
}
}
Troubleshooting and Best Practices
Debugging WAF Configuration
- Check Caddy logs:
journalctl -u caddy
- Validate Caddyfile:
caddy validate
- Test configuration incrementally
Performance Considerations
- Monitor resource usage
- Adjust rate limits based on traffic
- Use caching mechanisms
Comprehensive Security Checklist
- ✅ Implement strong security headers
- ✅ Configure rate limiting
- ✅ Set up detailed logging
- ✅ Protect against common web vulnerabilities
- ✅ Implement bot protection
- ✅ Use authentication mechanisms
- ✅ Perform regular security audits
- ✅ Keep Caddy and dependencies updated
Real-World Implementation Tips
- Start with basic configurations
- Gradually increase security complexity
- Test each configuration thoroughly
- Monitor performance impact
- Use staging environments for testing
- Regularly review and update rules
Additional Security Recommendations
- Keep Caddy and all dependencies updated
- Use fail2ban for IP-based attack prevention
- Implement multi-factor authentication
- Regularly audit logs
- Use strong, unique passwords
- Limit server exposure by closing unnecessary ports
Conclusion
Implementing a robust web application firewall with Caddy is a multi-layered approach combining built-in features, security headers, rate limiting, and advanced filtering techniques. By following this comprehensive guide, you'll significantly enhance your web application's security posture.
Final Recommendations
- Continuously update and patch
- Perform regular security audits
- Stay informed about emerging threats
- Consider professional security assessments
Additional Resources
- Caddy Documentation: https://caddyserver.com/docs
- OWASP Web Application Security Guide
- ModSecurity Documentation