Prevent Brute-Force SSH Attacks Using iptables

Prevent (or at least slow down) a brute-force SSH attack.
By default, iptables on a CentOS 6 SSH server allows all inbound SSH traffic on port 22. See /etc/sysconfig/iptables:

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

Modify /etc/sysconfig/iptables to the following in order to allow a particular IP to initiate 5 new SSH connections within a window of 60s. If additional new SSH connections are opened for that IP, then all packets from that IP will be dropped, and the incident will be logged to /var/log/messages. After 60s that IP will be able to open 5 new SSH connections, and so on. Please note that when I say that a new SSH connection is made that I do not mean to imply the SSH authentication was successful. Just that the two hosts initiated a new TCP/IP connection over port 22.

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH -j ACCEPT
-A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 5 --rttl --name SSH -j LOG --log-prefix "BRUTE_FORCE_SSH"
-A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 5 --rttl --name SSH -j DROP
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# service iptables stop && service iptables start

My System Configuration

  • CentOS 6.5 x86 64-bit

References

Leave a Reply

Your email address will not be published. Required fields are marked *