Is it possible to remove my default gateway from /etc/resolv.conf after successful VPN connection?

This is a well known bug of NetworkManager, specifically it is #1211110. It goes back to Ubuntu 13.04 up to 16.04 and to a worse extent to Ubuntu 16.10.

It seems that I do not have DNS leak issue with my current configuration.

Then consider yourself pretty lucky. :) Most users (including myself) experienced severe DNS leaks and tried different approaches to solve them.

Here are some approaches suggested in the bug report (summarized):

Comment #22 by Mac Bassett

Make a backup copy of this NetworkManager file:

sudo cp /usr/lib/NetworkManager/nm-openvpn-service-openvpn-helper /usr/lib/NetworkManager/nm-openvpn-service-openvpn-helper.orig

Add the following 3 lines to the file.

#!/bin/bash
/etc/openvpn/update-resolv-conf $@
/usr/lib/NetworkManager/nm-openvpn-service-openvpn-helper.orig $@

Then:

sudo chmod +x /usr/lib/NetworkManager/nm-openvpn-service-openvpn-helper

Caveat: you need to run the following command after disconnecting the VPN.

sudo script_type=down dev=tun0 /etc/openvpn/update-resolv-conf

Comments #27 and #29 by myself

Edit your VPN connection (via NM) and set up static DNS, for example using Google servers:

8.8.8.8, 8.8.4.4

This way, the DNS request is sent through an external IP, hence it is routed using the VPN.

Then also set up your wireless connection to use those static DNS servers.

Comment #31 by DaveHenson

Run openvpn through the command line.


(... some other cumbersome solutions that I won't discuss here ...)


Comment #81 by Çağatay Yüksel

Remove this configuration file:

sudo rm -rf /etc/resolv.conf

Add this line to the [main] section of /etc/NetworkManager/NetworkManager.conf:

dns=dnsmasq

If you have the dnsmasq package installed, you should make sure the dnsmasq service is not enabled otherwise this will not work. You should also reboot.

The real solution

This bug has been fixed in Ubuntu 17.04. Rather than trying random patches on your system, it is probably a better idea to simply upgrade. :)


Update 2 I wrote simple straightforward dirty dispatcher and placed it in /etc/NetworkManager/dispatcher.d/03vpn:

#!/bin/sh -e
RESOLV_CONF=`readlink /etc/resolv.conf`
ROUTER_IP="nameserver 192.168.3.1"

logger -t DNS-antileak "start"
# disable local router IP in /etc/resolv.conf
if [ "$2" = "vpn-up" ]; then
    sed -i "s/$ROUTER_IP/#$ROUTER_IP/g" $RESOLV_CONF
    logger -t DNS-antileak "disabled $ROUTER_IP on vpn-up"
fi 

if [ "$2" = "vpn-down" ]; then
   sed -i "s/#$ROUTER_IP/$ROUTER_IP/g" $RESOLV_CONF
    logger -t DNS-antileak "enabled $ROUTER_IP on vpn-down"
fi 
logger -t DNS-antileak "end"

exit 0

It may be activated with

sudo chown root:root /etc/NetworkManager/dispatcher.d/03vpn
sudo chmod 755 /etc/NetworkManager/dispatcher.d/03vpn

I tested it with OpenVPN and PPTP connections.

Also I found other DNS-leak tests: Whoer and WhatLeaks.