2023-12-14 21:01:26 +00:00
|
|
|
import TunnelKitCore
|
2021-12-01 12:54:00 +00:00
|
|
|
import TunnelKitWireGuardCore
|
|
|
|
import TunnelKitWireGuardManager
|
|
|
|
import WireGuardKit
|
2022-03-04 23:58:07 +00:00
|
|
|
import __TunnelKitUtils
|
|
|
|
import SwiftyBeaver
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// Copyright © 2018-2021 WireGuard LLC. All Rights Reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import NetworkExtension
|
|
|
|
import os
|
|
|
|
|
|
|
|
open class WireGuardTunnelProvider: NEPacketTunnelProvider {
|
2022-03-04 23:58:07 +00:00
|
|
|
private var cfg: WireGuard.ProviderConfiguration!
|
2021-12-01 12:54:00 +00:00
|
|
|
|
2023-12-14 21:01:26 +00:00
|
|
|
/// The number of milliseconds between data count updates. Set to 0 to disable updates (default).
|
|
|
|
public var dataCountInterval = 0
|
|
|
|
|
|
|
|
/// Once the tunnel starts, enable this property to update connection stats
|
|
|
|
private var tunnelIsStarted = false
|
|
|
|
|
|
|
|
private let tunnelQueue = DispatchQueue(label: WireGuardTunnelProvider.description(), qos: .utility)
|
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
private lazy var adapter: WireGuardAdapter = {
|
|
|
|
return WireGuardAdapter(with: self) { logLevel, message in
|
|
|
|
wg_log(logLevel.osLogLevel, message: message)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
open override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
|
|
|
|
|
|
|
|
// BEGIN: TunnelKit
|
2023-04-20 19:52:45 +00:00
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
guard let tunnelProviderProtocol = protocolConfiguration as? NETunnelProviderProtocol else {
|
|
|
|
fatalError("Not a NETunnelProviderProtocol")
|
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
guard let providerConfiguration = tunnelProviderProtocol.providerConfiguration else {
|
|
|
|
fatalError("Missing providerConfiguration")
|
2021-12-01 12:54:00 +00:00
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
let tunnelConfiguration: TunnelConfiguration
|
|
|
|
do {
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg = try fromDictionary(WireGuard.ProviderConfiguration.self, providerConfiguration)
|
|
|
|
tunnelConfiguration = cfg.configuration.tunnelConfiguration
|
2021-12-01 12:54:00 +00:00
|
|
|
} catch {
|
2023-07-02 09:56:40 +00:00
|
|
|
completionHandler(TunnelKitWireGuardError.savedProtocolConfigurationIsInvalid)
|
2021-12-01 12:54:00 +00:00
|
|
|
return
|
|
|
|
}
|
2023-04-20 19:52:45 +00:00
|
|
|
|
2022-06-16 18:54:48 +00:00
|
|
|
configureLogging()
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
// END: TunnelKit
|
|
|
|
|
|
|
|
// Start the tunnel
|
2023-12-14 21:01:26 +00:00
|
|
|
adapter.start(tunnelConfiguration: tunnelConfiguration) { [weak self] adapterError in
|
|
|
|
guard let self else {
|
|
|
|
completionHandler(nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
guard let adapterError = adapterError else {
|
|
|
|
let interfaceName = self.adapter.interfaceName ?? "unknown"
|
|
|
|
|
|
|
|
wg_log(.info, message: "Tunnel interface is \(interfaceName)")
|
2023-12-14 21:01:26 +00:00
|
|
|
self.tunnelQueue.async {
|
|
|
|
self.tunnelIsStarted = true
|
|
|
|
self.refreshDataCount()
|
|
|
|
}
|
2021-12-01 12:54:00 +00:00
|
|
|
completionHandler(nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch adapterError {
|
|
|
|
case .cannotLocateTunnelFileDescriptor:
|
|
|
|
wg_log(.error, staticMessage: "Starting tunnel failed: could not determine file descriptor")
|
2022-06-17 05:00:40 +00:00
|
|
|
self.cfg._appexSetLastError(.couldNotDetermineFileDescriptor)
|
2023-07-02 09:56:40 +00:00
|
|
|
completionHandler(TunnelKitWireGuardError.couldNotDetermineFileDescriptor)
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
case .dnsResolution(let dnsErrors):
|
2022-10-26 22:31:30 +00:00
|
|
|
let hostnamesWithDnsResolutionFailure = dnsErrors.map(\.address)
|
2021-12-01 12:54:00 +00:00
|
|
|
.joined(separator: ", ")
|
|
|
|
wg_log(.error, message: "DNS resolution failed for the following hostnames: \(hostnamesWithDnsResolutionFailure)")
|
2022-06-17 05:00:40 +00:00
|
|
|
self.cfg._appexSetLastError(.dnsResolutionFailure)
|
2023-07-02 09:56:40 +00:00
|
|
|
completionHandler(TunnelKitWireGuardError.dnsResolutionFailure)
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
case .setNetworkSettings(let error):
|
|
|
|
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
|
2022-06-17 05:00:40 +00:00
|
|
|
self.cfg._appexSetLastError(.couldNotSetNetworkSettings)
|
2023-07-02 09:56:40 +00:00
|
|
|
completionHandler(TunnelKitWireGuardError.couldNotSetNetworkSettings)
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
case .startWireGuardBackend(let errorCode):
|
|
|
|
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(errorCode)")
|
2022-06-17 05:00:40 +00:00
|
|
|
self.cfg._appexSetLastError(.couldNotStartBackend)
|
2023-07-02 09:56:40 +00:00
|
|
|
completionHandler(TunnelKitWireGuardError.couldNotStartBackend)
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
case .invalidState:
|
|
|
|
// Must never happen
|
|
|
|
fatalError()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
open override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
|
|
|
wg_log(.info, staticMessage: "Stopping tunnel")
|
|
|
|
|
2023-12-14 21:01:26 +00:00
|
|
|
adapter.stop { [weak self] error in
|
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
// BEGIN: TunnelKit
|
|
|
|
|
2023-12-14 21:01:26 +00:00
|
|
|
guard let self else {
|
|
|
|
completionHandler()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
self.tunnelQueue.async {
|
|
|
|
self.cfg._appexSetLastError(nil)
|
|
|
|
self.tunnelIsStarted = false
|
|
|
|
if let error = error {
|
|
|
|
wg_log(.error, message: "Failed to stop WireGuard adapter: \(error.localizedDescription)")
|
|
|
|
}
|
|
|
|
completionHandler()
|
2021-12-01 12:54:00 +00:00
|
|
|
}
|
2023-12-14 21:01:26 +00:00
|
|
|
|
|
|
|
// END: TunnelKit
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
#if os(macOS)
|
|
|
|
// HACK: This is a filthy hack to work around Apple bug 32073323 (dup'd by us as 47526107).
|
|
|
|
// Remove it when they finally fix this upstream and the fix has been rolled out to
|
|
|
|
// sufficient quantities of users.
|
|
|
|
exit(0)
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
open override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
|
2023-12-14 21:01:26 +00:00
|
|
|
guard let completionHandler = completionHandler else {
|
|
|
|
return
|
|
|
|
}
|
2021-12-01 12:54:00 +00:00
|
|
|
|
|
|
|
if messageData.count == 1 && messageData[0] == 0 {
|
|
|
|
adapter.getRuntimeConfiguration { settings in
|
|
|
|
var data: Data?
|
|
|
|
if let settings = settings {
|
|
|
|
data = settings.data(using: .utf8)!
|
|
|
|
}
|
|
|
|
completionHandler(data)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
completionHandler(nil)
|
|
|
|
}
|
|
|
|
}
|
2023-12-14 21:01:26 +00:00
|
|
|
|
|
|
|
// MARK: Data counter (tunnel queue)
|
|
|
|
|
|
|
|
// XXX: thread-safety here is poor, but we know that:
|
|
|
|
//
|
|
|
|
// - dataCountInterval is virtually constant, set on tunnel creation
|
|
|
|
// - cfg only modifies UserDefaults, which is thread-safe
|
|
|
|
// - adapter, used in fetchDataCount, is thread-safe
|
|
|
|
//
|
|
|
|
private func refreshDataCount() {
|
|
|
|
guard dataCountInterval > 0 else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tunnelQueue.schedule(after: DispatchTimeInterval.milliseconds(dataCountInterval)) { [weak self] in
|
|
|
|
self?.refreshDataCount()
|
|
|
|
}
|
|
|
|
|
|
|
|
guard tunnelIsStarted else {
|
|
|
|
cfg._appexSetDataCount(nil)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fetchDataCount { [weak self] result in
|
|
|
|
guard let self else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
switch result {
|
|
|
|
case .success(let dataCount):
|
|
|
|
self.cfg._appexSetDataCount(dataCount)
|
|
|
|
case .failure(let error):
|
|
|
|
wg_log(.error, message: "Failed to refresh data count \(error.localizedDescription)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-12-01 12:54:00 +00:00
|
|
|
}
|
|
|
|
|
2023-12-14 21:01:26 +00:00
|
|
|
private extension WireGuardTunnelProvider {
|
|
|
|
enum StatsError: Error {
|
|
|
|
case parseFailure
|
|
|
|
}
|
|
|
|
|
|
|
|
func configureLogging() {
|
2022-06-16 18:54:48 +00:00
|
|
|
let logLevel: SwiftyBeaver.Level = (cfg.shouldDebug ? .debug : .info)
|
|
|
|
let logFormat = cfg.debugLogFormat ?? "$Dyyyy-MM-dd HH:mm:ss.SSS$d $L $N.$F:$l - $M"
|
2023-04-20 19:52:45 +00:00
|
|
|
|
2022-06-16 18:54:48 +00:00
|
|
|
if cfg.shouldDebug {
|
2022-03-04 23:58:07 +00:00
|
|
|
let console = ConsoleDestination()
|
|
|
|
console.useNSLog = true
|
|
|
|
console.minLevel = logLevel
|
|
|
|
console.format = logFormat
|
|
|
|
SwiftyBeaver.addDestination(console)
|
|
|
|
}
|
|
|
|
|
2022-06-16 18:52:29 +00:00
|
|
|
let file = FileDestination(logFileURL: cfg._appexDebugLogURL)
|
2022-03-04 23:58:07 +00:00
|
|
|
file.minLevel = logLevel
|
|
|
|
file.format = logFormat
|
|
|
|
file.logFileMaxSize = 20000
|
|
|
|
SwiftyBeaver.addDestination(file)
|
2022-06-16 18:52:29 +00:00
|
|
|
|
|
|
|
// store path for clients
|
|
|
|
cfg._appexSetDebugLogPath()
|
2022-03-04 23:58:07 +00:00
|
|
|
}
|
2023-12-14 21:01:26 +00:00
|
|
|
|
|
|
|
func fetchDataCount(completiondHandler: @escaping (Result<DataCount, Error>) -> Void) {
|
|
|
|
adapter.getRuntimeConfiguration { configurationString in
|
|
|
|
if let configurationString = configurationString,
|
|
|
|
let wireGuardDataCount = DataCount.from(wireGuardString: configurationString) {
|
|
|
|
completiondHandler(.success(wireGuardDataCount))
|
|
|
|
} else {
|
|
|
|
completiondHandler(.failure(StatsError.parseFailure))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
}
|
|
|
|
|
2021-12-01 12:54:00 +00:00
|
|
|
extension WireGuardLogLevel {
|
|
|
|
var osLogLevel: OSLogType {
|
|
|
|
switch self {
|
|
|
|
case .verbose:
|
|
|
|
return .debug
|
|
|
|
case .error:
|
|
|
|
return .error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|