How To : block domains address with netfilter

This How To shows how to use netfilter firewall in order to block domains (in fact all area) name like google facebook or others.

Intro

Configuration

Commands

Block

Get the IPs to block

root@host:~# IP=$(host google.com | grep "has address" | head -n 1 | awk '{print $4}')
root@host:~# AS=$(whois -h whois.cymru.com $IP | grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | awk '{print $1}')
root@host:~# whois -h whois.radb.net -- -i origin -T route AS"$AS" | grep route: | awk '{print $2}'

Use iptables new chain

As we can see above, there are a lot of addresses to block. In order to keep visibility in our iptables rules we will create a new iptables chain.

root@host:~# iptables -N FORWARD-ipblock
root@host:~# iptables -t filter -A FORWARD -m iprange --src-range 10.0.0.10-10.0.0.100 -j FORWARD-ipblock

Insert IPs to our chain

root@host:~# for ip in $(whois -h whois.radb.net -- -i origin -T route AS$AS| grep route: | awk '{print $2}'); do iptables -I FORWARD-ipblock -d $ip -j DROP; done

Check blocked ips

root@host:~# iptables -L -n -v | tr -s ' ' | grep -v "^ 0 0"

Unblock

Flush chain

root@host:~# iptables -F FORWARD-ipblock

Unlink chain

root@host:~# iptables -D FORWARD -m iprange --src-range 10.0.0.10-10.0.0.100 -j FORWARD-ipblock

Delete chain

root@host:~# iptables -X FORWARD-ipblock

Script

Script it for multiple domains

#! /bin/sh

#create a new iptables chain FORWARD-ipblock
iptables -N FORWARD-ipblock
#link FORWARD-ipblock chain to FORWARD chain
iptables -t filter -A FORWARD -m iprange --src-range 10.0.0.10-10.0.0.100 -j FORWARD-ipblock

#Hi GAFA
for DOMAINS in google.com amazon.com facebook.com apple.com; do
        IP=$(host $DOMAINS | grep "has address" | head -n 1 | awk '{print $4}')
        AS=$(whois -h whois.cymru.com $IP| grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" | awk '{print $1}')
        IPS_BLOCK=$(whois -h whois.radb.net -- -i origin -T route AS$AS| grep route: | awk '{print $2}')
        for i in $IPS_BLOCK; do
                iptables -I FORWARD-ipblock -m iprange --src-range 10.0.0.10-10.0.0.100 -d $i -j DROP
                echo "iptables -I FORWARD-ipblock -m iprange --src-range 10.0.0.10-10.0.0.100 -d $i -j DROP"
        done
done
Licence Creative Commons
This website http://shebangthedolphins.net is licensed to the public under a licence Creative Commons Attribution licence.
Contact :