Putting fail2ban to good use: whitelisting SSH logins

I don't like fail2ban all that much (neither do I like denyhosts or other similar software, I'm really egalitarian there), because it is based on the idea of using blacklists. Which don't work. If you don't believe me and rather believe more famous people, read http://www.codinghorror.com/blog/2007/12/blacklists-dont-work.html

So, anyway.

I do like the idea of whitelists though. And I like the idea of rate-limiting connections.

Rate-limiting SSH logins using iptables has been done before, using the iptables recent module, see endless results when <search-engine-verb> for "ssh iptables recent".

Combined with whitelisting clients who successfully authenticated with SSH public keys, this is really nice. No more locking yourself out with the recent module when connecting more than <your limit here> times in short time, for example when using TAB completion over SSH or multiple scp/rsync/whatever commands in a script.

Quick HowTo:

  • install fail2ban
  • disable all possibly enabled jails in jail.conf (unless you like blacklists)
  • add to jail.conf:

enabled = true
port   = ssh
filter = sshd-whitelist
banaction = iptables-whitelist
logpath  = /var/log/auth.log
maxretry = 3
  • add the attached sshd-whitelist.conf to to fail2ban's filter.d/ directory
  • add the attached iptables-whitelist.conf to to fail2ban's action.d/ directory
  • restart fail2ban

You can tune the maxretry setting to match your limit of attempts you configured for the iptables recent module.

If you want to also whitelist SSH logins using passwords, you have to edit the file sshd-whitelist.conf to add the needed log regex.

Binary Data sshd-whitelist.conf797 bytes
Binary Data iptables-whitelist.conf1.83 KB


Andrew's picture

Thanks for sharing this! I was just thinking that this could be a very useful application of fail2ban. Your post saved me a lot of time.