~/posts/adblocking-lua-generator-for-the-powerdns-recursor

Adblocking Lua generator for the PowerDNS Recursor

1 min read

Download all wanted block lists and place them as TXT in the same directory as the following script. You can find lots of them on firebog.net.

#!/bin/bash

# Output Lua script file
LUA_SCRIPT="all-domains-pdns-recursor-script.lua"

echo "return{" > "$LUA_SCRIPT"

# Download all blocklists as .txt from https://firebog.net and place then
# in the same directory

# Use awk to process all .txt files and append to LUA_SCRIPT
awk '!/^#/ && NF { 
        sub(/\r$/,"");  # Remove carriage return at the end of line
        if ($1 == "0.0.0.0" && NF > 1) 
            print "\"" $2 "\",";
        else if ($1 != "0.0.0.0") 
            print "\"" $1 "\",";
     }' *.txt >> "$LUA_SCRIPT"

echo "}" >> "$LUA_SCRIPT"

echo "Lua script written to $LUA_SCRIPT"

Move the output file to: /etc/powerdns/blocklist.lua

Create a new script /etc/powerdns/adblock.lua

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"))

Add this to the configuration (recursor.conf):

lua-dns-script=adblock.lua

Inspired by: https://gist.github.com/ahupowerdns/bb1a043ce453a9f9eeed