2018-11-06 18:04:53 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
|
2018-06-22 06:23:39 +00:00
|
|
|
|
2018-11-29 10:16:21 +00:00
|
|
|
import Foundation
|
2018-12-11 22:12:04 +00:00
|
|
|
import Network
|
|
|
|
import NetworkExtension
|
2018-07-07 20:54:44 +00:00
|
|
|
import os.log
|
2018-06-22 06:23:39 +00:00
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
enum PacketTunnelProviderError: Error {
|
2018-11-08 12:20:47 +00:00
|
|
|
case savedProtocolConfigurationIsInvalid
|
|
|
|
case dnsResolutionFailure(hostnames: [String])
|
2018-10-27 09:32:32 +00:00
|
|
|
case couldNotStartWireGuard
|
|
|
|
case coultNotSetNetworkSettings
|
2018-08-03 20:24:41 +00:00
|
|
|
}
|
|
|
|
|
2018-06-22 06:23:39 +00:00
|
|
|
class PacketTunnelProvider: NEPacketTunnelProvider {
|
2018-12-17 05:51:25 +00:00
|
|
|
|
2018-09-26 09:22:54 +00:00
|
|
|
private var wgHandle: Int32?
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-11 22:12:04 +00:00
|
|
|
private var networkMonitor: NWPathMonitor?
|
2018-09-26 09:22:54 +00:00
|
|
|
|
2018-12-11 22:12:04 +00:00
|
|
|
deinit {
|
|
|
|
networkMonitor?.cancel()
|
|
|
|
}
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-19 07:40:42 +00:00
|
|
|
//swiftlint:disable:next function_body_length
|
2018-12-13 03:09:52 +00:00
|
|
|
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-12-13 20:54:53 +00:00
|
|
|
let activationAttemptId = options?["activationAttemptId"] as? String
|
|
|
|
let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId, tunnelProvider: self)
|
|
|
|
|
2018-12-14 23:12:59 +00:00
|
|
|
guard let tunnelProviderProtocol = protocolConfiguration as? NETunnelProviderProtocol,
|
2018-11-08 12:20:47 +00:00
|
|
|
let tunnelConfiguration = tunnelProviderProtocol.tunnelConfiguration() else {
|
2018-12-13 20:54:53 +00:00
|
|
|
errorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
|
2018-11-08 12:20:47 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid)
|
|
|
|
return
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-08-16 19:26:24 +00:00
|
|
|
|
2018-11-29 10:16:21 +00:00
|
|
|
configureLogger()
|
|
|
|
|
2018-12-13 12:39:38 +00:00
|
|
|
wg_log(.info, message: "Starting tunnel '\(tunnelConfiguration.interface.name)'")
|
2018-11-08 12:20:47 +00:00
|
|
|
|
|
|
|
let endpoints = tunnelConfiguration.peers.map { $0.endpoint }
|
2018-12-13 03:09:52 +00:00
|
|
|
var resolvedEndpoints = [Endpoint?]()
|
2018-11-08 12:20:47 +00:00
|
|
|
do {
|
|
|
|
resolvedEndpoints = try DNSResolver.resolveSync(endpoints: endpoints)
|
|
|
|
} catch DNSResolverError.dnsResolutionFailed(let hostnames) {
|
2018-12-04 10:28:02 +00:00
|
|
|
wg_log(.error, staticMessage: "Starting tunnel failed: DNS resolution failure")
|
|
|
|
wg_log(.error, message: "Hostnames for which DNS resolution failed: \(hostnames.joined(separator: ", "))")
|
2018-12-13 20:54:53 +00:00
|
|
|
errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure(hostnames: hostnames))
|
2018-11-08 12:20:47 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.dnsResolutionFailure(hostnames: hostnames))
|
|
|
|
return
|
|
|
|
} catch {
|
|
|
|
// There can be no other errors from DNSResolver.resolveSync()
|
|
|
|
fatalError()
|
2018-10-27 09:32:32 +00:00
|
|
|
}
|
2018-11-08 12:20:47 +00:00
|
|
|
assert(endpoints.count == resolvedEndpoints.count)
|
|
|
|
|
2018-12-12 18:28:27 +00:00
|
|
|
let packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration, resolvedEndpoints: resolvedEndpoints)
|
2018-11-08 12:20:47 +00:00
|
|
|
|
|
|
|
// Bring up wireguard-go backend
|
2018-10-27 09:32:32 +00:00
|
|
|
|
2018-12-12 21:33:14 +00:00
|
|
|
let fileDescriptor = packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32 //swiftlint:disable:this force_cast
|
2018-12-12 18:28:27 +00:00
|
|
|
if fileDescriptor < 0 {
|
2018-12-04 10:28:02 +00:00
|
|
|
wg_log(.error, staticMessage: "Starting tunnel failed: Could not determine file descriptor")
|
2018-12-13 20:54:53 +00:00
|
|
|
errorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard)
|
2018-11-06 14:46:44 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
|
|
|
|
return
|
|
|
|
}
|
2018-11-08 12:20:47 +00:00
|
|
|
|
2018-12-11 22:59:15 +00:00
|
|
|
let wireguardSettings = packetTunnelSettingsGenerator.uapiConfiguration()
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-11 22:59:15 +00:00
|
|
|
var handle: Int32 = -1
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-11 22:59:15 +00:00
|
|
|
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))
|
2018-12-13 18:36:43 +00:00
|
|
|
let err = withStringsAsGoStrings(endpointString, call: { return wgSetConfig(handle, $0.0) })
|
2018-12-11 23:45:50 +00:00
|
|
|
if err == -EADDRINUSE {
|
|
|
|
let endpointString = packetTunnelSettingsGenerator.endpointUapiConfiguration(currentListenPort: 0)
|
2018-12-13 18:36:43 +00:00
|
|
|
_ = withStringsAsGoStrings(endpointString, call: { return wgSetConfig(handle, $0.0) })
|
2018-12-11 22:59:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
networkMonitor?.start(queue: DispatchQueue(label: "NetworkMonitor"))
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-12 18:28:27 +00:00
|
|
|
handle = connect(interfaceName: tunnelConfiguration.interface.name, settings: wireguardSettings, fileDescriptor: fileDescriptor)
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
if handle < 0 {
|
2018-12-04 10:28:02 +00:00
|
|
|
wg_log(.error, staticMessage: "Starting tunnel failed: Could not start WireGuard")
|
2018-12-13 20:54:53 +00:00
|
|
|
errorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard)
|
2018-10-27 09:32:32 +00:00
|
|
|
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
|
|
|
|
2018-11-08 12:20:47 +00:00
|
|
|
let networkSettings: NEPacketTunnelNetworkSettings = packetTunnelSettingsGenerator.generateNetworkSettings()
|
2018-12-12 21:33:14 +00:00
|
|
|
setTunnelNetworkSettings(networkSettings) { error in
|
2018-08-27 20:32:47 +00:00
|
|
|
if let error = error {
|
2018-12-04 10:28:02 +00:00
|
|
|
wg_log(.error, staticMessage: "Starting tunnel failed: Error setting network settings.")
|
|
|
|
wg_log(.error, message: "Error from setTunnelNetworkSettings: \(error.localizedDescription)")
|
2018-12-13 20:54:53 +00:00
|
|
|
errorNotifier.notify(PacketTunnelProviderError.coultNotSetNetworkSettings)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.coultNotSetNetworkSettings)
|
2018-08-27 20:32:47 +00:00
|
|
|
} else {
|
2018-12-17 05:51:25 +00:00
|
|
|
startTunnelCompletionHandler(nil)
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-07-07 20:54:44 +00:00
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
2018-12-11 22:12:04 +00:00
|
|
|
networkMonitor?.cancel()
|
|
|
|
networkMonitor = nil
|
2018-12-12 17:40:57 +00:00
|
|
|
|
2018-12-13 20:54:53 +00:00
|
|
|
ErrorNotifier.removeLastErrorFile()
|
|
|
|
|
2018-12-04 10:28:02 +00:00
|
|
|
wg_log(.info, staticMessage: "Stopping tunnel")
|
2018-08-27 20:32:47 +00:00
|
|
|
if let handle = wgHandle {
|
|
|
|
wgTurnOff(handle)
|
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
completionHandler()
|
|
|
|
}
|
|
|
|
|
2018-08-28 12:03:53 +00:00
|
|
|
private func configureLogger() {
|
2018-12-14 21:53:42 +00:00
|
|
|
Logger.configureGlobal(withFilePath: FileManager.networkExtensionLogFileURL?.path)
|
2018-12-13 14:26:04 +00:00
|
|
|
wgSetLogger { level, msgC in
|
|
|
|
guard let msgC = msgC else { return }
|
2018-08-28 12:03:53 +00:00
|
|
|
let logType: OSLogType
|
|
|
|
switch level {
|
|
|
|
case 0:
|
|
|
|
logType = .debug
|
|
|
|
case 1:
|
|
|
|
logType = .info
|
|
|
|
case 2:
|
|
|
|
logType = .error
|
|
|
|
default:
|
|
|
|
logType = .default
|
|
|
|
}
|
2018-12-13 14:26:04 +00:00
|
|
|
wg_log(logType, message: String(cString: msgC))
|
2018-08-28 12:03:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-12 18:28:27 +00:00
|
|
|
private func connect(interfaceName: String, settings: String, fileDescriptor: Int32) -> Int32 {
|
2018-12-13 18:36:43 +00:00
|
|
|
return withStringsAsGoStrings(interfaceName, settings) { return wgTurnOn($0.0, $0.1, fileDescriptor) }
|
2018-08-28 12:04:38 +00:00
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
2018-08-27 20:32:47 +00:00
|
|
|
|
2018-12-13 19:06:37 +00:00
|
|
|
// swiftlint:disable:next large_tuple identifier_name
|
2018-12-13 18:43:12 +00:00
|
|
|
func withStringsAsGoStrings<R>(_ s1: String, _ s2: String? = nil, _ s3: String? = nil, _ s4: String? = nil, call: ((gostring_t, gostring_t, gostring_t, gostring_t)) -> R) -> R {
|
2018-12-13 19:06:37 +00:00
|
|
|
// swiftlint:disable:next large_tuple identifier_name
|
2018-12-13 18:43:12 +00:00
|
|
|
func helper(_ p1: UnsafePointer<Int8>?, _ p2: UnsafePointer<Int8>?, _ p3: UnsafePointer<Int8>?, _ p4: UnsafePointer<Int8>?, _ call: ((gostring_t, gostring_t, gostring_t, gostring_t)) -> R) -> R {
|
2018-12-13 18:36:43 +00:00
|
|
|
return call((gostring_t(p: p1, n: s1.utf8.count), gostring_t(p: p2, n: s2?.utf8.count ?? 0), gostring_t(p: p3, n: s3?.utf8.count ?? 0), gostring_t(p: p4, n: s4?.utf8.count ?? 0)))
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-12-13 18:43:12 +00:00
|
|
|
return helper(s1, s2, s3, s4, call)
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|