Skip to contentSkip to conversation

macOS: support multiple simultaneous tunnels

PATCH RESEND New Razvan Cremenescu 1 participant 11 messages Oct 5

lore
Share & tools
lore
#0 lore raw

cover macOS: support multiple simultaneous tunnels

This is a resend. I first sent this series on July 10, and two follow-up fixes on July 25, but none of the messages made it out of the list's moderation queue, so they never reached the archive. The patches are unchanged; the same commits are also on a branch and as a pull request on the GitHub mirror, if either is easier to pull from:

https://github.com/cremenescu/wireguard-apple/tree/macos-multiple-tunnels
https://github.com/WireGuard/wireguard-apple/pull/63

macOS, unlike iOS, can run multiple packet tunnel provider sessions at the same time, but the app serializes activation on both platforms: activating one tunnel deactivates the tunnel already in operation. On iOS that mirrors an OS restriction. On macOS it is purely app policy, and macOS users routinely need several disjoint split tunnels up at once.

Lifting the policy alone is not enough. When two sessions run in one extension process, each WireGuardAdapter locates its tunnel device by taking the first utun control socket in the process, so the second tunnel attaches to the first tunnel's device and passes no traffic. This looks like the failure reported on this list in July 2021 ("Running multiple tunnels simultaneously on macOS"), where two tunnels both reached Connected but only one passed traffic. Patch 3 fixes the device attachment; patches 4-6 then lift the single-tunnel policy on macOS while keeping iOS behaviour exactly as it is today.

The first two patches are independent fixes that the series happens to need:
a build fix for the strict module verifier in current Xcode, and a fix for an explicit deactivation losing against a pending restart.

Patch 7 adds an opt-in per-tunnel split DNS toggle. With several tunnels up, tunnels that install their DNS servers as the system-wide resolver fight over it; the toggle lets a tunnel's DNS servers be used only for that tunnel's DNS search domains. Existing full-tunnel setups keep their match-everything DNS by default. A related DNSMatchDomains approach was posted here in April 2024; this variant keeps the wg-quick config text untouched and portable, and gates the behaviour on an explicit opt-in.

Patches 8-10 are robustness fixes found while running the result daily: an alert that came up invisibly behind everything on a menu bar app, a crash opening the editor for a tunnel whose saved configuration cannot be read, and endpoints that were never set again after a network change. That last one is worth a number: a peer that had roamed to an address only reachable on the previous network went from 2 completed handshakes out of 130 attempts to 83 out of 129.

Tested on macOS 26 with Xcode 26: multiple concurrent tunnels passing traffic simultaneously on disjoint AllowedIPs, deactivating one tunnel leaving the others up, and DNS resolution verified with and without DNS= entries as well as with split DNS enabled. Every patch builds for both macOS and iOS on its own, so the series stays bisectable.

I would also be glad to help maintain wireguard-apple if that is useful - the repositories page says you would welcome someone taking it over.

Razvan Cremenescu (10):
WireGuardKitC: include sys/types.h for BSD type definitions
TunnelsManager: drop the restart intent when deactivation is requested
WireGuardKit: attach each adapter to its own utun device
TunnelsManager: restrict single-tunnel activation policy to iOS
PacketTunnelProvider: only exit on stop of last tunnel in the process
macOS: support multiple simultaneous tunnels in the menu bar UI Add opt-in split DNS support
macOS: activate the app before showing a modal alert without a window
macOS: don't crash opening the editor for an unreadable tunnel
macOS: reset peer endpoints after a network change

 .../NETunnelProviderProtocol+Extension.swift  |  26 +++
 .../Base.lproj/Localizable.strings            |  12 ++
 .../WireGuardApp/Tunnel/TunnelsManager.swift  |  43 ++++-
 .../TunnelEditTableViewController.swift       |  39 +++-
 .../WireGuardApp/UI/macOS/AppDelegate.swift   |  31 ++-
 .../UI/macOS/ErrorPresenter.swift             |   5 +
 .../UI/macOS/StatusItemController.swift       |  14 +-
 .../WireGuardApp/UI/macOS/StatusMenu.swift    |  25 ++-
 .../UI/macOS/TunnelsTracker.swift             |  31 ++-
 .../TunnelDetailTableViewController.swift     |   7 +
 .../TunnelEditViewController.swift            |  21 ++-
 .../PacketTunnelSettingsGenerator.swift       |  59 +++++-
 Sources/WireGuardKit/WireGuardAdapter.swift   | 176 +++++++++++++++++-
 Sources/WireGuardKitC/WireGuardKitC.h         |   2 +
 .../PacketTunnelProvider.swift                |  52 +++++-
 15 files changed, 485 insertions(+), 58 deletions(-)
Signature · 1 line
2.50.1 (Apple Git-155)
#1 lore raw

PATCH RESEND 1/10 WireGuardKitC: include sys/types.h for BSD type definitions

The ctl_info and sockaddr_ctl definitions use u_char, u_int16_t and u_int32_t without including <sys/types.h>. Newer clang versions with strict module verification (Xcode 16 and later) refuse to build the module because these declarations must be imported before use.

---
 Sources/WireGuardKitC/WireGuardKitC.h | 2 ++
 1 file changed, 2 insertions(+)
Sources/WireGuardKitC/WireGuardKitC.h +2 -0
index 54e4783..84c53f7 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: MIT
 // Copyright © 2018-2023 WireGuard LLC. All Rights Reserved.
 
+#include <sys/types.h>
+
 #include "key.h"
 #include "x25519.h"
 
Signature · 1 line
2.50.1 (Apple Git-155)
#2 lore raw

PATCH RESEND 2/10 TunnelsManager: drop the restart intent when deactivation is requested

In reply to Razvan Cremenescu

A tunnel in the .restarting state is automatically reactivated by the status observer when its connection reaches .disconnected. If the user asks for deactivation while the restart is still pending, the tunnel would go down and immediately come back up. Reset the status from the actual connection status before stopping, so an explicit deactivation request always wins over a pending restart.

---
 Sources/WireGuardApp/Tunnel/TunnelsManager.swift | 5 +++++
 1 file changed, 5 insertions(+)
