🖥️ Server Administration
10 min de lectura
fail2ban & Rate Limiting for Servers
Protect your server from brute-force attacks and abuse using fail2ban for automatic IP banning and rate limiting strategies.
What Is fail2ban?
fail2ban monitors log files for suspicious patterns (failed login attempts, exploit probes) and automatically bans the offending IP addresses by adding firewall rules. It is the simplest and most effective defense against brute-force attacks.
Installation & Basic Setup
# Install
sudo apt install fail2ban
# Create local config (never edit jail.conf directly)
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# Key settings in jail.local
[DEFAULT]
bantime = 1h # How long to ban
findtime = 10m # Time window for counting failures
maxretry = 5 # Failures before ban
ignoreip = 127.0.0.1/8 ::1 100.64.0.0/10 # Never ban these
Common Jails
SSH Protection
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 24h
Nginx Protection
[nginx-limit-req]
enabled = true
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 10
bantime = 1h
[nginx-botsearch]
enabled = true
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 2
bantime = 24h
Management Commands
# Check jail status
sudo fail2ban-client status sshd
# Manually ban/unban
sudo fail2ban-client set sshd banip 203.0.113.100
sudo fail2ban-client set sshd unbanip 203.0.113.100
# View all banned IPs
sudo fail2ban-client banned
Rate Limiting with Nginx
For web applications, rate limiting at the reverse proxy level is more effective than fail2ban alone:
# Define rate limit zone (10 requests/second per IP)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status 429;
proxy_pass http://upstream;
}
}
Rate Limiting with iptables
# Limit new SSH connections to 3 per minute per IP
iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
Best Practices
- Always add your own IP and management networks to
ignoreip. - Start with lenient settings and tighten gradually.
- Monitor false positives — check
fail2ban-client statusregularly. - Use Cloudflare or a CDN in front to handle volumetric attacks before they reach fail2ban.