Prefer VPN DNS, with a Designated Direct Fallback

3 Total views across this article’s versions; includes the historical baseline where available.

Compare all DNS policies.

The previous example takes a strict approach: upstream DNS requests use the VPN, and if the VPN is unavailable, those requests fail. That may be exactly what you want when keeping DNS off the direct Internet connection is more important than keeping name resolution available.

But you may prefer a more permissive approach. For example, you already have a designated DNS provider that you want to use for your normal Internet connection. When the VPN is working, you want to use the VPN provider’s DNS instead. If the VPN fails, you want DNS to return to your designated provider over the direct connection.

This walkthrough gives you those two configurations and the commands to select between them. You make the change explicitly. A missing VPN route does not automatically select the direct provider; failure detection and automatic switching are deferred.

Open the Walkthrough Shell

From your ordinary administrator account, open a root login shell first:

sudo -i

Use Bash in that root shell for the remaining setup, checks, and withdrawal. Do not nest another root shell when following a shared section. Confirm root access and retain the original account for comparison tests:

set -euo pipefail
test "$(id -u)" -eq 0
ORDINARY_USER="${SUDO_USER:-}"
test -n "$ORDINARY_USER"
test "$ORDINARY_USER" != root
test "$ORDINARY_USER" != newsvpn
test "$(id -u "$ORDINARY_USER")" -ne 0
id "$ORDINARY_USER"

Stop if the account is not your intended ordinary user. Administrative commands now run without repeated sudo. runuser -u ... -- deliberately runs a test under the named account; testing as root would not exercise the reader’s UID guard. When following a linked foundation check, keep its ordinary-user tests under ORDINARY_USER too; a root request is not the ordinary-account comparison. The examples require runuser as well as the tools listed below. Root login shells, account-specific commands

1. Start with Two Working Paths

Choose your normal DNS provider first. This is the provider you will explicitly select for direct mode; it is not whichever DNS server happens to be offered by the network.

Use one Ubuntu host with Bash, iproute2, iptables/ip6tables, getent, dig, tcpdump, and an existing systemd-resolved listener at 127.0.0.53. Ordinary applications already use that resolver. Ubuntu 24.04 is the proposed lab baseline, not a tested-platform claim.

Begin with the packet-marks foundation: dedicated account newsvpn, mark 0x100, table 101, source translation, return path, and independent IPv4/IPv6 account guards. Keep the priority-zero local routing rule. The shared resolver uses the main table under its own account; ordinary application connections remain direct.

Use this as an alternative lab configuration. Other examples’ DNS chains, host routes, private resolver launchers, and stub-guard replacements must not be active. Record the existing firewall, routes, and each link’s DNS servers, domains, and default-route setting. Reconcile other DNS links, global servers, and competing domains before starting. Keep managers from replacing this lab configuration during the exercise.

Run setup in one dedicated Bash shell. Replace all placeholders and topology values:

set -euo pipefail
DIRECT_IF='eth0'
DIRECT_GW='192.168.50.1'
DIRECT_ADDR='192.168.50.10'
DIRECT_DNS='REPLACE_WITH_NORMAL_PROVIDER_IPV4'
VPN_IF='tun0'
VPN_ADDR='10.8.0.2'
VPN_DNS='REPLACE_WITH_VPN_PROVIDER_DNS_IPV4'
DNS_STUB='127.0.0.53'
NEWS_UID=$(id -u newsvpn)
test "$NEWS_UID" -ne 0
test "$DIRECT_DNS" != 'REPLACE_WITH_NORMAL_PROVIDER_IPV4'
test "$VPN_DNS" != 'REPLACE_WITH_VPN_PROVIDER_DNS_IPV4'
test "$DIRECT_DNS" != "$VPN_DNS"
ip -4 rule show
ip -4 route show table main
ip -4 route show table 101
resolvectl status
iptables-save
ip6tables-save

Use distinct, valid nonlocal IPv4 resolver addresses, separate from VPN transport endpoints. Verify their availability yourself. The example uses a fixed-address point-to-point VPN and a directly reachable LAN gateway. New chain names and DNS host routes must be unused; do not flush or overwrite existing configuration. set -e is not automatic rollback.