Sources/WireGuardApp/Tunnel/TunnelsManager.swift +5 -0
index c277f6d..365094e 100644
@@ -473,6 +473,11 @@ class TunnelsManager {
     func startDeactivation(of tunnel: TunnelContainer) {
         tunnel.isAttemptingActivation = false
         guard tunnel.status != .inactive && tunnel.status != .deactivating else { return }
+        if tunnel.status == .restarting {
+            // The tunnel was going to be restarted on disconnection, but the
+            // user asked for deactivation, so drop the restart intent.
+            tunnel.status = TunnelStatus(from: tunnel.tunnelProvider.connection.status)
+        }
         #if targetEnvironment(simulator)
         tunnel.status = .inactive
         #else
Signature · 1 line
2.50.1 (Apple Git-155)
#3 lore raw

PATCH RESEND 3/10 WireGuardKit: attach each adapter to its own utun device

In reply to Razvan Cremenescu

The adapter located its tunnel device by scanning the process's file descriptors and taking the first utun control socket found. With a single tunnel per extension process that was always the right one, but macOS runs multiple simultaneous tunnel sessions in one extension
process: the second adapter would attach to the first tunnel's utun, leaving its own device without a reader. The second tunnel then passed no traffic at all, while the first suffered from two backends competing for the same descriptor.

Collect all utun control sockets instead, exclude the ones already claimed by other adapters in the process, and prefer the device that already carries this tunnel's addresses, which setTunnelNetworkSettings has assigned by the time the backend starts. The claim is released if the backend fails to start, on stop, and on deinit.

This makes simultaneous tunnels actually pass traffic on macOS.

---
 Sources/WireGuardKit/WireGuardAdapter.swift | 110 ++++++++++++++++++--
 1 file changed, 103 insertions(+), 7 deletions(-)
Sources/WireGuardKit/WireGuardAdapter.swift +103 -7
index f7be19b..ba49ec7 100644
@@ -56,8 +56,26 @@ public class WireGuardAdapter {
     /// Adapter state.
     private var state: State = .stopped
 
+    /// Tunnel device file descriptors claimed by the adapters in this process.
+    /// When multiple tunnels run in a single extension process, each adapter
+    /// must attach to its own utun device rather than to the first one found.
+    private static var claimedTunnelFileDescriptors = Set<Int32>()
+    private static let claimedTunnelFileDescriptorsLock = NSLock()
+
+    /// The utun file descriptor claimed by this adapter, if any.
+    private var claimedTunnelFileDescriptor: Int32?
+
     /// Tunnel device file descriptor.
     private var tunnelFileDescriptor: Int32? {
+        if let claimedTunnelFileDescriptor = claimedTunnelFileDescriptor {
+            return claimedTunnelFileDescriptor
+        }
+        return utunFileDescriptors.first
+    }
+
+    /// File descriptors of all utun devices opened by this process.
+    private var utunFileDescriptors: [Int32] {
+        var fileDescriptors = [Int32]()
         var ctlInfo = ctl_info()
         withUnsafeMutablePointer(to: &ctlInfo.ctl_name) {
             $0.withMemoryRebound(to: CChar.self, capacity: MemoryLayout.size(ofValue: $0.pointee)) {
@@ -83,10 +101,78 @@ public class WireGuardAdapter {
                 }
             }
             if addr.sc_id == ctlInfo.ctl_id {
-                return fd
+                fileDescriptors.append(fd)
             }
         }
-        return nil
+        return fileDescriptors
+    }
+
+    /// Claim the utun device belonging to this adapter's tunnel.
+    /// By the time the backend is started, `setTunnelNetworkSettings` has
+    /// already assigned this tunnel's addresses to its utun device, so among
+    /// the unclaimed devices prefer the one carrying one of our addresses.
+    private func claimTunnelFileDescriptor(for tunnelConfiguration: TunnelConfiguration) -> Int32? {
+        if let claimedTunnelFileDescriptor = claimedTunnelFileDescriptor {
+            return claimedTunnelFileDescriptor
+        }
+        Self.claimedTunnelFileDescriptorsLock.lock()
+        defer { Self.claimedTunnelFileDescriptorsLock.unlock() }
+        let candidates = utunFileDescriptors.filter { !Self.claimedTunnelFileDescriptors.contains($0) }
+        let matching = candidates.first { fd in
+            guard let interfaceName = Self.interfaceName(forTunnelFileDescriptor: fd) else { return false }
+            return Self.interface(interfaceName, hasAnyAddressOf: tunnelConfiguration.interface.addresses)
+        }
+        guard let fileDescriptor = matching ?? candidates.first else { return nil }
+        Self.claimedTunnelFileDescriptors.insert(fileDescriptor)
+        claimedTunnelFileDescriptor = fileDescriptor
+        return fileDescriptor
+    }
+
+    /// Release the utun device claimed by this adapter.
+    private func releaseTunnelFileDescriptor() {
+        Self.claimedTunnelFileDescriptorsLock.lock()
+        defer { Self.claimedTunnelFileDescriptorsLock.unlock() }
+        if let fileDescriptor = claimedTunnelFileDescriptor {
+            Self.claimedTunnelFileDescriptors.remove(fileDescriptor)
+            claimedTunnelFileDescriptor = nil
+        }
+    }
+
+    /// Returns true if the network interface carries at least one of the given addresses.
+    private class func interface(_ interfaceName: String, hasAnyAddressOf addresses: [IPAddressRange]) -> Bool {
+        var interfaceAddresses: UnsafeMutablePointer<ifaddrs>?
+        guard getifaddrs(&interfaceAddresses) == 0 else { return false }
+        defer { freeifaddrs(interfaceAddresses) }
+
+        let addressStrings = addresses.map { "\($0.address)" }
+        var cursor = interfaceAddresses
+        while let ifaddr = cursor?.pointee {
+            cursor = ifaddr.ifa_next
+            guard let ifaAddr = ifaddr.ifa_addr, String(cString: ifaddr.ifa_name) == interfaceName else {
+                continue
+            }
+            var addressString: String?
+            switch Int32(ifaAddr.pointee.sa_family) {
+            case AF_INET:
+                var sin = UnsafeRawPointer(ifaAddr).assumingMemoryBound(to: sockaddr_in.self).pointee
+                var buffer = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
+                if inet_ntop(AF_INET, &sin.sin_addr, &buffer, socklen_t(INET_ADDRSTRLEN)) != nil {
+                    addressString = String(cString: buffer)
+                }
+            case AF_INET6:
+                var sin6 = UnsafeRawPointer(ifaAddr).assumingMemoryBound(to: sockaddr_in6.self).pointee
+                var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
+                if inet_ntop(AF_INET6, &sin6.sin6_addr, &buffer, socklen_t(INET6_ADDRSTRLEN)) != nil {
+                    addressString = String(cString: buffer)
+                }
+            default:
+                break
+            }
+            if let addressString = addressString, addressStrings.contains(addressString) {
+                return true
+            }
+        }
+        return false
     }
 
     /// Returns a WireGuard version.
@@ -101,7 +187,11 @@ public class WireGuardAdapter {
     /// - Returns: String.
     public var interfaceName: String? {
         guard let tunnelFileDescriptor = self.tunnelFileDescriptor else { return nil }
+        return Self.interfaceName(forTunnelFileDescriptor: tunnelFileDescriptor)
+    }
 
+    /// Returns the interface name of a utun device file descriptor, or nil on error.
+    private class func interfaceName(forTunnelFileDescriptor tunnelFileDescriptor: Int32) -> String? {
         var buffer = [UInt8](repeating: 0, count: Int(IFNAMSIZ))
 
         return buffer.withUnsafeMutableBufferPointer { mutableBufferPointer in
@@ -148,6 +238,8 @@ public class WireGuardAdapter {
         if case .started(let handle, _) = self.state {
             wgTurnOff(handle)
         }
+
+        releaseTunnelFileDescriptor()
     }
 
     // MARK: - Public methods
@@ -195,7 +287,7 @@ public class WireGuardAdapter {
                 self.logEndpointResolutionResults(resolutionResults)
 
                 self.state = .started(
-                    try self.startWireGuardBackend(wgConfig: wgConfig),
+                    try self.startWireGuardBackend(wgConfig: wgConfig, tunnelConfiguration: tunnelConfiguration),
                     settingsGenerator
                 )
                 self.networkMonitor = networkMonitor
@@ -228,6 +320,7 @@ public class WireGuardAdapter {
             self.networkMonitor?.cancel()
             self.networkMonitor = nil
 
+            self.releaseTunnelFileDescriptor()
             self.state = .stopped
 
             completionHandler(nil)
@@ -365,16 +458,19 @@ public class WireGuardAdapter {
     }
 
     /// Start WireGuard backend.
-    /// - Parameter wgConfig: WireGuard configuration
+    /// - Parameters:
+    ///   - wgConfig: WireGuard configuration
+    ///   - tunnelConfiguration: tunnel configuration
     /// - Throws: an error of type `WireGuardAdapterError`
     /// - Returns: tunnel handle
-    private func startWireGuardBackend(wgConfig: String) throws -> Int32 {
-        guard let tunnelFileDescriptor = self.tunnelFileDescriptor else {
+    private func startWireGuardBackend(wgConfig: String, tunnelConfiguration: TunnelConfiguration) throws -> Int32 {
+        guard let tunnelFileDescriptor = self.claimTunnelFileDescriptor(for: tunnelConfiguration) else {
             throw WireGuardAdapterError.cannotLocateTunnelFileDescriptor
         }
 
         let handle = wgTurnOn(wgConfig, tunnelFileDescriptor)
         if handle < 0 {
+            releaseTunnelFileDescriptor()
             throw WireGuardAdapterError.startWireGuardBackend(handle)
         }
         #if os(iOS)
@@ -449,7 +545,7 @@ public class WireGuardAdapter {
                 self.logEndpointResolutionResults(resolutionResults)
 
                 self.state = .started(
-                    try self.startWireGuardBackend(wgConfig: wgConfig),
+                    try self.startWireGuardBackend(wgConfig: wgConfig, tunnelConfiguration: settingsGenerator.tunnelConfiguration),
                     settingsGenerator
                 )
             } catch {
Signature · 1 line
2.50.1 (Apple Git-155)
#4 lore raw

PATCH RESEND 4/10 TunnelsManager: restrict single-tunnel activation policy to iOS

In reply to Razvan Cremenescu

On iOS the OS allows only one active VPN configuration at a time, so activating a tunnel first parks it in the .waiting state, deactivates the tunnel currently in operation, and completes the activation once the latter is fully down.

On macOS there is no such OS-level restriction: each tunnel is its own NETunnelProviderManager session and multiple sessions can be active simultaneously. Make the deactivate-then-activate handoff iOS-only, so that on macOS activating a tunnel no longer tears down the tunnels already in operation.

Also add tunnelsInOperation(), returning every non-inactive tunnel, for use by the macOS UI. On multi-user systems the tunnels list deliberately retains other users' tunnels; those are excluded, since they are not this user's to display or deactivate.

---
 .../WireGuardApp/Tunnel/TunnelsManager.swift  | 21 +++++++++++++++++++
 1 file changed, 21 insertions(+)
Sources/WireGuardApp/Tunnel/TunnelsManager.swift +21 -0
index 365094e..63e1847 100644
@@ -24,7 +24,9 @@ class TunnelsManager {
     weak var tunnelsListDelegate: TunnelsManagerListDelegate?
     weak var activationDelegate: TunnelsManagerActivationDelegate?
     private var statusObservationToken: NotificationToken?
+    #if os(iOS)
     private var waiteeObservationToken: NSKeyValueObservation?
+    #endif
     private var configurationsObservationToken: NotificationToken?
 
     init(tunnelProviders: [NETunnelProviderManager]) {
@@ -428,6 +430,16 @@ class TunnelsManager {
         return tunnels.first { $0.status != .inactive }
     }
 
+    func tunnelsInOperation() -> [TunnelContainer] {
+        #if os(macOS)
+        // On multi-user systems the tunnels list retains other users'
+        // tunnels; those are not this user's to display or deactivate.
+        return tunnels.filter { $0.status != .inactive && $0.isTunnelAvailableToUser }
+        #else
+        return tunnels.filter { $0.status != .inactive }
+        #endif
+    }
+
     func startActivation(of tunnel: TunnelContainer) {
         guard tunnels.contains(tunnel) else { return } // Ensure it's not deleted
         guard tunnel.status == .inactive else {
@@ -435,6 +447,12 @@ class TunnelsManager {
             return
         }
 
+        #if os(iOS)
+        // In iOS, the OS allows only one VPN configuration to be active at a
+        // time, so bring down the tunnel in operation and queue this tunnel
+        // for activation once the former is fully deactivated. In macOS,
+        // multiple tunnels can be active simultaneously, so we activate the
+        // tunnel right away.
         if let alreadyWaitingTunnel = tunnels.first(where: { $0.status == .waiting }) {
             alreadyWaitingTunnel.status = .inactive
         }
@@ -458,6 +476,7 @@ class TunnelsManager {
             }
             return
         }
+        #endif
 
         #if targetEnvironment(simulator)
         tunnel.status = .active
@@ -489,6 +508,7 @@ class TunnelsManager {
         tunnels.forEach { $0.refreshStatus() }
     }
 
+    #if os(iOS)
     private func activateWaitingTunnelOnDeactivation(of tunnel: TunnelContainer) {
         waiteeObservationToken = tunnel.observe(\.status) { [weak self] tunnel, _ in
             guard let self = self else { return }
@@ -500,6 +520,7 @@ class TunnelsManager {
             }
         }
     }
+    #endif
 
     private func startObservingTunnelStatuses() {
         statusObservationToken = NotificationCenter.default.observe(name: .NEVPNStatusDidChange, object: nil, queue: OperationQueue.main) { [weak self] statusChangeNotification in
Signature · 1 line
2.50.1 (Apple Git-155)
#5 lore raw

PATCH RESEND 5/10 PacketTunnelProvider: only exit on stop of last tunnel in the process

In reply to Razvan Cremenescu

stopTunnel() works around Apple bug 32073323 by calling exit(0) on macOS. If the OS runs multiple simultaneous tunnel sessions in a single extension process, exiting on the first stop would tear down the remaining sessions too.

Keep a process-wide count of tunnels and only exit once the last one is being stopped. The count covers the whole duration of a start attempt - the adapter can spend seconds in DNS resolution and interface setup - so that a tunnel stopping meanwhile doesn't consider itself the last one in the process and kill a concurrent activation; the failure paths of startTunnel() remove the tunnel from the count again. When each session runs in its own process, the count is always 0 or 1 and the behavior is unchanged.

---
 .../PacketTunnelProvider.swift                | 50 ++++++++++++++++++-
 1 file changed, 49 insertions(+), 1 deletion(-)
Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift +49 -1
index 913b7e6..fe09026 100644
@@ -7,6 +7,38 @@ import os
 
 class PacketTunnelProvider: NEPacketTunnelProvider {
 
+    #if os(macOS)
+    // Number of tunnels starting or started in this process, used to ensure
+    // the exit(0) hack in stopTunnel() doesn't tear down other tunnels in
+    // case the OS runs multiple simultaneous tunnels in a single extension
+    // process. Tunnels are counted for the entire duration of the start
+    // attempt, so that another tunnel stopping meanwhile doesn't consider
+    // itself the last one in the process.
+    private static var startedTunnelCount = 0
+    private static let startedTunnelCountLock = NSLock()
+    private var hasStartedTunnel = false
+
+    private func registerStartedTunnel() {
+        PacketTunnelProvider.startedTunnelCountLock.lock()
+        PacketTunnelProvider.startedTunnelCount += 1
+        hasStartedTunnel = true
+        PacketTunnelProvider.startedTunnelCountLock.unlock()
+    }
+
+    // Returns true if this was the last starting or started tunnel in the
+    // process, i.e. the process is free to exit.
+    @discardableResult
+    private func unregisterStartedTunnel() -> Bool {
+        PacketTunnelProvider.startedTunnelCountLock.lock()
+        defer { PacketTunnelProvider.startedTunnelCountLock.unlock() }
+        if hasStartedTunnel {
+            hasStartedTunnel = false
+            PacketTunnelProvider.startedTunnelCount -= 1
+        }
+        return PacketTunnelProvider.startedTunnelCount == 0
+    }
+    #endif
+
     private lazy var adapter: WireGuardAdapter = {
         return WireGuardAdapter(with: self) { logLevel, message in
             wg_log(logLevel.osLogLevel, message: message)
@@ -21,9 +53,16 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
 
         wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app"))
 
+        #if os(macOS)
+        registerStartedTunnel()
+        #endif
+
         guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol,
               let tunnelConfiguration = tunnelProviderProtocol.asTunnelConfiguration() else {
             errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
+            #if os(macOS)
+            unregisterStartedTunnel()
+            #endif
             completionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
             return
         }
@@ -39,6 +78,10 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
                 return
             }
 
+            #if os(macOS)
+            self.unregisterStartedTunnel()
+            #endif
+
             switch adapterError {
             case .cannotLocateTunnelFileDescriptor:
                 wg_log(.error, staticMessage: "Starting tunnel failed: could not determine file descriptor")
@@ -84,7 +127,12 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
             // HACK: This is a filthy hack to work around Apple bug 32073323 (dup'd by us as 47526107).
             // Remove it when they finally fix this upstream and the fix has been rolled out to
             // sufficient quantities of users.
-            exit(0)
+            // Since multiple tunnels may be active simultaneously, only exit
+            // once the last starting or started tunnel in this process is
+            // being stopped.
+            if self.unregisterStartedTunnel() {
+                exit(0)
+            }
             #endif
         }
     }
Signature · 1 line
2.50.1 (Apple Git-155)
#6 lore raw

PATCH RESEND 6/10 macOS: support multiple simultaneous tunnels in the menu bar UI

In reply to Razvan Cremenescu

Now that TunnelsManager no longer serializes tunnel activation on macOS, generalize the menu bar UI from tracking a single current tunnel to tracking every tunnel in operation:

- TunnelsTracker publishes the list of non-inactive tunnels instead of a single currentTunnel slot.
- StatusMenu keeps the existing presentation when zero or one tunnel is in operation. With more than one, the status line shows the number of tunnels and the Deactivate item becomes Deactivate All, which deactivates every tunnel in operation, including tunnels that are still activating or restarting.
- StatusItemController shows the active icon when all tunnels in operation are active, and the progress animation while any of them is transitioning.
- AppDelegate's quit and App Store update alerts enumerate all active tunnels rather than just one; the App Store alert asks to disable on-demand only for the tunnels that actually have it enabled.

---
 .../Base.lproj/Localizable.strings            |  5 +++
 .../WireGuardApp/UI/macOS/AppDelegate.swift   | 31 ++++++++++++++-----
 .../UI/macOS/StatusItemController.swift       | 14 +++------
 .../WireGuardApp/UI/macOS/StatusMenu.swift    | 25 +++++++++++----
 .../UI/macOS/TunnelsTracker.swift             | 31 +++++++++----------
 5 files changed, 68 insertions(+), 38 deletions(-)
Sources/WireGuardApp/Base.lproj/Localizable.strings +5 -0
index f181953..2e23a91 100644
@@ -64,6 +64,7 @@
 "macToggleStatusButtonActivate" = "Activate";
 "macToggleStatusButtonActivating" = "Activating…";
 "macToggleStatusButtonDeactivate" = "Deactivate";
+"macToggleStatusButtonDeactivateAll" = "Deactivate All";
 "macToggleStatusButtonDeactivating" = "Deactivating…";
 "macToggleStatusButtonReasserting" = "Reactivating…";
 "macToggleStatusButtonRestarting" = "Restarting…";
@@ -369,6 +370,7 @@
 // Mac status display
 
 "macStatus (%@)" = "Status: %@";
+"macStatusMultipleTunnels (%d)" = "%d tunnels";
 
 // Mac editing config
 
@@ -419,6 +421,7 @@
 "macConfirmAndQuitAlertMessage" = "Do you want to close the tunnels manager or quit WireGuard entirely?";
 "macConfirmAndQuitAlertInfo" = "If you close the tunnels manager, WireGuard will continue to be available from the menu bar icon.";
 "macConfirmAndQuitInfoWithActiveTunnel (%@)" = "If you close the tunnels manager, WireGuard will continue to be available from the menu bar icon.\n\nNote that if you quit WireGuard entirely the currently active tunnel ('%@') will still remain active until you deactivate it from this application or through the Network panel in System Preferences.";
+"macConfirmAndQuitInfoWithMultipleActiveTunnels (%@)" = "If you close the tunnels manager, WireGuard will continue to be available from the menu bar icon.\n\nNote that if you quit WireGuard entirely the currently active tunnels ('%@') will still remain active until you deactivate them from this application or through the Network panel in System Preferences.";
 "macConfirmAndQuitAlertQuitWireGuard" = "Quit WireGuard";
 "macConfirmAndQuitAlertCloseWindow" = "Close Tunnels Manager";
 
@@ -448,6 +451,8 @@
 "macAppStoreUpdatingAlertMessage" = "App Store would like to update WireGuard";
 "macAppStoreUpdatingAlertInfoWithOnDemand (%@)" = "Please disable on-demand for tunnel ‘%@’, deactivate it, and then continue updating in App Store.";
 "macAppStoreUpdatingAlertInfoWithoutOnDemand (%@)" = "Please deactivate tunnel ‘%@’ and then continue updating in App Store.";
+"macAppStoreUpdatingAlertInfoWithOnDemandMultiple (%@)" = "Please disable on-demand for tunnels ‘%@’, deactivate all active tunnels, and then continue updating in App Store.";
+"macAppStoreUpdatingAlertInfoWithoutOnDemandMultiple (%@)" = "Please deactivate tunnels ‘%@’ and then continue updating in App Store.";
 
 // Donation
 
Sources/WireGuardApp/UI/macOS/AppDelegate.swift +24 -7
index 1dda3e6..b9c3a53 100644
@@ -65,11 +65,18 @@ class AppDelegate: NSObject, NSApplicationDelegate {
         }
     }
 
+    private var activeTunnels: [TunnelContainer] {
+        return tunnelsTracker?.tunnelsInOperation.filter { $0.status == .active || $0.status == .activating } ?? []
+    }
+
     @objc func confirmAndQuit() {
         let alert = NSAlert()
         alert.messageText = tr("macConfirmAndQuitAlertMessage")
-        if let currentTunnel = tunnelsTracker?.currentTunnel, currentTunnel.status == .active || currentTunnel.status == .activating {
-            alert.informativeText = tr(format: "macConfirmAndQuitInfoWithActiveTunnel (%@)", currentTunnel.name)
+        let activeTunnels = self.activeTunnels
+        if activeTunnels.count == 1 {
+            alert.informativeText = tr(format: "macConfirmAndQuitInfoWithActiveTunnel (%@)", activeTunnels[0].name)
+        } else if activeTunnels.count > 1 {
+            alert.informativeText = tr(format: "macConfirmAndQuitInfoWithMultipleActiveTunnels (%@)", activeTunnels.map { $0.name }.joined(separator: ", "))
         } else {
             alert.informativeText = tr("macConfirmAndQuitAlertInfo")
         }
@@ -99,7 +106,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
             return
         }
         registerLoginItem(shouldLaunchAtLogin: false)
-        guard let currentTunnel = tunnelsTracker?.currentTunnel, currentTunnel.status == .active || currentTunnel.status == .activating else {
+        guard !activeTunnels.isEmpty else {
             NSApp.terminate(nil)
             return
         }
@@ -119,7 +126,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
     }
 
     func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
-        guard let currentTunnel = tunnelsTracker?.currentTunnel, currentTunnel.status == .active || currentTunnel.status == .activating else {
+        let activeTunnels = self.activeTunnels
+        guard !activeTunnels.isEmpty else {
             return .terminateNow
         }
         guard let appleEvent = NSAppleEventManager.shared().currentAppleEvent else {
@@ -130,10 +138,19 @@ class AppDelegate: NSObject, NSApplicationDelegate {
         }
         let alert = NSAlert()
         alert.messageText = tr("macAppStoreUpdatingAlertMessage")
-        if currentTunnel.isActivateOnDemandEnabled {
-            alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithOnDemand (%@)", currentTunnel.name)
+        let onDemandTunnels = activeTunnels.filter { $0.isActivateOnDemandEnabled }
+        if activeTunnels.count == 1 {
+            if onDemandTunnels.isEmpty {
+                alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithoutOnDemand (%@)", activeTunnels[0].name)
+            } else {
+                alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithOnDemand (%@)", activeTunnels[0].name)
+            }
         } else {
-            alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithoutOnDemand (%@)", currentTunnel.name)
+            if onDemandTunnels.isEmpty {
+                alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithoutOnDemandMultiple (%@)", activeTunnels.map { $0.name }.joined(separator: ", "))
+            } else {
+                alert.informativeText = tr(format: "macAppStoreUpdatingAlertInfoWithOnDemandMultiple (%@)", onDemandTunnels.map { $0.name }.joined(separator: ", "))
+            }
         }
         NSApp.activate(ignoringOtherApps: true)
         if let manageWindow = manageTunnelsWindowObject {
Sources/WireGuardApp/UI/macOS/StatusItemController.swift +5 -9
index 3088574..e4ff7a5 100644
@@ -4,7 +4,7 @@
 import Cocoa
 
 class StatusItemController {
-    var currentTunnel: TunnelContainer? {
+    var tunnelsInOperation: [TunnelContainer] = [] {
         didSet {
             updateStatusItemImage()
         }
@@ -27,20 +27,16 @@ class StatusItemController {
     }
 
     func updateStatusItemImage() {
-        guard let currentTunnel = currentTunnel else {
+        guard !tunnelsInOperation.isEmpty else {
             stopActivatingAnimation()
             statusItem.button?.image = statusBarImageWhenInactive
             return
         }
-        switch currentTunnel.status {
-        case .inactive:
-            stopActivatingAnimation()
-            statusItem.button?.image = statusBarImageWhenInactive
-        case .active:
+        if tunnelsInOperation.contains(where: { $0.status != .active }) {
+            startActivatingAnimation()
+        } else {
             stopActivatingAnimation()
             statusItem.button?.image = statusBarImageWhenActive
-        case .activating, .waiting, .reasserting, .restarting, .deactivating:
-            startActivatingAnimation()
         }
     }
 
Sources/WireGuardApp/UI/macOS/StatusMenu.swift +19 -6
index 45d2283..9ebdca2 100644
@@ -23,9 +23,9 @@ class StatusMenu: NSMenu {
     private var numberOfTunnelMenuItems = 0
     private var tunnelsPresentationStyle = StatusMenuTunnelsPresentationStyle.inline
 
-    var currentTunnel: TunnelContainer? {
+    var tunnelsInOperation: [TunnelContainer] = [] {
         didSet {
-            updateStatusMenuItems(with: currentTunnel)
+            updateStatusMenuItems()
         }
     }
     weak var windowDelegate: StatusMenuWindowDelegate?
@@ -73,15 +73,27 @@ class StatusMenu: NSMenu {
         self.deactivateMenuItem = deactivateMenuItem
     }
 
-    func updateStatusMenuItems(with tunnel: TunnelContainer?) {
+    func updateStatusMenuItems() {
         guard let statusMenuItem = statusMenuItem, let networksMenuItem = networksMenuItem, let deactivateMenuItem = deactivateMenuItem else { return }
-        guard let tunnel = tunnel else {
+        guard !tunnelsInOperation.isEmpty else {
             statusMenuItem.title = tr(format: "macStatus (%@)", tr("tunnelStatusInactive"))
             networksMenuItem.title = ""
             networksMenuItem.isHidden = true
+            deactivateMenuItem.title = tr("macToggleStatusButtonDeactivate")
             deactivateMenuItem.isHidden = true
             return
         }
+
+        guard tunnelsInOperation.count == 1 else {
+            statusMenuItem.title = tr(format: "macStatus (%@)", tr(format: "macStatusMultipleTunnels (%d)", tunnelsInOperation.count))
+            networksMenuItem.title = ""
+            networksMenuItem.isHidden = true
+            deactivateMenuItem.title = tr("macToggleStatusButtonDeactivateAll")
+            deactivateMenuItem.isHidden = !tunnelsInOperation.contains { $0.status == .active }
+            return
+        }
+
+        let tunnel = tunnelsInOperation[0]
         var statusText: String
 
         switch tunnel.status {
@@ -115,6 +127,7 @@ class StatusMenu: NSMenu {
             }
             networksMenuItem.isHidden = false
         }
+        deactivateMenuItem.title = tr("macToggleStatusButtonDeactivate")
         deactivateMenuItem.isHidden = tunnel.status != .active
     }
 
@@ -137,8 +150,8 @@ class StatusMenu: NSMenu {
     }
 
     @objc func deactivateClicked() {
-        if let currentTunnel = currentTunnel {
-            tunnelsManager.startDeactivation(of: currentTunnel)
+        for tunnel in tunnelsInOperation {
+            tunnelsManager.startDeactivation(of: tunnel)
         }
     }
 
Sources/WireGuardApp/UI/macOS/TunnelsTracker.swift +15 -16
index 0ab59ee..ab8b478 100644
@@ -12,28 +12,28 @@ class TunnelsTracker {
 
     weak var statusMenu: StatusMenu? {
         didSet {
-            statusMenu?.currentTunnel = currentTunnel
+            statusMenu?.tunnelsInOperation = tunnelsInOperation
         }
     }
     weak var statusItemController: StatusItemController? {
         didSet {
-            statusItemController?.currentTunnel = currentTunnel
+            statusItemController?.tunnelsInOperation = tunnelsInOperation
         }
     }
     weak var manageTunnelsRootVC: ManageTunnelsRootViewController?
 
     private var tunnelsManager: TunnelsManager
     private var tunnelStatusObservers = [AnyObject]()
-    private(set) var currentTunnel: TunnelContainer? {
+    private(set) var tunnelsInOperation: [TunnelContainer] {
         didSet {
-            statusMenu?.currentTunnel = currentTunnel
-            statusItemController?.currentTunnel = currentTunnel
+            statusMenu?.tunnelsInOperation = tunnelsInOperation
+            statusItemController?.tunnelsInOperation = tunnelsInOperation
         }
     }
 
     init(tunnelsManager: TunnelsManager) {
         self.tunnelsManager = tunnelsManager
-        currentTunnel = tunnelsManager.tunnelInOperation()
+        tunnelsInOperation = tunnelsManager.tunnelsInOperation()
 
         for index in 0 ..< tunnelsManager.numberOfTunnels() {
             let tunnel = tunnelsManager.tunnel(at: index)
@@ -46,15 +46,11 @@ class TunnelsTracker {
     }
 
     func observeStatus(of tunnel: TunnelContainer) -> AnyObject {
-        return tunnel.observe(\.status) { [weak self] tunnel, _ in
+        return tunnel.observe(\.status) { [weak self] _, _ in
             guard let self = self else { return }
-            if tunnel.status == .deactivating || tunnel.status == .inactive {
-                if self.currentTunnel == tunnel {
-                    self.currentTunnel = self.tunnelsManager.tunnelInOperation()
-                }
-            } else {
-                self.currentTunnel = tunnel
-            }
+            // Always reassign, so that observers get to update their
+            // presentation even when the set of tunnels doesn't change.
+            self.tunnelsInOperation = self.tunnelsManager.tunnelsInOperation()
         }
     }
 }
@@ -62,8 +58,8 @@ class TunnelsTracker {
 extension TunnelsTracker: TunnelsManagerListDelegate {
     func tunnelAdded(at index: Int) {
         let tunnel = tunnelsManager.tunnel(at: index)
-        if tunnel.status != .deactivating && tunnel.status != .inactive {
-            self.currentTunnel = tunnel
+        if tunnel.status != .inactive {
+            tunnelsInOperation = tunnelsManager.tunnelsInOperation()
         }
         let statusObservationToken = observeStatus(of: tunnel)
         tunnelStatusObservers.insert(statusObservationToken, at: index)
@@ -86,6 +82,9 @@ extension TunnelsTracker: TunnelsManagerListDelegate {
 
     func tunnelRemoved(at index: Int, tunnel: TunnelContainer) {
         tunnelStatusObservers.remove(at: index)
+        if tunnelsInOperation.contains(tunnel) {
+            tunnelsInOperation = tunnelsManager.tunnelsInOperation()
+        }
 
         statusMenu?.removeTunnelMenuItem(at: index)
         manageTunnelsRootVC?.tunnelsListVC?.tunnelRemoved(at: index)
Signature · 1 line
2.50.1 (Apple Git-155)
#7 lore raw

PATCH RESEND 7/10 Add opt-in split DNS support

In reply to Razvan Cremenescu

When a tunnel lists DNS search domains (the non-IP entries of the wg-quick DNS= line), the tunnel's DNS servers have so far always been installed as the system-wide resolver (match domains [""]) while the search domains only served for completing short names. With multiple simultaneous tunnels this makes concurrently active tunnels fight over system DNS, and there was no way to use a tunnel's DNS only for the internal domains behind that tunnel.

Add a per-tunnel Split DNS toggle, stored in the provider configuration alongside the existing keys so the wg-quick config text remains untouched and portable. When enabled and the tunnel has search domains, the DNS servers are installed with the search domains as match domains, so only queries for those domains go through the tunnel; everything else stays on the system resolver. The default remains the current match-everything behavior, so existing full-tunnel setups keep their leak-free DNS.

The toggle is exposed as a checkbox in the macOS tunnel editor and as a switch in the iOS tunnel editor, and toggling it restarts an active tunnel the same way a configuration edit does.

---
 .../NETunnelProviderProtocol+Extension.swift  | 26 +++++++++++++
 .../Base.lproj/Localizable.strings            |  6 +++
 .../WireGuardApp/Tunnel/TunnelsManager.swift  | 17 +++++++-
 .../TunnelEditTableViewController.swift       | 39 ++++++++++++++++++-
 .../TunnelEditViewController.swift            | 21 +++++++++-
 .../PacketTunnelSettingsGenerator.swift       | 12 +++++-
 Sources/WireGuardKit/WireGuardAdapter.swift   | 13 ++++++-
 .../PacketTunnelProvider.swift                |  2 +-
 8 files changed, 125 insertions(+), 11 deletions(-)
Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift +26 -0
index 0a303f4..8f56434 100644
@@ -12,6 +12,21 @@ enum PacketTunnelProviderError: String, Error {
 }
 
 extension NETunnelProviderProtocol {
+    private static let splitDNSKey = "SplitDNS"
+
+    /// When enabled, the tunnel's DNS servers are used only for the tunnel's
+    /// DNS search domains rather than for all queries on the system.
+    var isSplitDNSEnabled: Bool {
+        get {
+            return providerConfiguration?[Self.splitDNSKey] as? Bool ?? false
+        }
+        set {
+            var configuration = providerConfiguration ?? [:]
+            configuration[Self.splitDNSKey] = newValue
+            providerConfiguration = configuration
+        }
+    }
+
     convenience init?(tunnelConfiguration: TunnelConfiguration, previouslyFrom old: NEVPNProtocol? = nil) {
         self.init()
 
@@ -25,6 +40,9 @@ extension NETunnelProviderProtocol {
         #if os(macOS)
         providerConfiguration = ["UID": getuid()]
         #endif
+        if let old = old as? NETunnelProviderProtocol, old.isSplitDNSEnabled {
+            isSplitDNSEnabled = true
+        }
 
         let endpoints = tunnelConfiguration.peers.compactMap { $0.endpoint }
         if endpoints.count == 1 {
@@ -64,6 +82,7 @@ extension NETunnelProviderProtocol {
          * around so that .mobileconfig files are easier.
          */
         if let oldConfig = providerConfiguration?["WgQuickConfig"] as? String {
+            let wasSplitDNSEnabled = isSplitDNSEnabled
             #if os(macOS)
             providerConfiguration = ["UID": getuid()]
             #elseif os(iOS)
@@ -71,6 +90,9 @@ extension NETunnelProviderProtocol {
             #else
             #error("Unimplemented")
             #endif
+            if wasSplitDNSEnabled {
+                isSplitDNSEnabled = true
+            }
             guard passwordReference == nil else { return true }
             wg_log(.info, message: "Migrating tunnel configuration '\(name)'")
             passwordReference = Keychain.makeReference(containing: oldConfig, called: name)
@@ -78,7 +100,11 @@ extension NETunnelProviderProtocol {
         }
         #if os(macOS)
         if passwordReference != nil && providerConfiguration?["UID"] == nil && verifyConfigurationReference() {
+            let wasSplitDNSEnabled = isSplitDNSEnabled
             providerConfiguration = ["UID": getuid()]
+            if wasSplitDNSEnabled {
+                isSplitDNSEnabled = true
+            }
             return true
         }
         #elseif os(iOS)
Sources/WireGuardApp/Base.lproj/Localizable.strings +6 -0
index 2e23a91..cacb316 100644
@@ -97,6 +97,12 @@
 "tunnelPeerLastHandshakeTime" = "Latest handshake";
 "tunnelPeerExcludePrivateIPs" = "Exclude private IPs";
 
+"tunnelSectionTitleSplitDNS" = "DNS";
+"tunnelEditSplitDNS" = "Split DNS";
+"tunnelEditSplitDNSTooltip" = "Use the tunnel's DNS servers only for the tunnel's DNS search domains, instead of for all queries on the system.";
+"alertSplitDNSRequiresSearchDomainsTitle" = "Split DNS requires DNS servers and search domains";
+"alertSplitDNSRequiresSearchDomainsMessage" = "To use split DNS, list both the DNS servers and the domains to route through them in the tunnel's DNS entry, e.g.: 'DNS = 10.0.0.53, corp.example.com'";
+
 "tunnelSectionTitleOnDemand" = "On-Demand Activation";
 
 "tunnelOnDemandCellular" = "Cellular";
Sources/WireGuardApp/Tunnel/TunnelsManager.swift +15 -2
index 63e1847..18829fe 100644
@@ -119,7 +119,7 @@ class TunnelsManager {
         }
     }
 
-    func add(tunnelConfiguration: TunnelConfiguration, onDemandOption: ActivateOnDemandOption = .off, completionHandler: @escaping (Result<TunnelContainer, TunnelsManagerError>) -> Void) {
+    func add(tunnelConfiguration: TunnelConfiguration, onDemandOption: ActivateOnDemandOption = .off, isSplitDNSEnabled: Bool = false, completionHandler: @escaping (Result<TunnelContainer, TunnelsManagerError>) -> Void) {
         let tunnelName = tunnelConfiguration.name ?? ""
         if tunnelName.isEmpty {
             completionHandler(.failure(TunnelsManagerError.tunnelNameEmpty))
@@ -133,6 +133,7 @@ class TunnelsManager {
 
         let tunnelProviderManager = NETunnelProviderManager()
         tunnelProviderManager.setTunnelConfiguration(tunnelConfiguration)
+        (tunnelProviderManager.protocolConfiguration as? NETunnelProviderProtocol)?.isSplitDNSEnabled = isSplitDNSEnabled
         tunnelProviderManager.isEnabled = true
 
         onDemandOption.apply(on: tunnelProviderManager)
@@ -210,6 +211,7 @@ class TunnelsManager {
 
     func modify(tunnel: TunnelContainer, tunnelConfiguration: TunnelConfiguration,
                 onDemandOption: ActivateOnDemandOption,
+                isSplitDNSEnabled: Bool? = nil,
                 shouldEnsureOnDemandEnabled: Bool = false,
                 completionHandler: @escaping (TunnelsManagerError?) -> Void) {
         let tunnelName = tunnelConfiguration.name ?? ""
@@ -224,7 +226,8 @@ class TunnelsManager {
         if isIntroducingOnDemandRules && tunnel.status != .inactive && tunnel.status != .deactivating {
             tunnel.onDeactivated = { [weak self] in
                 self?.modify(tunnel: tunnel, tunnelConfiguration: tunnelConfiguration,
-                             onDemandOption: onDemandOption, shouldEnsureOnDemandEnabled: true,
+                             onDemandOption: onDemandOption, isSplitDNSEnabled: isSplitDNSEnabled,
+                             shouldEnsureOnDemandEnabled: true,
                              completionHandler: completionHandler)
             }
             self.startDeactivation(of: tunnel)
@@ -248,6 +251,12 @@ class TunnelsManager {
             tunnelProviderManager.setTunnelConfiguration(tunnelConfiguration)
             isTunnelConfigurationChanged = true
         }
+        if let isSplitDNSEnabled = isSplitDNSEnabled,
+           let proto = tunnelProviderManager.protocolConfiguration as? NETunnelProviderProtocol,
+           proto.isSplitDNSEnabled != isSplitDNSEnabled {
+            proto.isSplitDNSEnabled = isSplitDNSEnabled
+            isTunnelConfigurationChanged = true
+        }
         tunnelProviderManager.isEnabled = true
 
         let isActivatingOnDemand = !tunnelProviderManager.isOnDemandEnabled && shouldEnsureOnDemandEnabled
@@ -637,6 +646,10 @@ class TunnelContainer: NSObject {
         return ActivateOnDemandOption(from: tunnelProvider)
     }
 
+    var isSplitDNSEnabled: Bool {
+        return (tunnelProvider.protocolConfiguration as? NETunnelProviderProtocol)?.isSplitDNSEnabled ?? false
+    }
+
     #if os(macOS)
     var isTunnelAvailableToUser: Bool {
         return (tunnelProvider.protocolConfiguration as? NETunnelProviderProtocol)?.providerConfiguration?["UID"] as? uid_t == getuid()
Sources/WireGuardApp/UI/iOS/ViewController/TunnelEditTableViewController.swift +37 -2
index dfb35c6..e79686f 100644
@@ -13,12 +13,14 @@ class TunnelEditTableViewController: UITableViewController {
         case interface
         case peer(_ peer: TunnelViewModel.PeerData)
         case addPeer
+        case splitDNS
         case onDemand
 
         static func == (lhs: Section, rhs: Section) -> Bool {
             switch (lhs, rhs) {
             case (.interface, .interface),
                  (.addPeer, .addPeer),
+                 (.splitDNS, .splitDNS),
                  (.onDemand, .onDemand):
                 return true
             case let (.peer(peerA), .peer(peerB)):
@@ -53,6 +55,7 @@ class TunnelEditTableViewController: UITableViewController {
     let tunnel: TunnelContainer?
     let tunnelViewModel: TunnelViewModel
     var onDemandViewModel: ActivateOnDemandViewModel
+    private var isSplitDNSEnabled: Bool
     private var sections = [Section]()
 
     // Use this initializer to edit an existing tunnel.
@@ -61,6 +64,7 @@ class TunnelEditTableViewController: UITableViewController {
         self.tunnel = tunnel
         tunnelViewModel = TunnelViewModel(tunnelConfiguration: tunnel.tunnelConfiguration)
         onDemandViewModel = ActivateOnDemandViewModel(tunnel: tunnel)
+        isSplitDNSEnabled = tunnel.isSplitDNSEnabled
         super.init(style: .grouped)
         loadSections()
     }
@@ -71,6 +75,7 @@ class TunnelEditTableViewController: UITableViewController {
         tunnel = nil
         tunnelViewModel = TunnelViewModel(tunnelConfiguration: nil)
         onDemandViewModel = ActivateOnDemandViewModel()
+        isSplitDNSEnabled = false
         super.init(style: .grouped)
         loadSections()
     }
@@ -100,6 +105,7 @@ class TunnelEditTableViewController: UITableViewController {
         interfaceFieldsBySection.forEach { _ in sections.append(.interface) }
         tunnelViewModel.peersData.forEach { sections.append(.peer($0)) }
         sections.append(.addPeer)
+        sections.append(.splitDNS)
         sections.append(.onDemand)
     }
 
@@ -113,10 +119,14 @@ class TunnelEditTableViewController: UITableViewController {
             ErrorPresenter.showErrorAlert(title: alertTitle, message: errorMessage, from: self)
             tableView.reloadData() // Highlight erroring fields
         case .saved(let tunnelConfiguration):
+            if isSplitDNSEnabled && (tunnelConfiguration.interface.dns.isEmpty || tunnelConfiguration.interface.dnsSearch.filter({ !$0.isEmpty }).isEmpty) {
+                ErrorPresenter.showErrorAlert(title: tr("alertSplitDNSRequiresSearchDomainsTitle"), message: tr("alertSplitDNSRequiresSearchDomainsMessage"), from: self)
+                return
+            }
             let onDemandOption = onDemandViewModel.toOnDemandOption()
             if let tunnel = tunnel {
                 // We're modifying an existing tunnel
-                tunnelsManager.modify(tunnel: tunnel, tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption) { [weak self] error in
+                tunnelsManager.modify(tunnel: tunnel, tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption, isSplitDNSEnabled: isSplitDNSEnabled) { [weak self] error in
                     if let error = error {
                         ErrorPresenter.showErrorAlert(error: error, from: self)
                     } else {
@@ -126,7 +136,7 @@ class TunnelEditTableViewController: UITableViewController {
                 }
             } else {
                 // We're adding a new tunnel
-                tunnelsManager.add(tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption) { [weak self] result in
+                tunnelsManager.add(tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption, isSplitDNSEnabled: isSplitDNSEnabled) { [weak self] result in
                     switch result {
                     case .failure(let error):
                         ErrorPresenter.showErrorAlert(error: error, from: self)
@@ -161,6 +171,8 @@ extension TunnelEditTableViewController {
             return peerFieldsToShow.count
         case .addPeer:
             return 1
+        case .splitDNS:
+            return 1
         case .onDemand:
             if onDemandViewModel.isWiFiInterfaceEnabled {
                 return 3
@@ -178,11 +190,22 @@ extension TunnelEditTableViewController {
             return tr("tunnelSectionTitlePeer")
         case .addPeer:
             return nil
+        case .splitDNS:
+            return tr("tunnelSectionTitleSplitDNS")
         case .onDemand:
             return tr("tunnelSectionTitleOnDemand")
         }
     }
 
+    override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
+        switch sections[section] {
+        case .splitDNS:
+            return tr("tunnelEditSplitDNSTooltip")
+        default:
+            return nil
+        }
+    }
+
     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         switch sections[indexPath.section] {
         case .interface:
@@ -191,6 +214,8 @@ extension TunnelEditTableViewController {
             return peerCell(for: tableView, at: indexPath, with: peerData)
         case .addPeer:
             return addPeerCell(for: tableView, at: indexPath)
+        case .splitDNS:
+            return splitDNSCell(for: tableView, at: indexPath)
         case .onDemand:
             return onDemandCell(for: tableView, at: indexPath)
         }
@@ -423,6 +448,16 @@ extension TunnelEditTableViewController {
         return cell
     }
 
+    private func splitDNSCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
+        let cell: SwitchCell = tableView.dequeueReusableCell(for: indexPath)
+        cell.message = tr("tunnelEditSplitDNS")
+        cell.isOn = isSplitDNSEnabled
+        cell.onSwitchToggled = { [weak self] isOn in
+            self?.isSplitDNSEnabled = isOn
+        }
+        return cell
+    }
+
     private func onDemandCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
         let field = onDemandFields[indexPath.row]
         if indexPath.row < 2 {
Sources/WireGuardApp/UI/macOS/ViewController/TunnelEditViewController.swift +19 -2
index 851498a..8065bdc 100644
@@ -60,6 +60,15 @@ class TunnelEditViewController: NSViewController {
         return checkbox
     }()
 
+    let splitDNSCheckbox: NSButton = {
+        let checkbox = NSButton()
+        checkbox.title = tr("tunnelEditSplitDNS")
+        checkbox.toolTip = tr("tunnelEditSplitDNSTooltip")
+        checkbox.setButtonType(.switch)
+        checkbox.state = .off
+        return checkbox
+    }()
+
     let discardButton: NSButton = {
         let button = NSButton()
         button.title = tr("macEditDiscard")
@@ -106,6 +115,7 @@ class TunnelEditViewController: NSViewController {
             // Editing an existing tunnel
             let tunnelConfiguration = tunnel.tunnelConfiguration!
             nameRow.value = tunnel.name
+            splitDNSCheckbox.state = tunnel.isSplitDNSEnabled ? .on : .off
             textView.string = tunnelConfiguration.asWgQuickConfig()
             publicKeyRow.value = tunnelConfiguration.interface.privateKey.publicKey.base64Key
             textView.privateKeyString = tunnelConfiguration.interface.privateKey.base64Key
@@ -163,6 +173,7 @@ class TunnelEditViewController: NSViewController {
 
         let buttonRowStackView = NSStackView()
         buttonRowStackView.setViews([discardButton, saveButton], in: .trailing)
+        buttonRowStackView.addView(splitDNSCheckbox, in: .leading)
         buttonRowStackView.addView(excludePrivateIPsCheckbox, in: .leading)
         buttonRowStackView.orientation = .horizontal
         buttonRowStackView.spacing = internalSpacing
@@ -229,11 +240,17 @@ class TunnelEditViewController: NSViewController {
             }
         }
 
+        let isSplitDNSEnabled = splitDNSCheckbox.state == .on
+        if isSplitDNSEnabled && (tunnelConfiguration.interface.dns.isEmpty || tunnelConfiguration.interface.dnsSearch.filter({ !$0.isEmpty }).isEmpty) {
+            ErrorPresenter.showErrorAlert(title: tr("alertSplitDNSRequiresSearchDomainsTitle"), message: tr("alertSplitDNSRequiresSearchDomainsMessage"), from: self)
+            return
+        }
+
         setUserInteractionEnabled(false)
 
         if let tunnel = tunnel {
             // We're modifying an existing tunnel
-            tunnelsManager.modify(tunnel: tunnel, tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption) { [weak self] error in
+            tunnelsManager.modify(tunnel: tunnel, tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption, isSplitDNSEnabled: isSplitDNSEnabled) { [weak self] error in
                 guard let self = self else { return }
                 self.setUserInteractionEnabled(true)
                 if let error = error {
@@ -245,7 +262,7 @@ class TunnelEditViewController: NSViewController {
             }
         } else {
             // We're creating a new tunnel
-            self.tunnelsManager.add(tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption) { [weak self] result in
+            self.tunnelsManager.add(tunnelConfiguration: tunnelConfiguration, onDemandOption: onDemandOption, isSplitDNSEnabled: isSplitDNSEnabled) { [weak self] result in
                 guard let self = self else { return }
                 self.setUserInteractionEnabled(true)
                 switch result {
Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift +10 -2
index 3658956..36c0e06 100644
@@ -15,10 +15,12 @@ typealias EndpointResolutionResult = Result<(Endpoint, Endpoint), DNSResolutionE
 class PacketTunnelSettingsGenerator {
     let tunnelConfiguration: TunnelConfiguration
     let resolvedEndpoints: [Endpoint?]
+    let isSplitDNSEnabled: Bool
 
-    init(tunnelConfiguration: TunnelConfiguration, resolvedEndpoints: [Endpoint?]) {
+    init(tunnelConfiguration: TunnelConfiguration, resolvedEndpoints: [Endpoint?], isSplitDNSEnabled: Bool = false) {
         self.tunnelConfiguration = tunnelConfiguration
         self.resolvedEndpoints = resolvedEndpoints
+        self.isSplitDNSEnabled = isSplitDNSEnabled
     }
 
     func endpointUapiConfiguration() -> (String, [EndpointResolutionResult?]) {
@@ -88,7 +90,13 @@ class PacketTunnelSettingsGenerator {
             let dnsSettings = NEDNSSettings(servers: dnsServerStrings)
             dnsSettings.searchDomains = tunnelConfiguration.interface.dnsSearch
             if !tunnelConfiguration.interface.dns.isEmpty {
-                dnsSettings.matchDomains = [""] // All DNS queries must first go through the tunnel's DNS
+                let splitDNSMatchDomains = isSplitDNSEnabled ? tunnelConfiguration.interface.dnsSearch.filter { !$0.isEmpty } : []
+                if !splitDNSMatchDomains.isEmpty {
+                    // Use the tunnel's DNS only for the tunnel's search domains
+                    dnsSettings.matchDomains = splitDNSMatchDomains
+                } else {
+                    dnsSettings.matchDomains = [""] // All DNS queries must first go through the tunnel's DNS
+                }
             }
             networkSettings.dnsSettings = dnsSettings
         }
Sources/WireGuardKit/WireGuardAdapter.swift +11 -2
index ba49ec7..82728e4 100644
@@ -56,6 +56,10 @@ public class WireGuardAdapter {
     /// Adapter state.
     private var state: State = .stopped
 
+    /// Whether the tunnel's DNS servers should be used only for the tunnel's
+    /// DNS search domains rather than for all queries on the system.
+    private var isSplitDNSEnabled = false
+
     /// Tunnel device file descriptors claimed by the adapters in this process.
     /// When multiple tunnels run in a single extension process, each adapter
     /// must attach to its own utun device rather than to the first one found.
@@ -265,14 +269,18 @@ public class WireGuardAdapter {
     /// Start the tunnel tunnel.
     /// - Parameters:
     ///   - tunnelConfiguration: tunnel configuration.
+    ///   - isSplitDNSEnabled: use the tunnel's DNS servers only for the
+    ///     tunnel's DNS search domains rather than for all queries.
     ///   - completionHandler: completion handler.
-    public func start(tunnelConfiguration: TunnelConfiguration, completionHandler: @escaping (WireGuardAdapterError?) -> Void) {
+    public func start(tunnelConfiguration: TunnelConfiguration, isSplitDNSEnabled: Bool = false, completionHandler: @escaping (WireGuardAdapterError?) -> Void) {
         workQueue.async {
             guard case .stopped = self.state else {
                 completionHandler(.invalidState)
                 return
             }
 
+            self.isSplitDNSEnabled = isSplitDNSEnabled
+
             let networkMonitor = NWPathMonitor()
             networkMonitor.pathUpdateHandler = { [weak self] path in
                 self?.didReceivePathUpdate(path: path)
@@ -486,7 +494,8 @@ public class WireGuardAdapter {
     private func makeSettingsGenerator(with tunnelConfiguration: TunnelConfiguration) throws -> PacketTunnelSettingsGenerator {
         return PacketTunnelSettingsGenerator(
             tunnelConfiguration: tunnelConfiguration,
-            resolvedEndpoints: try self.resolvePeers(for: tunnelConfiguration)
+            resolvedEndpoints: try self.resolvePeers(for: tunnelConfiguration),
+            isSplitDNSEnabled: isSplitDNSEnabled
         )
     }
 
Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift +1 -1
index fe09026..ac8050c 100644
@@ -68,7 +68,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
         }
 
         // Start the tunnel
-        adapter.start(tunnelConfiguration: tunnelConfiguration) { adapterError in
+        adapter.start(tunnelConfiguration: tunnelConfiguration, isSplitDNSEnabled: tunnelProviderProtocol.isSplitDNSEnabled) { adapterError in
             guard let adapterError = adapterError else {
                 let interfaceName = self.adapter.interfaceName ?? "unknown"
 
Signature · 1 line
2.50.1 (Apple Git-155)
#8 lore raw

PATCH RESEND 8/10 macOS: activate the app before showing a modal alert without a window

In reply to Razvan Cremenescu

WireGuard runs as a menu bar accessory app. When an error alert has no source window to attach to as a sheet - e.g. an activation failure while the Manage Tunnels window is closed - it falls back to NSAlert.runModal(). Shown while the app is inactive, the modal window comes up behind everything with no way to reach it, and the modal loop freezes the whole app until it is dismissed. Activate the app first so the alert is actually visible.

---
 Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift | 5 +++++
 1 file changed, 5 insertions(+)
Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift +5 -0
index dbab027..b3884ff 100644
@@ -16,6 +16,11 @@ class ErrorPresenter: ErrorPresenterProtocol {
                 onDismissal?()
             }
         } else {
+            // WireGuard runs as a menu bar (accessory) app, which is usually
+            // not the active app. A modal alert shown while inactive comes up
+            // behind other windows with no way to reach it, freezing the app
+            // until it is dismissed. Activate first so the alert is visible.
+            NSApp.activate(ignoringOtherApps: true)
             alert.runModal()
             onDismissal?()
         }
Signature · 1 line
2.50.1 (Apple Git-155)
#9 lore raw

PATCH RESEND 9/10 macOS: don't crash opening the editor for an unreadable tunnel

In reply to Razvan Cremenescu

TunnelEditViewController.populateFields() force-unwraps the tunnel's configuration. When the saved configuration cannot be read - for instance when its keychain entry is inaccessible - that configuration is nil and opening the editor traps. Check that the configuration is readable before presenting the editor and report the failure instead.

---
 Sources/WireGuardApp/Base.lproj/Localizable.strings        | 1 +
 .../ViewController/TunnelDetailTableViewController.swift   | 7 +++++++
 2 files changed, 8 insertions(+)
Sources/WireGuardApp/Base.lproj/Localizable.strings +1 -0
index cacb316..23037ce 100644
@@ -385,6 +385,7 @@
 
 "macAlertNameIsEmpty" = "Name is required";
 "macAlertDuplicateName (%@)" = "Another tunnel already exists with the name ‘%@’.";
+"macAlertCannotReadConfigTitle" = "Unable to read configuration";
 
 "macAlertInvalidLine (%@)" = "Invalid line: ‘%@’.";
 
Sources/WireGuardApp/UI/macOS/ViewController/TunnelDetailTableViewController.swift +7 -0
index 41d2b15..f1526d7 100644
@@ -208,6 +208,13 @@ class TunnelDetailTableViewController: NSViewController {
     @objc func handleEditTunnelAction() {
         PrivateDataConfirmation.confirmAccess(to: tr("macViewPrivateData")) { [weak self] in
             guard let self = self else { return }
+            guard self.tunnel.tunnelConfiguration != nil else {
+                // The configuration could not be read (e.g. the keychain entry
+                // is inaccessible). Opening the editor would crash, so report
+                // the failure instead.
+                ErrorPresenter.showErrorAlert(title: tr("macAlertCannotReadConfigTitle"), message: tr("alertTunnelActivationSavedConfigFailureMessage"), from: self)
+                return
+            }
             let tunnelEditVC = TunnelEditViewController(tunnelsManager: self.tunnelsManager, tunnel: self.tunnel)
             tunnelEditVC.delegate = self
             self.presentAsSheet(tunnelEditVC)
Signature · 1 line
2.50.1 (Apple Git-155)
#10 lore raw

PATCH RESEND 10/10 macOS: reset peer endpoints after a network change

In reply to Razvan Cremenescu

On iOS a network change sets the peer endpoints again before bumping the sockets, but on macOS the path update handler only bumps the sockets, leaving whatever endpoint each peer currently has. That breaks tunnels across a network change in two ways.

A peer configured with a hostname keeps the address the hostname resolved to on the previous network, so a dynamic DNS record that moved, or a name that resolves differently per network, is never picked up.

Worse, a peer that roamed keeps the roamed address. A server reached at an address that only exists on one network - its address inside another tunnel, or on the LAN it is hosted on - leaves the peer pinned to that address once the machine moves, and every handshake then fails with 'no route to host' until the tunnel is deactivated and activated again.

Set the endpoints of all peers again after a network change, re-resolving the ones configured with a hostname. Resolution failures keep the address the hostname last resolved to, so a network without working DNS does not tear the endpoints down.

The work is delayed and coalesced, since a single network change produces a burst of path updates and resolution blocks the queue. Peers configured with a literal address need no resolution at all.

---
 .../PacketTunnelSettingsGenerator.swift       | 47 +++++++++++++++-
 Sources/WireGuardKit/WireGuardAdapter.swift   | 53 +++++++++++++++++++
 2 files changed, 99 insertions(+), 1 deletion(-)
Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift +46 -1
index 36c0e06..3a8453d 100644
@@ -14,7 +14,7 @@ typealias EndpointResolutionResult = Result<(Endpoint, Endpoint), DNSResolutionE
 
 class PacketTunnelSettingsGenerator {
     let tunnelConfiguration: TunnelConfiguration
-    let resolvedEndpoints: [Endpoint?]
+    private(set) var resolvedEndpoints: [Endpoint?]
     let isSplitDNSEnabled: Bool
 
     init(tunnelConfiguration: TunnelConfiguration, resolvedEndpoints: [Endpoint?], isSplitDNSEnabled: Bool = false) {
@@ -181,6 +181,51 @@ class PacketTunnelSettingsGenerator {
         return (ipv4IncludedRoutes, ipv6IncludedRoutes)
     }
 
+    /// Return a UAPI configuration setting the endpoint of every peer,
+    /// re-resolving the peers that were configured with a hostname.
+    ///
+    /// The endpoints are set unconditionally, which is what makes this useful
+    /// after a network change: besides picking up a hostname that now resolves
+    /// elsewhere, it resets peers whose endpoint the backend has roamed to an
+    /// address that was only reachable on the previous network.
+    ///
+    /// The initial resolution replaces a configured hostname with the address
+    /// it resolved to, so the hostname is only available from the tunnel
+    /// configuration itself.
+    func endpointUapiConfigurationAfterNetworkChange() -> (String, [EndpointResolutionResult?]) {
+        let configuredEndpoints = tunnelConfiguration.peers.map { $0.endpoint }
+        // Resolution is skipped altogether when every endpoint is an address.
+        let results = DNSResolver.resolveSync(endpoints: configuredEndpoints)
+        assert(results.count == tunnelConfiguration.peers.count)
+        assert(resolvedEndpoints.count == tunnelConfiguration.peers.count)
+
+        var wgSettings = ""
+        var resolutionResults = [EndpointResolutionResult?]()
+
+        for (index, peer) in tunnelConfiguration.peers.enumerated() {
+            if let configuredEndpoint = configuredEndpoints[index], !configuredEndpoint.hasHostAsIPAddress() {
+                switch results[index] {
+                case .success(let resolvedEndpoint)?:
+                    resolutionResults.append(.success((configuredEndpoint, resolvedEndpoint)))
+                    resolvedEndpoints[index] = resolvedEndpoint
+                case .failure(let error)?:
+                    // Keep the address the hostname last resolved to.
+                    resolutionResults.append(.failure(error))
+                case nil:
+                    resolutionResults.append(nil)
+                }
+            } else {
+                resolutionResults.append(nil)
+            }
+
+            guard let endpoint = resolvedEndpoints[index] else { continue }
+            wgSettings.append("public_key=\(peer.publicKey.hexKey)\n")
+            wgSettings.append("endpoint=\(endpoint.stringRepresentation)\n")
+        }
+
+        return (wgSettings, resolutionResults)
+    }
+
     private class func reresolveEndpoint(endpoint: Endpoint) -> EndpointResolutionResult {
         return Result { (endpoint, try endpoint.withReresolvedIP()) }
             .mapError { error -> DNSResolutionError in
Sources/WireGuardKit/WireGuardAdapter.swift +53 -0

77 lines not on this page · raw message

Signature · 1 line
2.50.1 (Apple Git-155)