Fixing left-over VPN DNS entries

04 August 2024
For my remote workstations such as my laptop I use the NetworkManager StrongSwan plugin which on the whole is fine but sometimes it leaves stale name-server entries in my /etc/resolv.conf which causes name resolutions to be subject to a delay when the VPN is disconnected. In lieu of a proper fix I created a sed snippet that clears out the rogue nameserver entry and stuck it into a shell script. This file needs root permissions so the sed command needs to be run as root but Linux disallows shell scripts to be suid root, so a bit of trickery is needed so that this script can be run by non-root users, and this trickey amounts to setting up sudo to run the script without a password.

Safe method of suid root scripts

Firstly the script that has the sed snippet. The -i enables in-place mode rather than input and output being seperate files, and the regex deletes the offending line.

#!/bin/bash sed -i '/nameserver 192.168.2.3/d' /etc/resolv.conf

The next stage is to add a file in /etc/sudoers.d that contains the following, which allows the script to be run by sudo without a password. Needless to say replace remy with either your own username or one other catch-all such as %wheel.

remy ALL = (root) NOPASSWD: /home/remy/Scripts/vpn-fixresolve.sh

The final step is to wrap things up in a second shell script so there is no need to type sudo on the command-line.

#!/bin/bash /home/remy/Scripts/vpn-fixresolve.sh

Voila — in effect a suid root script!

Remarks

The next stage is to work out how to get NetworkManager to call an arbitrary script when a VPN is disconnected, but since this fault does not always show up I a happy running it manually. What annoyed me was having to type in my password every time I had to use it, and the above method gets around this.