Iptables – How to block ALL communications with an IP-address using iptables

firewalliptables

I have a FreeBSD system behind a Linux-based router (using DD-WRT firmware). The FreeBSD system is running sshd and is regularly probed by various script-kiddies.

It currently runs a script, that, upon seeing more than 3 failed attempts to login from the same IP-address, blocks the address completely. The block used to be local (using FreeBSD's ipfw), but I'd like to cover the entire LAN — by asking the router to do the blocking. Which brings me to using Linux' means of firewalling — the iptables.

If I use:

iptables -I INPUT -s $IP -j DROP

then the router will reject the IP trying to contact the router itself — but will happily forward the connection to the LAN.

If I use

iptables -I FORWARD -s $IP -j DROP

it will stop attackers from reaching my LAN, but will keep the router reachable to them.

Is there some single rule — or, at least, single command — I can make for each attacking IP to intercept any and all traffic to and from it?

Thank you!

Best Answer

Is there some single rule -- or, at least, single command -- I can make for each attacking IP to intercept any and all traffic to and from it?

You need the two iptables rules because you need to block two different flows.

But rather than blocking the ip-addresses directly: set up an ipset blacklist

ipset create blacklist hash:ip hashsize 4096

Setup the iptables rules to match against that blacklist, a one time effort:

 iptables -I INPUT  -m set --match-set blacklist src -j DROP 

iptables -I FORWARD  -m set --match-set blacklist src -j DROP 

And then you can use a single command to add each of the ip-addresses you need to block:

 ipset add blacklist 192.168.0.5 
 ipset add blacklist 192.168.0.100 

Etc.