Iptables are administration tools for ip4/ip6 packet filtering and nat.
The builten iptables rules for ubuntu are to allow traffic from every where to any where, to check run the command:
sudo iptables -L
To setup a firewall we will configure the iptables to block all the traffic from outside to the pc and then will allow the certain
traffic to some ports as for our need.
sudo iptables --fulsh
Now we will apply the general policy for our firewall, to block the all traffic from outside internet and allow form pc to the
outside:
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
If we running some servers like web server allow the people to connect to port 80 which is web server port, we will open this port
with iptables rule:
iptables -A INPUT -p tcp --sport 80 -j ACCEPT
Allow intranet (local LAN ) traffic between them:
iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT
iptables -A OUTPUT -s 192.168.0.0/24 -j ACCEPT
iptables -A INPUT -s 10.0.0.0/8 -j ACCEPT
iptables -A OUTPUT -s 10.0.0.0/8 -j ACCEPT
iptables -A INPUT -s 172.16.0.0/12 -j ACCEPT
iptables -A OUTPUT -s 172.16.0.0/12 -j ACCEPT
iptables -A INPUT -s 172.32.0.0/12 -j ACCEPT
iptables -A OUTPUT -s 172.32.0.0/12 -j ACCEPT
Enable established connections:
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
These are firewall rules i setup for my pc iptables-rules.sh
sudo chmod a+x iptables.rules.sh
Run the script:
sudo ./iptables-rules.sh
The script will apply all the rules and will setup the firewall.
sudo iptables-save > rules
The command will save the firewall to file rules, check with:
sudo cat rules
create a directory for example firewall in the /etc:
sudo mkdir /etc/firewall
copy the rules to this directory:
sudo cp rules /etc/firewall
Make a bash script 49firewall an put in a place to execute in every boot or every internet connection and restore the
firewall rules, this is 49firewall:
#!/bin/bash
iptables -F
iptables -X
iptables -Z
/sbin/iptables-restore < /etc/firewall/rules
The first three lines will delete the builten iptables rules and last line will restore the iptables rules from the file
/etc/firewall/rules.