DNS Ad Blocker
The DNS Advertisement blocker is an extension of blocking advertisements through the local hosts file, except using a real DNS server instead. There are various upsides to this approach such as the ability to blocking entire domains and sub-domains, and being able to block specific hosts on devices where editing the hosts file is not possible or practical (eg. a phone or tablet).
I do not recommend running this on a Raspberry Pi simply because a large list of zones will take a considerably long time to load and DNS queries may appear to be sluggish.
The Code
This blocker contains the following components:
- BIND DNS server
- A generator script that creates zones based on an ad list
- An ad list containing all servers to be blocked
- Optionally, a HTTP server to capture all redirected HTTP traffic
Setup
Install BIND with the following configuration in /etc/named.conf
/etc/named.conf
Make sure your named.conf contains at least the following:
include "/etc/named.advertisement.conf";
include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";
zone "." IN {
type hint;
file "named.ca";
};
Zones that are not defined should be looked up via root hints.
generate.sh
Create a script named generate.sh with the following:
# Normal advertisement zones
echo "" > /etc/named.advertisement.conf
for i in `cat adlist.txt` ; do
test -z $i && continue;
echo "zone \"$i\" {" >> /etc/named.advertisement.conf
echo "type master; file \"adredirect.zone\";" >> /etc/named.advertisement.conf
echo "};" >> /etc/named.advertisement.conf
echo "" >> /etc/named.advertisement.conf
done
# Or if using systemd: systemctl restart named.service
/etc/init.d/named restart
rndc status|grep OFF && rndc querylog
# systemctl restart named
sleep 4
rndc reload
rndc flush
adlist.txt
Get the latest adlist from DNS Ad Blocker/Ad List and place it into the adlist.txt file. Zones will be generated for each domain in this list which will also block all subdomains.
adredirect.zone
Create this zone file in /var/named/adredirect.zone. This zone will be referenced for every zone that is created.
Replace the IP address 9.11.9.11 with 0.0.0.0 if you do not plan on running a HTTP server to capture the ad requests.
$TTL 1h
@ IN SOA ns1.server. ns2.server. (
44 ; serial
3600 ; refresh
15M ; retry
1W ; expiry
1D ) ; minimum
@ NS ns1.server.
@ A 9.11.9.11
* A 9.11.9.11