2020-11-04 15:59:33 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// Copyright © 2018-2019 WireGuard LLC. All Rights Reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import NetworkExtension
|
2020-12-02 15:10:44 +00:00
|
|
|
|
|
|
|
#if SWIFT_PACKAGE
|
2020-12-02 11:32:20 +00:00
|
|
|
import WireGuardKitGo
|
2020-12-02 15:10:44 +00:00
|
|
|
#endif
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
public enum WireGuardAdapterError: Error {
|
2020-12-02 12:42:15 +00:00
|
|
|
/// Failure to locate tunnel file descriptor.
|
|
|
|
case cannotLocateTunnelFileDescriptor
|
2020-11-04 15:59:33 +00:00
|
|
|
|
2020-12-03 12:19:31 +00:00
|
|
|
/// Failure to perform an operation in such state.
|
2020-11-04 15:59:33 +00:00
|
|
|
case invalidState
|
|
|
|
|
2020-12-03 12:19:31 +00:00
|
|
|
/// Failure to resolve endpoints.
|
2020-11-04 15:59:33 +00:00
|
|
|
case dnsResolution([DNSResolutionError])
|
|
|
|
|
2020-12-03 12:19:31 +00:00
|
|
|
/// Failure to set network settings.
|
2020-11-04 15:59:33 +00:00
|
|
|
case setNetworkSettings(Error)
|
|
|
|
|
2020-12-03 12:19:31 +00:00
|
|
|
/// Timeout when calling to set network settings.
|
2020-11-04 15:59:33 +00:00
|
|
|
case setNetworkSettingsTimeout
|
|
|
|
|
2020-12-03 12:19:31 +00:00
|
|
|
/// Failure to start WireGuard backend.
|
2020-11-04 15:59:33 +00:00
|
|
|
case startWireGuardBackend(Int32)
|
|
|
|
}
|
|
|
|
|
|
|
|
public class WireGuardAdapter {
|
|
|
|
public typealias LogHandler = (WireGuardLogLevel, String) -> Void
|
|
|
|
|
|
|
|
/// Network routes monitor.
|
|
|
|
private var networkMonitor: NWPathMonitor?
|
|
|
|
|
|
|
|
/// Packet tunnel provider.
|
|
|
|
private weak var packetTunnelProvider: NEPacketTunnelProvider?
|
|
|
|
|
|
|
|
/// Log handler closure.
|
2020-12-02 12:48:24 +00:00
|
|
|
private let logHandler: LogHandler
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
/// WireGuard internal handle returned by `wgTurnOn` that's used to associate the calls
|
|
|
|
/// with the specific WireGuard tunnel.
|
|
|
|
private var wireguardHandle: Int32?
|
|
|
|
|
|
|
|
/// Private queue used to synchronize access to `WireGuardAdapter` members.
|
|
|
|
private let workQueue = DispatchQueue(label: "WireGuardAdapterWorkQueue")
|
|
|
|
|
|
|
|
/// Packet tunnel settings generator.
|
|
|
|
private var settingsGenerator: PacketTunnelSettingsGenerator?
|
|
|
|
|
|
|
|
/// Tunnel device file descriptor.
|
|
|
|
private var tunnelFileDescriptor: Int32? {
|
|
|
|
return self.packetTunnelProvider?.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32
|
|
|
|
}
|
|
|
|
|
2020-12-02 12:38:38 +00:00
|
|
|
/// Returns a WireGuard version.
|
2020-12-02 17:05:17 +00:00
|
|
|
class var backendVersion: String {
|
2020-11-04 15:59:33 +00:00
|
|
|
return String(cString: wgVersion())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the tunnel device interface name, or nil on error.
|
|
|
|
/// - Returns: String.
|
|
|
|
public var interfaceName: String? {
|
|
|
|
guard let tunnelFileDescriptor = self.tunnelFileDescriptor else { return nil }
|
|
|
|
|
|
|
|
var buffer = [UInt8](repeating: 0, count: Int(IFNAMSIZ))
|
|
|
|
|
2020-12-02 14:08:45 +00:00
|
|
|
return buffer.withUnsafeMutableBufferPointer { mutableBufferPointer in
|
2020-11-04 15:59:33 +00:00
|
|
|
guard let baseAddress = mutableBufferPointer.baseAddress else { return nil }
|
|
|
|
|
|
|
|
var ifnameSize = socklen_t(IFNAMSIZ)
|
|
|
|
let result = getsockopt(
|
|
|
|
tunnelFileDescriptor,
|
|
|
|
2 /* SYSPROTO_CONTROL */,
|
|
|
|
2 /* UTUN_OPT_IFNAME */,
|
|
|
|
baseAddress,
|
|
|
|
&ifnameSize)
|
|
|
|
|
|
|
|
if result == 0 {
|
|
|
|
return String(cString: baseAddress)
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Initialization
|
|
|
|
|
|
|
|
/// Designated initializer.
|
|
|
|
/// - Parameter packetTunnelProvider: an instance of `NEPacketTunnelProvider`. Internally stored
|
|
|
|
/// as a weak reference.
|
2020-12-02 12:48:24 +00:00
|
|
|
/// - Parameter logHandler: a log handler closure.
|
|
|
|
public init(with packetTunnelProvider: NEPacketTunnelProvider, logHandler: @escaping LogHandler) {
|
2020-11-04 15:59:33 +00:00
|
|
|
self.packetTunnelProvider = packetTunnelProvider
|
2020-12-02 12:48:24 +00:00
|
|
|
self.logHandler = logHandler
|
|
|
|
|
|
|
|
setupLogHandler()
|
2020-11-04 15:59:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
2020-12-02 12:48:24 +00:00
|
|
|
// Force remove logger to make sure that no further calls to the instance of this class
|
2020-11-04 15:59:33 +00:00
|
|
|
// can happen after deallocation.
|
2020-12-02 12:48:24 +00:00
|
|
|
wgSetLogger(nil, nil)
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
// Cancel network monitor
|
|
|
|
networkMonitor?.cancel()
|
|
|
|
|
|
|
|
// Shutdown the tunnel
|
|
|
|
if let handle = self.wireguardHandle {
|
|
|
|
wgTurnOff(handle)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Public methods
|
|
|
|
|
|
|
|
/// Returns a runtime configuration from WireGuard.
|
|
|
|
/// - Parameter completionHandler: completion handler.
|
|
|
|
public func getRuntimeConfiguration(completionHandler: @escaping (String?) -> Void) {
|
|
|
|
workQueue.async {
|
|
|
|
guard let handle = self.wireguardHandle else {
|
|
|
|
completionHandler(nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if let settings = wgGetConfig(handle) {
|
|
|
|
completionHandler(String(cString: settings))
|
|
|
|
free(settings)
|
|
|
|
} else {
|
|
|
|
completionHandler(nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Start the tunnel tunnel.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - tunnelConfiguration: tunnel configuration.
|
|
|
|
/// - completionHandler: completion handler.
|
|
|
|
public func start(tunnelConfiguration: TunnelConfiguration, completionHandler: @escaping (WireGuardAdapterError?) -> Void) {
|
|
|
|
workQueue.async {
|
2020-12-02 12:52:24 +00:00
|
|
|
guard self.wireguardHandle == nil else {
|
2020-11-04 15:59:33 +00:00
|
|
|
completionHandler(.invalidState)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
guard let tunnelFileDescriptor = self.tunnelFileDescriptor else {
|
2020-12-02 12:42:15 +00:00
|
|
|
completionHandler(.cannotLocateTunnelFileDescriptor)
|
2020-11-04 15:59:33 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
#if os(macOS)
|
|
|
|
wgEnableRoaming(true)
|
|
|
|
#endif
|
|
|
|
|
|
|
|
let networkMonitor = NWPathMonitor()
|
|
|
|
networkMonitor.pathUpdateHandler = { [weak self] path in
|
|
|
|
self?.didReceivePathUpdate(path: path)
|
|
|
|
}
|
|
|
|
|
|
|
|
networkMonitor.start(queue: self.workQueue)
|
|
|
|
self.networkMonitor = networkMonitor
|
|
|
|
|
2020-12-02 14:08:45 +00:00
|
|
|
self.updateNetworkSettings(tunnelConfiguration: tunnelConfiguration) { settingsGenerator, error in
|
2020-11-04 15:59:33 +00:00
|
|
|
if let error = error {
|
|
|
|
completionHandler(error)
|
|
|
|
} else {
|
|
|
|
var returnError: WireGuardAdapterError?
|
|
|
|
let handle = wgTurnOn(settingsGenerator!.uapiConfiguration(), tunnelFileDescriptor)
|
|
|
|
|
|
|
|
if handle >= 0 {
|
|
|
|
self.wireguardHandle = handle
|
|
|
|
} else {
|
|
|
|
returnError = .startWireGuardBackend(handle)
|
|
|
|
}
|
|
|
|
|
|
|
|
completionHandler(returnError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Stop the tunnel.
|
|
|
|
/// - Parameter completionHandler: completion handler.
|
|
|
|
public func stop(completionHandler: @escaping (WireGuardAdapterError?) -> Void) {
|
|
|
|
workQueue.async {
|
2020-12-02 12:52:24 +00:00
|
|
|
guard let handle = self.wireguardHandle else {
|
2020-11-04 15:59:33 +00:00
|
|
|
completionHandler(.invalidState)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
self.networkMonitor?.cancel()
|
|
|
|
self.networkMonitor = nil
|
|
|
|
|
2020-12-02 12:52:24 +00:00
|
|
|
wgTurnOff(handle)
|
|
|
|
self.wireguardHandle = nil
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
completionHandler(nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Update runtime configuration.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - tunnelConfiguration: tunnel configuration.
|
|
|
|
/// - completionHandler: completion handler.
|
|
|
|
public func update(tunnelConfiguration: TunnelConfiguration, completionHandler: @escaping (WireGuardAdapterError?) -> Void) {
|
|
|
|
workQueue.async {
|
2020-12-02 12:52:24 +00:00
|
|
|
guard let handle = self.wireguardHandle else {
|
2020-11-04 15:59:33 +00:00
|
|
|
completionHandler(.invalidState)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tell the system that the tunnel is going to reconnect using new WireGuard
|
|
|
|
// configuration.
|
|
|
|
// This will broadcast the `NEVPNStatusDidChange` notification to the GUI process.
|
|
|
|
self.packetTunnelProvider?.reasserting = true
|
|
|
|
|
2020-12-02 14:08:45 +00:00
|
|
|
self.updateNetworkSettings(tunnelConfiguration: tunnelConfiguration) { settingsGenerator, error in
|
2020-11-04 15:59:33 +00:00
|
|
|
if let error = error {
|
|
|
|
completionHandler(error)
|
|
|
|
} else {
|
2020-12-02 12:52:24 +00:00
|
|
|
wgSetConfig(handle, settingsGenerator!.uapiConfiguration())
|
2020-11-04 15:59:33 +00:00
|
|
|
completionHandler(nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
self.packetTunnelProvider?.reasserting = false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Private methods
|
|
|
|
|
2020-12-02 12:48:24 +00:00
|
|
|
/// Setup WireGuard log handler.
|
|
|
|
private func setupLogHandler() {
|
2020-11-04 15:59:33 +00:00
|
|
|
let context = Unmanaged.passUnretained(self).toOpaque()
|
2020-12-02 14:08:45 +00:00
|
|
|
wgSetLogger(context) { context, logLevel, message in
|
2020-11-04 15:59:33 +00:00
|
|
|
guard let context = context, let message = message else { return }
|
|
|
|
|
|
|
|
let unretainedSelf = Unmanaged<WireGuardAdapter>.fromOpaque(context)
|
|
|
|
.takeUnretainedValue()
|
|
|
|
|
|
|
|
let swiftString = String(cString: message).trimmingCharacters(in: .newlines)
|
|
|
|
let tunnelLogLevel = WireGuardLogLevel(rawValue: logLevel) ?? .debug
|
|
|
|
|
2020-12-02 12:53:16 +00:00
|
|
|
unretainedSelf.logHandler(tunnelLogLevel, swiftString)
|
2020-11-04 15:59:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve endpoints and update network configuration.
|
|
|
|
/// - Parameters:
|
|
|
|
/// - tunnelConfiguration: tunnel configuration
|
|
|
|
/// - completionHandler: completion handler
|
|
|
|
private func updateNetworkSettings(tunnelConfiguration: TunnelConfiguration, completionHandler: @escaping (PacketTunnelSettingsGenerator?, WireGuardAdapterError?) -> Void) {
|
|
|
|
let resolvedEndpoints: [Endpoint?]
|
|
|
|
|
|
|
|
let resolvePeersResult = Result { try self.resolvePeers(for: tunnelConfiguration) }
|
2020-12-02 14:08:45 +00:00
|
|
|
.mapError { error -> WireGuardAdapterError in
|
|
|
|
// swiftlint:disable:next force_cast
|
|
|
|
return error as! WireGuardAdapterError
|
|
|
|
}
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
switch resolvePeersResult {
|
|
|
|
case .success(let endpoints):
|
|
|
|
resolvedEndpoints = endpoints
|
|
|
|
case .failure(let error):
|
|
|
|
completionHandler(nil, error)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
let settingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints)
|
|
|
|
let networkSettings = settingsGenerator.generateNetworkSettings()
|
|
|
|
|
|
|
|
var systemError: Error?
|
|
|
|
let condition = NSCondition()
|
|
|
|
|
|
|
|
// Activate the condition
|
|
|
|
condition.lock()
|
|
|
|
defer { condition.unlock() }
|
|
|
|
|
2020-12-02 14:08:45 +00:00
|
|
|
self.packetTunnelProvider?.setTunnelNetworkSettings(networkSettings) { error in
|
2020-11-04 15:59:33 +00:00
|
|
|
systemError = error
|
|
|
|
condition.signal()
|
2020-12-02 14:08:45 +00:00
|
|
|
}
|
2020-11-04 15:59:33 +00:00
|
|
|
|
|
|
|
// Packet tunnel's `setTunnelNetworkSettings` times out in certain
|
|
|
|
// scenarios & never calls the given callback.
|
|
|
|
let setTunnelNetworkSettingsTimeout: TimeInterval = 5 // seconds
|
|
|
|
|
|
|
|
if condition.wait(until: Date().addingTimeInterval(setTunnelNetworkSettingsTimeout)) {
|
|
|
|
let returnError = systemError.map { WireGuardAdapterError.setNetworkSettings($0) }
|
|
|
|
|
2020-12-02 12:53:58 +00:00
|
|
|
// Only assign `settingsGenerator` when `setTunnelNetworkSettings` succeeded.
|
|
|
|
if returnError == nil {
|
|
|
|
self.settingsGenerator = settingsGenerator
|
|
|
|
}
|
|
|
|
|
2020-11-04 15:59:33 +00:00
|
|
|
completionHandler(settingsGenerator, returnError)
|
|
|
|
} else {
|
|
|
|
completionHandler(nil, .setNetworkSettingsTimeout)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve peers of the given tunnel configuration.
|
|
|
|
/// - Parameter tunnelConfiguration: tunnel configuration.
|
|
|
|
/// - Throws: an error of type `WireGuardAdapterError`.
|
|
|
|
/// - Returns: The list of resolved endpoints.
|
|
|
|
private func resolvePeers(for tunnelConfiguration: TunnelConfiguration) throws -> [Endpoint?] {
|
|
|
|
let endpoints = tunnelConfiguration.peers.map { $0.endpoint }
|
|
|
|
let resolutionResults = DNSResolver.resolveSync(endpoints: endpoints)
|
2020-12-02 14:08:45 +00:00
|
|
|
let resolutionErrors = resolutionResults.compactMap { result -> DNSResolutionError? in
|
2020-11-04 15:59:33 +00:00
|
|
|
if case .failure(let error) = result {
|
|
|
|
return error
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
assert(endpoints.count == resolutionResults.count)
|
|
|
|
guard resolutionErrors.isEmpty else {
|
|
|
|
throw WireGuardAdapterError.dnsResolution(resolutionErrors)
|
|
|
|
}
|
|
|
|
|
2020-12-02 14:08:45 +00:00
|
|
|
let resolvedEndpoints = resolutionResults.map { result -> Endpoint? in
|
|
|
|
// swiftlint:disable:next force_try
|
2020-12-02 12:54:31 +00:00
|
|
|
return try! result?.get()
|
2020-11-04 15:59:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return resolvedEndpoints
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Helper method used by network path monitor.
|
|
|
|
/// - Parameter path: new network path
|
|
|
|
private func didReceivePathUpdate(path: Network.NWPath) {
|
2020-12-02 12:53:16 +00:00
|
|
|
guard let handle = self.wireguardHandle else { return }
|
2020-11-04 15:59:33 +00:00
|
|
|
|
2020-12-02 12:53:16 +00:00
|
|
|
self.logHandler(.debug, "Network change detected with \(path.status) route and interface order \(path.availableInterfaces)")
|
2020-11-04 15:59:33 +00:00
|
|
|
|
2020-12-02 12:53:16 +00:00
|
|
|
#if os(iOS)
|
|
|
|
if let settingsGenerator = self.settingsGenerator {
|
2020-12-03 14:10:29 +00:00
|
|
|
let (wgSettings, resolutionErrors) = settingsGenerator.endpointUapiConfiguration()
|
|
|
|
for error in resolutionErrors {
|
|
|
|
self.logHandler(.error, "Failed to re-resolve \(error.address): \(error.errorDescription ?? "(nil)")")
|
|
|
|
}
|
|
|
|
wgSetConfig(handle, wgSettings)
|
2020-11-04 15:59:33 +00:00
|
|
|
}
|
2020-12-02 12:53:16 +00:00
|
|
|
#endif
|
|
|
|
|
|
|
|
wgBumpSockets(handle)
|
2020-11-04 15:59:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-02 12:49:25 +00:00
|
|
|
/// A enum describing WireGuard log levels defined in `api-ios.go`.
|
2020-11-04 15:59:33 +00:00
|
|
|
public enum WireGuardLogLevel: Int32 {
|
|
|
|
case debug = 0
|
|
|
|
case info = 1
|
|
|
|
case error = 2
|
|
|
|
}
|