Wednesday, August 19, 2009

secure SSH

SkyHi @ Wednesday, August 19, 2009
I got tired of logcheck emailing me with hundreds of login attempts every day, even after I installed fail2ban. The problem with fail2ban and other such scripts is they only work once the "attack" has already been attempted. It may be too late then ... If a 0-day remote SSH vuln is released ... you're screwed.

The best solution for me has been:

1) Whitelist good networks
2) Block SSH from all remaining networks
3) Install port knocker daemon

With the latest advances in port scanners, changing the port number probably won't help much if you leave it open to the world. Port scanners are smarter now, and can detect what services are running on which ports regardless of what number they are on. I use the following homegrown script on my Debian servers:

#!/bin/bash

# Create SSHSCAN bucket
iptables -N SSHSCAN

# Allow established SSH connections to continue to process
iptables -A INPUT -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT

# Whitelist good networks/hosts
for i in `cat /etc/firewall-whitelist`; do
echo Whitelisting $i
iptables -A INPUT -s $i -j ACCEPT
done

# Setup the SSHSCAN rules to prevent brute force attacks
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j SSHSCAN
iptables -A SSHSCAN -m recent --set --name SSH
iptables -A SSHSCAN -m recent --update --seconds 300 --hitcount 5 --name SSH -j LOG --log-level info --log-prefix "SSH SCAN blocked: "
iptables -A SSHSCAN -m recent --update --seconds 300 --hitcount 5 --name SSH -j DROP

# Drop any SSH connection we haven't explicitly authorized.
iptables -A INPUT -p tcp --dport 22 -j DROP

# Drop DB connections from outside hosts
iptables -A INPUT -p tcp --dport 3306 -j DROP
iptables -A INPUT -p tcp --dport 5432 -j DROP


With that and the port knocker, logcheck is very quiet, and I can get in from wherever I want, whenever I want. The bit about SSHSCAN will block entirely any IP address that tries to hit my SSH port more than 3 times. I also run portsentry on ports that I don't use for my port knocker which pretty much blocks out anyone that hits me with nmap.

It's not foolproof, but it's better than most, and that's all I really need. Just enough to make any casual cracker move on looking for an easier nut to crack.