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
|
|
|
|
|
|
|
import NetworkExtension
|
2018-11-29 10:16:21 +00:00
|
|
|
import Foundation
|
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-11-29 10:16:21 +00:00
|
|
|
private var logFileHandle: FileHandle?
|
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
/// A packet tunnel provider object.
|
2018-06-22 06:23:39 +00:00
|
|
|
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?
|
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
// MARK: NEPacketTunnelProvider
|
2018-06-22 06:23:39 +00:00
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
/// Begin the process of establishing the tunnel.
|
2018-10-27 09:32:32 +00:00
|
|
|
override func startTunnel(options: [String: NSObject]?,
|
|
|
|
completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-11-08 12:20:47 +00:00
|
|
|
guard let tunnelProviderProtocol = self.protocolConfiguration as? NETunnelProviderProtocol,
|
|
|
|
let tunnelConfiguration = tunnelProviderProtocol.tunnelConfiguration() else {
|
2018-11-09 11:23:52 +00:00
|
|
|
ErrorNotifier.notify(PacketTunnelProviderError.savedProtocolConfigurationIsInvalid, from: self)
|
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-09 14:19:48 +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, "Starting tunnel")
|
2018-11-09 14:19:48 +00:00
|
|
|
|
2018-11-08 12:20:47 +00:00
|
|
|
// 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) {
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(.error, "Starting tunnel failed: DNS resolution failure")
|
|
|
|
wg_log(.error, "Hostnames for which DNS resolution failed: \(hostnames.joined(separator: ", "))")
|
2018-11-09 11:23:52 +00:00
|
|
|
ErrorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure(hostnames: hostnames), from: self)
|
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)
|
|
|
|
|
|
|
|
// Setup packetTunnelSettingsGenerator
|
|
|
|
|
|
|
|
let packetTunnelSettingsGenerator = PacketTunnelSettingsGenerator(tunnelConfiguration: tunnelConfiguration,
|
|
|
|
resolvedEndpoints: resolvedEndpoints)
|
|
|
|
|
|
|
|
// Bring up wireguard-go backend
|
2018-10-27 09:32:32 +00:00
|
|
|
|
2018-11-06 14:46:44 +00:00
|
|
|
let fd = packetFlow.value(forKeyPath: "socket.fileDescriptor") as! Int32
|
|
|
|
if fd < 0 {
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(.error, "Starting tunnel failed: Could not determine file descriptor")
|
2018-11-09 11:23:52 +00:00
|
|
|
ErrorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard, from: self)
|
2018-11-06 14:46:44 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
|
|
|
|
return
|
|
|
|
}
|
2018-11-08 12:20:47 +00:00
|
|
|
|
|
|
|
let wireguardSettings = packetTunnelSettingsGenerator.generateWireGuardSettings()
|
|
|
|
let handle = connect(interfaceName: tunnelConfiguration.interface.name, settings: wireguardSettings, fd: fd)
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
if handle < 0 {
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(.error, "Starting tunnel failed: Could not start WireGuard")
|
2018-11-09 11:23:52 +00:00
|
|
|
ErrorNotifier.notify(PacketTunnelProviderError.couldNotStartWireGuard, from: self)
|
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
|
|
|
// Apply network settings
|
2018-08-27 20:32:47 +00:00
|
|
|
|
2018-11-08 12:20:47 +00:00
|
|
|
let networkSettings: NEPacketTunnelNetworkSettings = packetTunnelSettingsGenerator.generateNetworkSettings()
|
2018-10-27 09:32:32 +00:00
|
|
|
setTunnelNetworkSettings(networkSettings) { (error) in
|
2018-08-27 20:32:47 +00:00
|
|
|
if let error = error {
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(.error, "Starting tunnel failed: Error setting network settings.")
|
|
|
|
wg_log(.error, "Error from setTunnelNetworkSettings: \(error.localizedDescription)")
|
2018-11-09 11:23:52 +00:00
|
|
|
ErrorNotifier.notify(PacketTunnelProviderError.coultNotSetNetworkSettings, from: self)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.coultNotSetNetworkSettings)
|
2018-08-27 20:32:47 +00:00
|
|
|
} else {
|
|
|
|
startTunnelCompletionHandler(nil /* No errors */)
|
|
|
|
}
|
2018-07-07 20:54:44 +00:00
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
/// Begin the process of stopping the tunnel.
|
2018-06-22 06:23:39 +00:00
|
|
|
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(.info, "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()
|
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
completionHandler()
|
|
|
|
}
|
|
|
|
|
2018-08-28 12:03:53 +00:00
|
|
|
private func configureLogger() {
|
2018-11-29 10:16:21 +00:00
|
|
|
|
|
|
|
// Setup writing the log to a file
|
|
|
|
if let networkExtensionLogFileURL = FileManager.networkExtensionLogFileURL {
|
|
|
|
let fileManager = FileManager.default
|
|
|
|
let filePath = networkExtensionLogFileURL.path
|
|
|
|
fileManager.createFile(atPath: filePath, contents: nil) // Create the file if it doesn't already exist
|
|
|
|
if let fileHandle = FileHandle(forWritingAtPath: filePath) {
|
|
|
|
logFileHandle = fileHandle
|
|
|
|
} else {
|
|
|
|
os_log("Can't open log file for writing. Log is not saved to file.", log: OSLog.default, type: .error)
|
|
|
|
logFileHandle = nil
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
os_log("Can't obtain log file URL. Log is not saved to file.", log: OSLog.default, type: .error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setup WireGuard logger
|
2018-10-31 02:13:00 +00:00
|
|
|
wgSetLogger { (level, msgCStr) in
|
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
|
|
|
|
}
|
|
|
|
let msg = (msgCStr != nil) ? String(cString: msgCStr!) : ""
|
2018-11-29 10:16:21 +00:00
|
|
|
wg_log(logType, msg)
|
2018-08-28 12:03:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-06 14:46:44 +00:00
|
|
|
private func connect(interfaceName: String, settings: String, fd: Int32) -> Int32 { // swiftlint:disable:this cyclomatic_complexity
|
2018-08-28 12:04:38 +00:00
|
|
|
return withStringsAsGoStrings(interfaceName, settings) { (nameGoStr, settingsGoStr) -> Int32 in
|
2018-11-06 14:46:44 +00:00
|
|
|
return wgTurnOn(nameGoStr, settingsGoStr, fd)
|
2018-08-28 12:04:38 +00:00
|
|
|
}
|
|
|
|
}
|
2018-11-29 10:16:21 +00:00
|
|
|
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
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) -> R in
|
|
|
|
let gstr1 = gostring_t(p: s1cStr, n: str1.utf8.count)
|
|
|
|
return str2.withCString { (s2cStr) -> R in
|
|
|
|
let gstr2 = gostring_t(p: s2cStr, n: str2.utf8.count)
|
|
|
|
return closure(gstr1, gstr2)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-11-29 10:16:21 +00:00
|
|
|
|
|
|
|
private func wg_log(_ type: OSLogType, _ msg: StaticString) {
|
|
|
|
// Write to os log
|
|
|
|
os_log(msg, log: OSLog.default, type: type)
|
|
|
|
// Write to file log
|
|
|
|
let msgString: String = msg.withUTF8Buffer { (ptr: UnsafeBufferPointer<UInt8>) -> String in
|
|
|
|
return String(decoding: ptr, as: UTF8.self)
|
|
|
|
}
|
|
|
|
file_log(type: type, message: msgString)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func wg_log(_ type: OSLogType, _ msg: String) {
|
|
|
|
// Write to os log
|
|
|
|
os_log("%{public}s", log: OSLog.default, type: type, msg)
|
|
|
|
// Write to file log
|
|
|
|
file_log(type: type, message: msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func file_log(type: OSLogType, message: String) {
|
|
|
|
var msgLine = type.toMessagePrefix() + message
|
|
|
|
if (msgLine.last! != "\n") {
|
|
|
|
msgLine.append("\n")
|
|
|
|
}
|
|
|
|
let data = msgLine.data(using: .utf8)
|
|
|
|
if let data = data, let logFileHandle = logFileHandle {
|
|
|
|
logFileHandle.write(data)
|
|
|
|
logFileHandle.synchronizeFile()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension OSLogType {
|
|
|
|
func toMessagePrefix() -> String {
|
|
|
|
switch (self) {
|
|
|
|
case .debug: return "Debug: "
|
|
|
|
case .info: return "Info: "
|
|
|
|
case .error: return "Error: "
|
|
|
|
case .fault: return "Fault: "
|
|
|
|
default:
|
|
|
|
return "Unknown: "
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|