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?
private var ifname: String?
private var packetTunnelSettingsGenerator: PacketTunnelSettingsGenerator?
deinit {
networkMonitor?.cancel()
}
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
dispatchQueue.async {
let activationAttemptId = options?["activationAttemptId"] as? String let activationAttemptId = options?["activationAttemptId"] as? String
let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId) let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId)
Logger.configureGlobal(tagged: "NET", withFilePath: FileManager.logFileURL?.path)
wg_log(.info, message: "Starting tunnel from the " + (activationAttemptId == nil ? "OS directly, rather than the app" : "app"))
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:
self.setTunnelNetworkSettings(self.packetTunnelSettingsGenerator!.generateNetworkSettings()) { error in
self.dispatchQueue.async {
if let error = error {
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
} 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
if fileDescriptor < 0 {
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor") wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor) errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor) completionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
return
}
self.ifname = Self.getInterfaceName(fileDescriptor: fileDescriptor) case .dnsResolution(let dnsErrors):
wg_log(.info, message: "Tunnel interface is \(self.ifname ?? "unknown")") let hostnamesWithDnsResolutionFailure = dnsErrors.map { $0.address }
.joined(separator: ", ")
wg_log(.error, message: "DNS resolution failed for the following hostnames: \(hostnamesWithDnsResolutionFailure)")
errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure)
completionHandler(PacketTunnelProviderError.dnsResolutionFailure)
let handle = self.packetTunnelSettingsGenerator!.uapiConfiguration() case .setNetworkSettings(let error):
.withCString { return wgTurnOn($0, fileDescriptor) } wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
if handle < 0 { errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(handle)") completionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
case .setNetworkSettingsTimeout:
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings timing out")
errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
completionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)
case .startWireGuardBackend(let errorCode):
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(errorCode)")
errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend) errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartBackend) completionHandler(PacketTunnelProviderError.couldNotStartBackend)
return
} case .invalidState:
self.handle = handle // Must never happen
startTunnelCompletionHandler(nil) fatalError()
}
}
} }
} }
} }
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
dispatchQueue.async {
self.networkMonitor?.cancel()
self.networkMonitor = nil
ErrorNotifier.removeLastErrorFile() ErrorNotifier.removeLastErrorFile()
wg_log(.info, staticMessage: "Stopping tunnel") wg_log(.info, staticMessage: "Stopping tunnel")
if let handle = self.handle {
wgTurnOff(handle) adapter.stop { error in
if let error = error {
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?
if let settings = settings {
data = settings.data(using: .utf8)!
}
completionHandler(data) completionHandler(data)
free(settings)
} else {
completionHandler(nil)
} }
} else { } else {
completionHandler(nil) completionHandler(nil)
} }
} }
} }
private class func getInterfaceName(fileDescriptor: Int32) -> String? { extension WireGuardLogLevel {
var ifnameBytes = [CChar](repeating: 0, count: Int(IF_NAMESIZE)) var osLogLevel: OSLogType {
switch self {
return ifnameBytes.withUnsafeMutableBufferPointer { bufferPointer -> String? in case .debug:
guard let baseAddress = bufferPointer.baseAddress else { return nil } return .debug
case .info:
var ifnameSize = socklen_t(bufferPointer.count) return .info
let result = getsockopt( case .error:
fileDescriptor, return .error
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)
}
} }