Iptables comes shipped with Ubuntu, but without any rules.
Basically, you can control the flow of bytes passing through ports. It’s structured around INPUT (data flowing into the box), OUTPUT (data flowing from the box somewhere else) and FORWARD (instead of dealing with the data, divert or forward it somewhere else).
You say what can come in and where, or not, as the case may be. For example, TCP on port 22.
Useful commands:
iptables -L -v
This will give you verbose output about your existing rules.
iptables -h
This will explain how to use it.
Useful flags
-L lists all the rules
-A append a rule
-I insert a rule (useful as you add additional functionality. Pass in the numeric position too)
It’s important to remember that the rules added will be forgotten on reboot. The approach I’ve been advised to take is to create a shell script that loads the rules on reboot. It’s also a good idea to write a script to write the latest changes too.
Here is what I did.
First, save the Firewall rules:
sudo sh -c "iptables-save > /etc/iptables.rules"
Then create a shell script to load them on reboot (/etc/network/if-pre-up.d/iptablesload)
#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0
don't forget to chmod +x /etc/network/if-pre-up.d/iptablesload
Then write the shell script to save any changes (/etc/network/if-post-down.d/iptablessave):
#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
iptables-restore < /etc/iptables.downrules
fi
exit 0
Here is a useful tutorial from the guys at Ubuntu: https://help.ubuntu.com/community/IptablesHowTo. In this tutorial they also give example rules.
Another piece of useful advice I got was to ensure that you always have a couple of terminals open when changing iptables rules. For example, you don’t want to find that you can’t get back in after applying the wrong rule.