How to Configure Iptables in Stateful Mode Properly

Iptables is a software firewall based on Netfilter, in fact it’s a framework for working with Netfilter. Generally firewalls have two modes, stateless and stateful. In this post we will study a brief of how to configure Netfilter in stateful mode.

I’m going to assume your linux box is fresh installation and doesn’t have any rules on it. You can check your iptables rules by typing following command :

sudo iptables -nvL -t filter

Breakdown:

-L : Shows list of rules

-t filter : t stands for table. The table we want to work with is calling  filter, eventhough it’s the default table but I’d rather to mention it

-n : Avoid long reserve DNS and only shows IP addresses

-v : Verbose

Next write following commands :

sudo iptables -A INPUT -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A INPUT -p tcp -m state --state NEW -j ACCEPT

Rule of Thumb: The order of writing rules matters. You have to take take into account that Netfilter’s rules are checked sequentially and route of a packet is determined on the first match.

The first rule says if the packet is ESTABLISHED or is RELATED to another packet(e.g. ICMP error messages) then it can pass through. If the packet is completely NEW to Netfilter, it skips the first rule and try to match the packet with the second rule. Since ESTABLISHED and RELATED are more frequent, this helps iptables to perform faster by reducing number of rules to check.

Reason: When a client sends a packet to a server, it actually sends a SYN to server. Client’s packet enters into NEW state in Netfilter.

Then server sends a SYN+ACK back to the client, and now it’s client turn to send ACK to the server again. The client is in ESTABLISHED state after sending the ACK.

BreakDown:

-A : Append the rule to following chain, in this case INPUT chain

-p : Protocol (In this case TCP)

-m : Which module we want to use. For making Netfilter stateful we will use state module

–state : Identify the state of packet. This argument comes after the -m state

-j : What action Netfilter has to do with the packet ACCEPT / DROP or REJECT

Note: module state is deprecated and you can use conntack module instead, but according to this post state module is valid yet and no need to be worry about it.

In this post I dived into Netfilter stateful packet filtering and tried to reason why ones need to write rules in such order, of course there are so many stones remained unturned. Hopefully I will write more about Iptables/Netfilter.

Leave a Reply

Your email address will not be published. Required fields are marked *