iptables is used to configure the linux kernel based firewall. Quite substatial is its ability to open and close ports, which I will discuss here. One should also be aware that iptables can be used to route traffic as well.

View active rules

To view the rules in action watch can be used like so:

This will output a number of tables, called CHAIN, which are usually named INPUT, OUTPUT and FORWARD. As that name suggests these indicate the direction the traffic comes from or goes to.

Insert rules

It is good practise to specify the exact position inside the CHAIN where the new rules should be inserted.

This example adds a log directive at line 16 of the INPUT chain, at line 7 of the OUTPUT chain and at line 12 of the FORWARD chain. These were the last lines in my special case here, so that I have used them to log any traffic before it gets dropped. The log usually takes place in the system log and can therefore be viewed with journalctl -f.

Information from the system log can be used to indentify traffic which gets accidently blocked. This can happen for example if you set up qemu/kvm with bridging.

This will allow any traffic on the interface (-i) called virbr0 which got created automatically in this qemu/kvm-example.

Think negative and block everything

The basic concept of any firewall should be to block anything in the first place and lets you define what should not get blocked. A good starting point might be to drop everything from all chains. But if you are trying this on a computer via ssh you would lock out yourself. That is why I used this as a script:

It will create rules for ssh (which is on port 22) so that your connections stays open.

See also

More comprehensive examples (but a long read) can be found here
A shorter overview over the rule parameters can be found here

sample configuration