Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ergoz/5403ffafc7170853d3d97339856984eb to your computer and use it in GitHub Desktop.
Save ergoz/5403ffafc7170853d3d97339856984eb to your computer and use it in GitHub Desktop.
How to do really simple adblocking with the PowerDNS Recursor 4.x

First, clone the Mozilla focus project and make it fetch its list:

$ git clone https://github.com/mozilla/focus.git
$ cd focus
$ ./checkout.sh
$ cd Lists

This delivers several JSON formatted files, of which we are going to use disconnect-advertising.json. We'll filter out the good bits using jq, and create a Lua representation:

(
echo 'return{'
for a in $(jq '.[].trigger["url-filter"]' disconnect-advertising.json  | cut -f3 -d? | sed 's:\\\\.:.:g' | sed s:\"::)
do 
   echo \"$a\", 
done 
echo '}'
) > blocklist.lua    # ends up as return{"dom1.com", "dom2.com", .... "dom3.com"}

Next, we use this small file adblock.lua to tell the PowerDNS Recursor 4.x what to do:

adservers=newDS()

function preresolve(dq)
	if(not adservers:check(dq.qname)) then
		return false
	end
	
	if(dq.qtype == pdns.A) then
		dq:addAnswer(dq.qtype, "127.0.0.1")
	elseif(dq.qtype == pdns.AAAA) then
		dq:addAnswer(dq.qtype, "::1")
	end
	return true
end

adservers:add(dofile("blocklist.lua"))

Next add to recursor.conf:

lua-dns-script=adblock.lua

Now fire up the PowerDNS Recursor and access to the domain names from the Mozilla focus project will be replaced by a link to 127.0.0.1. Note: the actual blocking strategy used by Mozilla is a lot smarter, and includes knowledge of the website containing the ad!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment