Setup Iptables Firewall

How to use iptables to create a simple firewall and allow traffic to private services only for trusted interfaces

Copy this script to /etc/init.d/firewall:

#!/bin/sh

iptables=`which iptables`

case "$1" in
   start)
      echo "Starting Firewall..."

      # clear old rules
      $iptables -t nat -F
      $iptables -t filter -F
      $iptables -X

      # default policy
      $iptables -P INPUT DROP
      $iptables -P FORWARD DROP
      $iptables -P OUTPUT ACCEPT

      # chain to mark IP as attacker
      $iptables -N ATTACK
      $iptables -A ATTACK -j LOG --log-prefix "Attack detected: "
      $iptables -A ATTACK -m recent --set -j DROP

      # allow all from trusted interfaces
      $iptables -A INPUT -i lo -j ACCEPT
      $iptables -A INPUT -i tun0 -j ACCEPT
      $iptables -A FORWARD -i lo -j ACCEPT
      $iptables -A FORWARD -i tun0 -j ACCEPT

      # filter attackers for 10 seconds but keep existing connections
      $iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
      #$iptables -A INPUT -m recent --update --seconds 10 -j DROP
      $iptables -A INPUT -m state --state INVALID -j ATTACK

      # drop NetBIOS quietly
      $iptables -A INPUT -p tcp --dport 137 -j DROP
      $iptables -A INPUT -p udp --dport 137 -j DROP
      $iptables -A INPUT -p tcp --dport 138 -j DROP
      $iptables -A INPUT -p udp --dport 138 -j DROP
      $iptables -A INPUT -p tcp --dport 445 -j DROP
      $iptables -A INPUT -p udp --dport 445 -j DROP

      # input filters with rate limits
      $iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 3 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 22 -m limit --limit 1/s --limit-burst 3 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 80 -m limit --limit 5/s --limit-burst 10 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 143 -m limit --limit 1/s --limit-burst 3 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 443 -m limit --limit 5/s --limit-burst 10 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 587 -m limit --limit 1/s --limit-burst 3 -j ACCEPT
      $iptables -A INPUT -p tcp --dport 10654 -m limit --limit 1/s --limit-burst 3 -j ACCEPT
      $iptables -A INPUT -p udp --dport 10654 -m limit --limit 1/s --limit-burst 3 -j ACCEPT

      # mark IP with invalid packet as attacker
      $iptables -A INPUT -m recent --set -j ATTACK

      ;;

   stop)
      echo "Stopping Firewall..."
      $iptables -t nat -F
      $iptables -t filter -F
      $iptables -X
      $iptables -P INPUT ACCEPT
      $iptables -P OUTPUT ACCEPT
      $iptables -P FORWARD ACCEPT
      ;;

   restart|reload|force-reload)
   $0 stop
   $0 start
      ;;

   *)
      echo "Usage: /etc/init.d/firewall (start|stop)"
      exit 1
      ;;
esac

exit 0