Skip to content

Instantly share code, notes, and snippets.

@lehnerpat
Created November 14, 2012 17:36
Show Gist options
  • Save lehnerpat/4073558 to your computer and use it in GitHub Desktop.
Save lehnerpat/4073558 to your computer and use it in GitHub Desktop.
Firewall rules
These lines are saved to a text file and loaded into iptables with iptables-restore (like "/sbin/iptables-restore </etc/iptables.conf"):
:DO_BLACKLIST - [0:0]
:IN_SSH - [0:0]
-A INPUT -m recent --rcheck --seconds 3600 --name blacklist --rsource -j DROP
-A INPUT -p tcp -m tcp --dport 22 -j IN_SSH
-A IN_SSH -s 192.168.1.0/24 -p tcp -m tcp --dport 22 -j ACCEPT
-A IN_SSH -m recent --rcheck --seconds 60 --hitcount 4 --name ssh_limits --rsource -j DO_BLACKLIST
-A IN_SSH -p tcp -m tcp --dport 22 --tcp-flags FIN,SYN,RST,ACK SYN -m recent --set --name ssh_limits --rsource -j ACCEPT
-A IN_SSH -j ACCEPT
-A DO_BLACKLIST -j LOG
-A DO_BLACKLIST -m recent --set --name blacklist --rsource -j DROP
Explanation:
The first two lines create new chains named DO_BLACKLIST and IN_SSH.
Line 3 discards (drops) all incoming packets whose sender was added to the blacklist within the last hour.
Line 4 accepts all incoming SSH packets and forwards them into the IN_SSH chain.
Line 5 accepts everything from the local subnet, exempting it from getting added to the blacklist.
Line 6 forwards to the chain DO_BLACKLIST all packets from senders which have been added to the list "ssh_limits" 4 times within the last minute.
Line 7 accepts all packets that open a connection (filtered by the listed flags) and logs the respective sender to the list "ssh_limits"
Line 8 accepts all incoming SSH that has not been handled yet.
Lines 9 and 10 handle the DO_BLACKLIST chain: log it, add it to list "blacklist" and drop it.
This causes an IP to be blacklisted for an hour upon the fifth attempted SSH connection within one minute. (Being on the blacklist, the IP has no way of reaching your box since all its packets are dropped immediately). This usually gives you 12 tries to get the password right (4 connection attempts times 3 tries per ssh login) [if you use password auth].
On the rules for IN_SSH you could probably drop the switches "-p tcp --dport 22" since no other packets get fed into that chain anyway.
You will need the "recent" module in iptables for this to work, but that shouldn't be a problem.
You had best create the file for iptables-restore by using iptables-save. Then just add the rules above by hand once. That file will naturally contain the iptables default actions; the numbers in squared brackets might differ from [0:0], I don't know exactly what these values mean. At the end of the file, there needs to be a COMMIT.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment