Network-wide ad blocking with UniFi

I use uBlock Origin in my browser to block ads and malware. uBlock is great but it doesn’t work on all my (and my housemates’) devices. A Raspberry Pi with Pi-hole installed would offer an extra layer of protection, but I wasn’t too keen on adding yet another device to my home network. Why not use my Ubiquiti UniFi Security Gateway (USG)? It’s already blocking threats via its built-in threat management module. The USG uses dnsmasq as DNS forwarder which means it can be used to sinkhole DNS queries. It will simply respond with 0.0.0.0 instead of the real IP address for blacklisted domains.

Connect

Warning, playing around with the USG’s command line can brick the device. I am not liable for any damages.

  1. First enable SSH access via the UniFi controller: Settings ⇢ Network Settings ⇢ Device Authentication ⇢ Enable SSH Authentication.
  2. Next, find the IP address of your USG: Devices ⇢ select the USG ⇢ copy the IP address.
  3. Log in to your USG via SSH with the account configured in step 1.
  4. Don’t forget to disable the SSH access when done, it’s safer to have it disabled.

Install

The following is based on a Ubiquity forum post (archived) by ‘unifiMynet’. The script can be downloaded from this Github repository.

Elevate to root privileges and download the getBlacklistHosts script.

  sudo -i
  cd /config/scripts
  curl 'https://raw.githubusercontent.com/unifiMynet/dnsmasqAdBlock/master/getBlacklistHosts.V8.5.zip' > getBlacklistHosts.zip
  

Unpack the script, make it executable and run it twice.

  unzip getBlacklistHosts.zip
  rm getBlacklistHosts.zip
  chmod +x getBlacklistHosts.sh
  ./getBlacklistHosts.sh ()
  

The script will generate a config file the first time it has run. Update the config file (if you want) and run it a second time to download the blocklists. Your DNS is now blocking the domains from the blacklists.

Crontab

These blocklists change from time to time: new domains are added, old ones removed. You can configure the Security Gateway to download the new lists on a regular basis. Add to following to your ‘config.gateway.json’ to update daily at 5 A.M.

  {
    "system": {
      "task-scheduler": {
        "task": {
          "hostblacklist": {
            "crontab-spec": "0 5 * * *",
            "executable": {
              "path": "/config/scripts/getBlacklistHosts.sh"
            }
          }
        }
      }
    }
  }
  

Whitelist/blacklist

Maybe you need access to a blocked domain. This is easy to do with a client-side blocker, like uBlock Origin, but a bit harder with a network-wide blocklist.

This post is open source. Did you spot a mistake? Ideas for improvements? Contribute to this post via Github. Thank you!