The scope is ordinary IPv4 UDP/TCP DNS. Upstream IPv6 DNS and port 853 are blocked. Independently configured DoH and proxy resolution must be disabled or follow the chosen policy; these rules cannot identify DNS hidden inside HTTPS. Existing encrypted-DNS arrangements, multicast discovery, containers, and forwarding need separate treatment.

Record the Original DNS Settings

Save the full resolvectl status output shown above outside this shell. Record all DNS servers and search/routing domains for DIRECT_IF and VPN_IF, including empty lists. Use the complete DNS Servers list, not just Current DNS Server. Preserve server order, any server qualifiers, and the ~ prefix on routing domains. Prepare the corresponding restore commands before changing anything.

Leave the resolver’s default-route setting untouched. The selected link’s ~. domain already selects ordinary unicast DNS within this example’s stated scope; other DNS links, global servers, and competing domains must have been reconciled. This avoids replacing an automatically determined setting with an explicit value during withdrawal. It does not change the default IP route.

Keep the same interfaces present and the lab configuration stable. If a manager changes these settings or an interface is recreated, stop and inspect its configuration owner instead of guessing the original values.

2. Prepare the DNS Restrictions

Prepare VPN, direct, and closed checks, then attach a selector initially pointing to closed. The creation helper avoids repeating the same UDP/TCP rules. It runs only when called; it is not a controller or repeatable installer.

make_dns_mode() {
    local chain="$1" out_if="$2" server="$3" protocol
    iptables -w -N "$chain" || return 1
    for protocol in udp tcp; do
        iptables -w -A "$chain" -o lo -d "$DNS_STUB" -p "$protocol" --dport 53 -j RETURN || return 1
        if test "$out_if" != closed; then
            iptables -w -A "$chain" -o "$out_if" -d "$server" -p "$protocol" --dport 53 -j RETURN || return 1
        fi
        iptables -w -A "$chain" -p "$protocol" -m multiport --dports 53,853 -j REJECT || return 1
    done
    iptables -w -A "$chain" -j RETURN
}
make_dns_mode DH_FB_DIRECT "$DIRECT_IF" "$DIRECT_DNS"
make_dns_mode DH_FB_VPN "$VPN_IF" "$VPN_DNS"
make_dns_mode DH_FB_CLOSED closed unused
iptables -w -N DH_FB_ACTIVE
iptables -w -A DH_FB_ACTIVE -j DH_FB_CLOSED
ip6tables -w -N DH_FB_DNS6
ip6tables -w -A DH_FB_DNS6 -p udp -m multiport --dports 53,853 -j REJECT
ip6tables -w -A DH_FB_DNS6 -p tcp -m multiport --dports 53,853 -j REJECT
ip6tables -w -A DH_FB_DNS6 -j RETURN
iptables -w -I OUTPUT 1 -m comment --comment dns-fallback4 -j DH_FB_ACTIVE
ip6tables -w -I OUTPUT 1 -m comment --comment dns-fallback6 -j DH_FB_DNS6

DH_FB_ACTIVE must contain exactly one rule. Each mode permits the local stub; VPN and direct modes also permit their own provider/interface pair. Other upstream DNS is rejected. RETURN continues through the remaining firewall, not around it. Keep both DNS jumps and the reader guard before broad accepts, including established-connection accepts. Existing local-stub and reply rules still apply.

3. Prepare Both DNS Routes

Keep one usable route and one terminal route for each provider:

ip -4 route add unreachable "$DIRECT_DNS/32" metric 32767
ip -4 route add "$DIRECT_DNS/32" via "$DIRECT_GW" dev "$DIRECT_IF" src "$DIRECT_ADDR" metric 100
ip -4 route add unreachable "$VPN_DNS/32" metric 32767
ip -4 route add "$VPN_DNS/32" dev "$VPN_IF" src "$VPN_ADDR" metric 100
ip -4 route get "$DIRECT_DNS"
ip -4 route get "$VPN_DNS"

Both paths stay installed. Resolver selection chooses the provider; the firewall mode permits its path. If a usable route disappears, its unreachable host route prevents a broader main-table route from taking over. Earlier rules must not divert the shared resolver into another table. The routes cover all traffic to these addresses; src selects a preferred source rather than rewriting one. Verify actual source and reply traffic.

