IPTables Firewall Script for a Linux Server

My firewall script blocks traffic for both IPv4 and IPv6 protocols.

I open only port 80 for HTTP and port 22 for SSH.

Pings are allowed only from the HE.net IPv6 tunnel.

In addition, all IPs on the Spamhaus Drop List are blocked from accessing the server.

In the following steps, run all commands as root or using sudo.

  1. Get my firewall script.


    #description: Firewall



    case “$1” in


    #Flush all ipv4 chains

    $IPT -F

    $IPT-N Droplist

    #Script to add firewall rules to a linux system to completely block

    #all traffic to and from networks in the spamhaus drop list.

    rm /tmp/drop.lasso

    echo “Setting up Drop Lists”

    wget http://www.spamhaus.org/drop/drop.lasso -O /tmp/drop.lasso

    cat /tmp/drop.lasso \

    | sed -e ’s/;.*//’ \

    | grep -v ‘^ *$’ \

    | while read IP ; do

    echo “Adding $IP to DROPLIST”

    $IPT -I INPUT -s “$IP” -j DROPLIST






    $IPT -A INPUT -i eth0 -m state –state ESTABLISHED,RELATED -j ACCEPT

    #Accept HTTP server traffic

    $IPT -A INPUT -i eth0 -p tcp –dport 80 -j ACCEPT

    #Accept SSH traffic

    $IPT -A INPUT -i eth0 -p tcp –dport 22 -j ACCEPT

    #Accept PING only from HE.net tunnel

    $IPT -A INPUT -i eth0 -p icmp –source -j ACCEPT

    #Flush all ipv6 chains

    $IPT6 -F

    $IPT6 -A INPUT -i eth0 -m state –state ESTABLISHED,RELATED -j ACCEPT

    #Accept HTTP traffic

    $IPT6 -A INPUT -i eth0 -p tcp –dport 80 -j ACCEPT

    #Accept SSH traffic

    $IPT6 -A INPUT -i eth0 -p tcp –dport 22 -j ACCEPT

    #Drop everything else on ipv4 and ipv6

    $IPT -A INPUT -i eth0 -j DROP

    $IPT6 -A INPUT -i eth0 -j DROP

    exit 0



    $IPT -F

    $IPT6 -F

    exit 0



    echo “Usage: /etc/init.d/firewall {start|stop}”

    exit 1


  2. Change the public network interface if required. My firewall is set to work with eth0 as the interface.
  3. Save it as /etc/init.d/firewall
  4. Make it executable:

    chmod 700 /etc/init.d/firewall

  5. Run it:

    /etc/init.d/firewall start

  6. Add it to the programs to start at boot.

    On Debian, run:

    update-rc.d firewall defaults

Adapt step 6 accordingly based on the distribution that you use.

The Spamhaus Drop List needs to be refreshed each day.


crontab -e

and add the firewall script as shown in the following example:

0 6 * * * /etc/init.d/firewall stop && sleep 5 && /etc/init.d/firewall start

In the example, the firewall is stopped and restarted with the new drop list at 6 AM each day.


Leave a Reply

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