Iptables recipes

Contents

Port scanning "honeyport"

There are some ports I do not use on my server so I figured if someone attempts to connect to them, they are probably port scanning. The following rules accomplish this using the ftp port:

iptables -A INPUT -m recent --name portscan --rcheck --seconds 300 -j DROP
iptables -A INPUT -i eth0 -p tcp --dport ftp -m recent --name portscan --set -j DROP

It is important to note that some port scanners are smart enough to not scan ports sequentially so it is not enough to just apply these rules to an early port. Nmap, for example, scans ports randomly unless the -r option is used.

With that being said, I suggest you use multiple common ports that go unused on your server. Check out /etc/services for reference.

This is how you would write the above rules using the multiport module:

iptables -A INPUT -m recent --name portscan --rcheck --seconds 300 -j DROP
iptables -A INPUT -i eth0 -p tcp -m multiport --dport ftp-data,ftp,ssh,telnet -m recent --name portscan --set -j DROP

Port knocking

A simple way to protect a service port with iptables.

iptables -A INPUT -i eth0 -p tcp --dport 12345 -m recent --set --name ssh_knocked
iptables -A INPUT -i eth0 -p tcp --dport 22 -m recent --rcheck --seconds 5 --name ssh_knocked -j ACCEPT

This way, if someone wants to connect to port 22, they first have to hit port 12345 and connect to port 22 within 5 seconds.

If you want to kick it up a notch, you could go more complex by using a combination of knocks that have to be done in a certain sequence. I however prefer to keep my iptable rules simple so I chose this method since it is relatively effective.

Drip pan

These rules catch any packets that were destined for ports we were not listening to. After 3 such packets from a host, none of their packets are accepted until they have been quiet for 60 seconds.

# This has to be inserted to the top of your iptables INPUT chain
iptables -I INPUT 1 -m recent --name drippan --update --seconds 60 --hitcount 3 -j DROP
# This has to be inserted to the very bottom of your iptables INPUT chain
iptables -A INPUT -i eth0 -m recent --name drippan --set -j DROP

You could also add logging by replacing the last rule with:

iptables -A INPUT -i eth0 -m recent --name drippan --set -j LOG --log-prefix 'drippan packet: '

Caveats

  • Remember, the order of iptable rules is very important!

Sources