Level 1
0 / 100 XP

How to save iptables Rules Permanently

Saving iptables Rules

If you're using a distribution that doesn't have iptables-persistent or a similar tool, you can save your IP tables by using the iptables-save to dump your config to a file, write a script to use iptables-restore to add the rules again every time the system boots.

To have our script that we will make automatically executed, we will need to make sure the ifupdown package is installed on our system:

sudo apt install ifupdown

Installing this package ensures when we place our bash script in the /etc/network/if-pre-up.d/ directory, it will be executed automatically at boot.

Creating the backup file

Now run the following commands to save our newly created iptables rules to a file, then move that file into the /etc/iptables directory:

__

If the /etc/iptables directory does not exist, create it with the mkdir command

Bash
# Create the rules file sudo iptables-save > rules.v4 # Move the file to the iptables directory sudo mv rules.v4 /etc/iptables/rules.v4

The process of creating a backup file will need to be completed each time we update the firewall rules.

Create a Script to Load Rules on Boot :

Create a script in /etc/network/if-pre-up.d/ to load the rules when the network interface comes up:

sudo nano /etc/network/if-pre-up.d/iptables

Add the following lines to the script:

Bash
#!/bin/sh /sbin/iptables-restore < /etc/iptables/rules.v4

Make the script executable:

sudo chmod +x /etc/network/if-pre-up.d/iptables

Now we can safely reboot our server, and when we run iptables -L we should see our rule for port 22 still listed in the Input chain.