rss logo

How To block domains with netfilter

Intro

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

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

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"

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
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Contact :

contact mail address