Thursday, July 30, 2015

Limiting the rate of ssh connections

The internet is a wild place.  I have an SSH server that is open.  The machine is locked down with very few accounts, all with long passwords, but that doesn't deter attackers from trying to get into the machine.  Most attacks are against the root account, which is futile since the root password is hopelessly long.  And it only accepts public key authentication on that account.

Here is a script I use to limit the number of ssh connections.  As a sample, I show how to rate-limit connections to two ports (222 and 2222) down to one connection in a 60 second window.  Most automated attack scripts back off very rapidly when they notice that they don't get through.  So this easy remedy is enough to thwart a majority of the bot-infested machines.


#!/bin/bash


# Clear all chains
/sbin/iptables -F
/sbin/iptables -L -v -n

# Create a new chain to log and then to drop
/sbin/iptables -N LOGDROP
/sbin/iptables -A LOGDROP -j LOG
/sbin/iptables -A LOGDROP -j DROP

# The external ports 222 and 2222 need to be rate limited.
iptables -I INPUT -p tcp --dport 222 -i eth0 -m state --state NEW -m recent --set --name FIRST
iptables -I INPUT -p tcp --dport 2222 -i eth0 -m state --state NEW -m recent --set --name SECOND

# One connection in a 60 second window.
iptables -I INPUT -p tcp --dport 222 -i eth0 -m state --state NEW -m recent  --update  --name FIRST --seconds 60 --hitcount 1 -j LOGDR
OP
iptables -I INPUT -p tcp --dport 2222 -i eth0 -m state --state NEW -m recent  --update  --name SECOND --seconds 60 --hitcount 1 -j LOG
DROP