Ubuntu – OpenVPN client not getting DNS information

dnsnetworkingopenvpnservervpn

I'm using an OpenVPN server running on a router installed with DD-WRT and I'm using it to route all traffic through the VPN server. I'm connecting to it from several devices: Windows laptop, android devices and linux machines. The problem I have now is recent and previously everything worked fine. This problem happens only on the client machines with linux (ubuntu 16.04). The ubuntu client doesn't get the DNS server addresses automatically. After some research, I've found out that I should add the following to the end of the client config:

script-security 2
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf

This didn't help so I've added also:

dhcp-option DNS a.b.c.d
dhcp-option DNS e.f.g.h

The IP's are taken from the router and it makes things working. Until now it was enough to have "redirect-gateway def1" in the client config.

I don't like this solution of adding the "dhcp-option DNS" commands because I have to watch for any changes of the DNS server. Is there any way to get rid of adding "dhcp-option DNS" option?

Best Answer

I had the same problem but managed to solve it using the following hack: Instead of up /etc/openvpn/update-resolv-conf I created a file named up.sh in /etc/openvpn. Run the command sudo gedit /etc/openvpn/up.sh and paste the following:

#! /bin/bash
DEV=$1

if [ ! -d /tmp/openvpn ]; then
mkdir /tmp/openvpn
fi
CACHE_NAMESERVER="/tmp/openvpn/$DEV.nameserver"
echo -n "" > $CACHE_NAMESERVER

dns=dns
for opt in ${!foreign_option_*}
do
eval "dns=\${$opt#dhcp-option DNS }"
if [[ $dns =~ [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} ]]; then
if [ ! -f /etc/resolv.conf.default ]; then
cp /etc/resolv.conf /etc/resolv.conf.default
fi

cat /etc/resolv.conf | grep -v ^# | grep -v ^nameserver > /tmp/resolv.conf
echo "nameserver $dns" >> /tmp/resolv.conf
echo $dns >> $CACHE_NAMESERVER
cat /etc/resolv.conf | grep -v ^# | grep -v "nameserver $dns" | grep nameserver >> /tmp/resolv.conf
mv /tmp/resolv.conf /etc/resolv.conf

fi
done

Save it and run sudo chmod +x /etc/openvpn/up.sh Then create another file /etc/openvpn/down.sh and paste the following in it

#! /bin/bash
echo "Restoring original nameservers"
rm -f /etc/resolv.conf
ln -s /run/resolvconf/resolv.conf /etc/resolv.conf 
echo "Done restoring nameservers cheers"

Save it and run sudo chmod +x /etc/openvpn/down.sh

Now remove the lines:

script-security 2
up /etc/openvpn/update-resolv-conf
down /etc/openvpn/update-resolv-conf

And replace them with:

 script-security 2
    up /etc/openvpn/up.sh
    down /etc/openvpn/down.sh