Packet tunnel: Implement packet tunnel provider using WireGuardAdapter

Signed-off-by: Andrej Mihajlov <and@mullvad.net>
This commit is contained in:
Andrej Mihajlov 2020-11-19 13:29:31 +01:00
parent 828756e8ba
commit 6099975b71
1 changed files with 79 additions and 138 deletions

View File

@ -3,99 +3,87 @@
import Foundation import Foundation
import NetworkExtension import NetworkExtension
import WireGuardKit
import os
class PacketTunnelProvider: NEPacketTunnelProvider { class PacketTunnelProvider: NEPacketTunnelProvider {
private let dispatchQueue = DispatchQueue(label: "PacketTunnel", qos: .utility) private lazy var adapter = WireGuardAdapter(with: self)
private var handle: Int32? override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
private var networkMonitor: NWPathMonitor? let activationAttemptId = options?["activationAttemptId"] as? String
private var ifname: String? let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId)
private var packetTunnelSettingsGenerator: PacketTunnelSettingsGenerator?
deinit { Logger.configureGlobal(tagged: "NET", withFilePath: FileManager.logFileURL?.path)
networkMonitor?.cancel()
}
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) { wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app"))
dispatchQueue.async {
let activationAttemptId = options?["activationAttemptId"] as? String
let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId)
guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol, guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol,
let tunnelConfiguration = tunnelProviderProtocol.asTunnelConfiguration() else { let tunnelConfiguration = tunnelProviderProtocol.asTunnelConfiguration() else {
errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid) errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
startTunnelCompletionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid) completionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
return return
} }
self.configureLogger() // Setup WireGuard logger
#if os(macOS) adapter.setLogHandler { logLevel, message in
wgEnableRoaming(true) wg_log(logLevel.osLogLevel, message: message)
#endif }
wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app")) // Start the tunnel
adapter.start(tunnelConfiguration: tunnelConfiguration) { adapterError in
guard let adapterError = adapterError else {
let interfaceName = self.adapter.interfaceName ?? "unknown"
let endpoints = tunnelConfiguration.peers.map { $0.endpoint } wg_log(.info, message: "Tunnel interface is \(interfaceName)")
guard let resolvedEndpoints = DNSResolver.resolveSync(endpoints: endpoints) else {
errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure) completionHandler(nil)
startTunnelCompletionHandler(PacketTunnelProviderError.dnsResolutionFailure)
return return
} }
assert(endpoints.count == resolvedEndpoints.count)
self.packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints) switch adapterError {
case .cannotLocateSocketDescriptor:
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
completionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
self.setTunnelNetworkSettings(self.packetTunnelSettingsGenerator!.generateNetworkSettings()) { error in case .dnsResolution(let dnsErrors):
self.dispatchQueue.async { let hostnamesWithDnsResolutionFailure = dnsErrors.map { $0.address }
if let error = error { .joined(separator: ", ")
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)") wg_log(.error, message: "DNS resolution failed for the following hostnames: \(hostnamesWithDnsResolutionFailure)")
errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings) errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings) completionHandler(PacketTunnelProviderError.dnsResolutionFailure)
} else {
self.networkMonitor = NWPathMonitor()
self.networkMonitor!.pathUpdateHandler = { [weak self] path in
self?.pathUpdate(path: path)
}
self.networkMonitor!.start(queue: self.dispatchQueue)
let fileDescriptor = (self.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32) ?? -1 case .setNetworkSettings(let error):
if fileDescriptor < 0 { wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor") errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor) completionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
return
}
self.ifname = Self.getInterfaceName(fileDescriptor: fileDescriptor) case .setNetworkSettingsTimeout:
wg_log(.info, message: "Tunnel interface is \(self.ifname ?? "unknown")") wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings timing out")
errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
completionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
let handle = self.packetTunnelSettingsGenerator!.uapiConfiguration() case .startWireGuardBackend(let errorCode):
.withCString { return wgTurnOn($0, fileDescriptor) } wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(errorCode)")
if handle < 0 { errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend)
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(handle)") completionHandler(PacketTunnelProviderError.couldNotStartBackend)
errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartBackend) case .invalidState:
return // Must never happen
} fatalError()
self.handle = handle
startTunnelCompletionHandler(nil)
}
}
} }
} }
} }
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
dispatchQueue.async { ErrorNotifier.removeLastErrorFile()
self.networkMonitor?.cancel()
self.networkMonitor = nil
ErrorNotifier.removeLastErrorFile() wg_log(.info, staticMessage: "Stopping tunnel")
wg_log(.info, staticMessage: "Stopping tunnel") adapter.stop { error in
if let handle = self.handle { if let error = error {
wgTurnOff(handle) wg_log(.error, message: "Failed to stop WireGuard adapter: \(error.localizedDescription)")
} }
completionHandler() completionHandler()
@ -109,78 +97,31 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
} }
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) { override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
dispatchQueue.async { guard let completionHandler = completionHandler else { return }
guard let completionHandler = completionHandler else { return }
guard let handle = self.handle else {
completionHandler(nil)
return
}
if messageData.count == 1 && messageData[0] == 0 { if messageData.count == 1 && messageData[0] == 0 {
if let settings = wgGetConfig(handle) { adapter.getRuntimeConfiguration { settings in
let data = String(cString: settings).data(using: .utf8)! var data: Data?
completionHandler(data) if let settings = settings {
free(settings) data = settings.data(using: .utf8)!
} else {
completionHandler(nil)
} }
} else { completionHandler(data)
completionHandler(nil)
} }
} else {
completionHandler(nil)
}
}
}
extension WireGuardLogLevel {
var osLogLevel: OSLogType {
switch self {
case .debug:
return .debug
case .info:
return .info
case .error:
return .error
} }
} }
private class func getInterfaceName(fileDescriptor: Int32) -> String? {
var ifnameBytes = [CChar](repeating: 0, count: Int(IF_NAMESIZE))
return ifnameBytes.withUnsafeMutableBufferPointer { bufferPointer -> String? in
guard let baseAddress = bufferPointer.baseAddress else { return nil }
var ifnameSize = socklen_t(bufferPointer.count)
let result = getsockopt(
fileDescriptor,
2 /* SYSPROTO_CONTROL */,
2 /* UTUN_OPT_IFNAME */,
baseAddress, &ifnameSize
)
if result == 0 {
return String(cString: baseAddress)
} else {
return nil
}
}
}
private func configureLogger() {
Logger.configureGlobal(tagged: "NET", withFilePath: FileManager.logFileURL?.path)
wgSetLogger { level, msgC in
guard let msgC = msgC else { return }
let logType: OSLogType
switch level {
case 0:
logType = .debug
case 1:
logType = .info
case 2:
logType = .error
default:
logType = .default
}
wg_log(logType, message: String(cString: msgC))
}
}
private func pathUpdate(path: Network.NWPath) {
guard let handle = handle else { return }
wg_log(.debug, message: "Network change detected with \(path.status) route and interface order \(path.availableInterfaces)")
#if os(iOS)
if let packetTunnelSettingsGenerator = packetTunnelSettingsGenerator {
_ = packetTunnelSettingsGenerator.endpointUapiConfiguration()
.withCString { return wgSetConfig(handle, $0) }
}
#endif
wgBumpSockets(handle)
}
} }