From gawenr at protonmail.com Thu Jul 16 21:40:23 2026 From: gawenr at protonmail.com (Gawen Arab) Date: Thu, 16 Jul 2026 21:40:23 -0000 Subject: macOS: what was Apple bug 32073323 behind the exit(0) in stopTunnel? Message-ID: Hi, I've been hacking on the macOS app to let more than one tunnel be up at the same time, and I hit the exit(0) at the end of stopTunnel() in PacketTunnelProvider.swift, with the comment pointing at Apple bug 32073323 (dup'd as 47526107). The radar isn't public so I can't see the original symptom. >From git, 394a0cb ("proper fix for 32073323") swapped out an older workaround that held the tunnel in .deactivating for a few seconds; the comment there said that reactivating inside that window got the new tunnel torn down by the system about 25 seconds later. Was that the whole of it, or was there more to the bug? The reason I care: exit(0) gets in the way of multiple tunnels. macOS puts all of an app's packet-tunnel providers in a single extension process, so exit(0) on one stopTunnel kills the others too. On 26.5.1 I can no longer reproduce the ~25s auto-kill even with exit(0) removed - stop a tunnel, start it again a few seconds later, it stays up. So I'm wondering whether the hack can be dropped on recent macOS, or at least gated to the versions that still need it. While I'm here: does anyone know if the one-process-for-all-providers behaviour can be avoided, i.e. one process per tunnel? Or a way to tear a single tunnel down without taking the whole extension process with it? Stopping one tunnel currently drops every other active tunnel, which is the main thing blocking this. Thanks, ? Gawen Arab http://gawen.me/ From makupi at proton.me Wed Jul 22 09:38:09 2026 From: makupi at proton.me (Markus Pischinger) Date: Wed, 22 Jul 2026 09:38:09 -0000 Subject: wireguard-go: Windows winrio receive exits on ICMP unreachable Message-ID: <0YrBtS_pOagP-VBw5XRdiFC02Z7p9ZHF0803NKsVMkSV8ghWy-Qr5Xi3CUBALADA1tm7OkoQgpRtdCLwqw9EeK5xpOXyp83wiSctBFYuWug=@proton.me> Hey everyone, I've noticed an issue with the wireguard-go Windows implementation, specifically winrio and its handling of ICMP errors.? The default behaviour for Go is to disable SIO_UDP_CONNRESET [1] and SIO_UDP_NETRESET [2], but since the winrio implementation creates the socket directly via WSASocket rather than going through Go's net package, those flags are never disabled. This results in ICMP unreachable being received as an error, and bind_windows.go just wraps it as windows.Errno [3], which is a non-temporary error. So in?RoutineReceiveIncoming [4], if it receives this error, it just returns, leaving the receive path of wireguard-go broken, while the rest still runs as if nothing happened. In this state wireguard-go will continuously try to initiate a handshake every 5 seconds, and even if the peer answers, it will never receive the response.? This is fixed by disabling both SIO_UDP_CONNRESET and?SIO_UDP_NETRESET,?similar to how Go does it in src/net/fd_windows.go [5]. I can provide a patch if necessary, but I wanted to verify that there isn't a reason those flags aren't disabled. Thanks, Markus Pischinger [1]?https://github.com/golang/go/issues/5834 [2]?https://github.com/golang/go/issues/68614 [3]?https://github.com/WireGuard/wireguard-go/blob/ecfc5a8d54462e18e13c72173e2623d16d8e25a0/conn/bind_windows.go#L410-L412 [4]?https://github.com/WireGuard/wireguard-go/blob/ecfc5a8d54462e18e13c72173e2623d16d8e25a0/device/receive.go#L116-L118 [5]?https://go.googlesource.com/go/+/be79f939834898d38a7827ed6ebd521823ac3499/src/net/fd_windows.go#60 From davidberich at gmail.com Wed Jul 29 15:25:10 2026 From: davidberich at gmail.com (David Berichon) Date: Wed, 29 Jul 2026 15:25:10 -0000 Subject: macOS: DNS configured via DNS= is not restored after wg-quick down Message-ID: Hello, I observed what seems to be an unexpected behavior with the Darwin implementation of wg-quick. Environment ? macOS ? Homebrew wireguard-tools 1.0.20260223 ? wireguard-go backend Minimal configuration [Interface] PrivateKey = ... Address = 10.5.5.2/32 DNS = 10.5.5.7 [Peer] PublicKey = ... AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = ... PersistentKeepalive = 25 Steps to reproduce Bring the tunnel up: sudo wg-quick up ~/wireguard/pdc_mba.conf The DNS is correctly configured: networksetup -getdnsservers Wi-Fi returns 10.5.5.7 The route monitor is also started: pgrep -af "route -n monitor" returns something similar to: 35140 route -n monitor Then bring the tunnel down: sudo wg-quick down ~/wireguard/pdc_mba.conf The interface is correctly removed: sudo wg show returns no interfaces. However the DNS configuration is not restored: networksetup -getdnsservers Wi-Fi still returns 10.5.5.7 instead of restoring the previous DNS configuration. Additional observations Running the script with: sudo bash -x /opt/homebrew/bin/wg-quick down ~/wireguard/pdc_mba.conf shows that cmd_down() removes the interface and executes PostDown, but does not explicitly invoke del_dns(): cmd_down() { execute_hooks "${PRE_DOWN[@]}" [[ $SAVE_CONFIG -eq 0 ]] || save_config del_if execute_hooks "${POST_DOWN[@]}" } I also noticed that del_dns() is only referenced from the monitor_daemon() trap: trap 'del_routes; del_dns; exit 0' INT TERM EXIT Is this expected behavior on macOS, or should the DNS configuration be restored after wg-quick down? If this is expected, I?d appreciate understanding how the DNS restoration is intended to occur. Thanks. From razvan.cremenescu at gmail.com Fri Jul 10 13:22:47 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:47 -0000 Subject: [PATCH wireguard-apple 0/7] macOS: support multiple simultaneous tunnels Message-ID: <20260710132242.39814-1-razvan.cremenescu@gmail.com> macOS, unlike iOS, is able to run multiple packet tunnel provider sessions at the same time. The app has so far serialized activation on both platforms: activating one tunnel deactivates the tunnel already in operation. On iOS that mirrors an OS restriction, but on macOS it is purely app policy, and macOS users routinely need several disjoint split tunnels up at once. Simply lifting the policy is not enough, though. 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 same failure reported on this list back 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 behavior 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. The last patch adds an opt-in per-tunnel split DNS toggle. With several tunnels up simultaneously, 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 the tunnel's DNS search domains (the non-IP entries of the DNS= line). A related DNSMatchDomains approach was posted to this list in April 2024; this variant keeps the wg-quick config text untouched and portable and gates the behavior on an explicit per-tunnel opt-in, so existing full-tunnel setups keep their leak-free match-everything DNS by default. 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 in the series builds for both macOS and iOS. I'm happy to keep looking after this area of the codebase, and to help more broadly with wireguard-apple maintenance if that would be useful. Razvan Cremenescu (7): 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 .../NETunnelProviderProtocol+Extension.swift | 26 ++++ .../Base.lproj/Localizable.strings | 11 ++ .../WireGuardApp/Tunnel/TunnelsManager.swift | 43 +++++- .../TunnelEditTableViewController.swift | 39 +++++- .../WireGuardApp/UI/macOS/AppDelegate.swift | 31 ++++- .../UI/macOS/StatusItemController.swift | 14 +- .../WireGuardApp/UI/macOS/StatusMenu.swift | 25 +++- .../UI/macOS/TunnelsTracker.swift | 31 +++-- .../TunnelEditViewController.swift | 21 ++- .../PacketTunnelSettingsGenerator.swift | 12 +- Sources/WireGuardKit/WireGuardAdapter.swift | 123 ++++++++++++++++-- Sources/WireGuardKitC/WireGuardKitC.h | 2 + .../PacketTunnelProvider.swift | 52 +++++++- 13 files changed, 373 insertions(+), 57 deletions(-) -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:49 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:49 -0000 Subject: [PATCH wireguard-apple 1/7] WireGuardKitC: include sys/types.h for BSD type definitions In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-2-razvan.cremenescu@gmail.com> The ctl_info and sockaddr_ctl definitions use u_char, u_int16_t and u_int32_t without including . Newer clang versions with strict module verification (Xcode 16 and later) refuse to build the module because these declarations must be imported before use. Signed-off-by: Razvan Cremenescu --- Sources/WireGuardKitC/WireGuardKitC.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/WireGuardKitC/WireGuardKitC.h b/Sources/WireGuardKitC/WireGuardKitC.h index 54e4783..84c53f7 100644 --- a/Sources/WireGuardKitC/WireGuardKitC.h +++ b/Sources/WireGuardKitC/WireGuardKitC.h @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MIT // Copyright ? 2018-2023 WireGuard LLC. All Rights Reserved. +#include + #include "key.h" #include "x25519.h" -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:50 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:50 -0000 Subject: [PATCH wireguard-apple 2/7] TunnelsManager: drop the restart intent when deactivation is requested In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-3-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- Sources/WireGuardApp/Tunnel/TunnelsManager.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift index c277f6d..365094e 100644 --- a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift +++ b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift @@ -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 -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:51 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:51 -0000 Subject: [PATCH wireguard-apple 3/7] WireGuardKit: attach each adapter to its own utun device In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-4-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- Sources/WireGuardKit/WireGuardAdapter.swift | 110 ++++++++++++++++++-- 1 file changed, 103 insertions(+), 7 deletions(-) diff --git a/Sources/WireGuardKit/WireGuardAdapter.swift b/Sources/WireGuardKit/WireGuardAdapter.swift index f7be19b..ba49ec7 100644 --- a/Sources/WireGuardKit/WireGuardAdapter.swift +++ b/Sources/WireGuardKit/WireGuardAdapter.swift @@ -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() + 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? + 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 { -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:53 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:53 -0000 Subject: [PATCH wireguard-apple 4/7] TunnelsManager: restrict single-tunnel activation policy to iOS In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-5-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- .../WireGuardApp/Tunnel/TunnelsManager.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift index 365094e..63e1847 100644 --- a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift +++ b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift @@ -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 -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:54 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:54 -0000 Subject: [PATCH wireguard-apple 5/7] PacketTunnelProvider: only exit on stop of last tunnel in the process In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-6-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- .../PacketTunnelProvider.swift | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift b/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift index 913b7e6..fe09026 100644 --- a/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift +++ b/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift @@ -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 } } -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:56 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:56 -0000 Subject: [PATCH wireguard-apple 6/7] macOS: support multiple simultaneous tunnels in the menu bar UI In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-7-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- .../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(-) diff --git a/Sources/WireGuardApp/Base.lproj/Localizable.strings b/Sources/WireGuardApp/Base.lproj/Localizable.strings index f181953..2e23a91 100644 --- a/Sources/WireGuardApp/Base.lproj/Localizable.strings +++ b/Sources/WireGuardApp/Base.lproj/Localizable.strings @@ -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 diff --git a/Sources/WireGuardApp/UI/macOS/AppDelegate.swift b/Sources/WireGuardApp/UI/macOS/AppDelegate.swift index 1dda3e6..b9c3a53 100644 --- a/Sources/WireGuardApp/UI/macOS/AppDelegate.swift +++ b/Sources/WireGuardApp/UI/macOS/AppDelegate.swift @@ -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 { diff --git a/Sources/WireGuardApp/UI/macOS/StatusItemController.swift b/Sources/WireGuardApp/UI/macOS/StatusItemController.swift index 3088574..e4ff7a5 100644 --- a/Sources/WireGuardApp/UI/macOS/StatusItemController.swift +++ b/Sources/WireGuardApp/UI/macOS/StatusItemController.swift @@ -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() } } diff --git a/Sources/WireGuardApp/UI/macOS/StatusMenu.swift b/Sources/WireGuardApp/UI/macOS/StatusMenu.swift index 45d2283..9ebdca2 100644 --- a/Sources/WireGuardApp/UI/macOS/StatusMenu.swift +++ b/Sources/WireGuardApp/UI/macOS/StatusMenu.swift @@ -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) } } diff --git a/Sources/WireGuardApp/UI/macOS/TunnelsTracker.swift b/Sources/WireGuardApp/UI/macOS/TunnelsTracker.swift index 0ab59ee..ab8b478 100644 --- a/Sources/WireGuardApp/UI/macOS/TunnelsTracker.swift +++ b/Sources/WireGuardApp/UI/macOS/TunnelsTracker.swift @@ -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) -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Fri Jul 10 13:22:57 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Fri, 10 Jul 2026 13:22:57 -0000 Subject: [PATCH wireguard-apple 7/7] Add opt-in split DNS support In-Reply-To: <20260710132242.39814-1-razvan.cremenescu@gmail.com> References: <20260710132242.39814-1-razvan.cremenescu@gmail.com> Message-ID: <20260710132242.39814-8-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- .../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(-) diff --git a/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift b/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift index 0a303f4..8f56434 100644 --- a/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift +++ b/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift @@ -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) diff --git a/Sources/WireGuardApp/Base.lproj/Localizable.strings b/Sources/WireGuardApp/Base.lproj/Localizable.strings index 2e23a91..cacb316 100644 --- a/Sources/WireGuardApp/Base.lproj/Localizable.strings +++ b/Sources/WireGuardApp/Base.lproj/Localizable.strings @@ -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"; diff --git a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift index 63e1847..18829fe 100644 --- a/Sources/WireGuardApp/Tunnel/TunnelsManager.swift +++ b/Sources/WireGuardApp/Tunnel/TunnelsManager.swift @@ -119,7 +119,7 @@ class TunnelsManager { } } - func add(tunnelConfiguration: TunnelConfiguration, onDemandOption: ActivateOnDemandOption = .off, completionHandler: @escaping (Result) -> Void) { + func add(tunnelConfiguration: TunnelConfiguration, onDemandOption: ActivateOnDemandOption = .off, isSplitDNSEnabled: Bool = false, completionHandler: @escaping (Result) -> 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() diff --git a/Sources/WireGuardApp/UI/iOS/ViewController/TunnelEditTableViewController.swift b/Sources/WireGuardApp/UI/iOS/ViewController/TunnelEditTableViewController.swift index dfb35c6..e79686f 100644 --- a/Sources/WireGuardApp/UI/iOS/ViewController/TunnelEditTableViewController.swift +++ b/Sources/WireGuardApp/UI/iOS/ViewController/TunnelEditTableViewController.swift @@ -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 { diff --git a/Sources/WireGuardApp/UI/macOS/ViewController/TunnelEditViewController.swift b/Sources/WireGuardApp/UI/macOS/ViewController/TunnelEditViewController.swift index 851498a..8065bdc 100644 --- a/Sources/WireGuardApp/UI/macOS/ViewController/TunnelEditViewController.swift +++ b/Sources/WireGuardApp/UI/macOS/ViewController/TunnelEditViewController.swift @@ -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 { diff --git a/Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift b/Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift index 3658956..36c0e06 100644 --- a/Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift +++ b/Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift @@ -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 } diff --git a/Sources/WireGuardKit/WireGuardAdapter.swift b/Sources/WireGuardKit/WireGuardAdapter.swift index ba49ec7..82728e4 100644 --- a/Sources/WireGuardKit/WireGuardAdapter.swift +++ b/Sources/WireGuardKit/WireGuardAdapter.swift @@ -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 ) } diff --git a/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift b/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift index fe09026..ac8050c 100644 --- a/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift +++ b/Sources/WireGuardNetworkExtension/PacketTunnelProvider.swift @@ -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" -- 2.50.1 (Apple Git-155) From moody at posixcafe.org Fri Jul 10 16:07:10 2026 From: moody at posixcafe.org (Jacob Moody) Date: Fri, 10 Jul 2026 16:07:10 -0000 Subject: New implementation for 9front operating system Message-ID: <8110f311-a05a-4b90-bfd2-b7364d0350b3@posixcafe.org> All, I've been working on an implementation of wireguard for 9front. I am starting to get to the point where I feel like the implementation is getting pretty close, and its in a good spot to review before I do some tighter integration into 9front. I know in the past I've seen some desire from the wg community to ensure that code using the wireguard name at least be somewhat decent. So I wanted to share it here and get feedback if people felt inclined. Grab the code from your choice of git hosts: git://shithub.us/moody/wg https://github.com/majiru/wg I am happy to answer any questions regarding plan 9/9front specifics. One note is, I am not currently implementing DoS/Cookie challenges, we can respond to them but we don't currently generate them. This is blocked on there being some meaningful way of measuring "under load" from just userspace. Thank you, Jacob Moody From ml at mareichelt.com Sun Jul 19 20:09:41 2026 From: ml at mareichelt.com (Markus Reichelt) Date: Sun, 19 Jul 2026 20:09:41 -0000 Subject: Wireguard head of line blocking when CPUs saturate In-Reply-To: <874iiyfrrh.fsf@toke.dk> References: <874iiyfrrh.fsf@toke.dk> Message-ID: <20260719200935.GA5205@pc21.mareichelt.com> * Toke H?iland-J?rgensen wrote: > I'm sending this message to (a) see if anyone else is seeing the same > kind of stalling, and (b) to get input on whether the explanation > outlined above seems plausible. And, in the case of affirmative answers > to both (a) and (b), to hopefully start a discussion on what to do about > this :) I don't use a wireguard setup on arm hardware, I am just brainstorming... Given that you just use one tunnel, how about pinning wireguard to a core and, more importantly, pin the program that causes the 'fat tcp flow' to some other core? What you describe must be a common problem on low performance ARM setups running wg on openWRT (mikrotik comes to mind), so I'd have a look in that corner of the internet also ;) HTH From razvan.cremenescu at gmail.com Sat Jul 25 21:39:22 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Sat, 25 Jul 2026 21:39:22 -0000 Subject: [PATCH wireguard-apple 1/2] macOS: activate the app before showing a modal alert without a window Message-ID: <20260725213918.45422-1-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift b/Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift index dbab027..b3884ff 100644 --- a/Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift +++ b/Sources/WireGuardApp/UI/macOS/ErrorPresenter.swift @@ -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?() } -- 2.50.1 (Apple Git-155) From razvan.cremenescu at gmail.com Sat Jul 25 21:39:24 2026 From: razvan.cremenescu at gmail.com (Razvan Cremenescu) Date: Sat, 25 Jul 2026 21:39:24 -0000 Subject: [PATCH wireguard-apple 2/2] macOS: don't crash opening the editor for an unreadable tunnel In-Reply-To: <20260725213918.45422-1-razvan.cremenescu@gmail.com> References: <20260725213918.45422-1-razvan.cremenescu@gmail.com> Message-ID: <20260725213918.45422-2-razvan.cremenescu@gmail.com> 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. Signed-off-by: Razvan Cremenescu --- Sources/WireGuardApp/Base.lproj/Localizable.strings | 1 + .../ViewController/TunnelDetailTableViewController.swift | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/Sources/WireGuardApp/Base.lproj/Localizable.strings b/Sources/WireGuardApp/Base.lproj/Localizable.strings index cacb316..23037ce 100644 --- a/Sources/WireGuardApp/Base.lproj/Localizable.strings +++ b/Sources/WireGuardApp/Base.lproj/Localizable.strings @@ -385,6 +385,7 @@ "macAlertNameIsEmpty" = "Name is required"; "macAlertDuplicateName (%@)" = "Another tunnel already exists with the name ?%@?."; +"macAlertCannotReadConfigTitle" = "Unable to read configuration"; "macAlertInvalidLine (%@)" = "Invalid line: ?%@?."; diff --git a/Sources/WireGuardApp/UI/macOS/ViewController/TunnelDetailTableViewController.swift b/Sources/WireGuardApp/UI/macOS/ViewController/TunnelDetailTableViewController.swift index 41d2b15..f1526d7 100644 --- a/Sources/WireGuardApp/UI/macOS/ViewController/TunnelDetailTableViewController.swift +++ b/Sources/WireGuardApp/UI/macOS/ViewController/TunnelDetailTableViewController.swift @@ -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) -- 2.50.1 (Apple Git-155)