2018-08-23 08:19:25 +00:00
|
|
|
//
|
2019-05-23 19:59:15 +00:00
|
|
|
// OpenVPNTunnelProvider.swift
|
2018-08-23 10:07:55 +00:00
|
|
|
// TunnelKit
|
2018-08-23 08:19:25 +00:00
|
|
|
//
|
|
|
|
// Created by Davide De Rosa on 2/1/17.
|
2022-02-04 11:42:58 +00:00
|
|
|
// Copyright (c) 2022 Davide De Rosa. All rights reserved.
|
2018-08-27 18:30:09 +00:00
|
|
|
//
|
2019-05-14 08:58:47 +00:00
|
|
|
// https://github.com/passepartoutvpn
|
2018-08-27 18:30:09 +00:00
|
|
|
//
|
|
|
|
// This file is part of TunnelKit.
|
|
|
|
//
|
|
|
|
// TunnelKit is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
|
|
|
// TunnelKit is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with TunnelKit. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
//
|
|
|
|
// This file incorporates work covered by the following copyright and
|
|
|
|
// permission notice:
|
|
|
|
//
|
|
|
|
// Copyright (c) 2018-Present Private Internet Access
|
|
|
|
//
|
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
|
|
//
|
|
|
|
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
|
|
//
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
|
|
//
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
import NetworkExtension
|
|
|
|
import SwiftyBeaver
|
2020-11-21 17:40:47 +00:00
|
|
|
#if os(iOS)
|
|
|
|
import SystemConfiguration.CaptiveNetwork
|
|
|
|
#else
|
|
|
|
import CoreWLAN
|
|
|
|
#endif
|
2021-10-25 14:27:27 +00:00
|
|
|
import TunnelKitCore
|
2021-11-07 20:54:05 +00:00
|
|
|
import TunnelKitOpenVPNCore
|
|
|
|
import TunnelKitManager
|
|
|
|
import TunnelKitOpenVPNManager
|
|
|
|
import TunnelKitOpenVPNProtocol
|
2021-10-25 14:27:27 +00:00
|
|
|
import TunnelKitAppExtension
|
2021-11-07 20:54:05 +00:00
|
|
|
import CTunnelKitCore
|
2022-03-04 23:58:07 +00:00
|
|
|
import __TunnelKitUtils
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private let log = SwiftyBeaver.self
|
|
|
|
|
|
|
|
/**
|
|
|
|
Provides an all-in-one `NEPacketTunnelProvider` implementation for use in a
|
|
|
|
Packet Tunnel Provider extension both on iOS and macOS.
|
|
|
|
*/
|
2019-05-23 19:59:15 +00:00
|
|
|
open class OpenVPNTunnelProvider: NEPacketTunnelProvider {
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
// MARK: Tweaks
|
|
|
|
|
|
|
|
/// An optional string describing host app version on tunnel start.
|
|
|
|
public var appVersion: String?
|
|
|
|
|
|
|
|
/// The log separator between sessions.
|
|
|
|
public var logSeparator = "--- EOF ---"
|
|
|
|
|
2022-03-12 07:16:25 +00:00
|
|
|
/// The maximum size of the log.
|
|
|
|
public var maxLogSize = 20000
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-12-12 08:42:48 +00:00
|
|
|
/// The log level when `OpenVPNTunnelProvider.Configuration.shouldDebug` is enabled.
|
|
|
|
public var debugLogLevel: SwiftyBeaver.Level = .debug
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
/// The number of milliseconds after which a DNS resolution fails.
|
|
|
|
public var dnsTimeout = 3000
|
|
|
|
|
|
|
|
/// The number of milliseconds after which the tunnel gives up on a connection attempt.
|
|
|
|
public var socketTimeout = 5000
|
|
|
|
|
|
|
|
/// The number of milliseconds after which the tunnel is shut down forcibly.
|
|
|
|
public var shutdownTimeout = 2000
|
|
|
|
|
|
|
|
/// The number of milliseconds after which a reconnection attempt is issued.
|
|
|
|
public var reconnectionDelay = 1000
|
|
|
|
|
|
|
|
/// The number of link failures after which the tunnel is expected to die.
|
|
|
|
public var maxLinkFailures = 3
|
|
|
|
|
2019-03-27 23:04:35 +00:00
|
|
|
/// The number of milliseconds between data count updates. Set to 0 to disable updates (default).
|
|
|
|
public var dataCountInterval = 0
|
|
|
|
|
2019-04-28 08:56:39 +00:00
|
|
|
/// A list of public DNS servers to use as fallback when none are provided (defaults to CloudFlare).
|
|
|
|
public var fallbackDNSServers = [
|
|
|
|
"1.1.1.1",
|
|
|
|
"1.0.0.1",
|
|
|
|
"2606:4700:4700::1111",
|
|
|
|
"2606:4700:4700::1001"
|
|
|
|
]
|
2019-04-25 14:32:22 +00:00
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
// MARK: Constants
|
|
|
|
|
2022-03-12 07:16:25 +00:00
|
|
|
private var logFile: FileDestination?
|
|
|
|
|
2019-12-12 16:54:57 +00:00
|
|
|
private let tunnelQueue = DispatchQueue(label: OpenVPNTunnelProvider.description(), qos: .utility)
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private let prngSeedLength = 64
|
|
|
|
|
|
|
|
private var cachesURL: URL {
|
2022-03-04 23:58:07 +00:00
|
|
|
let appGroup = cfg.appGroup
|
2018-10-25 06:18:31 +00:00
|
|
|
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
|
|
|
fatalError("No access to app group: \(appGroup)")
|
|
|
|
}
|
|
|
|
return containerURL.appendingPathComponent("Library/Caches/")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2018-08-23 15:42:49 +00:00
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
// MARK: Tunnel configuration
|
|
|
|
|
2022-03-04 23:58:07 +00:00
|
|
|
private var cfg: OpenVPN.ProviderConfiguration!
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private var strategy: ConnectionStrategy!
|
|
|
|
|
|
|
|
// MARK: Internal state
|
|
|
|
|
2019-05-19 13:56:44 +00:00
|
|
|
private var session: OpenVPNSession?
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private var socket: GenericSocket?
|
|
|
|
|
|
|
|
private var pendingStartHandler: ((Error?) -> Void)?
|
|
|
|
|
|
|
|
private var pendingStopHandler: (() -> Void)?
|
|
|
|
|
2019-03-27 23:04:35 +00:00
|
|
|
private var isCountingData = false
|
|
|
|
|
2020-05-08 22:46:16 +00:00
|
|
|
private var shouldReconnect = false
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
// MARK: NEPacketTunnelProvider (XPC queue)
|
|
|
|
|
2019-12-02 09:17:51 +00:00
|
|
|
open override var reasserting: Bool {
|
|
|
|
didSet {
|
|
|
|
log.debug("Reasserting flag \(reasserting ? "set" : "cleared")")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
open override func startTunnel(options: [String : NSObject]? = nil, completionHandler: @escaping (Error?) -> Void) {
|
2018-10-05 17:13:59 +00:00
|
|
|
|
|
|
|
// required configuration
|
2018-08-23 08:19:25 +00:00
|
|
|
do {
|
|
|
|
guard let tunnelProtocol = protocolConfiguration as? NETunnelProviderProtocol else {
|
2021-11-07 20:54:05 +00:00
|
|
|
throw OpenVPNProviderConfigurationError.parameter(name: "protocolConfiguration")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2022-03-03 14:34:57 +00:00
|
|
|
guard let _ = tunnelProtocol.serverAddress else {
|
2021-11-07 20:54:05 +00:00
|
|
|
throw OpenVPNProviderConfigurationError.parameter(name: "protocolConfiguration.serverAddress")
|
2018-10-05 17:13:59 +00:00
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
guard let providerConfiguration = tunnelProtocol.providerConfiguration else {
|
2021-11-07 20:54:05 +00:00
|
|
|
throw OpenVPNProviderConfigurationError.parameter(name: "protocolConfiguration.providerConfiguration")
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg = try fromDictionary(OpenVPN.ProviderConfiguration.self, providerConfiguration)
|
2018-08-23 08:19:25 +00:00
|
|
|
} catch let e {
|
|
|
|
var message: String?
|
2021-11-07 20:54:05 +00:00
|
|
|
if let te = e as? OpenVPNProviderConfigurationError {
|
2018-08-23 08:19:25 +00:00
|
|
|
switch te {
|
2018-10-21 10:58:36 +00:00
|
|
|
case .parameter(let name):
|
|
|
|
message = "Tunnel configuration incomplete: \(name)"
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
NSLog(message ?? "Unexpected error in tunnel configuration: \(e)")
|
|
|
|
completionHandler(e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-06-11 14:32:31 +00:00
|
|
|
// prepare for logging (append)
|
2018-08-23 08:19:25 +00:00
|
|
|
configureLogging(
|
|
|
|
debug: cfg.shouldDebug,
|
|
|
|
customFormat: cfg.debugLogFormat
|
|
|
|
)
|
2022-03-12 07:16:25 +00:00
|
|
|
|
2020-06-11 14:32:31 +00:00
|
|
|
// logging only ACTIVE from now on
|
2022-03-12 07:16:25 +00:00
|
|
|
log.info("")
|
|
|
|
log.info(logSeparator)
|
|
|
|
log.info("")
|
|
|
|
|
2019-03-21 16:46:52 +00:00
|
|
|
// override library configuration
|
2022-03-04 23:58:07 +00:00
|
|
|
CoreConfiguration.masksPrivateData = cfg.masksPrivateData
|
2020-06-29 13:31:20 +00:00
|
|
|
if let versionIdentifier = cfg.versionIdentifier {
|
|
|
|
CoreConfiguration.versionIdentifier = versionIdentifier
|
|
|
|
}
|
2019-03-21 16:46:52 +00:00
|
|
|
|
2020-06-11 14:32:31 +00:00
|
|
|
// optional credentials
|
|
|
|
let credentials: OpenVPN.Credentials?
|
2021-02-07 19:20:11 +00:00
|
|
|
if let username = protocolConfiguration.username, let passwordReference = protocolConfiguration.passwordReference {
|
2021-11-22 23:24:01 +00:00
|
|
|
guard let password = try? Keychain.password(forReference: passwordReference) else {
|
|
|
|
completionHandler(OpenVPNProviderConfigurationError.credentials(details: "Keychain.password(forReference:)"))
|
2021-02-07 19:20:11 +00:00
|
|
|
return
|
|
|
|
}
|
2020-06-11 14:32:31 +00:00
|
|
|
credentials = OpenVPN.Credentials(username, password)
|
|
|
|
} else {
|
|
|
|
credentials = nil
|
|
|
|
}
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
log.info("Starting tunnel...")
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.lastError = nil
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-05-19 13:52:55 +00:00
|
|
|
guard OpenVPN.prepareRandomNumberGenerator(seedLength: prngSeedLength) else {
|
2021-11-07 20:54:05 +00:00
|
|
|
completionHandler(OpenVPNProviderConfigurationError.prngInitialization)
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-04 23:58:07 +00:00
|
|
|
if let appVersion = appVersion {
|
|
|
|
log.info("App version: \(appVersion)")
|
|
|
|
}
|
|
|
|
cfg.print()
|
2020-06-11 14:32:31 +00:00
|
|
|
|
|
|
|
// prepare to pick endpoints
|
2022-03-04 23:58:07 +00:00
|
|
|
strategy = ConnectionStrategy(configuration: cfg.configuration)
|
2020-06-11 14:32:31 +00:00
|
|
|
|
2019-05-19 13:56:44 +00:00
|
|
|
let session: OpenVPNSession
|
2018-08-23 08:19:25 +00:00
|
|
|
do {
|
2022-03-04 23:58:07 +00:00
|
|
|
session = try OpenVPNSession(queue: tunnelQueue, configuration: cfg.configuration, cachesURL: cachesURL)
|
2019-03-27 23:04:35 +00:00
|
|
|
refreshDataCount()
|
2018-08-23 08:19:25 +00:00
|
|
|
} catch let e {
|
|
|
|
completionHandler(e)
|
|
|
|
return
|
|
|
|
}
|
2019-05-19 13:56:44 +00:00
|
|
|
session.credentials = credentials
|
|
|
|
session.delegate = self
|
|
|
|
self.session = session
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
logCurrentSSID()
|
|
|
|
|
|
|
|
pendingStartHandler = completionHandler
|
|
|
|
tunnelQueue.sync {
|
|
|
|
self.connectTunnel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
open override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
|
|
|
pendingStartHandler = nil
|
|
|
|
log.info("Stopping tunnel...")
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.lastError = nil
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-05-19 13:56:44 +00:00
|
|
|
guard let session = session else {
|
2018-08-23 08:19:25 +00:00
|
|
|
flushLog()
|
|
|
|
completionHandler()
|
2019-07-07 21:34:45 +00:00
|
|
|
forceExitOnMac()
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
pendingStopHandler = completionHandler
|
2019-05-02 11:13:20 +00:00
|
|
|
tunnelQueue.schedule(after: .milliseconds(shutdownTimeout)) { [weak self] in
|
|
|
|
guard let weakSelf = self else {
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
2019-05-02 11:13:20 +00:00
|
|
|
guard let pendingHandler = weakSelf.pendingStopHandler else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.warning("Tunnel not responding after \(weakSelf.shutdownTimeout) milliseconds, forcing stop")
|
|
|
|
weakSelf.flushLog()
|
2018-08-23 08:19:25 +00:00
|
|
|
pendingHandler()
|
2019-07-07 21:34:45 +00:00
|
|
|
self?.forceExitOnMac()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
tunnelQueue.sync {
|
2019-05-19 13:56:44 +00:00
|
|
|
session.shutdown(error: nil)
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-12 14:05:21 +00:00
|
|
|
// MARK: Wake/Sleep (debugging placeholders)
|
|
|
|
|
|
|
|
open override func wake() {
|
|
|
|
log.verbose("Wake signal received")
|
|
|
|
}
|
|
|
|
|
|
|
|
open override func sleep(completionHandler: @escaping () -> Void) {
|
|
|
|
log.verbose("Sleep signal received")
|
|
|
|
completionHandler()
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
// MARK: Connection (tunnel queue)
|
|
|
|
|
2020-04-14 20:53:15 +00:00
|
|
|
private func connectTunnel(upgradedSocket: GenericSocket? = nil) {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.info("Creating link session")
|
|
|
|
|
|
|
|
// reuse upgraded socket
|
|
|
|
if let upgradedSocket = upgradedSocket, !upgradedSocket.isShutdown {
|
|
|
|
log.debug("Socket follows a path upgrade")
|
|
|
|
connectTunnel(via: upgradedSocket)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-03 14:34:57 +00:00
|
|
|
strategy.createSocket(from: self, timeout: dnsTimeout, queue: tunnelQueue) {
|
|
|
|
switch $0 {
|
|
|
|
case .success(let socket):
|
|
|
|
self.connectTunnel(via: socket)
|
|
|
|
|
|
|
|
case .failure(let error):
|
|
|
|
if case .dnsFailure = error {
|
|
|
|
self.tunnelQueue.async {
|
|
|
|
self.strategy.tryNextEndpoint()
|
|
|
|
self.connectTunnel()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
self.disposeTunnel(error: error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func connectTunnel(via socket: GenericSocket) {
|
|
|
|
log.info("Will connect to \(socket)")
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.lastError = nil
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
log.debug("Socket type is \(type(of: socket))")
|
|
|
|
self.socket = socket
|
|
|
|
self.socket?.delegate = self
|
|
|
|
self.socket?.observe(queue: tunnelQueue, activeTimeout: socketTimeout)
|
|
|
|
}
|
|
|
|
|
|
|
|
private func finishTunnelDisconnection(error: Error?) {
|
2020-05-08 22:46:16 +00:00
|
|
|
if let session = session, !(shouldReconnect && session.canRebindLink()) {
|
2019-05-19 13:56:44 +00:00
|
|
|
session.cleanup()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
socket?.delegate = nil
|
|
|
|
socket?.unobserve()
|
|
|
|
socket = nil
|
|
|
|
|
|
|
|
if let error = error {
|
|
|
|
log.error("Tunnel did stop (error: \(error))")
|
2018-10-21 21:30:55 +00:00
|
|
|
setErrorStatus(with: error)
|
2018-08-23 08:19:25 +00:00
|
|
|
} else {
|
|
|
|
log.info("Tunnel did stop on request")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func disposeTunnel(error: Error?) {
|
|
|
|
flushLog()
|
2018-10-21 21:30:55 +00:00
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
// failed to start
|
2019-07-07 21:34:45 +00:00
|
|
|
if pendingStartHandler != nil {
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
//
|
|
|
|
// CAUTION
|
|
|
|
//
|
|
|
|
// passing nil to this callback will result in an extremely undesired situation,
|
|
|
|
// because NetworkExtension would interpret it as "successfully connected to VPN"
|
|
|
|
//
|
|
|
|
// if we end up here disposing the tunnel with a pending start handled, we are
|
|
|
|
// 100% sure that something wrong happened while starting the tunnel. in such
|
|
|
|
// case, here we then must also make sure that an error object is ALWAYS
|
|
|
|
// provided, so we do this with optional fallback to .socketActivity
|
|
|
|
//
|
|
|
|
// socketActivity makes sense, given that any other error would normally come
|
2019-05-19 13:43:56 +00:00
|
|
|
// from OpenVPN.stopError. other paths to disposeTunnel() are only coming
|
2018-08-23 08:19:25 +00:00
|
|
|
// from stopTunnel(), in which case we don't need to feed an error parameter to
|
|
|
|
// the stop completion handler
|
|
|
|
//
|
2021-11-07 20:54:05 +00:00
|
|
|
pendingStartHandler?(error ?? OpenVPNProviderError.socketActivity)
|
2018-08-23 08:19:25 +00:00
|
|
|
pendingStartHandler = nil
|
|
|
|
}
|
|
|
|
// stopped intentionally
|
2019-07-07 21:34:45 +00:00
|
|
|
else if pendingStopHandler != nil {
|
2018-08-23 08:19:25 +00:00
|
|
|
pendingStopHandler?()
|
|
|
|
pendingStopHandler = nil
|
2019-07-07 21:34:45 +00:00
|
|
|
forceExitOnMac()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
// stopped externally, unrecoverable
|
|
|
|
else {
|
|
|
|
cancelTunnelWithError(error)
|
2019-07-07 21:34:45 +00:00
|
|
|
forceExitOnMac()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
2019-03-27 23:04:35 +00:00
|
|
|
|
|
|
|
// MARK: Data counter (tunnel queue)
|
|
|
|
|
|
|
|
private func refreshDataCount() {
|
|
|
|
guard dataCountInterval > 0 else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
tunnelQueue.schedule(after: .milliseconds(dataCountInterval)) { [weak self] in
|
|
|
|
self?.refreshDataCount()
|
|
|
|
}
|
2019-05-19 13:56:44 +00:00
|
|
|
guard isCountingData, let session = session, let dataCount = session.dataCount() else {
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.dataCount = nil
|
2019-03-27 23:04:35 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.dataCount = dataCount
|
2019-03-27 23:04:35 +00:00
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
2019-05-23 19:59:15 +00:00
|
|
|
extension OpenVPNTunnelProvider: GenericSocketDelegate {
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
// MARK: GenericSocketDelegate (tunnel queue)
|
|
|
|
|
2019-05-23 19:49:20 +00:00
|
|
|
public func socketDidTimeout(_ socket: GenericSocket) {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.debug("Socket timed out waiting for activity, cancelling...")
|
2020-05-08 22:46:16 +00:00
|
|
|
shouldReconnect = true
|
2018-08-23 08:19:25 +00:00
|
|
|
socket.shutdown()
|
2018-10-24 07:29:39 +00:00
|
|
|
|
|
|
|
// fallback: TCP connection timeout suggests falling back
|
|
|
|
if let _ = socket as? NETCPSocket {
|
2020-04-14 20:53:15 +00:00
|
|
|
guard tryNextEndpoint() else {
|
2018-10-24 07:29:39 +00:00
|
|
|
// disposeTunnel
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 19:49:20 +00:00
|
|
|
public func socketDidBecomeActive(_ socket: GenericSocket) {
|
2019-05-23 18:15:42 +00:00
|
|
|
guard let session = session, let producer = socket as? LinkProducer else {
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
2019-05-19 13:56:44 +00:00
|
|
|
if session.canRebindLink() {
|
2022-03-04 23:58:07 +00:00
|
|
|
session.rebindLink(producer.link(xorMask: cfg.configuration.xorMask))
|
2020-05-09 12:59:10 +00:00
|
|
|
reasserting = false
|
2018-08-23 08:19:25 +00:00
|
|
|
} else {
|
2022-03-04 23:58:07 +00:00
|
|
|
session.setLink(producer.link(xorMask: cfg.configuration.xorMask))
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 19:49:20 +00:00
|
|
|
public func socket(_ socket: GenericSocket, didShutdownWithFailure failure: Bool) {
|
2019-05-19 13:56:44 +00:00
|
|
|
guard let session = session else {
|
2018-08-23 08:19:25 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var shutdownError: Error?
|
2018-10-24 07:36:34 +00:00
|
|
|
let didTimeoutNegotiation: Bool
|
|
|
|
var upgradedSocket: GenericSocket?
|
|
|
|
|
|
|
|
// look for error causing shutdown
|
2019-05-19 13:56:44 +00:00
|
|
|
shutdownError = session.stopError
|
2018-10-24 07:36:34 +00:00
|
|
|
if failure && (shutdownError == nil) {
|
2021-11-07 20:54:05 +00:00
|
|
|
shutdownError = OpenVPNProviderError.linkError
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2019-05-19 13:43:56 +00:00
|
|
|
didTimeoutNegotiation = (shutdownError as? OpenVPNError == .negotiationTimeout)
|
2018-09-07 20:43:52 +00:00
|
|
|
|
2018-09-07 20:34:04 +00:00
|
|
|
// only try upgrade on network errors
|
2019-05-19 13:43:56 +00:00
|
|
|
if shutdownError as? OpenVPNError == nil {
|
2018-09-07 20:34:04 +00:00
|
|
|
upgradedSocket = socket.upgraded()
|
|
|
|
}
|
2018-09-07 20:43:52 +00:00
|
|
|
|
|
|
|
// clean up
|
|
|
|
finishTunnelDisconnection(error: shutdownError)
|
|
|
|
|
2018-10-24 07:29:39 +00:00
|
|
|
// fallback: UDP is connection-less, treat negotiation timeout as socket timeout
|
2018-09-07 20:43:52 +00:00
|
|
|
if didTimeoutNegotiation {
|
2020-04-14 20:53:15 +00:00
|
|
|
guard tryNextEndpoint() else {
|
2018-09-07 20:43:52 +00:00
|
|
|
// disposeTunnel
|
|
|
|
return
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
2018-09-07 20:43:52 +00:00
|
|
|
// reconnect?
|
2020-05-08 22:46:16 +00:00
|
|
|
if shouldReconnect {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.debug("Disconnection is recoverable, tunnel will reconnect in \(reconnectionDelay) milliseconds...")
|
|
|
|
tunnelQueue.schedule(after: .milliseconds(reconnectionDelay)) {
|
2019-03-08 12:19:26 +00:00
|
|
|
|
2020-05-08 22:46:16 +00:00
|
|
|
// give up if shouldReconnect cleared in the meantime
|
|
|
|
guard self.shouldReconnect else {
|
|
|
|
log.warning("Reconnection flag was cleared in the meantime")
|
2019-03-08 12:19:26 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-05-08 22:46:16 +00:00
|
|
|
log.debug("Tunnel is about to reconnect...")
|
|
|
|
self.reasserting = true
|
2020-04-14 20:53:15 +00:00
|
|
|
self.connectTunnel(upgradedSocket: upgradedSocket)
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2018-09-07 20:43:52 +00:00
|
|
|
|
|
|
|
// shut down
|
2018-08-23 08:19:25 +00:00
|
|
|
disposeTunnel(error: shutdownError)
|
|
|
|
}
|
|
|
|
|
2019-05-23 19:49:20 +00:00
|
|
|
public func socketHasBetterPath(_ socket: GenericSocket) {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.debug("Stopping tunnel due to a new better path")
|
|
|
|
logCurrentSSID()
|
2021-11-07 20:54:05 +00:00
|
|
|
session?.reconnect(error: OpenVPNProviderError.networkChanged)
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 19:59:15 +00:00
|
|
|
extension OpenVPNTunnelProvider: OpenVPNSessionDelegate {
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-05-19 13:43:56 +00:00
|
|
|
// MARK: OpenVPNSessionDelegate (tunnel queue)
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-05-19 13:56:44 +00:00
|
|
|
public func sessionDidStart(_ session: OpenVPNSession, remoteAddress: String, options: OpenVPN.Configuration) {
|
2018-08-23 08:19:25 +00:00
|
|
|
log.info("Session did start")
|
|
|
|
|
|
|
|
log.info("Returned ifconfig parameters:")
|
2018-10-24 16:06:39 +00:00
|
|
|
log.info("\tRemote: \(remoteAddress.maskedDescription)")
|
2019-05-19 13:43:56 +00:00
|
|
|
log.info("\tIPv4: \(options.ipv4?.description ?? "not configured")")
|
|
|
|
log.info("\tIPv6: \(options.ipv6?.description ?? "not configured")")
|
|
|
|
if let routingPolicies = options.routingPolicies {
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("\tGateway: \(routingPolicies.map { $0.rawValue })")
|
2019-04-27 12:06:30 +00:00
|
|
|
} else {
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("\tGateway: not configured")
|
2019-04-27 12:06:30 +00:00
|
|
|
}
|
2019-05-19 13:43:56 +00:00
|
|
|
if let dnsServers = options.dnsServers, !dnsServers.isEmpty {
|
2019-04-04 10:40:28 +00:00
|
|
|
log.info("\tDNS: \(dnsServers.map { $0.maskedDescription })")
|
|
|
|
} else {
|
2019-04-18 10:02:23 +00:00
|
|
|
log.info("\tDNS: not configured")
|
2019-04-04 10:40:28 +00:00
|
|
|
}
|
2019-10-25 15:14:59 +00:00
|
|
|
if let searchDomains = options.searchDomains, !searchDomains.isEmpty {
|
|
|
|
log.info("\tSearch domains: \(searchDomains.maskedDescription)")
|
2019-05-09 09:19:53 +00:00
|
|
|
} else {
|
2019-10-25 15:14:59 +00:00
|
|
|
log.info("\tSearch domains: not configured")
|
2019-05-09 09:19:53 +00:00
|
|
|
}
|
2019-04-13 17:03:27 +00:00
|
|
|
|
2019-10-22 23:08:39 +00:00
|
|
|
if options.httpProxy != nil || options.httpsProxy != nil || options.proxyAutoConfigurationURL != nil {
|
2019-04-13 17:03:27 +00:00
|
|
|
log.info("\tProxy:")
|
2019-05-19 13:43:56 +00:00
|
|
|
if let proxy = options.httpProxy {
|
2019-04-13 17:03:27 +00:00
|
|
|
log.info("\t\tHTTP: \(proxy.maskedDescription)")
|
|
|
|
}
|
2019-05-19 13:43:56 +00:00
|
|
|
if let proxy = options.httpsProxy {
|
2019-04-13 17:03:27 +00:00
|
|
|
log.info("\t\tHTTPS: \(proxy.maskedDescription)")
|
|
|
|
}
|
2019-10-22 19:03:25 +00:00
|
|
|
if let pacURL = options.proxyAutoConfigurationURL {
|
2019-10-21 19:47:45 +00:00
|
|
|
log.info("\t\tPAC: \(pacURL)")
|
|
|
|
}
|
2019-05-19 13:43:56 +00:00
|
|
|
if let bypass = options.proxyBypassDomains {
|
2019-04-13 17:03:27 +00:00
|
|
|
log.info("\t\tBypass domains: \(bypass.maskedDescription)")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.serverConfiguration = session.serverConfiguration() as? OpenVPN.Configuration
|
|
|
|
|
2019-05-19 13:56:44 +00:00
|
|
|
bringNetworkUp(remoteAddress: remoteAddress, localOptions: session.configuration, options: options) { (error) in
|
2019-12-02 09:17:51 +00:00
|
|
|
|
|
|
|
// FIXME: XPC queue
|
|
|
|
|
2019-10-17 12:23:16 +00:00
|
|
|
self.reasserting = false
|
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
if let error = error {
|
|
|
|
log.error("Failed to configure tunnel: \(error)")
|
|
|
|
self.pendingStartHandler?(error)
|
|
|
|
self.pendingStartHandler = nil
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.info("Tunnel interface is now UP")
|
|
|
|
|
2020-05-05 12:01:27 +00:00
|
|
|
session.setTunnel(tunnel: NETunnelInterface(impl: self.packetFlow))
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
self.pendingStartHandler?(nil)
|
|
|
|
self.pendingStartHandler = nil
|
|
|
|
}
|
2019-03-27 23:04:35 +00:00
|
|
|
|
|
|
|
isCountingData = true
|
2019-03-30 22:35:50 +00:00
|
|
|
refreshDataCount()
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
2020-05-08 19:13:57 +00:00
|
|
|
public func sessionDidStop(_: OpenVPNSession, withError error: Error?, shouldReconnect: Bool) {
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.serverConfiguration = nil
|
|
|
|
|
2020-05-08 19:13:57 +00:00
|
|
|
if let error = error {
|
|
|
|
log.error("Session did stop with error: \(error)")
|
|
|
|
} else {
|
|
|
|
log.info("Session did stop")
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2019-03-27 23:04:35 +00:00
|
|
|
isCountingData = false
|
|
|
|
refreshDataCount()
|
|
|
|
|
2020-05-08 22:46:16 +00:00
|
|
|
self.shouldReconnect = shouldReconnect
|
2018-08-23 08:19:25 +00:00
|
|
|
socket?.shutdown()
|
|
|
|
}
|
|
|
|
|
2019-05-19 13:43:56 +00:00
|
|
|
private func bringNetworkUp(remoteAddress: String, localOptions: OpenVPN.Configuration, options: OpenVPN.Configuration, completionHandler: @escaping (Error?) -> Void) {
|
|
|
|
let routingPolicies = localOptions.routingPolicies ?? options.routingPolicies
|
2019-04-27 20:34:13 +00:00
|
|
|
let isIPv4Gateway = routingPolicies?.contains(.IPv4) ?? false
|
|
|
|
let isIPv6Gateway = routingPolicies?.contains(.IPv6) ?? false
|
2019-04-27 21:08:39 +00:00
|
|
|
let isGateway = isIPv4Gateway || isIPv6Gateway
|
2019-04-27 20:34:13 +00:00
|
|
|
|
2018-08-24 13:27:20 +00:00
|
|
|
var ipv4Settings: NEIPv4Settings?
|
2019-05-19 13:43:56 +00:00
|
|
|
if let ipv4 = options.ipv4 {
|
2019-04-25 11:57:41 +00:00
|
|
|
var routes: [NEIPv4Route] = []
|
|
|
|
|
|
|
|
// route all traffic to VPN?
|
2019-04-27 20:34:13 +00:00
|
|
|
if isIPv4Gateway {
|
|
|
|
let defaultRoute = NEIPv4Route.default()
|
|
|
|
defaultRoute.gatewayAddress = ipv4.defaultGateway
|
|
|
|
routes.append(defaultRoute)
|
|
|
|
// for network in ["0.0.0.0", "128.0.0.0"] {
|
|
|
|
// let route = NEIPv4Route(destinationAddress: network, subnetMask: "128.0.0.0")
|
|
|
|
// route.gatewayAddress = ipv4.defaultGateway
|
|
|
|
// routes.append(route)
|
|
|
|
// }
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing.IPv4: Setting default gateway to \(ipv4.defaultGateway.maskedDescription)")
|
2019-04-25 11:57:41 +00:00
|
|
|
}
|
2018-08-24 13:27:20 +00:00
|
|
|
|
|
|
|
for r in ipv4.routes {
|
|
|
|
let ipv4Route = NEIPv4Route(destinationAddress: r.destination, subnetMask: r.mask)
|
2019-04-04 10:40:28 +00:00
|
|
|
ipv4Route.gatewayAddress = r.gateway
|
2018-08-24 13:27:20 +00:00
|
|
|
routes.append(ipv4Route)
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing.IPv4: Adding route \(r.destination.maskedDescription)/\(r.mask) -> \(r.gateway)")
|
2018-08-24 13:27:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ipv4Settings = NEIPv4Settings(addresses: [ipv4.address], subnetMasks: [ipv4.addressMask])
|
|
|
|
ipv4Settings?.includedRoutes = routes
|
|
|
|
ipv4Settings?.excludedRoutes = []
|
|
|
|
}
|
|
|
|
|
|
|
|
var ipv6Settings: NEIPv6Settings?
|
2019-05-19 13:43:56 +00:00
|
|
|
if let ipv6 = options.ipv6 {
|
2019-04-25 11:57:41 +00:00
|
|
|
var routes: [NEIPv6Route] = []
|
|
|
|
|
|
|
|
// route all traffic to VPN?
|
2019-04-27 20:34:13 +00:00
|
|
|
if isIPv6Gateway {
|
|
|
|
let defaultRoute = NEIPv6Route.default()
|
|
|
|
defaultRoute.gatewayAddress = ipv6.defaultGateway
|
|
|
|
routes.append(defaultRoute)
|
|
|
|
// for network in ["2000::", "3000::"] {
|
|
|
|
// let route = NEIPv6Route(destinationAddress: network, networkPrefixLength: 4)
|
|
|
|
// route.gatewayAddress = ipv6.defaultGateway
|
|
|
|
// routes.append(route)
|
|
|
|
// }
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing.IPv6: Setting default gateway to \(ipv6.defaultGateway.maskedDescription)")
|
2019-04-25 11:57:41 +00:00
|
|
|
}
|
2018-08-24 13:27:20 +00:00
|
|
|
|
|
|
|
for r in ipv6.routes {
|
|
|
|
let ipv6Route = NEIPv6Route(destinationAddress: r.destination, networkPrefixLength: r.prefixLength as NSNumber)
|
2019-04-04 10:40:28 +00:00
|
|
|
ipv6Route.gatewayAddress = r.gateway
|
2018-08-24 13:27:20 +00:00
|
|
|
routes.append(ipv6Route)
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing.IPv6: Adding route \(r.destination.maskedDescription)/\(r.prefixLength) -> \(r.gateway)")
|
2018-08-24 13:27:20 +00:00
|
|
|
}
|
2018-09-15 17:42:43 +00:00
|
|
|
|
2018-08-24 13:27:20 +00:00
|
|
|
ipv6Settings = NEIPv6Settings(addresses: [ipv6.address], networkPrefixLengths: [ipv6.addressPrefixLength as NSNumber])
|
2019-04-25 11:57:41 +00:00
|
|
|
ipv6Settings?.includedRoutes = routes
|
2018-08-24 13:27:20 +00:00
|
|
|
ipv6Settings?.excludedRoutes = []
|
2018-08-24 09:45:41 +00:00
|
|
|
}
|
2019-04-05 10:58:05 +00:00
|
|
|
|
2019-05-11 14:33:08 +00:00
|
|
|
// shut down if default gateway is not attainable
|
|
|
|
var hasGateway = false
|
|
|
|
if isIPv4Gateway && (ipv4Settings != nil) {
|
|
|
|
hasGateway = true
|
|
|
|
}
|
|
|
|
if isIPv6Gateway && (ipv6Settings != nil) {
|
|
|
|
hasGateway = true
|
|
|
|
}
|
|
|
|
guard !isGateway || hasGateway else {
|
2021-11-07 20:54:05 +00:00
|
|
|
session?.shutdown(error: OpenVPNProviderError.gatewayUnattainable)
|
2019-05-11 14:33:08 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-01-26 10:12:16 +00:00
|
|
|
var dnsServers: [String] = []
|
2021-01-26 09:03:22 +00:00
|
|
|
var dnsSettings: NEDNSSettings?
|
2021-01-22 09:29:03 +00:00
|
|
|
if #available(iOS 14, macOS 11, *) {
|
2022-03-04 23:58:07 +00:00
|
|
|
switch cfg.configuration.dnsProtocol {
|
2021-01-22 09:29:03 +00:00
|
|
|
case .https:
|
2022-03-04 23:58:07 +00:00
|
|
|
dnsServers = cfg.configuration.dnsServers ?? []
|
|
|
|
guard let serverURL = cfg.configuration.dnsHTTPSURL else {
|
2021-01-22 09:29:03 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
let specific = NEDNSOverHTTPSSettings(servers: dnsServers)
|
|
|
|
specific.serverURL = serverURL
|
|
|
|
dnsSettings = specific
|
2021-01-26 10:12:16 +00:00
|
|
|
log.info("DNS over HTTPS: Using servers \(dnsServers.maskedDescription)")
|
|
|
|
log.info("\tHTTPS URL: \(serverURL.maskedDescription)")
|
2021-01-26 09:03:22 +00:00
|
|
|
|
2021-01-22 09:29:03 +00:00
|
|
|
case .tls:
|
2022-03-04 23:58:07 +00:00
|
|
|
guard let dnsServers = cfg.configuration.dnsServers else {
|
2021-11-07 20:54:05 +00:00
|
|
|
session?.shutdown(error: OpenVPNProviderError.dnsFailure)
|
2021-01-26 10:12:16 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
guard let serverName = cfg.configuration.dnsTLSServerName else {
|
2021-01-22 09:29:03 +00:00
|
|
|
break
|
|
|
|
}
|
|
|
|
let specific = NEDNSOverTLSSettings(servers: dnsServers)
|
|
|
|
specific.serverName = serverName
|
|
|
|
dnsSettings = specific
|
2021-01-26 10:12:16 +00:00
|
|
|
log.info("DNS over TLS: Using servers \(dnsServers.maskedDescription)")
|
|
|
|
log.info("\tTLS server name: \(serverName.maskedDescription)")
|
2021-01-22 09:29:03 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-26 09:03:22 +00:00
|
|
|
// fall back
|
2021-01-26 09:59:37 +00:00
|
|
|
if dnsSettings == nil {
|
2021-01-26 15:31:57 +00:00
|
|
|
dnsServers = []
|
2022-03-04 23:58:07 +00:00
|
|
|
if let servers = cfg.configuration.dnsServers,
|
2021-01-26 15:31:57 +00:00
|
|
|
!servers.isEmpty {
|
|
|
|
dnsServers = servers
|
|
|
|
} else if let servers = options.dnsServers {
|
|
|
|
dnsServers = servers
|
|
|
|
}
|
2021-01-26 09:59:37 +00:00
|
|
|
if !dnsServers.isEmpty {
|
|
|
|
log.info("DNS: Using servers \(dnsServers.maskedDescription)")
|
|
|
|
dnsSettings = NEDNSSettings(servers: dnsServers)
|
|
|
|
} else {
|
|
|
|
// log.warning("DNS: No servers provided, using fall-back servers: \(fallbackDNSServers.maskedDescription)")
|
|
|
|
// dnsSettings = NEDNSSettings(servers: fallbackDNSServers)
|
|
|
|
log.warning("DNS: No settings provided, using current network settings")
|
|
|
|
}
|
2021-01-26 09:03:22 +00:00
|
|
|
}
|
|
|
|
|
2021-01-22 09:29:03 +00:00
|
|
|
// "hack" for split DNS (i.e. use VPN only for DNS)
|
2019-04-27 21:08:39 +00:00
|
|
|
if !isGateway {
|
2021-01-26 09:03:22 +00:00
|
|
|
dnsSettings?.matchDomains = [""]
|
2019-04-27 21:08:39 +00:00
|
|
|
}
|
2021-01-22 09:29:03 +00:00
|
|
|
|
2022-03-04 23:58:07 +00:00
|
|
|
if let searchDomains = cfg.configuration.searchDomains ?? options.searchDomains {
|
2019-10-25 17:08:34 +00:00
|
|
|
log.info("DNS: Using search domains \(searchDomains.maskedDescription)")
|
2021-01-26 09:03:22 +00:00
|
|
|
dnsSettings?.domainName = searchDomains.first
|
|
|
|
dnsSettings?.searchDomains = searchDomains
|
2019-04-27 21:08:39 +00:00
|
|
|
if !isGateway {
|
2021-01-26 09:03:22 +00:00
|
|
|
dnsSettings?.matchDomains = dnsSettings?.searchDomains
|
2019-04-27 21:08:39 +00:00
|
|
|
}
|
2019-04-03 10:50:43 +00:00
|
|
|
}
|
2019-04-12 06:14:18 +00:00
|
|
|
|
2019-04-28 13:43:23 +00:00
|
|
|
// add direct routes to DNS servers
|
|
|
|
if !isGateway {
|
|
|
|
for server in dnsServers {
|
|
|
|
if server.contains(":") {
|
|
|
|
ipv6Settings?.includedRoutes?.insert(NEIPv6Route(destinationAddress: server, networkPrefixLength: 128), at: 0)
|
|
|
|
} else {
|
|
|
|
ipv4Settings?.includedRoutes?.insert(NEIPv4Route(destinationAddress: server, subnetMask: "255.255.255.255"), at: 0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-12 06:14:18 +00:00
|
|
|
var proxySettings: NEProxySettings?
|
2022-03-04 23:58:07 +00:00
|
|
|
if let httpsProxy = cfg.configuration.httpsProxy ?? options.httpsProxy {
|
2019-04-12 06:14:18 +00:00
|
|
|
proxySettings = NEProxySettings()
|
2019-10-22 19:03:25 +00:00
|
|
|
proxySettings?.httpsServer = httpsProxy.neProxy()
|
|
|
|
proxySettings?.httpsEnabled = true
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing: Setting HTTPS proxy \(httpsProxy.address.maskedDescription):\(httpsProxy.port)")
|
2019-04-13 15:55:08 +00:00
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
if let httpProxy = cfg.configuration.httpProxy ?? options.httpProxy {
|
2019-04-13 15:55:08 +00:00
|
|
|
if proxySettings == nil {
|
|
|
|
proxySettings = NEProxySettings()
|
|
|
|
}
|
2019-10-22 19:03:25 +00:00
|
|
|
proxySettings?.httpServer = httpProxy.neProxy()
|
|
|
|
proxySettings?.httpEnabled = true
|
2019-05-09 09:19:53 +00:00
|
|
|
log.info("Routing: Setting HTTP proxy \(httpProxy.address.maskedDescription):\(httpProxy.port)")
|
2019-04-12 06:14:18 +00:00
|
|
|
}
|
2022-03-04 23:58:07 +00:00
|
|
|
if let pacURL = cfg.configuration.proxyAutoConfigurationURL ?? options.proxyAutoConfigurationURL {
|
2019-10-21 19:47:45 +00:00
|
|
|
if proxySettings == nil {
|
|
|
|
proxySettings = NEProxySettings()
|
|
|
|
}
|
2019-10-22 19:03:25 +00:00
|
|
|
proxySettings?.proxyAutoConfigurationURL = pacURL
|
|
|
|
proxySettings?.autoProxyConfigurationEnabled = true
|
2022-03-07 22:50:38 +00:00
|
|
|
log.info("Routing: Setting PAC \(pacURL.maskedDescription)")
|
2019-10-21 19:47:45 +00:00
|
|
|
}
|
2019-05-09 09:19:53 +00:00
|
|
|
|
2019-04-13 17:03:27 +00:00
|
|
|
// only set if there is a proxy (proxySettings set to non-nil above)
|
2022-03-04 23:58:07 +00:00
|
|
|
if let bypass = cfg.configuration.proxyBypassDomains ?? options.proxyBypassDomains {
|
2019-05-09 09:19:53 +00:00
|
|
|
proxySettings?.exceptionList = bypass
|
|
|
|
log.info("Routing: Setting proxy by-pass list: \(bypass.maskedDescription)")
|
|
|
|
}
|
|
|
|
|
2019-05-01 15:15:41 +00:00
|
|
|
// block LAN if desired
|
|
|
|
if routingPolicies?.contains(.blockLocal) ?? false {
|
|
|
|
let table = RoutingTable()
|
|
|
|
if isIPv4Gateway,
|
|
|
|
let gateway = table.defaultGateway4()?.gateway(),
|
|
|
|
let route = table.broadestRoute4(matchingDestination: gateway) {
|
|
|
|
|
2020-05-23 15:07:59 +00:00
|
|
|
route.partitioned()?.forEach {
|
2019-05-01 15:15:41 +00:00
|
|
|
let destination = $0.network()
|
|
|
|
guard let netmask = $0.networkMask() else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.info("Block local: Suppressing IPv4 route \(destination)/\($0.prefix())")
|
|
|
|
|
|
|
|
let included = NEIPv4Route(destinationAddress: destination, subnetMask: netmask)
|
2019-05-19 13:43:56 +00:00
|
|
|
included.gatewayAddress = options.ipv4?.defaultGateway
|
2019-05-01 15:15:41 +00:00
|
|
|
ipv4Settings?.includedRoutes?.append(included)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if isIPv6Gateway,
|
|
|
|
let gateway = table.defaultGateway6()?.gateway(),
|
|
|
|
let route = table.broadestRoute6(matchingDestination: gateway) {
|
|
|
|
|
2020-05-23 15:07:59 +00:00
|
|
|
route.partitioned()?.forEach {
|
2019-05-01 15:15:41 +00:00
|
|
|
let destination = $0.network()
|
|
|
|
let prefix = $0.prefix()
|
|
|
|
|
|
|
|
log.info("Block local: Suppressing IPv6 route \(destination)/\($0.prefix())")
|
|
|
|
|
|
|
|
let included = NEIPv6Route(destinationAddress: destination, networkPrefixLength: prefix as NSNumber)
|
2019-05-19 13:43:56 +00:00
|
|
|
included.gatewayAddress = options.ipv6?.defaultGateway
|
2019-05-01 15:15:41 +00:00
|
|
|
ipv6Settings?.includedRoutes?.append(included)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-24 09:57:09 +00:00
|
|
|
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress)
|
2018-09-15 17:42:43 +00:00
|
|
|
newSettings.ipv4Settings = ipv4Settings
|
|
|
|
newSettings.ipv6Settings = ipv6Settings
|
2018-08-23 08:19:25 +00:00
|
|
|
newSettings.dnsSettings = dnsSettings
|
2019-04-12 06:14:18 +00:00
|
|
|
newSettings.proxySettings = proxySettings
|
2022-03-04 23:58:07 +00:00
|
|
|
if let mtu = cfg.configuration.mtu {
|
2020-12-28 11:45:00 +00:00
|
|
|
newSettings.mtu = NSNumber(value: mtu)
|
|
|
|
}
|
2020-01-13 18:56:09 +00:00
|
|
|
|
2018-08-23 08:19:25 +00:00
|
|
|
setTunnelNetworkSettings(newSettings, completionHandler: completionHandler)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-23 19:59:15 +00:00
|
|
|
extension OpenVPNTunnelProvider {
|
2020-04-14 20:53:15 +00:00
|
|
|
private func tryNextEndpoint() -> Bool {
|
|
|
|
guard strategy.tryNextEndpoint() else {
|
2022-03-03 14:34:57 +00:00
|
|
|
disposeTunnel(error: OpenVPNProviderError.exhaustedEndpoints)
|
2018-10-24 07:29:39 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
|
2018-10-23 21:14:13 +00:00
|
|
|
// MARK: Logging
|
2018-08-23 08:19:25 +00:00
|
|
|
|
|
|
|
private func configureLogging(debug: Bool, customFormat: String? = nil) {
|
2019-12-12 08:42:48 +00:00
|
|
|
let logLevel: SwiftyBeaver.Level = (debug ? debugLogLevel : .info)
|
2018-08-23 08:19:25 +00:00
|
|
|
let logFormat = customFormat ?? "$Dyyyy-MM-dd HH:mm:ss.SSS$d $L $N.$F:$l - $M"
|
|
|
|
|
|
|
|
if debug {
|
|
|
|
let console = ConsoleDestination()
|
|
|
|
console.useNSLog = true
|
|
|
|
console.minLevel = logLevel
|
|
|
|
console.format = logFormat
|
|
|
|
log.addDestination(console)
|
|
|
|
}
|
2022-03-12 07:16:25 +00:00
|
|
|
|
|
|
|
let file = FileDestination(logFileURL: cfg.urlForDebugLog)
|
|
|
|
file.minLevel = logLevel
|
|
|
|
file.format = logFormat
|
|
|
|
file.logFileMaxSize = maxLogSize
|
|
|
|
log.addDestination(file)
|
|
|
|
|
|
|
|
logFile = file
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private func flushLog() {
|
|
|
|
log.debug("Flushing log...")
|
2022-03-12 07:16:25 +00:00
|
|
|
|
|
|
|
// XXX: should enforce SwiftyBeaver flush?
|
|
|
|
// if let url = cfg.urlForDebugLog {
|
|
|
|
// memoryLog.flush(to: url)
|
|
|
|
// }
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2020-11-21 17:40:47 +00:00
|
|
|
|
2018-10-23 21:14:13 +00:00
|
|
|
private func logCurrentSSID() {
|
2020-11-21 17:40:47 +00:00
|
|
|
InterfaceObserver.fetchCurrentSSID {
|
|
|
|
if let ssid = $0 {
|
|
|
|
log.debug("Current SSID: '\(ssid.maskedDescription)'")
|
|
|
|
} else {
|
|
|
|
log.debug("Current SSID: none (disconnected from WiFi)")
|
|
|
|
}
|
2018-10-23 21:14:13 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-21 17:40:47 +00:00
|
|
|
|
2018-10-23 21:14:13 +00:00
|
|
|
// private func anyPointer(_ object: Any?) -> UnsafeMutableRawPointer {
|
|
|
|
// let anyObject = object as AnyObject
|
|
|
|
// return Unmanaged<AnyObject>.passUnretained(anyObject).toOpaque()
|
|
|
|
// }
|
|
|
|
|
|
|
|
// MARK: Errors
|
|
|
|
|
2018-10-21 21:30:55 +00:00
|
|
|
private func setErrorStatus(with error: Error) {
|
2022-03-04 23:58:07 +00:00
|
|
|
cfg.lastError = unifiedError(from: error)
|
2018-10-21 21:30:55 +00:00
|
|
|
}
|
2018-10-23 21:14:13 +00:00
|
|
|
|
2021-11-07 20:54:05 +00:00
|
|
|
private func unifiedError(from error: Error) -> OpenVPNProviderError {
|
2021-11-23 17:32:59 +00:00
|
|
|
if let te = error.openVPNErrorCode() {
|
2018-10-23 21:14:13 +00:00
|
|
|
switch te {
|
2019-05-19 10:03:46 +00:00
|
|
|
case .cryptoRandomGenerator, .cryptoAlgorithm:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .encryptionInitialization
|
|
|
|
|
2019-05-19 10:03:46 +00:00
|
|
|
case .cryptoEncryption, .cryptoHMAC:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .encryptionData
|
|
|
|
|
2021-11-25 11:36:17 +00:00
|
|
|
case .tlscaRead, .tlscaUse, .tlscaPeerVerification,
|
|
|
|
.tlsClientCertificateRead, .tlsClientCertificateUse,
|
|
|
|
.tlsClientKeyRead, .tlsClientKeyUse:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .tlsInitialization
|
|
|
|
|
2020-05-08 22:02:16 +00:00
|
|
|
case .tlsServerCertificate, .tlsServerEKU, .tlsServerHost:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .tlsServerVerification
|
|
|
|
|
2019-05-19 10:03:46 +00:00
|
|
|
case .tlsHandshake:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .tlsHandshake
|
|
|
|
|
|
|
|
case .dataPathOverflow, .dataPathPeerIdMismatch:
|
|
|
|
return .unexpectedReply
|
2019-02-28 16:10:50 +00:00
|
|
|
|
|
|
|
case .dataPathCompression:
|
|
|
|
return .serverCompression
|
2019-03-18 22:33:36 +00:00
|
|
|
|
2019-03-30 19:23:09 +00:00
|
|
|
default:
|
|
|
|
break
|
2018-10-23 21:14:13 +00:00
|
|
|
}
|
2019-05-19 13:43:56 +00:00
|
|
|
} else if let se = error as? OpenVPNError {
|
2018-10-23 21:14:13 +00:00
|
|
|
switch se {
|
2018-10-24 09:02:08 +00:00
|
|
|
case .negotiationTimeout, .pingTimeout, .staleSession:
|
2018-10-23 21:14:13 +00:00
|
|
|
return .timeout
|
|
|
|
|
|
|
|
case .badCredentials:
|
|
|
|
return .authentication
|
|
|
|
|
2019-02-25 22:07:17 +00:00
|
|
|
case .serverCompression:
|
|
|
|
return .serverCompression
|
|
|
|
|
2018-10-23 21:14:13 +00:00
|
|
|
case .failedLinkWrite:
|
|
|
|
return .linkError
|
2019-04-19 07:44:54 +00:00
|
|
|
|
|
|
|
case .noRouting:
|
|
|
|
return .routing
|
2020-02-29 18:17:36 +00:00
|
|
|
|
|
|
|
case .serverShutdown:
|
|
|
|
return .serverShutdown
|
2018-10-21 21:30:55 +00:00
|
|
|
|
2018-10-23 21:14:13 +00:00
|
|
|
default:
|
|
|
|
return .unexpectedReply
|
|
|
|
}
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
2021-11-07 20:54:05 +00:00
|
|
|
return error as? OpenVPNProviderError ?? .linkError
|
2018-08-23 08:19:25 +00:00
|
|
|
}
|
|
|
|
}
|
2019-04-12 06:14:18 +00:00
|
|
|
|
|
|
|
private extension Proxy {
|
|
|
|
func neProxy() -> NEProxyServer {
|
|
|
|
return NEProxyServer(address: address, port: Int(port))
|
|
|
|
}
|
|
|
|
}
|
2019-07-07 21:34:45 +00:00
|
|
|
|
|
|
|
private extension NEPacketTunnelProvider {
|
|
|
|
func forceExitOnMac() {
|
|
|
|
#if os(macOS)
|
|
|
|
exit(0)
|
|
|
|
#endif
|
|
|
|
}
|
|
|
|
}
|