Bash script to manage Linux Iptables
Here is an attempt to create an easy initialisation script for Iptables. The basic idea is this script sets up all basic rules including management on port 22 to all interfaces from any source address on your host, you can build on the rules from there. This script also allows you to use the Linux host as a router/gateway/firewall too you just need to enable kernel ip forwarding and then the respective rules in the script (see below and Github page for more details on kernel ip forwarding).
The script contains examples for basic port forwarding functions, SNAT, DNAT, support for multiple external IP’s and outbound NAT. It will also attempt to determine the Linux distribution so that it correctly saves the Iptables rules:
For Redhat based distros CentOS/Fedora it will use;
1 |
service iptables save |
For Ubuntu it will save the changes to a file /etc/iptables.rules and the two scripts /etc/network/if-pre-up.d/iptables-load and /etc/network/if-pre-down.d/iptables-save will load and save the rules respectively. You’ll need to add the scripts to those folders from the git repository.
To enable ip_forward and use your host as a router /proc/sys/net/ipv4/ip_forward must be set to 1. Linux will not forward packets through its interfaces unless this option is set to 1 be sure to make it **persistent**.
Check if its enabled:
1 |
cat /proc/sys/net/ipv4/ip_forward |
or
1 |
sysctl net.ipv4.ip_forward |
Enable without a reboot:
1 |
echo 1 > /proc/sys/net/ipv4/ip_forward |
or
1 |
sysctl -w net.ipv4.ip_forward=1 |
Persistently enable
Edit /etc/sysctl.conf and set;
net.ipv4.ip_forward = 1
Download the script (All dists) and related files for Ubuntu: