rss logo

How To block domains with netfilter


This How To shows how to use netfilter firewall (iptables command) to block domains (in fact all area) name like google, facebook and others.




Get the IPs to block

root@host:~# IP=$(host | grep "has address" | head -n 1 | awk '{print $4}') root@host:~# AS=$(whois -h $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 -- -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 -j FORWARD-ipblock

Insert IPs to our chain

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

List rules from specific Chain

root@host:~# iptables -L FORWARD-ipblock -n -v

Check blocked ips

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


Flush chain

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

Unlink chain

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

Delete chain

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


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 -j FORWARD-ipblock #Hi GAFA for DOMAINS in; do IP=$(host $DOMAINS | grep "has address" | head -n 1 | awk '{print $4}') AS=$(whois -h $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 -- -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 -d $i -j DROP echo "iptables -I FORWARD-ipblock -m iprange --src-range -d $i -j DROP" done done
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Contact :

contact mail address