bashintermediate

Fail2ban Security Configuration

Configure Fail2ban to protect SSH and Nginx from brute force attacks with custom jail rules.

bash
#!/usr/bin/env bash
set -euo pipefail

# Install fail2ban
sudo apt update && sudo apt install -y fail2ban

# Create local config (never edit jail.conf directly)
sudo tee /etc/fail2ban/jail.local > /dev/null << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
destemail = admin@example.com
sender = fail2ban@example.com
action = %(action_mwl)s

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400

[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5

[nginx-limit-req]
enabled = true
port = http,https
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 10
findtime = 120
bantime = 600
EOF

# Enable and start
sudo systemctl enable fail2ban
sudo systemctl restart fail2ban

# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Unban an IP
# sudo fail2ban-client set sshd unbanip 192.168.1.100

# View banned IPs
# sudo fail2ban-client get sshd banned

Use Cases

  • Protecting SSH from brute force attacks
  • Rate limiting web server abuse
  • Automated intrusion prevention

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.