I've setup an OpenWRT travel router such that establishes a Wireguard tunnel and sends all traffic through that tunnel (config shown here.
Now it seems that some wifis I connect to pass on a DNS IP which is only accessible from within the hotel wifi IP range. This means that once the VPN is established, the upstream DNS used by OpenWRT's dnsmasq doesn't work anymore. As a consequence, neither the router nor the clients can resolve any DNS names anymore.
It works again on the clients if I manually give them the IP of my DNS in the VPN (or a public one like 8.8.8.8).
Question: Can I tell OpenWRT to use a different upstream DNS once the Wireguard VPN is established, and use the ISP provided DNS when the VPN is disconnected?
I had a similar question a while back:
https://forum.openwrt.org/t/wireguard-dns-in-21-02-x/110853/5
The short answer is that there are some methods to do this, but they're not quite as straightforward as I had hoped. I didn't end up implementing any methods of switching DNS servers in the end.
Well, as it's currently not really working great, I'd like to tweak things. From your thread, it looks like the "Configure hotplug to switch DNS dynamically based on the VPN connection status." option is what I'm looking for.
I can't seem to find the right Google search terms, though, to see how to do this with Wireguard.
Ok, so as a quick hack, I've put together the below script. Run once per minute via crontab, it appears to get the job done.
#!/bin/ash
function test_ip {
IP="${1}"
PING=$(ping -c 1 ${IP} 2>/dev/null | grep "1 packets received")
if [ -z "${PING}" ]; then
STATE="offline"
else
STATE="online"
fi
}
function is_our_dns_used {
DNSCHECK=$(cat "${RESOLV}" | grep "# WG script resolv.conf")
if [ -z "${DNSCHECK}" ]; then
OURDNS="no"
else
OURDNS="yes"
fi
}
# configure here:
WG_SERVER="10.7.0.1"
WG_DNS="192.168.1.102"
DEFAULT_DNS="9.9.9.9"
# OpenWRT resolv.conf file
RESOLV="/tmp/resolv.conf.d/resolv.conf.auto"
# our resolv.conf file
WG_RESOLV="/tmp/resolv.conf.d/resolv.conf.wg"
# original resolv.conf backup
BKP_RESOLV="/tmp/resolv.conf.d/resolv.conf.bkp"
# if needed, create WG script resolv.conf
if [ ! -f "${WG_RESOLV}" ]; then
echo "# WG script resolv.conf" >"${WG_RESOLV}"
echo "nameserver ${WG_DNS}" >>"${WG_RESOLV}"
fi
# Check if WG DNS is already active
is_our_dns_used
# Check if WG peer is online
test_ip "${WG_SERVER}"
if [ "${STATE}" = "offline" ]; then
if [ "${OURDNS}" = "yes" ]; then
if [ -f "${BKP_RESOLV}" ]; then
# restore old resolv.conf
mv -f "${BKP_RESOLV}" "${RESOLV}"
else
echo "${DEFAULT_DNS}" >"${RESOLV}"
fi
/etc/init.d/dnsmasq restart
fi
else
if [ "${OURDNS}" = "no" ]; then
if [ -f "${RESOLV}" ]; then
cp "${RESOLV}" "${BKP_RESOLV}"
fi
cp "${WG_RESOLV}" "${RESOLV}"
/etc/init.d/dnsmasq restart
fi
fi