4. Let the Reader Use the Local Resolver

The original reader guard blocks loopback too. Build a replacement that permits only DNS to the existing stub and still drops other output outside the VPN. Attach it before removing the original guard:

iptables -w -C OUTPUT -m owner --uid-owner "$NEWS_UID" ! -o "$VPN_IF" -m comment --comment newsvpn-guard4 -j DROP
ip6tables -w -C OUTPUT -m owner --uid-owner "$NEWS_UID" -m comment --comment newsvpn-guard6 -j DROP
iptables -w -N DH_NEWS_STUB
iptables -w -A DH_NEWS_STUB -o lo -d "$DNS_STUB" -p udp --dport 53 -j RETURN
iptables -w -A DH_NEWS_STUB -o lo -d "$DNS_STUB" -p tcp --dport 53 -j RETURN
iptables -w -A DH_NEWS_STUB ! -o "$VPN_IF" -j DROP
iptables -w -A DH_NEWS_STUB -j RETURN
iptables -w -I OUTPUT 1 -m owner --uid-owner "$NEWS_UID" -m comment --comment newsvpn-stub-guard4 -j DH_NEWS_STUB
iptables -w -S DH_NEWS_STUB
iptables -w -S OUTPUT
iptables -w -D OUTPUT -m owner --uid-owner "$NEWS_UID" ! -o "$VPN_IF" -m comment --comment newsvpn-guard4 -j DROP

Keep both the replacement and host-wide DNS check ahead of broad accepts. The IPv6 account guard, mark, table, and source translation remain unchanged. Run the reader under newsvpn with the host’s resolver configuration, not Example 1’s private launch environment. Requests to the stub stay local; its separate upstream packets follow the selected DNS mode.

5. Select a Mode Explicitly

Your host keeps using its existing local resolver. The change is which upstream provider and route are active. Select VPN mode when you want DNS to use the VPN; select direct mode when you deliberately allow DNS outside it. Once the VPN route is usable again, you can explicitly select VPN mode.

This model favors keeping DNS available, but the privacy protection changes while direct mode is active. Allowing DNS to fall back does not mean that VPN-selected application traffic should fall back too.

Define the helper in the same shell. It closes upstream DNS first, changes resolver selection, then opens only the chosen provider/path:

dns_mode='closed'
set_dns_mode() {
    local requested="$1" active_if inactive_if server target
    case "$requested" in
        direct)
            active_if="$DIRECT_IF"; inactive_if="$VPN_IF"
            server="$DIRECT_DNS"; target=DH_FB_DIRECT
            ;;
        vpn)
            active_if="$VPN_IF"; inactive_if="$DIRECT_IF"
            server="$VPN_DNS"; target=DH_FB_VPN
            ;;
        *) return 2 ;;
    esac
    iptables -w -R DH_FB_ACTIVE 1 -j DH_FB_CLOSED || return 1
    dns_mode='closed'
    if ip link show dev "$inactive_if" >/dev/null 2>&1; then
        resolvectl dns "$inactive_if" '' || return 1
        resolvectl domain "$inactive_if" '' || return 1
    fi
    resolvectl dns "$active_if" "$server" || return 1
    resolvectl domain "$active_if" '~.' || return 1
    iptables -w -R DH_FB_ACTIVE 1 -j "$target" || return 1
    dns_mode="$requested"
    printf 'DNS mode: %s\n' "$dns_mode"
}
set_dns_mode direct
resolvectl status
iptables -w -S DH_FB_ACTIVE

Now choose the mode you want:

set_dns_mode vpn
set_dns_mode direct

The initial call selected direct mode. The two blocks above are alternatives, not an automatic sequence. The helper never creates a tunnel, probes a service, or decides when to switch. Losing the VPN route leaves VPN-mode DNS blocked until you explicitly select direct mode. Route selection alone cannot replace one provider’s address with another.

If a resolver update fails, the helper leaves DNS closed. If closing fails, it stops before changing resolver selection; inspect the existing policy. Do not continue after either error. Cached answers may still work. ~. is a DNS routing domain, not an IP route. These temporary settings can be overwritten by a manager or lost with an interface.

