simple port knocking with iptables
Tuesday, November 18th, 2008Here’s a simple snippet of iptables, using the “recent” module:
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -m recent --rcheck --name MY_RULE --rsource -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -m recent --rcheck --name MY_RULE --rsource -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -m recent --rcheck --name MY_RULE --rsource -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 31499 -m recent --remove --name MY_RULE --rsource -j DROP
-A INPUT -p tcp -m state --state NEW -m tcp --dport 31500 -m recent --set --name MY_RULE --rsource -j DROP
-A INPUT -p tcp -m state --state NEW -m tcp --dport 31501 -m recent --remove --name MY_RULE --rsource -j DROP
This code will set a rule called MY_RULE when it gets a TCP packet on port 31600. This rule will remember the source IP, and thereafter that source IP will be allowed to connect to SSH/HTTP/HTTPS. Sending a TCP packet to port 31499 or 31501 will remove that rule and access will be lost. Simple and neat. Now, whether this is an effective security strategy…
edit: those rules are in RH-style /etc/sysconfig/iptables formatting; also, i’m not willing to fight WordPress formatting, so just paste it into your $EDITOR.