4

How to get a deterministic complete dump of all iptables rules?

By complete, I mean all tables of iptables.

By deterministic, I mean when the command is run multiple times without modifying any iptables, it should always output the same.

Use case: Refactoring a firewall script. Using for example a for loop rather than writing similar command multiple times and stuff like that. Running the iptables-dump command before and after to check the refactoring has not changed any actual iptables rules.

As per Answer by Gilles, to get a complete output, -v should to be used.

iptables controls five different tables: filter, nat, mangle, raw and security. On a given call, iptables only displays or modifies one of these tables, specified by the argument to the option -t (defaulting to filter). To see the complete state of the firewall, you need to call iptables on each of the tables successively.

Additionally, to get an accurate representation of the rules, you need to pass the option -v. Otherwise some important criteria are omitted in the output, such as the interface in filter rules (e.g. a rule that says “accept everything” and a rule that says “accept everything on the loopback interface” can only be distinguished with -v).

Thus, to get a complete presentation of the netfilter rules, you need

iptables -vL -t filter
iptables -vL -t nat
iptables -vL -t mangle
iptables -vL -t raw
iptables -vL -t security

Alternatively, you can call the iptables-save program, which displays all the rules in all tables in a format that can be parsed by iptables-restore. This format is also reasonably readable by humans (it's pretty much like a series of calls to the iptables command to build the table).

But when using -v, the packages and bytes counter will be added. Thereby making the output non-deterministic.

How to get best of both worlds? How to get a deterministic complete dump of all iptables rules?

adrelanos
  • 1,836
  • 7
  • 30
  • 58

1 Answers1

8

The iptables-save command has a very straightforward output. The varying parts are in square brackets after a rule, or in comments:

# Generated by iptables-save v1.4.21 on Sun Jan 10 16:02:30 2016
: INPUT ACCEPT [38:2132]

It then becomes an exercise to nullify or even remove such entities, resulting in a completely deterministic output that can still be re-read with iptables-restore:

iptables-save | sed -e 's/\[[0-9:]*\]/[0,0]/' -e '/^#/d'
*filter
:INPUT ACCEPT [0,0]
....
Chris Davies
  • 116,213
  • 16
  • 160
  • 287