Configuring Fail2ban for Dynamic Protection

Configuring Fail2ban for Dynamic Protection

Fail2ban provides intelligent, log-based intrusion prevention by monitoring authentication logs and dynamically creating firewall rules to block attacking IPs. Its flexible configuration allows customized responses to different attack patterns.

Install and configure fail2ban with optimized settings:

# Install fail2ban
apt-get install fail2ban

# Create local configuration
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Configure jail.local for SSH protection
cat > /etc/fail2ban/jail.d/sshd.local << 'EOF'
[DEFAULT]
# Global settings
bantime = 3600
findtime = 600
maxretry = 3
ignoreip = 127.0.0.1/8 10.0.0.0/8 192.168.0.0/16
banaction = iptables-multiport
backend = systemd

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
maxretry = 3
findtime = 600
bantime = 3600

# Aggressive mode for repeat offenders
[sshd-aggressive]
enabled = true
port = ssh
filter = sshd
logpath = %(sshd_log)s
maxretry = 2
findtime = 3600
bantime = 86400

# Custom filter for specific attack patterns
[sshd-ddos]
enabled = true
port = ssh
filter = sshd-ddos
logpath = %(sshd_log)s
maxretry = 10
findtime = 60
bantime = 600

# Block invalid usernames immediately
[sshd-invaliduser]
enabled = true
port = ssh
filter = sshd-invaliduser
logpath = %(sshd_log)s
maxretry = 1
findtime = 86400
bantime = 604800
EOF

Create custom fail2ban filters:

# Filter for DDoS-style attacks
cat > /etc/fail2ban/filter.d/sshd-ddos.conf << 'EOF'
[Definition]
failregex = ^%(__prefix_line)sDid not receive identification string from <HOST>
            ^%(__prefix_line)sConnection reset by <HOST> port \d+ \[preauth\]
            ^%(__prefix_line)sConnection closed by <HOST> port \d+ \[preauth\]
ignoreregex =
EOF

# Filter for invalid username attempts
cat > /etc/fail2ban/filter.d/sshd-invaliduser.conf << 'EOF'
[Definition]
failregex = ^%(__prefix_line)sInvalid user .* from <HOST>
            ^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers
            ^%(__prefix_line)sFailed password for invalid user .* from <HOST>
ignoreregex =
EOF

# Advanced filter with attack scoring
cat > /etc/fail2ban/filter.d/sshd-score.conf << 'EOF'
[Definition]
# Assign scores to different failure types
failregex = ^%(__prefix_line)sFailed password for .* from <HOST>(?:\s*port \d*)?(?: ssh\d*)?$
            ^%(__prefix_line)sInvalid user .* from <HOST>.*$
            ^%(__prefix_line)sDid not receive identification string from <HOST>.*$
            ^%(__prefix_line)sReceived disconnect from <HOST>.*: 11: Bye Bye \[preauth\]$
            
# Weight different patterns
# Failed password = 1 point
# Invalid user = 2 points  
# No identification = 3 points
[Init]
journalmatch = _SYSTEMD_UNIT=sshd.service + _COMM=sshd
EOF