iptables
iptables-persistent, netfilter-persistent
Basic options
There are a few basic concepts within iptables:
Tables
Within each table, there are a few available chain options. The values will be listed down under each table, and will be further discussed in a later section.
filter (default)
INPUT
FORWARD
OUTPUT
nat
...
mangle
...
raw
...
Chain
INPUT
FORWARD
OUTPUT
Target
ACCEPT
DROP
REJECT
Basic flag options
-A OR --append
-I OR --insert
-D OR --delete
-t OR --table
-L OR --list
-p OR --protocol
-P or --policy
-j OR --jump
-s OR --source
-d OR --destination
--sport OR --source-port
--dport OR --destination-port
Add/insert rules examples
Add an INPUT rule to DROP all traffic regardless of the protocol, destination port, source address, or any other parameters
$ sudo iptables -A INPUT -j DROP
Add an INPUT rule to DROP all SSH traffic (TCP port 22)
$ sudo iptables -A INPUT -p tcp --dport 22 -j DROP
An additional rule can be added to allow SSH traffic from a source address range. Note that the -I
flag option is used instead of -A
to insert, rather than append the new rule. This allow sthe new rule to take precedence over the previously defined rule (for matching traffic).
$ sudo iptables -I INPUT -p tcp --dport 22 -s 192.168.1.0/24 -j ACCEPT
View the rules
$ sudo iptables -L
$ sudo iptables --list
Persistent rules with iptables-persistent
Install iptables-persistent
$ sudo apt install iptables-persistent
Update rules with iptables commandSave to rules file:/etc/iptables/rules.v4(For IPv4)
$ sudo iptables-save | sudo tee /etc/iptables/rules.v4
Persistent rules with netfilter-persistent
All the same steps as above for iptables-persistent, with some additional steps:
Install netfilter-persistent and iptables-persistent
seems like installing iptables-persistent automatically adds the current rules in the iptables into the file: /etc/iptables/rules.v4
$ sudo apt install netfilter-persistent
$ sudo install iptables-persistent
Enable netfilter-persistent service
$ sudo systemctl enable netfilter-persistent
Check to ensure that it is enabled. It doesn't matter if its not running yet, as it will be started on reboot as long its enabled.
$ sudo systemctl status netfilter-persistent
Verify if the rules have been added to the configuration file: /etc/iptables/rules.v4
$ sudo cat /etc/iptables/rules.v4
Otherwise, manually add the rules using the iptables-save tool
$ sudo iptables-save | sudo tee /etc/iptables/rules.v4
The iptables-save tool simply returns the current iptables rules
$ sudo iptables-save
...
...
...
Reboot the system
$ reboot
Check iptables rule
$ sudo iptables --list
$ sudo iptables -L
The iptables rules should persist from the previous configurations.
Example use case
Last updated