Network-Wide Ad-Blocking with UniFi

Implementing network-wide ad-blocking with a Ubiquiti UniFi Security Gateway (USG).

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 instead of the real IP address for blacklisted domains.

Connect to the Ubiquiti UniFi Security Gateway via SSH

Warning, playing around with the Ubiquiti 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 ⇢ System Settings ⇢ Controller Configuration ⇢ Device SSH Authentication ⇢ enable Device 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 dnsmasq Ad-Block Script

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 '' >

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

chmod +x
./ ()

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.

Configure 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 regularly. 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/"


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.

Countrywide Blocking

I would also like to implement some sort of countrywide blocking for added protection. I don’t understand <insert random language>, so what are the chances I would ever visit a website from that country? Is anyone blocking whole countries on their USG’s?