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 0.0.0.0 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.
- First enable SSH access via the UniFi controller: Settings ⇢ System Settings ⇢ Controller Configuration ⇢ Device SSH Authentication ⇢ enable Device SSH Authentication.
- Next, find the IP address of your USG: Devices ⇢ select the USG ⇢ copy the IP address.
- Log in to your USG via SSH with the account configured in step 1.
- 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.
Unpack the script, make it executable and run it twice.
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.
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.
- Create a file named ‘dnswhitelist’ (no extension) in the same directory as the getBlacklistHosts.sh script and add the domain(s) you want to whitelist, one per line. Rerun the getBlacklistHosts script for it to pick up the changes.
- You can also create a ‘dnsblacklist’ file in the same style to block extra domains.
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?