Example iptables configuration for Web Servers

Setting up a host based firewall on your server to protect it from the nasties of the internet is a very simple step, that can easily backfire when you lock yourself out of SSH….

Below is a very simple script to setup basic firewall restrictions for a web server such as Apache or Nginx, allowing the below:

  • Allow all traffic from the server to its local loopback interface – this is needed for lots of system and application level functions
  • Allow ports 80 and 443 inbound access from all sources for your HTTP and HTTPS websites
  • Allow all connections outbound from your server to the internet and allow the reply traffic from those connection – this is needed to connect to repositories, APIs, send email etc.
  • Allow SSH inbound connections from the internet, but at the same time, blocking anyone trying to connect more than 4 times a minute in order to prevent easy SSH Brute Forcing

As with any firewall change, make sure you have appropriate methods to connect back to your server should the policy be incorrect, apply to widely or other failure. For most users, this would be via your hosting provider’s console access.

To use this, simply create a script file and then assign the owner execution rights. Once completed, save the below script contents to the file and then run the script.

vi firewall.sh <insert script contents from below> 
chmod u+x firewall.sh 
./firewall.sh

The script

#!/bin/bash 
 iptables -F 
 iptables -A INPUT -i lo -j ACCEPT 
 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT 
 iptables -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name SSH --rsource 
 iptables -A INPUT -p tcp -m tcp --dport 22 -m recent --rcheck --seconds 60 --hitcount 4 --rttl --name SSH --rsource -j REJECT --reject-with tcp-reset 
 iptables -A INPUT -p tcp --dport 22 -j ACCEPT 
 iptables -A INPUT -p tcp --dport 80 -j ACCEPT 
 iptables -A INPUT -p tcp --dport 443 -j ACCEPT 
 iptables -P INPUT DROP 
 iptables -P FORWARD DROP 
 iptables -P OUTPUT ACCEPT /sbin/service 
 iptables save iptables -L -v

 

Image credit: Jordan Wall

 

Leave a Reply

Your email address will not be published. Required fields are marked *