Advanced Features of netfilter/iptables
Source: linuxgazette.net
Introduction
It is commonly known that netfilter/iptables is the firewall of the Linux operating system. What is not commonly known is that iptables has many hidden gems that can allow you do things with your firewall that you might never have even imagined. In this article I am going to introduce many of these features with some practical uses. If you are not au fait with the basics of iptables then you should read my previous article in the Gazette, « Firewalling with netfilter/iptables« .
The following features are discussed:
- Specifying multiple ports in one rule
- Load balancing
- Restricting the number of connections
- Maintaining a list of recent connections to match against
- Matching against a string in a packet’s data payload
- Time-based rules
- Setting transfer quotas
- Packet matching based on TTL values
All of the features discussed in this article are extensions to the packet matching modules of iptables. I used only two of these extensions in the previous article: the --state module which allowed us to filter packets based on whether they were NEW, ESTABLISHED, RELATED or INVALID connections; and the multiport extension, of which I will go into more detail on in this article.
Some of the modules introduced in this article (marked with an asterisk) have not made their way into the default Linux kernel yet but a netfilter utility called « patch-o-matic » can be used to add them to your own kernel and this will be discussed at the end of the article.
1. Specifying Multiple Ports with multiport
The multiport module allows one to specify a number of different ports in one rule. This allows for fewer rules and easier maintenance of iptables configuration files. For example, if we wanted to allow global access to the SMTP, HTTP, HTTPS and SSH ports on our server we would normally use something like the following:
-A INPUT -i eth0 -p tcp -m state --state NEW --dport ssh -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport smtp -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport http -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport https -j ACCEPT
Using the multiport matching module, we can now write:
-A INPUT -i eth0 -p tcp -m state --state NEW -m multiport --dports ssh,smtp,http,https -j ACCEPT
It must be used in conjunction with either -p tcp or -p udp and only up to 15 ports may be specified. The supported options are:
--sports port[,port,port...]- matches source port(s)
--dports port[,port,port...]- matches destination port(s)
--ports port[,port,port...]- matches both source and destination port(s)
mport* is another similar extension that also allows you to specify port ranges, e.g. --dport 22,80,6000:6100.