6. Check Both Modes and Route Loss

Allow expected diagnostic failures in the walkthrough shell. Use fresh, permitted names absent from hosts files and caches:

set +e
TEST_NAME='REPLACE_WITH_FRESH_PERMITTED_FQDN.'
OTHER_DNS4='REPLACE_WITH_OTHER_PERMITTED_RESOLVER_IPV4'
OTHER_DNS6='REPLACE_WITH_PERMITTED_RESOLVER_IPV6'
ip -4 route get "$DNS_STUB" mark 0x100

Require the marked stub route to remain local. Replace the test placeholders; OTHER_DNS4 must differ from both configured providers. Check every mode-selection and restoration result explicitly.

In another terminal, first open a root shell with sudo -i, then capture each test’s DNS traffic:

tcpdump -ni any -vv 'port 53 or port 853'

In each mode, check both application contexts and inspect the selector/counters:

runuser -u "$ORDINARY_USER" -- getent ahostsv4 "$TEST_NAME"
runuser -u newsvpn -- getent ahostsv4 "$TEST_NAME"
runuser -u "$ORDINARY_USER" -- dig -r -4 @"$DNS_STUB" +notcp +ignore +time=2 +tries=1 "$TEST_NAME" A
runuser -u "$ORDINARY_USER" -- dig -r -4 @"$DNS_STUB" +tcp +time=2 +tries=1 "$TEST_NAME" A
runuser -u newsvpn -- dig -r -4 @"$DNS_STUB" +notcp +ignore +time=2 +tries=1 "$TEST_NAME" A
runuser -u newsvpn -- dig -r -4 @"$DNS_STUB" +tcp +time=2 +tries=1 "$TEST_NAME" A
resolvectl status
iptables -w -S DH_FB_ACTIVE
iptables -w -nvL DH_FB_DIRECT
iptables -w -nvL DH_FB_VPN
iptables -w -nvL DH_FB_CLOSED

Require both groups’ upstream queries to use only the active provider and interface, with the correct source and replies. The local stub’s reply or a successful exit code alone is insufficient evidence. From the root shell, use the ordinary-account commands below to query the active provider directly over both transports, substituting its address for ACTIVE_DNS:

ACTIVE_DNS="$VPN_DNS"
runuser -u "$ORDINARY_USER" -- dig -r -4 @"$ACTIVE_DNS" +notcp +ignore +time=2 +tries=1 "$TEST_NAME" A
runuser -u "$ORDINARY_USER" -- dig -r -4 @"$ACTIVE_DNS" +tcp +time=2 +tries=1 "$TEST_NAME" A

Use ACTIVE_DNS="$DIRECT_DNS" in direct mode. A TCP query to the stub does not prove TCP upstream. Repeat these ordinary-account queries against the inactive provider and OTHER_DNS4: they must be rejected. Repeat with dig -r -6 @"$OTHER_DNS6" over UDP and TCP, and with port -p 853 against the active provider. Require matching rejection evidence and no delivered query. An IPv6 test without a usable route is inconclusive unless counters or a capable lab establish enforcement.

Exercise the Explicit Fallback

Select VPN mode successfully, then remove only its preferred DNS route:

ip -4 route del "$VPN_DNS/32" dev "$VPN_IF" src "$VPN_ADDR" metric 100
ip -4 route show table main exact "$VPN_DNS/32"
ip -4 route get "$VPN_DNS"

Require the usable entry to be absent and fresh upstream lookups to fail without direct escape. If a manager reinstalls it, the intended fault was not established. Explicitly run set_dns_mode direct; repeat fresh lookups and require the designated direct provider. DNS switching must not change the reader’s application routing.

Verify the VPN interface and source address are unchanged, then restore its route:

ip -4 route add "$VPN_DNS/32" dev "$VPN_IF" src "$VPN_ADDR" metric 100

Run set_dns_mode vpn and repeat the successful checks. For direct-path failure, select direct mode and remove only its preferred route:

ip -4 route del "$DIRECT_DNS/32" via "$DIRECT_GW" dev "$DIRECT_IF" src "$DIRECT_ADDR" metric 100
ip -4 route show table main exact "$DIRECT_DNS/32"
ip -4 route get "$DIRECT_DNS"

