🌐 Force all DNS traffic to Pi-hole on a USG Pro

I was looking for a way to force all DNS queries on my network to be pushed to my Pi-Hole no matter what hardcoded DNS servers were set up on the device. After a little research, I came across a couple of blog posts that pointed me in the right direction.

The main reason for this is not only that the kids are getting smarter to be able to adjust settings on their devices to bypass the Pi-Hole, but also I wanted to make sure all devices that jumped on my network were going through the same DNS servers for caching reasons. I also didn’t want to have to make sure I configured each device when added to my network.

In order to achieve this, I had to edit the config.gateway.json on my Controller. By adding the following bit of JSON code to the file located in /usr/lib/unifi/data/sites/default/ on the controller I was able to force all DNS traffic to be routed to my Pi-Hole even if someone were to do a direct dig command to another DNS server.

{
   "service": {
     "nat": {
         "rule": {
                "1": {
                    "description": "Redirect DNS queries to pihole",
                    "destination": {
                        "port": "53",
                        "address": "!10.0.1.23"
                    },
                    "inside-address": {
                        "address": "10.0.1.23",
                        "port": "53"
                    },
                    "source": {
                        "address": [
                                   "!10.0.1.23",
                                   ]
                    },
                    "inbound-interface": "eth0",
                    "protocol": "tcp_udp",
                    "type": "destination"
                },
                "5002": {
                    "description": "Translate reply back to pihole",
                    "destination": {
                        "address": "10.0.1.23",
                        "port": "53"
                    },
                    "outbound-interface": "eth0",
                    "protocol": "tcp_udp",
                    "type": "masquerade"
                }
            }
        }
    }
}

The IP address of my Pi-Hole is 10.0.1.23, you would need to change this accordingly. Also take note that I am using eth0 since I have the USG Pro, if you are using the Ubiquiti Unifi Security Gateway then it would be eth1 instead.

After adding that code to the config.gateway.json file I was able to reprovision my USG Pro and it picked up the new settings.