Table of Contents

Ubiquiti - Security Gateway - pfBlockerNG-like ad blocking

/config/user-data/update-adblock-dnsmasq.sh
#!/bin/bash
#
# original writeup: https://medium.com/server-guides/how-to-integrate-ad-blocking-using-a-unifi-usg-a165dc2233c1
#
 
# note this script needs to run as root, but that doesn't mean everything
# has to run as root
 
if [ "$(whoami)" != "root" ]; then
    echo "Script must be run as root"
    exit 1
fi
 
ad_list_url="https://pgl.yoyo.org/adservers/serverlist.php?hostformat=dnsmasq&showintro=0&mimetype=plaintext"
#The IP address below should point to the IP of your router or to 0.0.0.0
pixelserv_ip="0.0.0.0"
ad_file="/etc/dnsmasq.d/dnsmasq.adlist.conf"
temp_ad_file=$(su -c "mktemp /tmp/nobody.XXXXXX" nobody)
#temp_ad_file="/etc/dnsmasq.d/dnsmasq.adlist.conf.tmp"
 
sudo -u nobody curl -s "${ad_list_url}" | sed "s/127\.0\.0\.1/${pixelserv_ip}/" > ${temp_ad_file}
 
if [ -f "${temp_ad_file}" ]; then
    sed -i -e '/googleadservices\.com/d' ${temp_ad_file}
    sed -i -e '/doubleclick\.net/d' ${temp_ad_file}
    sed -i -e '/awin1\.com/d' ${temp_ad_file}
    cp -f  ${temp_ad_file} ${ad_file}
    chmod 644 ${ad_file}
 
else
    echo "Error building the ad list, please try again."
    exit 1
fi
 
rm -f ${temp_ad_file}
 
# before restarting, test the validation so we can remove the ad file if
# it's going to cause problems
 
if [ "$(dnsmasq --test >/dev/null 2>&1; echo $?)" == "0" ]; then
    /etc/init.d/dnsmasq force-reload
else
    rm -f ${ad_file}
    echo "Removing ad configuration due to validation errors"
    exit 1
fi

NOTE: Remember to make the script executable.


Check for errors

Run it manually to check for errors.

sudo sh -x update-adblock-dnsmasq.sh

Add the script to root's crontab

sudo crontab -e
56 4 * * 6 /config/user-data/update-adblock-dnsmasq.sh

Check root's crontab

sudo crontab -l

returns:

0 */24 * * * /opt/unifi/ips/bin/getsig.sh
56 4 * * 6 /config/user-data/update-adblock-dnsmasq.sh