Skip to main content

DNS over HTTPS w/ cloudflared

Installation & Configuration

Cloudflare does a lot for me, I'm using their DNS hosting, as well as using them for upstream DNS over HTTPS using their cloudflared utility. I've had some reliability issues with it, though, so I'm documenting how I got through it.

1. Install cloudflared

Follow the instructions on Cloudflare's website to get cloudflared installed
https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation

2. Configure cloudflared options

We'll set up a file for cloudflared to use for it's command line parameters

echo "CLOUDFLARED_OPTS=--port 5053 --upstream https://security.cloudflare-dns.com/dns-query" | sudo tee /etc/default/cloudflared

I'm hosting cloudflared on the same system as my PiHole (which is using port 53), so I adjusted the port from the default. Also, I'm taking advantage of Cloudflare's 1.1.1.1 for Families, which has malware-protected DOH Client services. You can read about these here.

3. Create the Watchdog

My personal issue with cloudflared is that when the internet blips the service never seems to recover until you bounce it. This Systemd watchdog will allow us to perform DNS tests against cloudflared, restart when faulted, and keep restarting it until the service is properly alive.

Create the watchdog file and add the script contents:

sudo touch /usr/local/bin/cloudflared-watchdog
sudo chmod +x /usr/local/bin/cloudflared-watchdog
sudo vim /usr/local/bin/cloudflared-watchdog

copy in the below content

#!/usr/bin/env bash

watchdog() {
	while(true); do
		result=$(dig @127.0.0.1 -p5053 dohtest.ljlapierre.com +short +time=1 +tries=3)
		if [[ $? -eq 0 && -n "$result" ]]; then
			/bin/systemd-notify WATCHDOG=1;
		fi
		sleep 10
	done
}

watchdog &

My "dohtest" DNS entry is there just to have a small TTL, 2 minutes. cloudflared will cache longer TTLs, and I want the daemon to figure out it's broken as soon as possible.

4. Create the Systemd service

Lastly, we'll set up the Systemd service, and test.

sudo adduser --system --home / --no-create-home cloudflared
sudo vim /etc/systemd/system/cloudflared.service
[Unit]
Description=cloudflared DNS over HTTPS proxy
After=syslog.target network-online.target

[Service]
Type=simple
User=cloudflared
EnvironmentFile=/etc/default/cloudflared
ExecStart=/usr/local/bin/cloudflared proxy-dns $CLOUDFLARED_OPTS
ExecStartPost=/usr/local/bin/cloudflared-watchdog
Restart=always
WatchdogSec=30
NotifyAccess=all
KillSignal=SIGKILL

[Install]
WantedBy=multi-user.target

Notice the WatchdogSec & ExecStartPost. When the service starts it'll begin making checks at the interval specified in the infinite loop of the watchdog. If the watchdog doesn't hear anything for 30 seconds it will bounce the service.

Reporting False Positives

If you find Cloudflare for Families is falsely removing a domain, you can report it here: https://report.teams.cloudflare.com