How can I programmatically manage iptables rules on the fly? How can I programmatically manage iptables rules on the fly? linux linux

How can I programmatically manage iptables rules on the fly?


From the netfilter FAQ:

The answer unfortunately is: No.

Now you might think 'but what about libiptc?'. As has been pointed out numerous times on the mailinglist(s), libiptc was NEVER meant to be used as a public interface. We don't guarantee a stable interface, and it is planned to remove it in the next incarnation of linux packet filtering. libiptc is way too low-layer to be used reasonably anyway.

We are well aware that there is a fundamental lack for such an API, and we are working on improving that situation. Until then, it is recommended to either use system() or open a pipe into stdin of iptables-restore. The latter will give you a way better performance.


Using iptables-save and iptables-restore to query and regenerate rules is easily the most efficient way of doing it. These used to, once, be shell scripts, but now they are C programs that work very efficiently.

However, I should point out that there is a tool that you can use which will make maintaining iptables much easier. Most dynamic rulesets are really the same rule repeated many times, such as:

iptables -A INPUT -s 1.1.1.1 -p tcp -m --dport 22 -j ACCEPTiptables -A INPUT -s 2.2.2.0/24 -p tcp -m --dport 22 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 22 -j REJECT

Instead of replacing those rules every time you want to change what ports can access port 22 (useful for say, port knocking), you can use ipsets. Viz:

ipset -N ssh_allowed nethashiptables -A ssh_allowed -m set --set ssh_allowed src -p tcp -m --dport 22 -j ACCEPTipset -A ssh_allowed 1.1.1.1ipset -A ssh_allowed 2.2.2.0/24

Sets can hold ip addresses, networks, ports, mac addresses, and have timeouts on their records. (Ever wanted to add something for just an hour?).

There is even an atomic way of swapping one set with another, so a refresh means creating a new temporary set, then swapping it in as the name of the existing set.


You may consider using rfw which is the REST API for iptables.It is serializing iptables commands from various potentially concurrent sources and remotely executes iptables on the fly.

rfw is designed for distributed systems that try to update firewall rules on multiple boxes but it can be run also on a single machine on localhost interface. Then it allows avoiding the SSL and authentication overhead as it can be run on plain HTTP in this case.

Sample command:

PUT /drop/input/eth0/11.22.33.44

which corresponds to:

iptables -I INPUT -i eth0 -s 11.22.33.44 -j DROP

You can insert and delete rules as well as query for current status to get the existing rules in JSON format:

GET /list/input

Disclaimer: I started that project. It's open source under the MIT license.