Basic iptables rules

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

iptables -P INPUT ACCEPT

Erase old iptables rules

iptables -F

Accept all connections to a local device

iptables -A INPUT -i lo -j ACCEPT

Allow all established connections to transmit

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

Allow SSH from all hosts

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

Allow HTTP from all hosts

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

Allow Redis from only known hosts

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

Allow mySQL from only known hosts

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

Drop everything else

iptables -P INPUT DROP
iptables -P FORWARD DROP

We trust the machine to send out valid traffic

iptables -P OUTPUT ACCEPT

Output the current rules

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

And save

iptables-save > /etc/iptables.rules

And setup for restore on reboot

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

Published:
April 17, 2013

Category
How To