SSH Security with Fail2Ban on Gentoo

I accidentally looked at my syslog messages on my home (Gentoo) Linux server and found that there were thousands of SSH connection attempts from all over the world: people trying to brute-force my root password. The worst bit was that it was filling up my logs and causing lots of things to die when the computer ran out of disk-space. It needed a bit of playing around to get this to stop, but in case you run across the same situation, I’ve documented what I did:

  • Make sure you have the tcpd USE-flag on net-misc/openssh. If you don’t, the easiest way to add it is with the command echo "net-misc/openssh tcpd" >> /etc/portage/package.use
  • Emerge fail2ban
  • If you’re using syslog-ng, you need to configure it to log sshd logs to a different place (reduces load on the server) by adding the following lines to /etc/syslog-ng/syslog-ng.conf
    filter f_sshd {match('^sshd\[[0-9]+\]:'); };
    destination sshd { file("/var/log/sshd.log"); };
    log { source(src); filter(f_sshd); destination(sshd); flags(final); }
  • Enable the ssh-tcpwrapper setting in /etc/fail2ban/jail.conf, checking that the logpath is pointing to your log file. It should end up looking something like

    enabled = true
    filter = sshd
    action = hostsdeny
    logpath = /var/log/sshd.log
  • Set up the hosts allow/deny files (if you don’t have them) by pumping out the following commands to bash

    touch /etc/hosts.allow
    touch /etc/hosts.deny
    chmod 644 /etc/hosts.allow
    chmod 644 /etc/hosts.deny
  • Reload syslog-ng /etc/init.d/syslog-ng reload, restart openssh /etc/init.d/sshd restart, and start fail2ban /etc/init.d/fail2ban start && rc-update add fail2ban default

That should do it. I also recommend disabling the root account and disabling password authentication in your /etc/ssh/sshd_config file.

  1. #1 by Gufo on 2009-08-07 - 3:36 am

    If feasible, changing the default port is one of the most effective ways to get rid of the vast majority of attempts, without the need to use any external program. 🙂 Gufo

  2. #2 by Martin on 2010-06-14 - 11:03 pm

    When you use fail2ban, so you can create Abuse-Reports about the Attacks over my project so the Abuse-Departments get a Complaint in X-ARF. You have Statistics over your Server and can replace Data and more. regards Martin

Comments are closed.