Securing Server with Iptables ( Block Except )

Securing Server with Iptables

Iptables is a great firewall when configured properly but sometimes you can lock yourself out with what you didn’t mean to. When you are starting to work on your firewall, it is always a good idea to create a cron job that will stop iptables every 2 minutes. So that even if you lock yourself out, it’s just for two minutes and after that you can work on it to fix the problem. once finished testing you can remove the cron.

Crontab To Stop Iptables ( In case things go wrong )
*/2 * * * *   /sbin/service iptables stop
Now Comes the Show…..

Few Important Things :

Dont panic if you lock yourself out… You will be fine in 2 minutes..

Review the rules before you apply ( to avoid 2 min. down time )

If you are allowing few things and blocking everything else, make sure you have allowed both inbound and outbound traffic for those services you want to allow access.

Be sure to allow both inbound and outbound for your ssh access, at least for your ip.

Here Comes the …………Rule :

Allow anything that is new or established:
-A INPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT

  1. Aceept Everything on LoopBack
    iptables -A INPUT -i lo -j ACCEPT
  2. Allow DNS Lookup from server.
    iptables -A INPUT -p udp --sport 53 -j ACCEPT
  3. Accept Connection to SSH
    iptables -A INPUT -p tcp --dport  22 -j ACCEPT
    or for specific ip only :
    iptables -A INPUT -p tcp -s <ip Addr> --dport 22 -j ACCEPT
  4. Now Drop Everything, please note if you need to accept anything in the INPUT should go before this line. Anything after this line will not be granted access in the Inbound Traffic.
    iptables -A INPUT -j DROP
    If you want to be even more restrictive you can also block outbound traffic. It is similar to inbound traffic but you just have to create same rules in the output chain .
    iptables -A OUTPUT -o lo -j ACCEPT

iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

<br></br>
iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT```

`iptables -A OUTPUT -j DROP`


# ** Some sample rules of interest :**

**Allow ICMP Requests :**  
`iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT`  
**Allowing multiple ports in one line :**  
`iptables -A INPUT -p tcp -m multiport --dport 80,443 -j ACCEPT`