Fresh upstream DNS must fail without choosing another provider. Verify the direct interface/address/gateway, restore the route, and repeat the baseline:

ip -4 route add "$DIRECT_DNS/32" via "$DIRECT_GW" dev "$DIRECT_IF" src "$DIRECT_ADDR" metric 100

Leave terminal routes and every guard installed throughout. Stop on restoration errors. Test fresh real reader and ordinary application connections too; use the packet-marks foundation’s known-address and table-101 failure checks to prove the reader cannot escape directly. Removing a DNS host route alone is not a VPN outage. Confirm the reader cannot use unrelated loopback services.

VPN operation, availability monitoring, and automatic switching remain separate. None is added here.

Compare the Public Exit Addresses

  1. Visit WhatIsMyIP.com in your ordinary browser and note the displayed public IPv4 address.
  2. Visit the same website in a browser using the VPN-selected account’s route and compare the displayed IPv4 address. It should show the application VPN’s public exit address.

Use the separate DNS, route-loss, and application-isolation checks for diagnosis.

Check the Local DNS Exception

The shared-stub exception must not grant access to other loopback services. Choose an existing, permitted test listener on a different TCP port. First confirm the ordinary account can connect to that exact loopback address and port, then require the same attempt as newsvpn to be blocked. Compare the DH_NEWS_STUB drop counter and capture evidence before and after. A refusal from an unused port proves nothing about the guard. Keep the listener and its test method unchanged between attempts; do not create a proxy or broaden an allowance for this check.

7. Withdraw the Lab Configuration

Stop affected workloads. Keep upstream DNS closed during withdrawal. Inspect DH_FB_ACTIVE and its owned closed chain first; if the selector is incomplete or missing, stop and resolve that partial setup before continuing.

set -e
iptables -w -S

Only after confirming the existing selector and closed chain match this example:

iptables -w -R DH_FB_ACTIVE 1 -j DH_FB_CLOSED
iptables -w -S DH_FB_ACTIVE

Verify the selector now points to DH_FB_CLOSED; stop on any failure.

Restore the Account Guard

Keep the reader and its helpers stopped. Continue in the existing root shell; if it was lost, run sudo -i once, use Bash, and recover the recorded NEWS_UID and application VPN_IF. Use the same firewall backend as setup, with no other firewall manager changing its rules. Run each command separately and check its result. After an interruption or unexpected error, inspect again before continuing.

set -e
iptables -w -S
ip6tables -w -S OUTPUT

Inspect the full rules and their order, not just comments or chain names. The original IPv4 guard (newsvpn-guard4) must match the recorded account and block output outside its application VPN. The IPv6 guard (newsvpn-guard6) must still block that account. Both must precede broad acceptance rules. If neither IPv4 guard is effective, or IPv6 protection is missing, stop normal withdrawal and recover the original protection using verified recorded values. Leave unknown or shared rules untouched.

Keep a valid original guard already present. Only if it is absent and the replacement is verified, restore it:

iptables -w -I OUTPUT 1 -m owner --uid-owner "$NEWS_UID" ! -o "$VPN_IF" -m comment --comment newsvpn-guard4 -j DROP

Verify the original guards before removing anything:

iptables -w -C OUTPUT -m owner --uid-owner "$NEWS_UID" ! -o "$VPN_IF" -m comment --comment newsvpn-guard4 -j DROP
ip6tables -w -C OUTPUT -m owner --uid-owner "$NEWS_UID" -m comment --comment newsvpn-guard6 -j DROP
iptables -w -S OUTPUT
ip6tables -w -S OUTPUT

The checks confirm existence; inspect the listings for correct position. If the exact replacement jump is present, remove it:

iptables -w -D OUTPUT -m owner --uid-owner "$NEWS_UID" -m comment --comment newsvpn-stub-guard4 -j DH_NEWS_STUB

Inspect the whole filter table again:

iptables -w -S

Require the original guard to remain effective and no jump or goto references to DH_NEWS_STUB. If duplicate owned jumps remain, remove them one at a time and inspect again. Stop for unexpected references from other chains. If the replacement jump was already absent, skip its deletion.

