From c29c57639a53778639e6056ede7d19a7802491df Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Sun, 25 Oct 2026 22:55:51 +0800 Subject: [PATCH] fix: preserve physical DNS while selecting VPN DNS on macOS --- crates/gpvpnc/src/macos-vpnc-script.sh | 239 ++++++++++++----------- crates/gpvpnc/src/macos.rs | 4 + crates/gpvpnc/src/macos_dns_tests.rs | 257 +++++++++++++++++++++++++ 3 files changed, 379 insertions(+), 121 deletions(-) create mode 100644 crates/gpvpnc/src/macos_dns_tests.rs diff --git a/crates/gpvpnc/src/macos-vpnc-script.sh b/crates/gpvpnc/src/macos-vpnc-script.sh index 857769f..29a6e35 100644 --- a/crates/gpvpnc/src/macos-vpnc-script.sh +++ b/crates/gpvpnc/src/macos-vpnc-script.sh @@ -165,7 +165,10 @@ if [ $? = 0 ];then fi fi -if [ -r /etc/openwrt_release ] && [ -n "$OPENWRT_INTERFACE" ]; then +if [ "$OS" = "Darwin" ]; then + MODIFYRESOLVCONF=configure_macos_dns + RESTORERESOLVCONF=remove_macos_dns +elif [ -r /etc/openwrt_release ] && [ -n "$OPENWRT_INTERFACE" ]; then . /etc/functions.sh include /lib/network MODIFYRESOLVCONF=modify_resolvconf_openwrt @@ -582,7 +585,109 @@ fi # =========== resolv.conf handling ==================================== -# =========== resolv.conf handling for any OS ========================= +# =========== macOS resolver configuration ========================= + +macos_scutil_update() { + local output status + output=$(scutil 2>&1) + status=$? + # scutil can print a command error and still exit successfully. Updates + # produce no output on success; do not hide failures behind its exit status. + if [ "$status" -ne 0 ] || [ -n "$output" ]; then + printf 'macOS network configuration failed: %s\n' "$output" >&2 + return 1 + fi +} + +macos_remove_state() { + local key output status + key="State:/Network/Service/$TUNDEV/$1" + output=$(printf 'get %s\nquit\n' "$key" | scutil 2>&1) + status=$? + if [ "$status" -eq 0 ] && [ "$output" = " No such key" ]; then + return 0 + fi + if [ "$status" -ne 0 ] || [ -n "$output" ]; then + printf 'Cannot inspect macOS network state: %s\n' "$output" >&2 + return 1 + fi + macos_scutil_update <<-EOF + remove $key + quit + EOF +} + +macos_dns_source_service() { + local output source + output=$(printf 'show State:/Network/Global/IPv4\nquit\n' | scutil 2>&1) || { + printf 'macOS network configuration failed: cannot read primary IPv4 service: %s\n' "$output" >&2 + return 1 + } + source=$(printf '%s\n' "$output" | awk '$1 == "PrimaryService" && $2 == ":" { print $3 }') + if [ "$source" = "$TUNDEV" ]; then + # Our DNS service may now be primary. Re-read its original service on + # reconnect so DHCP changes are not copied from an outdated snapshot. + output=$(printf 'show State:/Network/Service/%s/IPv4\nquit\n' "$TUNDEV" | scutil 2>&1) || { + printf 'macOS network configuration failed: cannot read DNS source service: %s\n' "$output" >&2 + return 1 + } + source=$(printf '%s\n' "$output" | awk '$1 == "GPConnectSourceService" && $2 == ":" { print $3 }') + fi + if [ -z "$source" ] || [ "$source" = "$TUNDEV" ]; then + printf 'Cannot identify the primary macOS IPv4 service for VPN DNS\n' >&2 + return 1 + fi + printf '%s\n' "$source" +} + +configure_macos_dns() { + local search_domains ipv4 + if [ -z "$INTERNAL_IP4_DNS" ]; then + remove_macos_dns + return $? + fi + search_domains="" + if [ -n "$CISCO_DEF_DOMAIN" ]; then + search_domains="d.add SearchDomains * $CISCO_DEF_DOMAIN" + fi + if [ -n "$CISCO_SPLIT_INC" ]; then + local source + source=$(macos_dns_source_service) || return 1 + # A split tunnel has no default router. Like GlobalProtect, register + # a copy of the primary service so DNS can become primary without + # moving ordinary internet traffic onto the tunnel interface. + ipv4="get State:/Network/Service/$source/IPv4 +d.add GPConnectSourceService $source" + else + ipv4="d.init +d.add Addresses * $INTERNAL_IP4_ADDRESS +d.add SubnetMasks * 255.255.255.255 +d.add InterfaceName $TUNDEV +d.add Router $INTERNAL_IP4_ADDRESS" + fi + # Publish a default resolver owned by this tunnel. Search suffixes do not + # imply supplemental DNS matching, and physical-service DNS stays intact. + macos_scutil_update <<-EOF + $ipv4 + d.add OverridePrimary # 1 + set State:/Network/Service/$TUNDEV/IPv4 + d.init + d.add ServerAddresses * $INTERNAL_IP4_DNS + $search_domains + d.add SearchOrder # 50000 + set State:/Network/Service/$TUNDEV/DNS + quit + EOF +} + +remove_macos_dns() { + local status=0 + macos_remove_state DNS || status=1 + macos_remove_state IPv4 || status=1 + return "$status" +} + +# =========== resolv.conf handling for other OSes ========================= modify_resolvconf_generic() { grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 || cp -- /etc/resolv.conf "$RESOLV_CONF_BACKUP" @@ -617,81 +722,6 @@ nameserver $i" search $DOMAINS" fi echo "$NEW_RESOLVCONF" > /etc/resolv.conf - - if [ "$OS" = "Darwin" ]; then - case "`uname -r`" in - # Skip for pre-10.4 systems - 4.*|5.*|6.*|7.*) - ;; - # 10.4 and later require use of scutil for DNS to work properly - *) - OVERRIDE_PRIMARY="" - if [ -n "$CISCO_SPLIT_INC" ]; then - if [ $CISCO_SPLIT_INC -lt 1 ]; then - # Must override for correct default route - # Cannot use multiple DNS matching in this case - OVERRIDE_PRIMARY='d.add OverridePrimary # 1' - fi - # Overriding the default gateway breaks split routing - OVERRIDE_GATEWAY="" - # Not overriding the default gateway breaks usage of - # INTERNAL_IP4_DNS. Prepend INTERNAL_IP4_DNS to list - # of used DNS servers - SERVICE=`echo "show State:/Network/Global/IPv4" | scutil | grep -oE '[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}'` - SERVICE_DNS=`echo "show State:/Network/Service/$SERVICE/DNS" | scutil | grep -oE '([0-9]{1,3}[\.]){3}[0-9]{1,3}' | xargs` - if [ X"$SERVICE_DNS" != X"$INTERNAL_IP4_DNS" ]; then - scutil >/dev/null 2>&1 <<-EOF - open - get State:/Network/Service/$SERVICE/DNS - d.add ServerAddresses * $INTERNAL_IP4_DNS $SERVICE_DNS - set State:/Network/Service/$SERVICE/DNS - close - EOF - fi - else - # No split routing. Override default gateway - OVERRIDE_GATEWAY="d.add Router $INTERNAL_IP4_ADDRESS" - fi - # Uncomment the following if/fi pair to use multiple - # DNS matching when available. When multiple DNS matching - # is present, anything reading the /etc/resolv.conf file - # directly will probably not work as intended. - #if [ -z "$CISCO_DEF_DOMAIN" ]; then - # Cannot use multiple DNS matching without a domain - OVERRIDE_PRIMARY='d.add OverridePrimary # 1' - #fi - scutil >/dev/null 2>&1 <<-EOF - open - d.init - d.add ServerAddresses * $INTERNAL_IP4_DNS - set State:/Network/Service/$TUNDEV/DNS - d.init - $OVERRIDE_GATEWAY - d.add Addresses * $INTERNAL_IP4_ADDRESS - d.add SubnetMasks * 255.255.255.255 - d.add InterfaceName $TUNDEV - $OVERRIDE_PRIMARY - set State:/Network/Service/$TUNDEV/IPv4 - close - EOF - if [ -n "$CISCO_DEF_DOMAIN" ]; then - scutil >/dev/null 2>&1 <<-EOF - open - get State:/Network/Service/$TUNDEV/DNS - d.add DomainName $CISCO_DEF_DOMAIN - d.add SearchDomains * $CISCO_DEF_DOMAIN - d.add SupplementalMatchDomains * $CISCO_DEF_DOMAIN - set State:/Network/Service/$TUNDEV/DNS - close - EOF - fi - # For newer MacOS versions it is needed to set DNS - ACTIVE_INTERFACE=`route -n get default | grep interface | awk '{print $2}'` - ACTIVE_NETWORK_SERVICE=`networksetup -listnetworkserviceorder | grep -B 1 "$ACTIVE_INTERFACE" | head -n 1 | awk '/\([0-9]+\)/{ print }'|cut -d " " -f2-` - networksetup -setdnsservers "$ACTIVE_NETWORK_SERVICE" $INTERNAL_IP4_DNS - ;; - esac - fi } restore_resolvconf_generic() { @@ -700,43 +730,6 @@ restore_resolvconf_generic() { fi grep '^#@VPNC_GENERATED@' /etc/resolv.conf > /dev/null 2>&1 && cat "$RESOLV_CONF_BACKUP" > /etc/resolv.conf rm -f -- "$RESOLV_CONF_BACKUP" - - if [ "$OS" = "Darwin" ]; then - case "`uname -r`" in - # Skip for pre-10.4 systems - 4.*|5.*|6.*|7.*) - ;; - # 10.4 and later require use of scutil for DNS to work properly - *) - scutil >/dev/null 2>&1 <<-EOF - open - remove State:/Network/Service/$TUNDEV/IPv4 - remove State:/Network/Service/$TUNDEV/DNS - close - EOF - # Split routing required prepending of INTERNAL_IP4_DNS - # to list of used DNS servers - if [ -n "$CISCO_SPLIT_INC" ]; then - SERVICE=`echo "show State:/Network/Global/IPv4" | scutil | grep -oE '[a-fA-F0-9]{8}-([a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}'` - SERVICE_DNS=`echo "show State:/Network/Service/$SERVICE/DNS" | scutil | grep -oE '([0-9]{1,3}[\.]){3}[0-9]{1,3}'` - FILTERED_SERVICE_DNS=`echo "$SERVICE_DNS" | grep -Fv "$(echo $INTERNAL_IP4_DNS | tr ' ' '\n')" | xargs` - if [ -n "$FILTERED_SERVICE_DNS" ]; then - scutil >/dev/null 2>&1 <<-EOF - open - get State:/Network/Service/$SERVICE/DNS - d.add ServerAddresses * ${FILTERED_SERVICE_DNS} - set State:/Network/Service/$SERVICE/DNS - close - EOF - fi - fi - # For newer MacOS versions it is needed to unset DNS - ACTIVE_INTERFACE=`route -n get default | grep interface | awk '{print $2}'` - ACTIVE_NETWORK_SERVICE=`networksetup -listnetworkserviceorder | grep -B 1 "$ACTIVE_INTERFACE" | head -n 1 | awk '/\([0-9]+\)/{ print }'|cut -d " " -f2-` - networksetup -setdnsservers "$ACTIVE_NETWORK_SERVICE" Empty - ;; - esac - fi } # === resolv.conf handling via /sbin/netconfig (Suse 11.1) ===================== @@ -1037,12 +1030,13 @@ do_connect() { set_ipv6_default_route fi - if [ -n "$INTERNAL_IP4_DNS" ]; then - $MODIFYRESOLVCONF + if [ "$OS" = "Darwin" ] || [ -n "$INTERNAL_IP4_DNS" ]; then + $MODIFYRESOLVCONF || return $? fi } do_disconnect() { + local dns_status=0 if [ -n "$CISCO_SPLIT_INC" ]; then i=0 while [ $i -lt $CISCO_SPLIT_INC ] ; do @@ -1102,8 +1096,8 @@ do_disconnect() { del_vpngateway_route - if [ -n "$INTERNAL_IP4_DNS" ]; then - $RESTORERESOLVCONF + if [ "$OS" = "Darwin" ] || [ -n "$INTERNAL_IP4_DNS" ]; then + $RESTORERESOLVCONF || dns_status=$? fi @@ -1140,6 +1134,7 @@ do_disconnect() { ifconfig "$TUNDEV" destroy > /dev/null 2>&1 & ;; esac + return "$dns_status" } do_attempt_reconnect() { @@ -1158,10 +1153,10 @@ case "$reason" in do_pre_init ;; connect) - do_connect + do_connect || exit $? ;; disconnect) - do_disconnect + do_disconnect || exit $? ;; attempt-reconnect) # Invoked before each attempt to re-establish the session. @@ -1172,7 +1167,9 @@ case "$reason" in ;; reconnect) # After successfully re-establishing the session. - : + if [ "$OS" = "Darwin" ]; then + configure_macos_dns || exit $? + fi ;; *) echo "unknown reason '$reason'. Maybe vpnc-script is out of date" 1>&2 diff --git a/crates/gpvpnc/src/macos.rs b/crates/gpvpnc/src/macos.rs index 1d1f46a..a5bafe4 100644 --- a/crates/gpvpnc/src/macos.rs +++ b/crates/gpvpnc/src/macos.rs @@ -229,3 +229,7 @@ mod tests { assert!(run_script("exit 23", "connect", &environment).is_err()); } } + +#[cfg(test)] +#[path = "macos_dns_tests.rs"] +mod dns_tests; diff --git a/crates/gpvpnc/src/macos_dns_tests.rs b/crates/gpvpnc/src/macos_dns_tests.rs new file mode 100644 index 0000000..e23e2f5 --- /dev/null +++ b/crates/gpvpnc/src/macos_dns_tests.rs @@ -0,0 +1,257 @@ +use super::VPNC_SCRIPT; +use std::process::{Command, Output}; + +// Exercise the production DNS functions and lifecycle dispatch without running +// script initialization or any real network commands. The fake store persists +// across scutil subprocesses, just as the real dynamic store does. +fn dns_script() -> String { + let selection_start = VPNC_SCRIPT + .find("if [ \"$OS\" = \"Darwin\" ]; then\n\tMODIFYRESOLVCONF=") + .unwrap(); + let selection = VPNC_SCRIPT[selection_start..] + .split_once("# =========== tunnel interface handling") + .unwrap() + .0; + let functions = VPNC_SCRIPT + .split_once("# =========== macOS resolver configuration =========================") + .unwrap() + .1 + .split_once("# =========== resolv.conf handling for other OSes =========================") + .unwrap() + .0; + format!( + r#" +state_dir=$(mktemp -d) || exit 1 +trap 'rm -rf "$state_dir"' EXIT +TUNDEV=utun42 +OS=Darwin +INTERNAL_IP4_ADDRESS=10.1.2.3 +INTERNAL_IP4_DNS='10.0.0.53 10.0.0.54' +CISCO_DEF_DOMAIN='corp.example.com internal.example.com' +CISCO_SPLIT_INC=0 +printf 'physical-service\n' > "$state_dir/primary-service" +printf '%s\n' 'd.add Addresses * 192.168.1.100' 'd.add SubnetMasks * 255.255.255.0' \ + 'd.add InterfaceName en0' 'd.add Router 192.168.1.1' > "$state_dir/physical-ipv4" +printf '192.168.1.1\n' > "$state_dir/physical-dns" +cp "$state_dir/physical-dns" "$state_dir/original-physical-dns" +networksetup() {{ echo 'Unexpected physical DNS modification' >&2; exit 99; }} +scutil() {{ + if [ "$scutil_failure" = process ]; then return 1; fi + dictionary='' + while IFS= read -r command; do + case "$command" in + '') ;; + d.init) dictionary='' ;; + 'd.add '*) dictionary="$dictionary +$command" ;; + 'set State:/Network/Service/utun42/'*) + if [ "$scutil_failure" = command ]; then + echo ' Permission denied' + else + printf '%s\n' "$dictionary" > "$state_dir/${{command##*/}}" + fi + ;; + 'get State:/Network/Service/utun42/'*) + if [ -f "$state_dir/${{command##*/}}" ]; then + dictionary=$(cat "$state_dir/${{command##*/}}") + else + echo ' No such key' + fi + ;; + 'show State:/Network/Global/IPv4') + printf ' PrimaryService : %s\n' "$(cat "$state_dir/primary-service")" + ;; + 'show State:/Network/Service/utun42/IPv4') + sed -n 's/^d.add GPConnectSourceService / GPConnectSourceService : /p' "$state_dir/IPv4" + ;; + 'get State:/Network/Service/physical-service/IPv4') + dictionary=$(cat "$state_dir/physical-ipv4") + ;; + 'remove State:/Network/Service/utun42/'*) + if [ "$scutil_failure" = remove ]; then + echo ' Permission denied' + else + rm "$state_dir/${{command##*/}}" || return 1 + fi + ;; + quit) ;; + *) echo "Unexpected scutil command: $command" >&2; return 1 ;; + esac + done +}} +{selection} +{functions} +"# + ) +} + +fn run_dns_test(body: &str) -> Output { + let script = format!("{}\n{}", dns_script(), body); + Command::new("/bin/sh").args(["-c", &script]).output().unwrap() +} + +fn assert_success(output: Output) { + assert!( + output.status.success(), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stderr.is_empty(), "{}", String::from_utf8_lossy(&output.stderr)); +} + +#[test] +fn publishes_default_dns_and_search_suffixes_without_physical_dns_changes() { + assert_success(run_dns_test( + r#" +configure_macos_dns || exit 1 +grep -Fx 'd.add ServerAddresses * 10.0.0.53 10.0.0.54' "$state_dir/DNS" || exit 2 +grep -Fx 'd.add SearchDomains * corp.example.com internal.example.com' "$state_dir/DNS" || exit 3 +grep -Fx 'd.add SearchOrder # 50000' "$state_dir/DNS" || exit 4 +grep -Eq 'SupplementalMatchDomains|DomainName' "$state_dir/DNS" && exit 5 +grep -Fx 'd.add OverridePrimary # 1' "$state_dir/IPv4" || exit 6 +grep -Fx 'd.add Router 192.168.1.1' "$state_dir/IPv4" || exit 7 +grep -Fx 'd.add InterfaceName en0' "$state_dir/IPv4" || exit 13 +grep -Fx 'd.add GPConnectSourceService physical-service' "$state_dir/IPv4" || exit 14 +grep -q '10.1.2.3' "$state_dir/IPv4" && exit 15 +cmp "$state_dir/physical-dns" "$state_dir/original-physical-dns" || exit 8 +cp "$state_dir/DNS" "$state_dir/first-dns" +# Once macOS elects our service, reconnect must read the original source, +# rather than clone the VPN-owned snapshot again. +printf 'utun42\n' > "$state_dir/primary-service" +sed -i '' 's/192.168.1.100/192.168.1.101/' "$state_dir/physical-ipv4" +configure_macos_dns || exit 9 +cmp "$state_dir/DNS" "$state_dir/first-dns" || exit 10 +grep -Fx 'd.add Addresses * 192.168.1.101' "$state_dir/IPv4" || exit 16 +# Full-tunnel service registration retains its existing Router behavior. +unset CISCO_SPLIT_INC +configure_macos_dns || exit 11 +grep -Fx 'd.add Router 10.1.2.3' "$state_dir/IPv4" || exit 12 +"#, + )); +} + +#[test] +fn replaces_dns_and_removes_stale_suffixes_and_owned_state() { + assert_success(run_dns_test( + r#" +configure_macos_dns || exit 1 +INTERNAL_IP4_DNS=10.0.0.55 +CISCO_DEF_DOMAIN='' +configure_macos_dns || exit 2 +grep -Fx 'd.add ServerAddresses * 10.0.0.55' "$state_dir/DNS" || exit 3 +grep -Eq '10.0.0.53|SearchDomains|corp.example.com' "$state_dir/DNS" && exit 4 +INTERNAL_IP4_DNS='' +configure_macos_dns || exit 5 +[ ! -f "$state_dir/DNS" ] && [ ! -f "$state_dir/IPv4" ] || exit 6 +# Removing missing owned state is idempotent, even without a DNS environment. +remove_macos_dns || exit 7 +cmp "$state_dir/physical-dns" "$state_dir/original-physical-dns" || exit 8 +"#, + )); +} + +#[test] +fn reports_scutil_command_and_process_failures_and_attempts_both_removals() { + for failure in ["command", "process"] { + let output = run_dns_test(&format!("scutil_failure={failure}\nconfigure_macos_dns")); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("macOS network configuration failed")); + } + let output = run_dns_test( + r#" +configure_macos_dns || exit 1 +scutil_failure=remove +remove_macos_dns +"#, + ); + assert!(!output.status.success()); + let errors = String::from_utf8_lossy(&output.stderr); + assert_eq!(errors.matches("macOS network configuration failed").count(), 2); +} + +// Stub route/interface operations and use production lifecycle functions to +// check DNS dispatch, failure propagation, and interface cleanup after failure. +fn lifecycle_script() -> String { + let lifecycle = VPNC_SCRIPT.split_once("do_connect() {").unwrap().1; + format!( + r#" +{prefix} +do_ifconfig() {{ :; }} +set_vpngateway_route() {{ :; }} +del_vpngateway_route() {{ :; }} +reset_default_route() {{ :; }} +ifconfig() {{ printf '%s\n' "$*" >> "$state_dir/interface-operations"; }} +ifconfig_syntax_del() {{ printf '%s\n' "$1"; }} +do_connect() {{{lifecycle} +"#, + prefix = dns_script(), + ) +} + +#[test] +fn lifecycle_reapplies_dns_on_reconnect_and_propagates_failures() { + // Source just the production lifecycle definitions, then run its dispatch. + let script = lifecycle_script(); + for reason in ["connect", "reconnect"] { + let output = Command::new("/bin/sh") + .args(["-c", &script]) + .env("reason", reason) + .env("scutil_failure", "command") + .output() + .unwrap(); + assert!(!output.status.success(), "{reason} hid DNS failure"); + assert!(String::from_utf8_lossy(&output.stderr).contains("macOS network configuration failed")); + } + let (definitions, dispatch) = script.split_once("#### Main").unwrap(); + let dispatch = dispatch.trim_end().strip_suffix("exit 0").unwrap(); + for reason in ["connect", "reconnect"] { + let script = format!( + r#" +{definitions} +reason={reason} +{dispatch} +grep -Fx 'd.add ServerAddresses * 10.0.0.53 10.0.0.54' "$state_dir/DNS" || exit 1 +"# + ); + assert_success(Command::new("/bin/sh").args(["-c", &script]).output().unwrap()); + } + let script = format!( + r#" +{definitions} +configure_macos_dns || exit 1 +INTERNAL_IP4_DNS='' +reason=disconnect +{dispatch} +[ ! -f "$state_dir/DNS" ] && [ ! -f "$state_dir/IPv4" ] || exit 2 +grep -Fx 'utun42 down' "$state_dir/interface-operations" || exit 3 +cmp "$state_dir/physical-dns" "$state_dir/original-physical-dns" || exit 4 +"# + ); + let output = Command::new("/bin/sh").args(["-c", &script]).output().unwrap(); + assert_success(output); +} + +#[test] +fn disconnect_still_tears_down_interface_when_dns_cleanup_fails() { + let script = lifecycle_script(); + let (definitions, _) = script.split_once("#### Main").unwrap(); + let script = format!( + r#" +{definitions} +configure_macos_dns || exit 1 +scutil_failure=remove +do_disconnect +[ "$?" -ne 0 ] || exit 2 +grep -Fx 'utun42 down' "$state_dir/interface-operations" || exit 3 +"# + ); + let output = Command::new("/bin/sh").args(["-c", &script]).output().unwrap(); + assert!(output.status.success()); + assert_eq!( + String::from_utf8_lossy(&output.stderr) + .matches("macOS network configuration failed") + .count(), + 2 + ); +}