Important to understand

Rules are read from top to bottom

As soon as a rule is found that covers whatever is happeneing at the firewall, it is used and anything below ignored. So, for instance, a DROP deny all rule (sudo iptables -A INPUT -j DROP) must be last because everything after it in that section will be ignored).

Useful Iptable commands

List available optons
iptables -h
List all rules
sudo iptables -L
Delete a rule

List all rules with line numbers

sudo iptables -L --line-numbers

Delete rule at line number

sudo iptables -D INPUT 2

(Where ‘2’ is the rules line number)

Add a rule

To add a rule to the beginning:

sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT

To add a rule to the end:

sudo iptables -A INPUT -j DROP

(NOTE – everything after a DROP deny all rule will be ignored in that section!!! It must be last.)

Editing rules in a text editor

Export the exisiting rules to a text file:

sudo iptables-save > ~/iptables.txt

Make your changes:

nano ~/iptables.txt

Then import the new rules, overwriting what’s already there:

sudo iptables-restore < ~/iptables.txt

Saving entries

Your changed rules won’t be used after a reboot unless they are saved for the OS fetch them on boot. You’ll need the iptables-persistent package installed:

apt-get install iptables-persistent
Save current iptables config for IPv4
sudo -i
iptables-save > /etc/iptables/rules.v4
exit

(The “-i” is needed to switch into root user because sudo is lost after the ‘>’ character, but its needed on the path for the save)

Save iptables config for IPv^

We’re going to simply block all IPv6 traffic in this example

Dangerous commands!

sudo iptables -F

Before you use -F to flush (delete) all the rules, check the ‘policy’ for all 3 chains (sudo iptables -L). If you’ve used ‘sudo iptables -P INPUT DROP’ then the policy will have been set to DROP, so once all of your rules are flushed everything will then be dropped…it will immediately disconnect your SSH session! Set the policy to ACCEPT before using -F

You’ll need to reboot it to get the server back!

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *