Banning IP address in iptables (linux stateless firewalling)

6th Jan 2019

At work, amongst other things, maintaining a dozen servers is something I do as well. Part of it is analyzing traffic to make sure there isn't a mis-behaving scraper, bot or more specifically an IP address acting nasty. Once infringing IP address has been identified, the next step is handover the details to internal IT deparment personnel, who then take care of it in firewall. Not the greatest of ways for identifying, handling malacious traffic but it works.

It works to a certain extent, as long as the need isn't urgent. More recently though there have been instances wherein an IP has had to be dealt with right away instead of waiting for the communication round trip with IT department. Note that I am not a linux/system administrator by any stretch but having hosted a bunch of (virtual) machine in my homelab, on server firewall isn't new to me. And that's what we decided to use for urgent cases! Use the IP tables for stateless firewalling while IT takes action on their end.

Getting started is relatively easy. Assuming that firewall is configured on (your) server, to block an IP address, issue following command,

iptables -I INPUT 1 -s <IP_ADDRESS> -j DROP

iptables -I INPUT essentially implies block the traffic, on INPUT chain, that is coming back to your server whereas 1 -s indicates appending the IP address at first position. Why first position? As per my understanding of iptables, the first matching rule wins. The rules are processed in line order of the file. If there is a match for a rule then the rules following the match aren't processed.

For cleaning up iptables rules, you can get rid of the rule (added above), by issuing following command,

iptables -D INPUT -s <IP_ADDRESS> -j DROP

And for viewing all rules use iptables -L INPUT -v -n

This isn't really the best of way of handling traffic blocking considering, theoritically, traffic is still flowing in to companies network and being blocked on the server instead of at the (companies) gate but it does give our team a quick way of ensuring some degree of safeguard.