IPTables quick setup script

Sometimes it is necessary, for example, to delete all IPTables rules and to add only the necessary, so for convenience, you can specify them in the script, and then execute it.

Switch to root user, in Ubuntu it can be done like this:

sudo -i

First, look at the existing rules (maybe some will be needed and they can be copied to the script):

iptables -nvL
iptables -L -t nat
iptables -L -t mangle

And actually below I will give an example of a script with imbued IPTables rules:

#!/bin/sh
# An example of cleaning and deleting all existing rules and chains
iptables -t filter -F
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -t filter -X
iptables -t nat -X
iptables -t mangle -X
iptables -X
# We will block all incoming and forward connections, allow all outgoing from the server
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow local interface
iptables -A INPUT -i lo -j ACCEPT
# Do not touch already established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Open the ports SSH, HTTP, HTTPS for all if needed
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# If necessary, you can allow all incoming connections to a specific IP address.
iptables -A INPUT -s 192.168.10.101 -j ACCEPT
# Allow PING
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT
# etc.

Make the script file executable:

chmod +x rules.sh

Run it:

./rules.sh

To conveniently save the rules in Ubuntu so that they are not reset after the system is restarted, you can install iptables-persistent:

apt-get install iptables-persistent

Then save the rules with the command:

service iptables-persistent save

You can tick save the current active rules to files:

iptables-save >/etc/firewall.conf
ip6tables-save >/etc/firewall6.conf

Create a file, for example, through the nano editor (Ctrl+X to exit the editor, y/n and Enter to save or discard changes):

nano -w /etc/network/if-up.d/00-iptables

Add content to it:

#!/bin/sh
iptables-restore < /etc/firewall.conf
ip6tables-restore < /etc/firewall6.conf

And make the file executable:

chmod 744 /etc/network/if-up.d/00-iptables

See also my article:
How to configure IPTables

Did my article help you? How about buying me a cup of coffee as an encouragement? Buy me a coffe.

Leave a comment

Leave a Reply