I've seen a significant increase in ssh port-knocking on my private servers, so figured I'd give Fail2ban a go.
This guide focuses on Fail2ban using CentOS 6.
For Ubuntu, use this instead; https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-ubuntu-14-04.
Ubuntu 14.04 is stated, but works with little to no modifications for the latest Ubuntu 18.04 LTS Bionic Beaver as well.
- I followed this excellent guide over at Digital Ocean; https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-centos-6.
- Did some changes to the /etc/fail2ban/jail.local.
enabled = true
# Default ssh port setting
#port = ssh
# If you use something other than port 22 for ssh, this is where you set it. No, port 2222 is not my real ssh-port!
port = 2222
# Ignore any IP's on the internal network and the localhost
ignoreip = 127.0.0.1 192.168.0.0/24
bantime = 3600
maxretry = 3
- Restart the fail2ban daemon for good measure.
# service fail2ban restart
Stopping fail2ban: [ OK ]
Starting fail2ban: [ OK ]
- Done, it's that simple!
3. Tips and tricks
3.1. Unblocking IP-addresses
Sometimes you need to unblock IP's. Use the fail2ban-client for this.
# fail2ban-client set <JAIL> unbanip <IP>
Unblock IP 192.168.0.100 from the sshd-jail:
# fail2ban-client set sshd unbanip 192.168.0.100
3.2. List all jails
For some reason fail2ban doesn't have a "fail2ban-client status --all", so here's a script to overcome that.
JAILS=`fail2ban-client status | grep "Jail list" | sed -E 's/^[^:]+:[ \t]+//' | sed 's/,//g'`
for JAIL in $JAILS
fail2ban-client status $JAIL
A shorter version from the same thred on github as above:
# fail2ban-client status | sed -n 's/,//g;s/.*Jail list://p' | xargs -n1 fail2ban-client status
3.3. Got yourself locked out?
Set the the bantime to something shorter and-or see below about whitelisting IP's.
Add or change this line to your /etc/fail2ban/jail.local in the default-block.
# Set bantime to five minutes, default is ten minutes, or 3600 seconds.
bantime = 300
3.4. Whitelisting own IP's
Add this line to your /etc/fail2ban/jail.local in the default-block. It might be a single IP-address, a CIDR-mask or something else, as stated inline below.
[DEFAULT] # "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not # ban a host which matches an address in this list. Several addresses can be # defined using space separator. ignoreip = 127.0.0.1 192.168.1.0/24 126.96.36.199
Ignore common private networks.
# This will ignore connection coming from common private networks. # Note that local connections can come from other than just 127.0.0.1, so # this needs CIDR range too. ignoreip = 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16