Basic iptables rules

17 Apr 2013 in TIL

This post is a quick one for me, as I'm sure I'll need these rules again at some point. I'll probably need to mix and match the rules, but these ones should cover most bases.

Allow input from all as the default policy

bash
iptables -P INPUT ACCEPT

Erase old iptables rules

bash
iptables -F

Accept all connections to a local device

bash
iptables -A INPUT -i lo -j ACCEPT

Allow all established connections to transmit

bash
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allow SSH from all hosts

bash
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Allow HTTP from all hosts

bash
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Allow Redis from only known hosts

bash
iptables -A INPUT -s 192.168.1.1 -p tcp --dport 6379 -j ACCEPT

Allow mySQL from only known hosts

bash
iptables -A INPUT -s 192.168.1.1 -p tcp --dport 3306 -j ACCEPT

Drop everything else

bash
iptables -P INPUT DROP
iptables -P FORWARD DROP

We trust the machine to send out valid traffic

bash
iptables -P OUTPUT ACCEPT

Output the current rules

bash
iptables -n -L -v --line-numbers

And save

bash
iptables-save > /etc/iptables.rules

And setup for restore on reboot

bash
if [[ "`cat /etc/network/interfaces`" != *pre-up* ]]
then
echo "pre-up iptables-restore < /etc/iptables.rules" >> /etc/network/interfaces
fi