06 February 2014

How To: Set basic iptables rules

Create a shell script which does the following:

  1. Delete all existing rules
  2. Set default chain policies
  3. Allow inbound SSH
  4. Allow inbound HTTP
  5. Allow outbound SSH

Create the set-iptables-rules.sh
# nano set-iptables-rules.sh

and copy-paste the following:

#Delete all existing rules
iptables -F

#Set default chain policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

#Allow incoming SSH
iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

#Allow incoming HTTP
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT

#Allow outgoing SSH
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Next, make the script executable and execute it to view the rules:
# chmod u+x set-iptables-rules.sh
# ./set-iptables-rules.sh

See all the rules with:

# iptables -L
Chain INPUT (policy DROP)
target     prot opt source      destination
ACCEPT     tcp  --  anywhere    anywhere      tcp dpt:ssh state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere    anywhere      tcp dpt:http state NEW,ESTABLISHED
ACCEPT     tcp  --  anywhere    anywhere      tcp spt:ssh state ESTABLISHED 

Chain FORWARD (policy DROP)
target     prot opt source      destination         

Chain OUTPUT (policy DROP)
target     prot opt source      destination
ACCEPT     tcp  --  anywhere    anywhere      tcp spt:ssh state ESTABLISHED
ACCEPT     tcp  --  anywhere    anywhere      tcp spt:http state ESTABLISHED
ACCEPT     tcp  --  anywhere    anywhere      tcp dpt:ssh state NEW,ESTABLISHED


Use it to reset iptables or to quickly set rules on a new server. Enjoy!

No comments: