wireguard-apple/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift

210 lines
8.5 KiB
Swift
Raw Normal View History

2018-11-06 18:04:53 +00:00
// SPDX-License-Identifier: MIT
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
2018-11-29 10:16:21 +00:00
import Foundation
import Network
import NetworkExtension
import os.log
2018-08-03 20:24:41 +00:00
enum PacketTunnelProviderError: Error {
case savedProtocolConfigurationIsInvalid
case dnsResolutionFailure(hostnames: [String])
case couldNotStartWireGuard
case coultNotSetNetworkSettings
2018-08-03 20:24:41 +00:00
}
2018-11-29 10:16:21 +00:00
private var logFileHandle: FileHandle?
2018-08-03 20:24:41 +00:00
/// A packet tunnel provider object.
class PacketTunnelProvider: NEPacketTunnelProvider {
2018-08-03 20:24:41 +00:00
// MARK: Properties
2018-09-26 09:22:54 +00:00
private var wgHandle: Int32?
private var networkMonitor: NWPathMonitor?
2018-09-26 09:22:54 +00:00
2018-08-03 20:24:41 +00:00
// MARK: NEPacketTunnelProvider
deinit {
networkMonitor?.cancel()
}
2018-08-03 20:24:41 +00:00
/// Begin the process of establishing the tunnel.
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol,
let tunnelConfiguration = tunnelProviderProtocol.tunnelConfiguration() else {
ErrorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid, from: self)
startTunnelCompletionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
return
2018-08-27 20:32:47 +00:00
}
2018-08-16 19:26:24 +00:00
startTunnel(with: tunnelConfiguration, completionHandler: startTunnelCompletionHandler)
}
func startTunnel(with tunnelConfiguration: TunnelConfiguration, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
2018-11-29 10:16:21 +00:00
// Configure logging
configureLogger()
wg_log(.info, message: "WireGuard for iOS version \(appVersion())")
wg_log(.info, message: "WireGuard Go backend version \(goBackendVersion())")
wg_log(.info, message: "Tunnel interface name: \(tunnelConfiguration.interface.name)")
wg_log(.info, staticMessage: "Starting tunnel")
// Resolve endpoint domains
let endpoints = tunnelConfiguration.peers.map { $0.endpoint }
var resolvedEndpoints = [Endpoint?]()
do {
resolvedEndpoints = try DNSResolver.resolveSync(endpoints: endpoints)
} catch DNSResolverError.dnsResolutionFailed(let hostnames) {
wg_log(.error, staticMessage: "Starting tunnel failed: DNS resolution failure")
wg_log(.error, message: "Hostnames for which DNS resolution failed: \(hostnames.joined(separator: ", "))")
ErrorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure(hostnames: hostnames), from: self)
startTunnelCompletionHandler(PacketTunnelProviderError.dnsResolutionFailure(hostnames: hostnames))
return
} catch {
// There can be no other errors from DNSResolver.resolveSync()
fatalError()
}
assert(endpoints.count == resolvedEndpoints.count)
// Setup packetTunnelSettingsGenerator
let packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints)
// Bring up wireguard-go backend
let fileDescriptor = packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32 //swiftlint:disable:this force_cast
if fileDescriptor < 0 {
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
ErrorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard, from: self)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
return
}
let wireguardSettings = packetTunnelSettingsGenerator.uapiConfiguration()
var handle: Int32 = -1
networkMonitor = NWPathMonitor()
networkMonitor?.pathUpdateHandler = { path in
guard handle >= 0 else { return }
if path.status == .satisfied {
2018-12-11 23:45:50 +00:00
wg_log(.debug, message: "Network change detected, re-establishing sockets and IPs: \(path.availableInterfaces)")
let endpointString = packetTunnelSettingsGenerator.endpointUapiConfiguration(currentListenPort: wgGetListenPort(handle))
let err = endpointString.withCString {
wgSetConfig(handle, gostring_t(p: $0, n: endpointString.utf8.count))
2018-12-11 23:45:50 +00:00
}
if err == -EADDRINUSE {
let endpointString = packetTunnelSettingsGenerator.endpointUapiConfiguration(currentListenPort: 0)
_ = endpointString.withCString {
wgSetConfig(handle, gostring_t(p: $0, n: endpointString.utf8.count))
2018-12-11 23:45:50 +00:00
}
}
}
}
networkMonitor?.start(queue: DispatchQueue(label: "NetworkMonitor"))
handle = connect(interfaceName: tunnelConfiguration.interface.name, settings: wireguardSettings, fileDescriptor: fileDescriptor)
2018-08-27 20:32:47 +00:00
if handle < 0 {
wg_log(.error, staticMessage: "Starting tunnel failed: Could not start WireGuard")
ErrorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard, from: self)
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
2018-08-27 20:32:47 +00:00
return
}
2018-08-15 20:57:40 +00:00
2018-08-27 20:32:47 +00:00
wgHandle = handle
2018-08-15 20:57:40 +00:00
// Apply network settings
2018-08-27 20:32:47 +00:00
let networkSettings: NEPacketTunnelNetworkSettings = packetTunnelSettingsGenerator.generateNetworkSettings()
setTunnelNetworkSettings(networkSettings) { error in
2018-08-27 20:32:47 +00:00
if let error = error {
wg_log(.error, staticMessage: "Starting tunnel failed: Error setting network settings.")
wg_log(.error, message: "Error from setTunnelNetworkSettings: \(error.localizedDescription)")
ErrorNotifier.notify(PacketTunnelProviderError.coultNotSetNetworkSettings, from: self)
startTunnelCompletionHandler(PacketTunnelProviderError.coultNotSetNetworkSettings)
2018-08-27 20:32:47 +00:00
} else {
startTunnelCompletionHandler(nil /* No errors */)
}
}
}
2018-08-03 20:24:41 +00:00
/// Begin the process of stopping the tunnel.
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
networkMonitor?.cancel()
networkMonitor = nil
wg_log(.info, staticMessage: "Stopping tunnel")
2018-08-27 20:32:47 +00:00
if let handle = wgHandle {
wgTurnOff(handle)
}
2018-11-29 10:16:21 +00:00
if let fileHandle = logFileHandle {
fileHandle.closeFile()
}
completionHandler()
}
private func configureLogger() {
2018-11-29 10:16:21 +00:00
// Setup writing the log to a file
if let networkExtensionLogFilePath = FileManager.networkExtensionLogFileURL?.path {
if !Logger.configure(withFilePath: networkExtensionLogFilePath) {
2018-11-29 10:16:21 +00:00
os_log("Can't open log file for writing. Log is not saved to file.", log: OSLog.default, type: .error)
}
} else {
os_log("Can't obtain log file URL. Log is not saved to file.", log: OSLog.default, type: .error)
}
// Setup WireGuard logger
wgSetLogger { level, msgCStr in
let logType: OSLogType
switch level {
case 0:
logType = .debug
case 1:
logType = .info
case 2:
logType = .error
default:
logType = .default
}
let msg = (msgCStr != nil) ? String(cString: msgCStr!) : ""
wg_log(logType, message: msg)
}
}
private func connect(interfaceName: String, settings: String, fileDescriptor: Int32) -> Int32 {
return withStringsAsGoStrings(interfaceName, settings) { nameGoStr, settingsGoStr in
return wgTurnOn(nameGoStr, settingsGoStr, fileDescriptor)
}
}
2018-11-29 10:16:21 +00:00
func appVersion() -> String {
var appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown version"
if let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
appVersion += " (\(appBuild))"
}
return appVersion
}
func goBackendVersion() -> String {
return WIREGUARD_GO_VERSION
}
}
2018-08-27 20:32:47 +00:00
private func withStringsAsGoStrings<R>(_ str1: String, _ str2: String, closure: (gostring_t, gostring_t) -> R) -> R {
return str1.withCString { s1cStr in
2018-08-27 20:32:47 +00:00
let gstr1 = gostring_t(p: s1cStr, n: str1.utf8.count)
return str2.withCString { s2cStr in
2018-08-27 20:32:47 +00:00
let gstr2 = gostring_t(p: s2cStr, n: str2.utf8.count)
return closure(gstr1, gstr2)
}
}
}