Only when this example’s chain exists and is unreferenced, empty it, check success, then delete it:

iptables -w -F DH_NEWS_STUB
iptables -w -X DH_NEWS_STUB

Skip these two commands if the chain is already absent. Never flush a referenced chain, OUTPUT, or an entire table. Keep the IPv6 guard and DNS restrictions installed. Restoring the original guard blocks the local DNS exception; keep the reader stopped while completing the DNS restoration below.

Restore the Recorded DNS Lists

Keep the DNS restrictions and application guards installed. For each of DIRECT_IF and VPN_IF, restore exactly the server and domain lists saved before setup. Run one command at a time and check its result before continuing.

These are command forms: replace the uppercase names with the recorded interface and entries. Include every original entry, whether one or several; quote routing domains to preserve their ~ prefix.

resolvectl dns INTERFACE ORIGINAL_SERVER_1 ORIGINAL_SERVER_2
resolvectl domain INTERFACE 'ORIGINAL_DOMAIN_1' '~ORIGINAL_ROUTING_DOMAIN'

For an originally empty list, use one empty argument instead:

resolvectl dns INTERFACE ''
resolvectl domain INTERFACE ''

For example, only if the saved configuration had eth0 using 1.1.1.1 and 1.0.0.1 with no domains, and tun0 with no DNS servers or domains, the restoration would be:

resolvectl dns eth0 1.1.1.1 1.0.0.1
resolvectl domain eth0 ''
resolvectl dns tun0 ''
resolvectl domain tun0 ''

These are illustrative previous values, not a new provider selection. Substitute your recorded values; do not assume that the VPN lists were empty.

resolvectl status

Compare the affected links with the saved lists before continuing. A direct-DNS lookup may still be blocked by the installed restrictions; check the configuration now and perform the ordinary-account lookup/path tests after deliberately removing those restrictions. Do not use resolvectl revert: it resets defaults rather than restoring your saved lists.

If you ran an earlier draft: its commands also changed default-route. Restoring only the lists is not a complete undo of that older setup. Restore a recorded explicit value through resolvectl default-route; an automatically determined baseline needs its configuration owner’s restoration. Do not guess a value or use a blanket reset. The revised setup leaves this setting alone.

Remove only the owned routes:

ip -4 route del "$DIRECT_DNS/32" via "$DIRECT_GW" dev "$DIRECT_IF" src "$DIRECT_ADDR" metric 100
ip -4 route del unreachable "$DIRECT_DNS/32" metric 32767
ip -4 route del "$VPN_DNS/32" dev "$VPN_IF" src "$VPN_ADDR" metric 100
ip -4 route del unreachable "$VPN_DNS/32" metric 32767

After restoring the prior DNS policy, remove the owned jumps and chains:

iptables -w -D OUTPUT -m comment --comment dns-fallback4 -j DH_FB_ACTIVE
ip6tables -w -D OUTPUT -m comment --comment dns-fallback6 -j DH_FB_DNS6
iptables -w -F DH_FB_ACTIVE
iptables -w -X DH_FB_ACTIVE
for chain in DH_FB_DIRECT DH_FB_VPN DH_FB_CLOSED; do
    iptables -w -F "$chain"
    iptables -w -X "$chain"
done
ip6tables -w -F DH_FB_DNS6
ip6tables -w -X DH_FB_DNS6

Check each result. Omit a deletion only after confirming that entry is already absent; never flush the host’s tables or OUTPUT. After removing the intended DNS restrictions, repeat the existing ordinary-account lookup and packet-path checks with a fresh permitted name. Require the original provider/path; a cached answer is insufficient. Keep the reader stopped until its own intended DNS environment and application route are verified: restoring the original account guard removes its local-stub exception. Withdrawal is not a response to VPN failure.

References: iptables replacement and traversal, resolver settings, and route types. All Linux runtime checks remain untested.

Leave the Root Shell

After verification or withdrawal is complete, return to your ordinary shell:

exit

Review History

Preserved pre-review draft (text). Technical source review and local page validation were completed November 26, 2026. These simple examples retain explicit manual route/provider selection. The separate advanced Ubuntu walkthrough covers automatic controls, persistence, installation and rollback using the completed local reference source. Linux runtime validation remains deferred.