IPTables is very efficient with a small to medium number of rules, once the number of rules increases, packet latency can increase across the firewall interfaces, as every new connection has to be checked against every rule.
Using custom chains within IPTables, can improve the efficiency and overall throughput of the firewall.
A good firewall design is important! Using the principle of Block All, Allow Some
As well as the standard INPUT, FORWARD and OUTPUT chains in IPTables it is very useful to add your own. Custom chains also allow selective tracking and logging of traffic flows.
For example:
# Make a new chain called “dropandlog”
iptables -N dropandlog# Configure the chain.
# Limit how many log entries to make, and log.
iptables -A dropandlog -m limit –limit 15/minute -j LOG –log-prefix Firewall:# Drop the packets passed to this chain.
iptables -A dropandlog -j DROP
Now any rules which have a jump (-j) target of dropandlog will pass the matched traffic to the chain.
For example:
iptables -A INPUT -p tcp –dport 22 -j dropandlog
This rule sends any packets on the default ssh port, coming in on the input chain to the chain dropandlog. They will be shown in the logfile with the prefix “Firewall:”.
Using separate chains cuts down the amount of rules traffic has to pass through and so improves firewall efficiency.
For example the following script:
iptables -A INPUT -p tcp ! –syn -m state –state NEW -j drop
iptables -A INPUT -p tcp –tcp-flags ALL FIN,URG,PSH -j drop
iptables -A INPUT -p tcp –tcp-flags ALL ALL -j drop
iptables -A INPUT -p tcp –tcp-flags ALL NONE -j drop
iptables -A INPUT -p tcp –tcp-flags SYN,RST SYN,RST -j drop
iptables -A INPUT -p tcp –tcp-flags SYN,FIN SYN,FIN -j dropThese rules only match TCP traffic. However all UDP and ICMP traffic will also be forced to go through each rule, slowing them down. It is much more efficient therefore to refactor this to use protocol specific chains.
#New chain tcpfilter.
iptables -N tcpfilter# Rules for chain tcpfilter.
iptables -A tcpfilter -p tcp ! –syn -m state –state NEW -j drop
iptables -A tcpfilter -p tcp –tcp-flags ALL FIN,URG,PSH -j drop
iptables -A tcpfilter -p tcp –tcp-flags ALL ALL -j drop
iptables -A tcpfilter -p tcp –tcp-flags ALL NONE -j drop
iptables -A tcpfilter -p tcp –tcp-flags SYN,RST SYN,RST -j drop
iptables -A tcpfilter -p tcp –tcp-flags SYN,FIN SYN,FIN -j drop# Redirect all tcp traffic to tcpfilter
iptables -A INPUT -p tcp -j tcpfilter
This type of chain can be replicated for each protocol, or for different traffic Each traffic type can then make its way through the firewall, in the most efficient way possible.