Skip to content

Instantly share code, notes, and snippets.

@ahupowerdns
Last active June 27, 2023 18:05
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahupowerdns/bb1a043ce453a9f9eeed to your computer and use it in GitHub Desktop.
Save ahupowerdns/bb1a043ce453a9f9eeed 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!

@mdzidic
Copy link

mdzidic commented Feb 19, 2016

Hello,

I have problems when I try to load adblock.lua:

attempt to call global 'newDS' (a nil value)

@dmgeurts
Copy link

dmgeurts commented Nov 2, 2021

Hello,

I have problems when I try to load adblock.lua:

attempt to call global 'newDS' (a nil value)

Has anyone got a solution for this one?

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