Here's an example of the auth.log file. You can see that even as I'm writing this article bots are trying different account combinations to get into my server:
impala sshd: Illegal user office from 213.191.xx.xxx
impala sshd: Failed password for illegal user office from 213.191.xx.xx
impala sshd: Illegal user samba from 213.191.xx.xxx
impala sshd: Failed password for illegal user samba from 213.191.xx.xxx
impala sshd: Illegal user tomcat from 213.191.xx.xxx
impala sshd: Failed password for illegal user tomcat from 213.191.xx.xxx
impala sshd: Illegal user webadmin from 213.191.xx.xxx
impala sshd: Failed password for illegal user webadmin from 213.191.xx.xxx
Do you see the rate at which this is happening? Nowadays' connection speeds allow for crackers to try an enormous amount of combinations every second! It's time to stop this before someone hits the jackpot and my server is compromised.
Iptables is the standard Linux firewall and though I use Ubuntu, it should be installed by default on any modern distribution. But it doesn't do anything yet. It's just sitting there, so we need to teach it some rules to prevent brute force attacks.
There are tools available to do this for us like fail2ban. Though it's a great piece of software and certainly has it's advantages, in this article I'd like to stick with iptables because fail2ban parses log files to detect brute force attacks at a certain interval, whereas iptables works directly on the kernel level. Besides I don't think many people know about iptables' full capabilities, and it comes preinstalled!
Easy setup - just 2 rules
Because iptables comes standard with every Linux distribution we'll skip right to setting up the specific firewall rules we need. In depth configuring of iptables takes a bit of understanding and is not within the scope of this article, but let's take a look at these two statements:
sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
sudo iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 8 --rttl --name SSH -j DROP
The -i eth0 is the network interface to which ssh connections are made. Typically this is eth0, but maybe you need to change it.
That's it! Together they will rate-limit all incoming SSH connections to 8 in a one minute window. Normal users will have no trouble logging in, but the brute force attacks will be dropped, limiting the number of possible account combinations from unlimited, to 8. That's awesome!
While you're still testing, you might want to add the following line to your crontab
*/10 * * * * /sbin/iptables -F
This will flush all the rules every 10 minutes, just in case you lock yourself out. When you're happy with the results of your work, remove the line from your crontab, and you're in business.