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
/sbin/iptables -t filter -F
/sbin/iptables -t nat -F
/sbin/iptables -t mangle -F
/sbin/iptables -F
/sbin/iptables -t filter -X
/sbin/iptables -t nat -X
/sbin/iptables -t mangle -X
/sbin/iptables -X
# We will block all incoming and forward connections, allow all outgoing from the server
/sbin/iptables -P INPUT DROP
/sbin/iptables -P FORWARD DROP
/sbin/iptables -P OUTPUT ACCEPT
/sbin/ip6tables -P INPUT DROP
/sbin/ip6tables -P FORWARD DROP
/sbin/ip6tables -P OUTPUT ACCEPT
# Allow local interface
/sbin/iptables -A INPUT -i lo -j ACCEPT
/sbin/ip6tables -A INPUT -i lo -j ACCEPT
# Do not touch already established connections
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
/sbin/ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Open the ports SSH, HTTP, HTTPS for all if needed
/sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 80 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# If necessary, you can allow all incoming connections to a specific IP address.
/sbin/iptables -A INPUT -s 192.168.10.101 -j ACCEPT
# Allow PING
/sbin/iptables -A INPUT -p icmp -j ACCEPT
/sbin/iptables -A OUTPUT -p icmp -j ACCEPT
# etc.

Make the script file executable:

chmod +x rules.sh

Run it:

./rules.sh

See also my articles:
How to save IPTables rules
How to configure IPTables

Leave a comment

Leave a Reply