[PATCH v2] wg-quick: use bind mount for DNS when no openresolv

Jason A. Donenfeld Jason at zx2c4.com
Thu Oct 26 15:41:25 CEST 2017


Version 2 uses the mount namespace trick, so that we don't leave
anything dangling under any circumstances, and chroot envrionments still
have the ability to bind mount /etc/resolv.conf to their chroots.

---
 src/tools/wg-quick.bash | 40 +++++++++++++++++++++++++++++++++++++---
 1 file changed, 37 insertions(+), 3 deletions(-)

diff --git a/src/tools/wg-quick.bash b/src/tools/wg-quick.bash
index def78af..b6903ec 100755
--- a/src/tools/wg-quick.bash
+++ b/src/tools/wg-quick.bash
@@ -83,6 +83,7 @@ add_if() {
 
 del_if() {
 	local fwmark
+	[[ $HAVE_SET_DNS -eq 0 ]] || unset_dns
 	fwmark="$(wg show "$INTERFACE" fwmark)"
 	DEFAULT_TABLE=0
 	[[ $fwmark != off ]] && DEFAULT_TABLE=$(( fwmark ))
@@ -130,12 +131,45 @@ set_mtu() {
 	cmd ip link set mtu $(( mtu - 80 )) dev "$INTERFACE"
 }
 
+HAVE_SET_DNS=0
 set_dns() {
-	[[ ${#DNS[@]} -eq 0 ]] || printf 'nameserver %s\n' "${DNS[@]}" | cmd resolvconf -a "tun.$INTERFACE" -m 0 -x
+	[[ ${#DNS[@]} -gt 0 ]] || return 0
+
+	if [[ $(resolvconf --version 2>/dev/null) == openresolv\ * ]]; then
+		printf 'nameserver %s\n' "${DNS[@]}" | cmd resolvconf -a "$INTERFACE" -m 0 -x
+	else
+		echo "[#] mount \`${DNS[*]}' /etc/resolv.conf" >&2
+		[[ -e /etc/resolv.conf ]] || touch /etc/resolv.conf
+		{ cat <<-_EOF
+			# This file was generated by wg-quick(8) for use with
+			# the WireGuard interface $INTERFACE. It cannot be
+			# removed or altered directly. You may remove this file
+			# by running \`wg-quick down $INTERFACE', or if that
+			# poses problems, run \`umount /etc/resolv.conf'.
+
+		_EOF
+		printf 'nameserver %s\n' "${DNS[@]}"
+		} | unshare -m --propagation shared bash -c "$(cat <<-_EOF
+			set -e
+			mount --make-private /tmp
+			mount -t tmpfs none /tmp
+			cat > /tmp/resolv.conf
+			mount -o remount,ro /tmp
+			mount -B /tmp/resolv.conf /etc/resolv.conf
+		_EOF
+		)"
+	fi
+	HAVE_SET_DNS=1
 }
 
 unset_dns() {
-	[[ ${#DNS[@]} -eq 0 ]] || cmd resolvconf -d "tun.$INTERFACE"
+	[[ ${#DNS[@]} -gt 0 ]] || return 0
+
+	if [[ $(resolvconf --version 2>/dev/null) == openresolv\ * ]]; then
+		cmd resolvconf -d "$INTERFACE"
+	else
+		cmd umount /etc/resolv.conf
+	fi
 }
 
 add_route() {
@@ -254,8 +288,8 @@ cmd_down() {
 	[[ " $(wg show interfaces) " == *" $INTERFACE "* ]] || die "\`$INTERFACE' is not a WireGuard interface"
 	execute_hooks "${PRE_DOWN[@]}"
 	[[ $SAVE_CONFIG -eq 0 ]] || save_config
-	unset_dns
 	del_if
+	unset_dns
 	execute_hooks "${POST_DOWN[@]}"
 }
 
-- 
2.14.2



More information about the WireGuard mailing list