unpredicta

technology, sound, and design

pfSense


blocking ad servers


pfSense is a powerful, yet intuitive, FreeBSD-based firewall distribution designed to run on embedded or repurposed systems. It is one of two notable forks (the other being OPNsense) of Manuel Kasper's now-discontinued m0n0wall project.

Blocking ad servers with pfSense is rather easy provided you have a clearly delimited list. Just as a disclaimer, I'm not writing this to condone blocking ads, but some organizations do find it necessary.

Since pfSense uses Unbound as its default DNS resolver, network admins can enter host overrides to control DNS requests. Typically, this involves having to manually enter hostnames one at a time through the GUI interface.

To speed things up, I wrote a simple script, below, that takes in all the hostnames from a popular ad server list maintained by Peter Lowe (in this case, a single-line CSV copied from https://pgl.yoyo.org/as/) and outputs tagged XML which can be added to an existing Backup configuration file (only the DNS resolver area is needed). You can then import the updated config file back into pfSense through its Restore configuration feature. Isn't that cool?


<?php

// paste single-line CSV of hostnames to be blocked within the double quotes
$x "ads.example.com,ads.example.org,ads.example.net";

// define which ip address to redirect to, 127.0.0.1 (loopback) or 0.0.0.0 for instance
$ip "0.0.0.0";

// create the array
$a explode(",",$x);

// format the output
echo "<pre>";

for (
$i 0$i count($a); $i++) {
  echo 
htmlspecialchars("    <hosts>
        <host/>
        <domain>
$a[$i]</domain>
        <ip>
$ip</ip>
        <descr/>
        <aliases/>
    </hosts>
"
);
}

echo 
"</pre>";


?>

Here's an example of its output.