IPTables is, without a doubt, one of the more frustrating components of Linux administration. It is pretty much ubiquitous in need but documentation is often lacking and the differences in de facto use between distributions can create a degree of complexity that should be wholly unnecessary for such a common system function. Red Hat (and ergo CentOS) uses its own tools to alter IPTables which, if you are limited to very basic needs as can be address pretty easily. The Red Hat tools are great for doing the every day tasks like opening a needed port.
However, it is not uncommon to need a lot more flexibility in IPTables and once that is necessary the Red Hat tools make the job for more cumbersome and less portable. For my own firewall administration I have moved to creating my own configuration file and loading it manually into IPTables.
You can put your configuration file anywhere that you want. In etc makes sense, or in var, perhaps. This is not the final configuration file, just an interim, so it is acceptable to keep in the var filesystem.
In this IPTables configuration file, you can place standard IPTables commands in the following format:
-bash-3.2$ sudo head /var/iptables_primary
-A INPUT -s 184.108.40.206/255.0.0.0 -j DROP
-A INPUT -s 220.127.116.11/255.0.0.0 -j DROP
-A INPUT -s 18.104.22.168/255.0.0.0 -j DROP
-A INPUT -s 22.214.171.124/255.0.0.0 -j DROP
-A INPUT -s 126.96.36.199/255.0.0.0 -j DROP
-A INPUT -s 188.8.131.52/255.0.0.0 -j DROP
-A INPUT -s 184.108.40.206/255.0.0.0 -j DROP
-A INPUT -s 220.127.116.11/255.0.0.0 -j DROP
-A INPUT -s 18.104.22.168/255.0.0.0 -j DROP
-A INPUT -s 22.214.171.124/255.0.0.0 -j DROP
This makes it very easy to test and modify your IPTables settings because the commands that you use to modify IPTables on the fly are exactly the same commands that you put into this file. Now to actually use this file, we simply need to read it in line by line. If you want to be sure that IPTables is in a clean state, stop it first and then load this file. Don’t forget to save when you are done. I’ll use the built in Red Hat / CentOS service commands below for the example.
service iptables stop
while read line; do iptables $line; done < /var/iptables_primary
service iptables save
And with that, your new IPTables configuration should be up and running and easy to edit.