Merge pull request #82 from keeshux/reuse-options-parser

Reuse options parser
This commit is contained in:
Davide De Rosa 2019-04-03 14:12:08 +02:00 committed by GitHub
commit 5b618e1e7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 1139 additions and 995 deletions

View File

@ -22,6 +22,8 @@ custom_categories:
- StaticKey
- SessionProxy
- SessionProxyDelegate
- OptionsBundle
- OptionsError
- SessionReply
- IPv4Settings
- IPv6Settings

View File

@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
### Changed
- Refactor options parser into `OptionsBundle` for reuse.
- Group `SessionReply.*` fields into `SessionReply.options`.
- Rename `ConfigurationParser.ParsingError` to `OptionsError`.
### Fixed
- Unrecognized PKCS#8 encrypted private keys. [#80](https://github.com/keeshux/tunnelkit/issues/80)

View File

@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "TunnelKit"
s.version = "1.5.3"
s.version = "1.6.0"
s.summary = "Non-official OpenVPN client for Apple platforms."
s.homepage = "https://github.com/keeshux/tunnelkit"

View File

@ -65,8 +65,8 @@
0E3B65752249253B00EFF4DA /* tunnelbear.enc.1.ovpn in Resources */ = {isa = PBXBuildFile; fileRef = 0E3B656E224923EC00EFF4DA /* tunnelbear.enc.1.ovpn */; };
0E3B65762249253F00EFF4DA /* tunnelbear.key in Resources */ = {isa = PBXBuildFile; fileRef = 0E3B65712249247E00EFF4DA /* tunnelbear.key */; };
0E3B65772249254000EFF4DA /* tunnelbear.key in Resources */ = {isa = PBXBuildFile; fileRef = 0E3B65712249247E00EFF4DA /* tunnelbear.key */; };
0E3E0F212108A8CC00B371C1 /* SessionProxy+PushReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E3E0F202108A8CC00B371C1 /* SessionProxy+PushReply.swift */; };
0E3E0F222108A8CC00B371C1 /* SessionProxy+PushReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E3E0F202108A8CC00B371C1 /* SessionProxy+PushReply.swift */; };
0E3E0F212108A8CC00B371C1 /* SessionProxy+SessionReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E3E0F202108A8CC00B371C1 /* SessionProxy+SessionReply.swift */; };
0E3E0F222108A8CC00B371C1 /* SessionProxy+SessionReply.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E3E0F202108A8CC00B371C1 /* SessionProxy+SessionReply.swift */; };
0E500EA622493B5B00CAE560 /* tunnelbear.enc.1.key in Resources */ = {isa = PBXBuildFile; fileRef = 0E500EA522493B5B00CAE560 /* tunnelbear.enc.1.key */; };
0E500EA722493B5B00CAE560 /* tunnelbear.enc.1.key in Resources */ = {isa = PBXBuildFile; fileRef = 0E500EA522493B5B00CAE560 /* tunnelbear.enc.1.key */; };
0E50D57521634E0A00FC87A8 /* ControlChannelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E50D57421634E0A00FC87A8 /* ControlChannelTests.swift */; };
@ -137,6 +137,12 @@
0EC1BBA620D712DE007C4C7B /* DNSResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EC1BBA420D71190007C4C7B /* DNSResolver.swift */; };
0EC1BBA820D7D803007C4C7B /* ConnectionStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EC1BBA720D7D803007C4C7B /* ConnectionStrategy.swift */; };
0EC1BBA920D7D803007C4C7B /* ConnectionStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EC1BBA720D7D803007C4C7B /* ConnectionStrategy.swift */; };
0ECC60D5225497400020BEAC /* OptionsBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60D4225497400020BEAC /* OptionsBundle.swift */; };
0ECC60D6225497400020BEAC /* OptionsBundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60D4225497400020BEAC /* OptionsBundle.swift */; };
0ECC60D82254981A0020BEAC /* OptionsError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60D72254981A0020BEAC /* OptionsError.swift */; };
0ECC60D92254981A0020BEAC /* OptionsError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60D72254981A0020BEAC /* OptionsError.swift */; };
0ECC60DB2254C8190020BEAC /* OptionsBundleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60DA2254C8190020BEAC /* OptionsBundleTests.swift */; };
0ECC60DC2254C8190020BEAC /* OptionsBundleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECC60DA2254C8190020BEAC /* OptionsBundleTests.swift */; };
0ECE3528212EB7770040F253 /* CryptoContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECE3527212EB7770040F253 /* CryptoContainer.swift */; };
0ECE352A212EB88E0040F253 /* CryptoContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ECE3527212EB7770040F253 /* CryptoContainer.swift */; };
0ECEB1152252C8E900E9E551 /* tunnelbear.enc.8.ovpn in Resources */ = {isa = PBXBuildFile; fileRef = 0ECEB1132252C8E900E9E551 /* tunnelbear.enc.8.ovpn */; };
@ -304,7 +310,7 @@
0E3B15C62152B05E00984B17 /* CryptoCTR.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CryptoCTR.m; sourceTree = "<group>"; };
0E3B656E224923EC00EFF4DA /* tunnelbear.enc.1.ovpn */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = tunnelbear.enc.1.ovpn; sourceTree = "<group>"; };
0E3B65712249247E00EFF4DA /* tunnelbear.key */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = tunnelbear.key; sourceTree = "<group>"; };
0E3E0F202108A8CC00B371C1 /* SessionProxy+PushReply.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionProxy+PushReply.swift"; sourceTree = "<group>"; };
0E3E0F202108A8CC00B371C1 /* SessionProxy+SessionReply.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SessionProxy+SessionReply.swift"; sourceTree = "<group>"; };
0E500EA522493B5B00CAE560 /* tunnelbear.enc.1.key */ = {isa = PBXFileReference; lastKnownFileType = text; path = tunnelbear.enc.1.key; sourceTree = "<group>"; };
0E50D57421634E0A00FC87A8 /* ControlChannelTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ControlChannelTests.swift; sourceTree = "<group>"; };
0E58BF2F22405410006FB157 /* lzoconf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lzoconf.h; sourceTree = "<group>"; };
@ -342,6 +348,9 @@
0EBBF2FF2085196000E36B40 /* NWTCPConnectionState+Description.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NWTCPConnectionState+Description.swift"; sourceTree = "<group>"; };
0EC1BBA420D71190007C4C7B /* DNSResolver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DNSResolver.swift; sourceTree = "<group>"; };
0EC1BBA720D7D803007C4C7B /* ConnectionStrategy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionStrategy.swift; sourceTree = "<group>"; };
0ECC60D4225497400020BEAC /* OptionsBundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OptionsBundle.swift; sourceTree = "<group>"; };
0ECC60D72254981A0020BEAC /* OptionsError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OptionsError.swift; sourceTree = "<group>"; };
0ECC60DA2254C8190020BEAC /* OptionsBundleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OptionsBundleTests.swift; sourceTree = "<group>"; };
0ECE3527212EB7770040F253 /* CryptoContainer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CryptoContainer.swift; sourceTree = "<group>"; };
0ECEB1132252C8E900E9E551 /* tunnelbear.enc.8.ovpn */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = tunnelbear.enc.8.ovpn; sourceTree = "<group>"; };
0ECEB1142252C8E900E9E551 /* tunnelbear.enc.8.key */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = tunnelbear.enc.8.key; sourceTree = "<group>"; };
@ -464,6 +473,7 @@
0EB2B45E20F0C098004233D7 /* EncryptionPerformanceTests.swift */,
0EB2B45220F0BB44004233D7 /* EncryptionTests.swift */,
0EB2B45820F0BD9A004233D7 /* LinkTests.swift */,
0ECC60DA2254C8190020BEAC /* OptionsBundleTests.swift */,
0E12B2A22145341B00B4BAE9 /* PacketTests.swift */,
0E245D682135972800B012A2 /* PushTests.swift */,
0EB2B45620F0BD16004233D7 /* RandomTests.swift */,
@ -646,6 +656,8 @@
0EFEB42D2006D3C800F81029 /* MSS.h */,
0EFEB43D2006D3C800F81029 /* MSS.m */,
0E12B29D21449ADB00B4BAE9 /* NSRegularExpression+Shortcuts.swift */,
0ECC60D4225497400020BEAC /* OptionsBundle.swift */,
0ECC60D72254981A0020BEAC /* OptionsError.swift */,
0EFEB43E2006D3C800F81029 /* Packet.swift */,
0EE7A79420F61EDC00B42E6A /* PacketMacros.h */,
0EE7A79720F6296F00B42E6A /* PacketMacros.m */,
@ -661,8 +673,8 @@
0E0C2124212ED29D008AB282 /* SessionProxy+Configuration.swift */,
0EFEB42A2006D3C800F81029 /* SessionProxy+EncryptionBridge.swift */,
0E749F5E2178885500BB2701 /* SessionProxy+PIA.swift */,
0E3E0F202108A8CC00B371C1 /* SessionProxy+PushReply.swift */,
0EFEB42B2006D3C800F81029 /* SessionProxy+SessionKey.swift */,
0E3E0F202108A8CC00B371C1 /* SessionProxy+SessionReply.swift */,
0E041D082152E6FE0025FE3C /* SessionProxy+TLSWrap.swift */,
0E011F792196D93600BA59EE /* SocketType.swift */,
0EE3B3E321471C3A0027AB17 /* StaticKey.swift */,
@ -1143,6 +1155,7 @@
files = (
0EB2B45720F0BD16004233D7 /* RandomTests.swift in Sources */,
0E011F812196E23700BA59EE /* ConfigurationParserTests.swift in Sources */,
0ECC60DB2254C8190020BEAC /* OptionsBundleTests.swift in Sources */,
0EB2B45920F0BD9A004233D7 /* LinkTests.swift in Sources */,
0EB2B45520F0BB53004233D7 /* DataManipulationTests.swift in Sources */,
0E50D57521634E0A00FC87A8 /* ControlChannelTests.swift in Sources */,
@ -1224,7 +1237,8 @@
0ED9C8642138139000621BA3 /* SessionProxy+CompressionFraming.swift in Sources */,
0EFEB4722006D3C800F81029 /* ReplayProtector.m in Sources */,
0EFEB4782006D3C800F81029 /* TunnelKitProvider+Configuration.swift in Sources */,
0E3E0F212108A8CC00B371C1 /* SessionProxy+PushReply.swift in Sources */,
0E3E0F212108A8CC00B371C1 /* SessionProxy+SessionReply.swift in Sources */,
0ECC60D82254981A0020BEAC /* OptionsError.swift in Sources */,
0EFEB4752006D3C800F81029 /* Errors.m in Sources */,
0E58BF532240FAA6006FB157 /* SessionProxy+CompressionAlgorithm.swift in Sources */,
0E12B2A521454F7F00B4BAE9 /* BidirectionalState.swift in Sources */,
@ -1232,6 +1246,7 @@
0EFEB4762006D3C800F81029 /* DataPath.m in Sources */,
0E0C2127212ED29D008AB282 /* SessionProxy+Configuration.swift in Sources */,
0EFEB4692006D3C800F81029 /* Packet.swift in Sources */,
0ECC60D5225497400020BEAC /* OptionsBundle.swift in Sources */,
0E011F7A2196D93600BA59EE /* SocketType.swift in Sources */,
0EFEB45A2006D3C800F81029 /* TunnelInterface.swift in Sources */,
);
@ -1292,13 +1307,15 @@
0EFEB4AF2007627700F81029 /* InterfaceObserver.swift in Sources */,
0EFEB4A42006D7F300F81029 /* DataPath.m in Sources */,
0EBBF2E62084FE6F00E36B40 /* GenericSocket.swift in Sources */,
0E3E0F222108A8CC00B371C1 /* SessionProxy+PushReply.swift in Sources */,
0ECC60D92254981A0020BEAC /* OptionsError.swift in Sources */,
0E3E0F222108A8CC00B371C1 /* SessionProxy+SessionReply.swift in Sources */,
0E58BF542240FAA6006FB157 /* SessionProxy+CompressionAlgorithm.swift in Sources */,
0E12B2A621454F7F00B4BAE9 /* BidirectionalState.swift in Sources */,
0EFEB4912006D7F300F81029 /* TLSBox.m in Sources */,
0EFEB49D2006D7F300F81029 /* IOInterface.swift in Sources */,
0E0C2128212ED29D008AB282 /* SessionProxy+Configuration.swift in Sources */,
0EFEB4972006D7F300F81029 /* SessionProxy+Authenticator.swift in Sources */,
0ECC60D6225497400020BEAC /* OptionsBundle.swift in Sources */,
0E011F7B2196D93600BA59EE /* SocketType.swift in Sources */,
0EFEB49B2006D7F300F81029 /* Packet.swift in Sources */,
);
@ -1310,6 +1327,7 @@
files = (
0EA82A3A2190B2B9007960EB /* RandomTests.swift in Sources */,
0E011F822196E23800BA59EE /* ConfigurationParserTests.swift in Sources */,
0ECC60DC2254C8190020BEAC /* OptionsBundleTests.swift in Sources */,
0EA82A332190B2B9007960EB /* DataPathPerformanceTests.swift in Sources */,
0EA82A372190B2B9007960EB /* LinkTests.swift in Sources */,
0EA82A352190B2B9007960EB /* EncryptionPerformanceTests.swift in Sources */,
@ -1464,7 +1482,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 429;
CURRENT_PROJECT_VERSION = 451;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
@ -1528,7 +1546,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 429;
CURRENT_PROJECT_VERSION = 451;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
@ -1561,7 +1579,7 @@
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 429;
DYLIB_CURRENT_VERSION = 451;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = "$(SRCROOT)/TunnelKit-iOS/Info.plist";
@ -1585,7 +1603,7 @@
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = "";
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 429;
DYLIB_CURRENT_VERSION = 451;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
INFOPLIST_FILE = "$(SRCROOT)/TunnelKit-iOS/Info.plist";
@ -1609,7 +1627,7 @@
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 429;
DYLIB_CURRENT_VERSION = 451;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/TunnelKit-macOS/Info.plist";
@ -1633,7 +1651,7 @@
COMBINE_HIDPI_IMAGES = YES;
DEFINES_MODULE = YES;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 429;
DYLIB_CURRENT_VERSION = 451;
DYLIB_INSTALL_NAME_BASE = "@rpath";
FRAMEWORK_VERSION = A;
INFOPLIST_FILE = "$(SRCROOT)/TunnelKit-macOS/Info.plist";

View File

@ -66,9 +66,9 @@ extension TunnelKitProvider {
tlsWrap: nil,
keepAliveInterval: nil,
renegotiatesAfter: nil,
usesPIAPatches: nil,
dnsServers: nil,
randomizeEndpoint: false
randomizeEndpoint: false,
usesPIAPatches: nil
),
shouldDebug: false,
debugLogFormat: nil,

View File

@ -463,9 +463,9 @@ extension TunnelKitProvider: SessionProxyDelegate {
log.info("Returned ifconfig parameters:")
log.info("\tRemote: \(remoteAddress.maskedDescription)")
log.info("\tIPv4: \(reply.ipv4?.description ?? "not configured")")
log.info("\tIPv6: \(reply.ipv6?.description ?? "not configured")")
log.info("\tDNS: \(reply.dnsServers.map { $0.maskedDescription })")
log.info("\tIPv4: \(reply.options.ipv4?.description ?? "not configured")")
log.info("\tIPv6: \(reply.options.ipv6?.description ?? "not configured")")
log.info("\tDNS: \(reply.options.dnsServers.map { $0.maskedDescription })")
bringNetworkUp(remoteAddress: remoteAddress, reply: reply) { (error) in
if let error = error {
@ -477,7 +477,7 @@ extension TunnelKitProvider: SessionProxyDelegate {
log.info("Tunnel interface is now UP")
proxy.setTunnel(tunnel: NETunnelInterface(impl: self.packetFlow, isIPv6: reply.ipv6 != nil))
proxy.setTunnel(tunnel: NETunnelInterface(impl: self.packetFlow, isIPv6: reply.options.ipv6 != nil))
self.pendingStartHandler?(nil)
self.pendingStartHandler = nil
@ -502,7 +502,7 @@ extension TunnelKitProvider: SessionProxyDelegate {
// route all traffic to VPN
var ipv4Settings: NEIPv4Settings?
if let ipv4 = reply.ipv4 {
if let ipv4 = reply.options.ipv4 {
let defaultRoute = NEIPv4Route.default()
defaultRoute.gatewayAddress = ipv4.defaultGateway
@ -519,7 +519,7 @@ extension TunnelKitProvider: SessionProxyDelegate {
}
var ipv6Settings: NEIPv6Settings?
if let ipv6 = reply.ipv6 {
if let ipv6 = reply.options.ipv6 {
let defaultRoute = NEIPv6Route.default()
defaultRoute.gatewayAddress = ipv6.defaultGateway
@ -535,7 +535,7 @@ extension TunnelKitProvider: SessionProxyDelegate {
ipv6Settings?.excludedRoutes = []
}
let dnsSettings = NEDNSSettings(servers: cfg.sessionConfiguration.dnsServers ?? reply.dnsServers)
let dnsSettings = NEDNSSettings(servers: cfg.sessionConfiguration.dnsServers ?? reply.options.dnsServers)
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress)
newSettings.ipv4Settings = ipv4Settings

View File

@ -32,22 +32,6 @@ private let log = SwiftyBeaver.self
/// Provides methods to parse a `SessionProxy.Configuration` from an .ovpn configuration file.
public class ConfigurationParser {
/// Error raised by the parser, with details about the line that triggered it.
public enum ParsingError: Error {
/// The file misses a required option.
case missingConfiguration(option: String)
/// The file includes an unsupported option.
case unsupportedConfiguration(option: String)
/// Passphrase required to decrypt private keys.
case encryptionPassphrase
/// Encryption passphrase is incorrect or key is corrupt.
case unableToDecrypt(error: Error)
}
/// Result of the parser.
public struct ParsingResult {
@ -63,57 +47,11 @@ public class ConfigurationParser {
/// The overall parsed `SessionProxy.Configuration`.
public let configuration: SessionProxy.Configuration
/// The lines of the configuration file stripped of any sensitive data. Lines that
/// the parser does not recognize are discarded in the first place.
///
/// - Seealso: `ConfigurationParser.parsed(...)`
/// - Seealso: `OptionsBundle.init(...)`
public let strippedLines: [String]?
/// Holds an optional `ParsingError` that didn't block the parser, but it would be worth taking care of.
public let warning: ParsingError?
}
private struct Regex {
static let proto = NSRegularExpression("^proto +(udp6?|tcp6?)")
static let port = NSRegularExpression("^port +\\d+")
static let remote = NSRegularExpression("^remote +[^ ]+( +\\d+)?( +(udp6?|tcp6?))?")
static let cipher = NSRegularExpression("^cipher +[\\w\\-]+")
static let auth = NSRegularExpression("^auth +[\\w\\-]+")
static let compLZO = NSRegularExpression("^comp-lzo.*")
static let compress = NSRegularExpression("^compress.*")
static let ping = NSRegularExpression("^ping +\\d+")
static let renegSec = NSRegularExpression("^reneg-sec +\\d+")
static let keyDirection = NSRegularExpression("^key-direction +\\d")
static let eku = NSRegularExpression("^remote-cert-tls +server")
static let blockBegin = NSRegularExpression("^<[\\w\\-]+>")
static let blockEnd = NSRegularExpression("^<\\/[\\w\\-]+>")
static let dns = NSRegularExpression("^dhcp-option +DNS6? +[\\d\\.a-fA-F:]+")
static let remoteRandom = NSRegularExpression("^remote-random")
// unsupported
// static let fragment = NSRegularExpression("^fragment +\\d+")
static let fragment = NSRegularExpression("^fragment")
static let proxy = NSRegularExpression("^\\w+-proxy")
static let externalFiles = NSRegularExpression("^(ca|cert|key|tls-auth|tls-crypt) ")
static let connection = NSRegularExpression("^<connection>")
/// - Seealso: `OptionsBundle.warning`
public let warning: OptionsError?
}
/**
@ -123,7 +61,7 @@ public class ConfigurationParser {
- Parameter passphrase: The optional passphrase for encrypted data.
- Parameter returnsStripped: When `true`, stores the stripped file into `ParsingResult.strippedLines`. Defaults to `false`.
- Returns: The `ParsingResult` outcome of the parsing.
- Throws: `ParsingError` if the configuration file is wrong or incomplete.
- Throws: `OptionsError` if the configuration file is wrong or incomplete.
*/
public static func parsed(fromURL url: URL, passphrase: String? = nil, returnsStripped: Bool = false) throws -> ParsingResult {
let lines = try String(contentsOf: url).trimmedLines()
@ -138,362 +76,56 @@ public class ConfigurationParser {
- Parameter originalURL: The optional original URL of the configuration file.
- Parameter returnsStripped: When `true`, stores the stripped file into `ParsingResult.strippedLines`. Defaults to `false`.
- Returns: The `ParsingResult` outcome of the parsing.
- Throws: `ParsingError` if the configuration file is wrong or incomplete.
- Throws: `OptionsError` if the configuration file is wrong or incomplete.
*/
public static func parsed(fromLines lines: [String], passphrase: String? = nil, originalURL: URL? = nil, returnsStripped: Bool = false) throws -> ParsingResult {
var strippedLines: [String]? = returnsStripped ? [] : nil
var warning: ParsingError? = nil
let options = try OptionsBundle(from: lines, returnsStripped: returnsStripped)
var defaultProto: SocketType?
var defaultPort: UInt16?
var remotes: [(String, UInt16?, SocketType?)] = []
var cipher: SessionProxy.Cipher?
var digest: SessionProxy.Digest?
var compressionFraming: SessionProxy.CompressionFraming = .disabled
var compressionAlgorithm: SessionProxy.CompressionAlgorithm = .disabled
var optCA: CryptoContainer?
var clientCertificate: CryptoContainer?
var clientKey: CryptoContainer?
var checksEKU = false
var keepAliveSeconds: TimeInterval?
var renegotiateAfterSeconds: TimeInterval?
var keyDirection: StaticKey.Direction?
var tlsStrategy: SessionProxy.TLSWrap.Strategy?
var tlsKeyLines: [Substring]?
var tlsWrap: SessionProxy.TLSWrap?
var dnsServers: [String]?
var randomizeEndpoint = false
var currentBlockName: String?
var currentBlock: [String] = []
var unsupportedError: ParsingError? = nil
log.verbose("Configuration file:")
for line in lines {
log.verbose(line)
var isHandled = false
var strippedLine = line
defer {
if isHandled {
strippedLines?.append(strippedLine)
}
}
// check blocks first
Regex.connection.enumerateComponents(in: line) { (_) in
unsupportedError = ParsingError.unsupportedConfiguration(option: "<connection> blocks")
}
if unsupportedError == nil {
if currentBlockName == nil {
Regex.blockBegin.enumerateComponents(in: line) {
isHandled = true
let tag = $0.first!
let from = tag.index(after: tag.startIndex)
let to = tag.index(before: tag.endIndex)
currentBlockName = String(tag[from..<to])
currentBlock = []
}
}
Regex.blockEnd.enumerateComponents(in: line) {
isHandled = true
let tag = $0.first!
let from = tag.index(tag.startIndex, offsetBy: 2)
let to = tag.index(before: tag.endIndex)
let blockName = String(tag[from..<to])
guard blockName == currentBlockName else {
return
}
// first is opening tag
currentBlock.removeFirst()
switch blockName {
case "ca":
optCA = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
case "cert":
clientCertificate = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
case "key":
let isEncrypted = normalizeEncryptedPEMBlock(block: &currentBlock)
let container = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
if isEncrypted {
guard let passphrase = passphrase else {
unsupportedError = ParsingError.encryptionPassphrase
break
}
do {
clientKey = try container.decrypted(with: passphrase)
} catch let e {
unsupportedError = ParsingError.unableToDecrypt(error: e)
}
} else {
clientKey = container
}
case "tls-auth":
tlsKeyLines = currentBlock.map { Substring($0) }
tlsStrategy = .auth
case "tls-crypt":
tlsKeyLines = currentBlock.map { Substring($0) }
tlsStrategy = .crypt
default:
break
}
currentBlockName = nil
currentBlock = []
}
}
if let _ = currentBlockName {
currentBlock.append(line)
continue
}
Regex.eku.enumerateComponents(in: line) { (_) in
checksEKU = true
}
Regex.proto.enumerateArguments(in: line) {
isHandled = true
guard let str = $0.first else {
return
}
defaultProto = SocketType(protoString: str)
if defaultProto == nil {
unsupportedError = ParsingError.unsupportedConfiguration(option: "proto \(str)")
}
}
Regex.port.enumerateArguments(in: line) {
isHandled = true
guard let str = $0.first else {
return
}
defaultPort = UInt16(str)
}
Regex.remote.enumerateArguments(in: line) {
isHandled = true
guard let hostname = $0.first else {
return
}
var port: UInt16?
var proto: SocketType?
var strippedComponents = ["remote", "<hostname>"]
if $0.count > 1 {
port = UInt16($0[1])
strippedComponents.append($0[1])
}
if $0.count > 2 {
proto = SocketType(protoString: $0[2])
strippedComponents.append($0[2])
}
remotes.append((hostname, port, proto))
// replace private data
strippedLine = strippedComponents.joined(separator: " ")
}
Regex.cipher.enumerateArguments(in: line) {
isHandled = true
guard let rawValue = $0.first else {
return
}
cipher = SessionProxy.Cipher(rawValue: rawValue.uppercased())
if cipher == nil {
unsupportedError = ParsingError.unsupportedConfiguration(option: "cipher \(rawValue)")
}
}
Regex.auth.enumerateArguments(in: line) {
isHandled = true
guard let rawValue = $0.first else {
return
}
digest = SessionProxy.Digest(rawValue: rawValue.uppercased())
if digest == nil {
unsupportedError = ParsingError.unsupportedConfiguration(option: "auth \(rawValue)")
}
}
Regex.compLZO.enumerateArguments(in: line) {
isHandled = true
compressionFraming = .compLZO
if !LZOIsSupported() {
guard let arg = $0.first else {
warning = warning ?? .unsupportedConfiguration(option: line)
return
}
guard arg == "no" else {
unsupportedError = .unsupportedConfiguration(option: line)
return
}
} else {
let arg = $0.first
compressionAlgorithm = (arg == "no") ? .disabled : .LZO
}
}
Regex.compress.enumerateArguments(in: line) {
isHandled = true
compressionFraming = .compress
if !LZOIsSupported() {
guard $0.isEmpty else {
unsupportedError = .unsupportedConfiguration(option: line)
return
}
} else {
if let arg = $0.first {
compressionAlgorithm = (arg == "lzo") ? .LZO : .other
} else {
compressionAlgorithm = .disabled
}
}
}
Regex.keyDirection.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first, let value = Int(arg) else {
return
}
keyDirection = StaticKey.Direction(rawValue: value)
}
Regex.ping.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first else {
return
}
keepAliveSeconds = TimeInterval(arg)
}
Regex.renegSec.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first else {
return
}
renegotiateAfterSeconds = TimeInterval(arg)
}
Regex.dns.enumerateArguments(in: line) {
isHandled = true
guard $0.count == 2 else {
return
}
if dnsServers == nil {
dnsServers = []
}
dnsServers?.append($0[1])
}
Regex.remoteRandom.enumerateComponents(in: line) { (_) in
randomizeEndpoint = true
}
Regex.fragment.enumerateComponents(in: line) { (_) in
unsupportedError = ParsingError.unsupportedConfiguration(option: "fragment")
}
Regex.proxy.enumerateComponents(in: line) { (_) in
unsupportedError = ParsingError.unsupportedConfiguration(option: "proxy: \"\(line)\"")
}
Regex.externalFiles.enumerateComponents(in: line) { (_) in
unsupportedError = ParsingError.unsupportedConfiguration(option: "external file: \"\(line)\"")
}
if line.contains("mtu") || line.contains("mssfix") {
isHandled = true
}
if let error = unsupportedError {
throw error
}
guard let ca = options.ca else {
throw OptionsError.missingConfiguration(option: "ca")
}
guard let ca = optCA else {
throw ParsingError.missingConfiguration(option: "ca")
guard let hostname = options.hostname, !options.remotes.isEmpty else {
throw OptionsError.missingConfiguration(option: "remote")
}
let endpointProtocols = options.remotes.map { EndpointProtocol($0.2, $0.1) }
// XXX: only reads first remote
// hostnames = remotes.map { $0.0 }
guard !remotes.isEmpty else {
throw ParsingError.missingConfiguration(option: "remote")
}
let hostname = remotes[0].0
defaultProto = defaultProto ?? .udp
defaultPort = defaultPort ?? 1194
// XXX: reads endpoints from remotes with matching hostname
var endpointProtocols: [EndpointProtocol] = []
remotes.forEach {
guard $0.0 == hostname else {
return
var optClientKey: CryptoContainer?
if let clientKey = options.clientKey, clientKey.isEncrypted {
guard let passphrase = passphrase else {
throw OptionsError.encryptionPassphrase
}
guard let port = $0.1 ?? defaultPort else {
return
}
guard let socketType = $0.2 ?? defaultProto else {
return
}
endpointProtocols.append(EndpointProtocol(socketType, port))
}
assert(!endpointProtocols.isEmpty, "Must define an endpoint protocol")
if let keyLines = tlsKeyLines, let strategy = tlsStrategy {
let optKey: StaticKey?
switch strategy {
case .auth:
optKey = StaticKey(lines: keyLines, direction: keyDirection)
case .crypt:
optKey = StaticKey(lines: keyLines, direction: .client)
}
if let key = optKey {
tlsWrap = SessionProxy.TLSWrap(strategy: strategy, key: key)
do {
optClientKey = try clientKey.decrypted(with: passphrase)
} catch let e {
throw OptionsError.unableToDecrypt(error: e)
}
} else {
optClientKey = options.clientKey
}
var sessionBuilder = SessionProxy.ConfigurationBuilder(ca: ca)
sessionBuilder.cipher = cipher ?? .aes128cbc
sessionBuilder.digest = digest ?? .sha1
sessionBuilder.compressionFraming = compressionFraming
sessionBuilder.compressionAlgorithm = compressionAlgorithm
sessionBuilder.tlsWrap = tlsWrap
sessionBuilder.clientCertificate = clientCertificate
sessionBuilder.clientKey = clientKey
sessionBuilder.checksEKU = checksEKU
sessionBuilder.keepAliveInterval = keepAliveSeconds
sessionBuilder.renegotiatesAfter = renegotiateAfterSeconds
sessionBuilder.dnsServers = dnsServers
sessionBuilder.randomizeEndpoint = randomizeEndpoint
sessionBuilder.cipher = options.cipher ?? .aes128cbc
sessionBuilder.digest = options.digest ?? .sha1
sessionBuilder.compressionFraming = options.compressionFraming ?? .disabled
sessionBuilder.compressionAlgorithm = options.compressionAlgorithm ?? .disabled
sessionBuilder.tlsWrap = options.tlsWrap
sessionBuilder.clientCertificate = options.clientCertificate
sessionBuilder.clientKey = optClientKey
sessionBuilder.checksEKU = options.checksEKU
sessionBuilder.keepAliveInterval = options.keepAliveSeconds
sessionBuilder.renegotiatesAfter = options.renegotiateAfterSeconds
sessionBuilder.dnsServers = options.dnsServers
sessionBuilder.randomizeEndpoint = options.randomizeEndpoint
return ParsingResult(
url: originalURL,
hostname: hostname,
protocols: endpointProtocols,
configuration: sessionBuilder.build(),
strippedLines: strippedLines,
warning: warning
strippedLines: options.strippedLines,
warning: options.warning
)
}
private static func normalizeEncryptedPEMBlock(block: inout [String]) -> Bool {
if block.count >= 1 && block[0].contains("ENCRYPTED") {
return true
}
// XXX: restore blank line after encryption header (easier than tweaking trimmedLines)
if block.count >= 3 && block[1].contains("Proc-Type") {
block.insert("", at: 3)
return true
}
return false
}
}
private extension SocketType {
init?(protoString: String) {
var str = protoString
if str.hasSuffix("6") {
str.removeLast()
}
self.init(rawValue: str.uppercased())
}
}
extension String {

View File

@ -82,7 +82,12 @@ extension CryptoContainer: Codable {
}
}
extension CryptoContainer {
/// :nodoc:
public extension CryptoContainer {
var isEncrypted: Bool {
return pem.contains("ENCRYPTED")
}
func decrypted(with passphrase: String) throws -> CryptoContainer {
let decryptedPEM = try TLSBox.decryptedPrivateKey(fromPEM: pem, passphrase: passphrase)
return CryptoContainer(pem: decryptedPEM)

View File

@ -0,0 +1,779 @@
//
// OptionsBundle.swift
// TunnelKit
//
// Created by Davide De Rosa on 4/3/19.
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
//
// https://github.com/keeshux
//
// 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/>.
//
import Foundation
import SwiftyBeaver
import __TunnelKitNative
private let log = SwiftyBeaver.self
/// Wraps together all recognized options from either configuration files or PUSH_REPLY.
public struct OptionsBundle {
struct Regex {
// MARK: General
static let cipher = NSRegularExpression("^cipher +[^,\\s]+")
static let auth = NSRegularExpression("^auth +[\\w\\-]+")
static let compLZO = NSRegularExpression("^comp-lzo.*")
static let compress = NSRegularExpression("^compress.*")
static let keyDirection = NSRegularExpression("^key-direction +\\d")
static let ping = NSRegularExpression("^ping +\\d+")
static let renegSec = NSRegularExpression("^reneg-sec +\\d+")
static let blockBegin = NSRegularExpression("^<[\\w\\-]+>")
static let blockEnd = NSRegularExpression("^<\\/[\\w\\-]+>")
// MARK: Client
static let proto = NSRegularExpression("^proto +(udp6?|tcp6?)")
static let port = NSRegularExpression("^port +\\d+")
static let remote = NSRegularExpression("^remote +[^ ]+( +\\d+)?( +(udp6?|tcp6?))?")
static let eku = NSRegularExpression("^remote-cert-tls +server")
static let remoteRandom = NSRegularExpression("^remote-random")
// MARK: Server
static let authToken = NSRegularExpression("^auth-token +[a-zA-Z0-9/=+]+")
static let peerId = NSRegularExpression("^peer-id +[0-9]+")
// MARK: Routing
static let topology = NSRegularExpression("^topology +(net30|p2p|subnet)")
static let ifconfig = NSRegularExpression("^ifconfig +[\\d\\.]+ [\\d\\.]+")
static let ifconfig6 = NSRegularExpression("^ifconfig-ipv6 +[\\da-fA-F:]+/\\d+ [\\da-fA-F:]+")
static let route = NSRegularExpression("^route +[\\d\\.]+( +[\\d\\.]+){0,2}")
static let route6 = NSRegularExpression("^route-ipv6 +[\\da-fA-F:]+/\\d+( +[\\da-fA-F:]+){0,2}")
static let gateway = NSRegularExpression("^route-gateway +[\\d\\.]+")
static let dns = NSRegularExpression("^dhcp-option +DNS6? +[\\d\\.a-fA-F:]+")
// MARK: Unsupported
// static let fragment = NSRegularExpression("^fragment +\\d+")
static let fragment = NSRegularExpression("^fragment")
static let proxy = NSRegularExpression("^\\w+-proxy")
static let externalFiles = NSRegularExpression("^(ca|cert|key|tls-auth|tls-crypt) ")
static let connection = NSRegularExpression("^<connection>")
}
private enum Topology: String {
case net30
case p2p
case subnet
}
/// The lines of the configuration file stripped of any sensitive data. Lines that
/// the parser does not recognize are discarded in the first place.
///
/// - Seealso: `OptionsBundle.init(...)`
public let strippedLines: [String]?
/// Holds an optional `OptionsError` that didn't block the parser, but it would be worth taking care of.
public let warning: OptionsError?
// MARK: General
/// The cipher algorithm for data encryption.
public let cipher: SessionProxy.Cipher?
/// The digest algorithm for HMAC.
public let digest: SessionProxy.Digest?
/// Compression framing, disabled by default.
public let compressionFraming: SessionProxy.CompressionFraming?
/// Compression algorithm, disabled by default.
public let compressionAlgorithm: SessionProxy.CompressionAlgorithm?
/// The CA for TLS negotiation (PEM format).
public let ca: CryptoContainer?
/// The optional client certificate for TLS negotiation (PEM format).
public let clientCertificate: CryptoContainer?
/// The private key for the certificate in `clientCertificate` (PEM format).
public let clientKey: CryptoContainer?
/// The optional TLS wrapping.
public let tlsWrap: SessionProxy.TLSWrap?
/// Sends periodical keep-alive packets if set.
public let keepAliveSeconds: TimeInterval?
/// The number of seconds after which a renegotiation should be initiated. If `nil`, the client will never initiate a renegotiation.
public let renegotiateAfterSeconds: TimeInterval?
// MARK: Client
/// The server hostname (picked from first remote).
public let hostname: String?
/// The list of server endpoints (address, port, socket).
public let remotes: [(String, UInt16, SocketType)]
/// If true, checks EKU of server certificate.
public let checksEKU: Bool
/// Picks endpoint from `remotes` randomly.
public let randomizeEndpoint: Bool
// MARK: Server
/// The auth-token returned by the server.
public let authToken: String?
/// The peer-id returned by the server.
public let peerId: UInt32?
// MARK: Routing
/// The settings for IPv4.
public let ipv4: IPv4Settings?
/// The settings for IPv6.
public let ipv6: IPv6Settings?
/// The DNS servers.
public let dnsServers: [String]
/**
Parses options from an array of lines.
- Parameter lines: The array of lines holding the options.
- Parameter returnsStripped: When `true`, stores the stripped lines into `strippedLines`. Defaults to `false`.
- Throws: `OptionsError` if the options are wrong or incomplete.
*/
public init(from lines: [String], returnsStripped: Bool = false) throws {
var optStrippedLines: [String]? = returnsStripped ? [] : nil
var optWarning: OptionsError?
var unsupportedError: OptionsError?
var currentBlockName: String?
var currentBlock: [String] = []
var optCipher: SessionProxy.Cipher?
var optDigest: SessionProxy.Digest?
var optCompressionFraming: SessionProxy.CompressionFraming?
var optCompressionAlgorithm: SessionProxy.CompressionAlgorithm?
var optCA: CryptoContainer?
var optClientCertificate: CryptoContainer?
var optClientKey: CryptoContainer?
var optKeyDirection: StaticKey.Direction?
var optTLSKeyLines: [Substring]?
var optTLSStrategy: SessionProxy.TLSWrap.Strategy?
var optKeepAliveSeconds: TimeInterval?
var optRenegotiateAfterSeconds: TimeInterval?
//
var optHostname: String?
var optDefaultProto: SocketType?
var optDefaultPort: UInt16?
var optRemotes: [(String, UInt16?, SocketType?)] = [] // address, port, socket
var optChecksEKU: Bool?
var optRandomizeEndpoint: Bool?
//
var optAuthToken: String?
var optPeerId: UInt32?
//
var optTopology: String?
var optIfconfig4Arguments: [String]?
var optIfconfig6Arguments: [String]?
var optGateway4Arguments: [String]?
var optRoutes4: [(String, String, String?)] = [] // address, netmask, gateway
var optRoutes6: [(String, UInt8, String?)] = [] // destination, prefix, gateway
var optDNSServers: [String] = []
log.verbose("Configuration file:")
for line in lines {
log.verbose(line)
var isHandled = false
var strippedLine = line
defer {
if isHandled {
optStrippedLines?.append(strippedLine)
}
}
// MARK: Unsupported
// check blocks first
Regex.connection.enumerateComponents(in: line) { (_) in
unsupportedError = OptionsError.unsupportedConfiguration(option: "<connection> blocks")
}
Regex.fragment.enumerateComponents(in: line) { (_) in
unsupportedError = OptionsError.unsupportedConfiguration(option: "fragment")
}
Regex.proxy.enumerateComponents(in: line) { (_) in
unsupportedError = OptionsError.unsupportedConfiguration(option: "proxy: \"\(line)\"")
}
Regex.externalFiles.enumerateComponents(in: line) { (_) in
unsupportedError = OptionsError.unsupportedConfiguration(option: "external file: \"\(line)\"")
}
if line.contains("mtu") || line.contains("mssfix") {
isHandled = true
}
// MARK: Inline content
if unsupportedError == nil {
if currentBlockName == nil {
Regex.blockBegin.enumerateComponents(in: line) {
isHandled = true
let tag = $0.first!
let from = tag.index(after: tag.startIndex)
let to = tag.index(before: tag.endIndex)
currentBlockName = String(tag[from..<to])
currentBlock = []
}
}
Regex.blockEnd.enumerateComponents(in: line) {
isHandled = true
let tag = $0.first!
let from = tag.index(tag.startIndex, offsetBy: 2)
let to = tag.index(before: tag.endIndex)
let blockName = String(tag[from..<to])
guard blockName == currentBlockName else {
return
}
// first is opening tag
currentBlock.removeFirst()
switch blockName {
case "ca":
optCA = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
case "cert":
optClientCertificate = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
case "key":
OptionsBundle.normalizeEncryptedPEMBlock(block: &currentBlock)
optClientKey = CryptoContainer(pem: currentBlock.joined(separator: "\n"))
case "tls-auth":
optTLSKeyLines = currentBlock.map { Substring($0) }
optTLSStrategy = .auth
case "tls-crypt":
optTLSKeyLines = currentBlock.map { Substring($0) }
optTLSStrategy = .crypt
default:
break
}
currentBlockName = nil
currentBlock = []
}
}
if let _ = currentBlockName {
currentBlock.append(line)
continue
}
// MARK: General
Regex.cipher.enumerateArguments(in: line) {
isHandled = true
guard let rawValue = $0.first else {
return
}
optCipher = SessionProxy.Cipher(rawValue: rawValue.uppercased())
if optCipher == nil {
unsupportedError = OptionsError.unsupportedConfiguration(option: "cipher \(rawValue)")
}
}
Regex.auth.enumerateArguments(in: line) {
isHandled = true
guard let rawValue = $0.first else {
return
}
optDigest = SessionProxy.Digest(rawValue: rawValue.uppercased())
if optDigest == nil {
unsupportedError = OptionsError.unsupportedConfiguration(option: "auth \(rawValue)")
}
}
Regex.compLZO.enumerateArguments(in: line) {
isHandled = true
optCompressionFraming = .compLZO
if !LZOIsSupported() {
guard let arg = $0.first else {
optWarning = optWarning ?? .unsupportedConfiguration(option: line)
return
}
guard arg == "no" else {
unsupportedError = .unsupportedConfiguration(option: line)
return
}
} else {
let arg = $0.first
optCompressionAlgorithm = (arg == "no") ? .disabled : .LZO
}
}
Regex.compress.enumerateArguments(in: line) {
isHandled = true
optCompressionFraming = .compress
if !LZOIsSupported() {
guard $0.isEmpty else {
unsupportedError = .unsupportedConfiguration(option: line)
return
}
} else {
if let arg = $0.first {
optCompressionAlgorithm = (arg == "lzo") ? .LZO : .other
} else {
optCompressionAlgorithm = .disabled
}
}
}
Regex.keyDirection.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first, let value = Int(arg) else {
return
}
optKeyDirection = StaticKey.Direction(rawValue: value)
}
Regex.ping.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first else {
return
}
optKeepAliveSeconds = TimeInterval(arg)
}
Regex.renegSec.enumerateArguments(in: line) {
isHandled = true
guard let arg = $0.first else {
return
}
optRenegotiateAfterSeconds = TimeInterval(arg)
}
// MARK: Client
Regex.proto.enumerateArguments(in: line) {
isHandled = true
guard let str = $0.first else {
return
}
optDefaultProto = SocketType(protoString: str)
if optDefaultProto == nil {
unsupportedError = OptionsError.unsupportedConfiguration(option: "proto \(str)")
}
}
Regex.port.enumerateArguments(in: line) {
isHandled = true
guard let str = $0.first else {
return
}
optDefaultPort = UInt16(str)
}
Regex.remote.enumerateArguments(in: line) {
isHandled = true
guard let hostname = $0.first else {
return
}
var port: UInt16?
var proto: SocketType?
var strippedComponents = ["remote", "<hostname>"]
if $0.count > 1 {
port = UInt16($0[1])
strippedComponents.append($0[1])
}
if $0.count > 2 {
proto = SocketType(protoString: $0[2])
strippedComponents.append($0[2])
}
optRemotes.append((hostname, port, proto))
// replace private data
strippedLine = strippedComponents.joined(separator: " ")
}
Regex.eku.enumerateComponents(in: line) { (_) in
isHandled = true
optChecksEKU = true
}
Regex.remoteRandom.enumerateComponents(in: line) { (_) in
isHandled = true
optRandomizeEndpoint = true
}
// MARK: Server
Regex.authToken.enumerateArguments(in: line) {
optAuthToken = $0[0]
}
Regex.peerId.enumerateArguments(in: line) {
optPeerId = UInt32($0[0])
}
// MARK: Routing
Regex.topology.enumerateArguments(in: line) {
optTopology = $0.first
}
Regex.ifconfig.enumerateArguments(in: line) {
optIfconfig4Arguments = $0
}
Regex.ifconfig6.enumerateArguments(in: line) {
optIfconfig6Arguments = $0
}
Regex.route.enumerateArguments(in: line) {
let routeEntryArguments = $0
let address = routeEntryArguments[0]
let mask = (routeEntryArguments.count > 1) ? routeEntryArguments[1] : "255.255.255.255"
let gateway = (routeEntryArguments.count > 2) ? routeEntryArguments[2] : nil // defaultGateway4
optRoutes4.append((address, mask, gateway))
}
Regex.route6.enumerateArguments(in: line) {
let routeEntryArguments = $0
let destinationComponents = routeEntryArguments[0].components(separatedBy: "/")
guard destinationComponents.count == 2 else {
return
}
guard let prefix = UInt8(destinationComponents[1]) else {
return
}
let destination = destinationComponents[0]
let gateway = (routeEntryArguments.count > 1) ? routeEntryArguments[1] : nil // defaultGateway6
optRoutes6.append((destination, prefix, gateway))
}
Regex.gateway.enumerateArguments(in: line) {
optGateway4Arguments = $0
}
Regex.dns.enumerateArguments(in: line) {
guard $0.count == 2 else {
return
}
optDNSServers.append($0[1])
}
//
if let error = unsupportedError {
throw error
}
}
//
strippedLines = optStrippedLines
warning = optWarning
// MARK: General
cipher = optCipher
digest = optDigest
compressionFraming = optCompressionFraming
compressionAlgorithm = optCompressionAlgorithm
ca = optCA
clientCertificate = optClientCertificate
clientKey = optClientKey
if let keyLines = optTLSKeyLines, let strategy = optTLSStrategy {
let optKey: StaticKey?
switch strategy {
case .auth:
optKey = StaticKey(lines: keyLines, direction: optKeyDirection)
case .crypt:
optKey = StaticKey(lines: keyLines, direction: .client)
}
if let key = optKey {
tlsWrap = SessionProxy.TLSWrap(strategy: strategy, key: key)
} else {
tlsWrap = nil
}
} else {
tlsWrap = nil
}
keepAliveSeconds = optKeepAliveSeconds
renegotiateAfterSeconds = optRenegotiateAfterSeconds
// MARK: Client
optDefaultProto = optDefaultProto ?? .udp
optDefaultPort = optDefaultPort ?? 1194
if !optRemotes.isEmpty {
hostname = optRemotes[0].0
var fullRemotes: [(String, UInt16, SocketType)] = []
let hostname = optRemotes[0].0
optRemotes.forEach {
guard $0.0 == hostname else {
return
}
guard let port = $0.1 ?? optDefaultPort else {
return
}
guard let socketType = $0.2 ?? optDefaultProto else {
return
}
fullRemotes.append((hostname, port, socketType))
}
remotes = fullRemotes
} else {
hostname = nil
remotes = []
}
checksEKU = optChecksEKU ?? false
randomizeEndpoint = optRandomizeEndpoint ?? false
// MARK: Server
authToken = optAuthToken
peerId = optPeerId
// MARK: Routing
//
// excerpts from OpenVPN manpage
//
// "--ifconfig l rn":
//
// Set TUN/TAP adapter parameters. l is the IP address of the local VPN endpoint. For TUN devices in point-to-point mode, rn is the IP address of
// the remote VPN endpoint. For TAP devices, or TUN devices used with --topology subnet, rn is the subnet mask of the virtual network segment which
// is being created or connected to.
//
// "--topology mode":
//
// Note: Using --topology subnet changes the interpretation of the arguments of --ifconfig to mean "address netmask", no longer "local remote".
//
if let ifconfig4Arguments = optIfconfig4Arguments {
guard ifconfig4Arguments.count == 2 else {
throw OptionsError.malformed(option: "ifconfig takes 2 arguments")
}
let address4: String
let addressMask4: String
let defaultGateway4: String
let topology = Topology(rawValue: optTopology ?? "") ?? .net30
switch topology {
case .subnet:
// default gateway required when topology is subnet
guard let gateway4Arguments = optGateway4Arguments, gateway4Arguments.count == 1 else {
throw OptionsError.malformed(option: "route-gateway takes 1 argument")
}
address4 = ifconfig4Arguments[0]
addressMask4 = ifconfig4Arguments[1]
defaultGateway4 = gateway4Arguments[0]
default:
address4 = ifconfig4Arguments[0]
addressMask4 = "255.255.255.255"
defaultGateway4 = ifconfig4Arguments[1]
}
let routes4 = optRoutes4.map { IPv4Settings.Route($0.0, $0.1, $0.2 ?? defaultGateway4) }
ipv4 = IPv4Settings(
address: address4,
addressMask: addressMask4,
defaultGateway: defaultGateway4,
routes: routes4
)
} else {
ipv4 = nil
}
if let ifconfig6Arguments = optIfconfig6Arguments {
guard ifconfig6Arguments.count == 2 else {
throw OptionsError.malformed(option: "ifconfig-ipv6 takes 2 arguments")
}
let address6Components = ifconfig6Arguments[0].components(separatedBy: "/")
guard address6Components.count == 2 else {
throw OptionsError.malformed(option: "ifconfig-ipv6 address must have a /prefix")
}
guard let addressPrefix6 = UInt8(address6Components[1]) else {
throw OptionsError.malformed(option: "ifconfig-ipv6 address prefix must be a 8-bit number")
}
let address6 = address6Components[0]
let defaultGateway6 = ifconfig6Arguments[1]
let routes6 = optRoutes6.map { IPv6Settings.Route($0.0, $0.1, $0.2 ?? defaultGateway6) }
ipv6 = IPv6Settings(
address: address6,
addressPrefixLength: addressPrefix6,
defaultGateway: defaultGateway6,
routes: routes6
)
} else {
ipv6 = nil
}
dnsServers = optDNSServers
}
private static func normalizeEncryptedPEMBlock(block: inout [String]) {
// if block.count >= 1 && block[0].contains("ENCRYPTED") {
// return true
// }
// XXX: restore blank line after encryption header (easier than tweaking trimmedLines)
if block.count >= 3 && block[1].contains("Proc-Type") {
block.insert("", at: 3)
// return true
}
// return false
}
}
/// Encapsulates the IPv4 settings for the tunnel.
public struct IPv4Settings: CustomStringConvertible {
/// Represents an IPv4 route in the routing table.
public struct Route: CustomStringConvertible {
/// The destination host or subnet.
public let destination: String
/// The address mask.
public let mask: String
/// The address of the gateway (uses default gateway if not set).
public let gateway: String?
fileprivate init(_ destination: String, _ mask: String?, _ gateway: String?) {
self.destination = destination
self.mask = mask ?? "255.255.255.255"
self.gateway = gateway
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "{\(destination.maskedDescription)/\(mask) \(gateway?.maskedDescription ?? "default")}"
}
}
/// The address.
let address: String
/// The address mask.
let addressMask: String
/// The address of the default gateway.
let defaultGateway: String
/// The additional routes.
let routes: [Route]
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "addr \(address.maskedDescription) netmask \(addressMask) gw \(defaultGateway.maskedDescription) routes \(routes.map { $0.maskedDescription })"
}
}
/// Encapsulates the IPv6 settings for the tunnel.
public struct IPv6Settings: CustomStringConvertible {
/// Represents an IPv6 route in the routing table.
public struct Route: CustomStringConvertible {
/// The destination host or subnet.
public let destination: String
/// The address prefix length.
public let prefixLength: UInt8
/// The address of the gateway (uses default gateway if not set).
public let gateway: String?
fileprivate init(_ destination: String, _ prefixLength: UInt8?, _ gateway: String?) {
self.destination = destination
self.prefixLength = prefixLength ?? 3
self.gateway = gateway
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "{\(destination.maskedDescription)/\(prefixLength) \(gateway?.maskedDescription ?? "default")}"
}
}
/// The address.
public let address: String
/// The address prefix length.
public let addressPrefixLength: UInt8
/// The address of the default gateway.
public let defaultGateway: String
/// The additional routes.
public let routes: [Route]
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "addr \(address.maskedDescription)/\(addressPrefixLength) gw \(defaultGateway.maskedDescription) routes \(routes.map { $0.maskedDescription })"
}
}
private extension SocketType {
init?(protoString: String) {
var str = protoString
if str.hasSuffix("6") {
str.removeLast()
}
self.init(rawValue: str.uppercased())
}
}

View File

@ -0,0 +1,45 @@
//
// OptionsError.swift
// TunnelKit
//
// Created by Davide De Rosa on 4/3/19.
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
//
// https://github.com/keeshux
//
// 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/>.
//
import Foundation
/// Error raised by the options parser, with details about the line that triggered it.
public enum OptionsError: Error {
/// Option syntax is incorrect.
case malformed(option: String)
/// A required option is missing.
case missingConfiguration(option: String)
/// An option is unsupported.
case unsupportedConfiguration(option: String)
/// Passphrase required to decrypt private keys.
case encryptionPassphrase
/// Encryption passphrase is incorrect or key is corrupt.
case unableToDecrypt(error: Error)
}

View File

@ -59,9 +59,6 @@ public enum SessionError: String, Error {
/// The provided credentials failed authentication.
case badCredentials
/// The reply to PUSH_REQUEST is malformed.
case malformedPushReply
/// A write operation failed at the link layer (e.g. network unreachable).
case failedLinkWrite

View File

@ -135,48 +135,48 @@ extension SessionProxy {
/// The way to create a `SessionProxy.Configuration` object for a `SessionProxy`.
public struct ConfigurationBuilder {
/// The cipher algorithm for data encryption.
/// - Seealso: `OptionsBundle.cipher`
public var cipher: Cipher
/// The digest algorithm for HMAC.
/// - Seealso: `OptionsBundle.digest`
public var digest: Digest
/// The CA for TLS negotiation (PEM format).
/// - Seealso: `OptionsBundle.ca`
public let ca: CryptoContainer
/// The optional client certificate for TLS negotiation (PEM format).
/// - Seealso: `OptionsBundle.clientCertificate`
public var clientCertificate: CryptoContainer?
/// The private key for the certificate in `clientCertificate` (PEM format).
/// - Seealso: `OptionsBundle.clientKey`
public var clientKey: CryptoContainer?
/// If true, checks EKU of server certificate.
/// - Seealso: `OptionsBundle.checksEKU`
public var checksEKU: Bool?
/// Sets compression framing, disabled by default.
/// - Seealso: `OptionsBundle.compressionFraming`
public var compressionFraming: CompressionFraming
/// Sets compression algorithm, disabled by default.
/// - Seealso: `OptionsBundle.compressionAlgorithm`
public var compressionAlgorithm: CompressionAlgorithm?
/// The optional TLS wrapping.
/// - Seealso: `OptionsBundle.tlsWrap`
public var tlsWrap: TLSWrap?
/// Sends periodical keep-alive packets if set.
/// - Seealso: `OptionsBundle.keepAliveInterval`
public var keepAliveInterval: TimeInterval?
/// The number of seconds after which a renegotiation should be initiated. If `nil`, the client will never initiate a renegotiation.
/// - Seealso: `OptionsBundle.renegotiatesAfter`
public var renegotiatesAfter: TimeInterval?
/// - Seealso: `OptionsBundle.dnsServers`
public var dnsServers: [String]?
/// - Seealso: `OptionsBundle.randomizeEndpoint`
public var randomizeEndpoint: Bool?
/// Server is patched for the PIA VPN provider.
public var usesPIAPatches: Bool?
/// Optionally override the server DNS entries.
public var dnsServers: [String]?
/// Optionally randomize endpoint order.
public var randomizeEndpoint: Bool?
/// :nodoc:
public init(ca: CryptoContainer) {
cipher = .aes128cbc
@ -190,9 +190,9 @@ extension SessionProxy {
tlsWrap = nil
keepAliveInterval = nil
renegotiatesAfter = nil
usesPIAPatches = false
dnsServers = nil
randomizeEndpoint = false
usesPIAPatches = false
}
/**
@ -213,9 +213,9 @@ extension SessionProxy {
tlsWrap: tlsWrap,
keepAliveInterval: keepAliveInterval,
renegotiatesAfter: renegotiatesAfter,
usesPIAPatches: usesPIAPatches,
dnsServers: dnsServers,
randomizeEndpoint: randomizeEndpoint
randomizeEndpoint: randomizeEndpoint,
usesPIAPatches: usesPIAPatches
)
}
}
@ -256,15 +256,15 @@ extension SessionProxy {
/// - Seealso: `SessionProxy.ConfigurationBuilder.renegotiatesAfter`
public let renegotiatesAfter: TimeInterval?
/// - Seealso: `SessionProxy.ConfigurationBuilder.usesPIAPatches`
public let usesPIAPatches: Bool?
/// - Seealso: `SessionProxy.ConfigurationBuilder.dnsServers`
public let dnsServers: [String]?
/// - Seealso: `SessionProxy.ConfigurationBuilder.randomizeEndpoint`
public let randomizeEndpoint: Bool?
/// - Seealso: `SessionProxy.ConfigurationBuilder.usesPIAPatches`
public let usesPIAPatches: Bool?
/**
Returns a `SessionProxy.ConfigurationBuilder` to use this configuration as a starting point for a new one.
@ -282,9 +282,9 @@ extension SessionProxy {
builder.tlsWrap = tlsWrap
builder.keepAliveInterval = keepAliveInterval
builder.renegotiatesAfter = renegotiatesAfter
builder.usesPIAPatches = usesPIAPatches
builder.dnsServers = dnsServers
builder.randomizeEndpoint = randomizeEndpoint
builder.usesPIAPatches = usesPIAPatches
return builder
}
@ -303,9 +303,9 @@ extension SessionProxy {
(lhs.compressionAlgorithm == rhs.compressionAlgorithm) &&
(lhs.keepAliveInterval == rhs.keepAliveInterval) &&
(lhs.renegotiatesAfter == rhs.renegotiatesAfter) &&
(lhs.usesPIAPatches == rhs.usesPIAPatches) &&
(lhs.dnsServers == rhs.dnsServers) &&
(lhs.randomizeEndpoint == rhs.randomizeEndpoint)
(lhs.randomizeEndpoint == rhs.randomizeEndpoint) &&
(lhs.usesPIAPatches == rhs.usesPIAPatches)
}
}
}

View File

@ -1,463 +0,0 @@
//
// SessionProxy+PushReply.swift
// TunnelKit
//
// Created by Davide De Rosa on 7/25/18.
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
//
// https://github.com/keeshux
//
// 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.
//
//
import Foundation
/// Encapsulates the IPv4 settings for the tunnel.
public struct IPv4Settings: CustomStringConvertible {
/// Represents an IPv4 route in the routing table.
public struct Route: CustomStringConvertible {
/// The destination host or subnet.
public let destination: String
/// The address mask.
public let mask: String
/// The address of the gateway (uses default gateway if not set).
public let gateway: String?
fileprivate init(_ destination: String, _ mask: String?, _ gateway: String?) {
self.destination = destination
self.mask = mask ?? "255.255.255.255"
self.gateway = gateway
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "{\(destination.maskedDescription)/\(mask) \(gateway?.maskedDescription ?? "default")}"
}
}
/// The address.
let address: String
/// The address mask.
let addressMask: String
/// The address of the default gateway.
let defaultGateway: String
/// The additional routes.
let routes: [Route]
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "addr \(address.maskedDescription) netmask \(addressMask) gw \(defaultGateway.maskedDescription) routes \(routes.map { $0.maskedDescription })"
}
}
/// Encapsulates the IPv6 settings for the tunnel.
public struct IPv6Settings: CustomStringConvertible {
/// Represents an IPv6 route in the routing table.
public struct Route: CustomStringConvertible {
/// The destination host or subnet.
public let destination: String
/// The address prefix length.
public let prefixLength: UInt8
/// The address of the gateway (uses default gateway if not set).
public let gateway: String?
fileprivate init(_ destination: String, _ prefixLength: UInt8?, _ gateway: String?) {
self.destination = destination
self.prefixLength = prefixLength ?? 3
self.gateway = gateway
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "{\(destination.maskedDescription)/\(prefixLength) \(gateway?.maskedDescription ?? "default")}"
}
}
/// The address.
public let address: String
/// The address prefix length.
public let addressPrefixLength: UInt8
/// The address of the default gateway.
public let defaultGateway: String
/// The additional routes.
public let routes: [Route]
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
return "addr \(address.maskedDescription)/\(addressPrefixLength) gw \(defaultGateway.maskedDescription) routes \(routes.map { $0.maskedDescription })"
}
}
/// Groups the parsed reply of a successfully started session.
public protocol SessionReply {
/// The IPv4 settings.
var ipv4: IPv4Settings? { get }
/// The IPv6 settings.
var ipv6: IPv6Settings? { get }
/// The DNS servers set up for this session.
var dnsServers: [String] { get }
/// The optional compression framing.
var compressionFraming: SessionProxy.CompressionFraming? { get }
/// The optional compression algorithm.
var compressionAlgorithm: SessionProxy.CompressionAlgorithm? { get }
/// The optional keep-alive interval.
var ping: Int? { get }
/// The optional authentication token.
var authToken: String? { get }
/// The optional 24-bit peer-id.
var peerId: UInt32? { get }
/// The negotiated cipher if any (NCP).
var cipher: SessionProxy.Cipher? { get }
}
extension SessionProxy {
// XXX: parsing is very optimistic
struct PushReply: SessionReply, CustomStringConvertible {
private enum Topology: String {
case net30
case p2p
case subnet
}
private struct Regex {
static let prefix = "PUSH_REPLY,"
static let topology = NSRegularExpression("topology (net30|p2p|subnet)")
static let ifconfig = NSRegularExpression("ifconfig [\\d\\.]+ [\\d\\.]+")
static let ifconfig6 = NSRegularExpression("ifconfig-ipv6 [\\da-fA-F:]+/\\d+ [\\da-fA-F:]+")
static let gateway = NSRegularExpression("route-gateway [\\d\\.]+")
static let route = NSRegularExpression("route [\\d\\.]+( [\\d\\.]+){0,2}")
static let route6 = NSRegularExpression("route-ipv6 [\\da-fA-F:]+/\\d+( [\\da-fA-F:]+){0,2}")
static let dns = NSRegularExpression("dhcp-option DNS6? [\\d\\.a-fA-F:]+")
static let comp = NSRegularExpression("comp(ress|-lzo)[ \\w]*")
static let ping = NSRegularExpression("ping \\d+")
static let authToken = NSRegularExpression("auth-token [a-zA-Z0-9/=+]+")
static let peerId = NSRegularExpression("peer-id [0-9]+")
static let cipher = NSRegularExpression("cipher [^,\\s]+")
}
private let original: String
let ipv4: IPv4Settings?
let ipv6: IPv6Settings?
let dnsServers: [String]
let compressionFraming: SessionProxy.CompressionFraming?
let compressionAlgorithm: SessionProxy.CompressionAlgorithm?
let ping: Int?
let authToken: String?
let peerId: UInt32?
let cipher: SessionProxy.Cipher?
init?(message: String) throws {
guard message.hasPrefix(Regex.prefix) else {
return nil
}
let prefixOffset = message.index(message.startIndex, offsetBy: Regex.prefix.count)
original = String(message[prefixOffset..<message.endIndex])
var optTopologyArguments: [String]?
var optIfconfig4Arguments: [String]?
var optGateway4Arguments: [String]?
let address4: String
let addressMask4: String
let defaultGateway4: String
var routes4: [IPv4Settings.Route] = []
var optIfconfig6Arguments: [String]?
var dnsServers: [String] = []
var compressionFraming: SessionProxy.CompressionFraming?
var compressionAlgorithm: SessionProxy.CompressionAlgorithm?
var ping: Int?
var authToken: String?
var peerId: UInt32?
var cipher: SessionProxy.Cipher?
// MARK: Routing (IPv4)
Regex.topology.enumerateArguments(in: message) {
optTopologyArguments = $0
}
guard let topologyArguments = optTopologyArguments, topologyArguments.count == 1 else {
throw SessionError.malformedPushReply
}
// assumes "topology" to be always pushed to clients, even when not explicitly set (defaults to net30)
guard let topology = Topology(rawValue: topologyArguments[0]) else {
fatalError("Bad topology regexp, accepted unrecognized value: \(topologyArguments[0])")
}
Regex.ifconfig.enumerateArguments(in: message) {
optIfconfig4Arguments = $0
}
guard let ifconfig4Arguments = optIfconfig4Arguments, ifconfig4Arguments.count == 2 else {
throw SessionError.malformedPushReply
}
Regex.gateway.enumerateArguments(in: message) {
optGateway4Arguments = $0
}
//
// excerpts from OpenVPN manpage
//
// "--ifconfig l rn":
//
// Set TUN/TAP adapter parameters. l is the IP address of the local VPN endpoint. For TUN devices in point-to-point mode, rn is the IP address of
// the remote VPN endpoint. For TAP devices, or TUN devices used with --topology subnet, rn is the subnet mask of the virtual network segment which
// is being created or connected to.
//
// "--topology mode":
//
// Note: Using --topology subnet changes the interpretation of the arguments of --ifconfig to mean "address netmask", no longer "local remote".
//
switch topology {
case .subnet:
// default gateway required when topology is subnet
guard let gateway4Arguments = optGateway4Arguments, gateway4Arguments.count == 1 else {
throw SessionError.malformedPushReply
}
address4 = ifconfig4Arguments[0]
addressMask4 = ifconfig4Arguments[1]
defaultGateway4 = gateway4Arguments[0]
default:
address4 = ifconfig4Arguments[0]
addressMask4 = "255.255.255.255"
defaultGateway4 = ifconfig4Arguments[1]
}
Regex.route.enumerateArguments(in: message) {
let routeEntryArguments = $0
let address = routeEntryArguments[0]
let mask: String?
let gateway: String?
if routeEntryArguments.count > 1 {
mask = routeEntryArguments[1]
} else {
mask = nil
}
if routeEntryArguments.count > 2 {
gateway = routeEntryArguments[2]
} else {
gateway = defaultGateway4
}
routes4.append(IPv4Settings.Route(address, mask, gateway))
}
ipv4 = IPv4Settings(
address: address4,
addressMask: addressMask4,
defaultGateway: defaultGateway4,
routes: routes4
)
// MARK: Routing (IPv6)
Regex.ifconfig6.enumerateArguments(in: message) {
optIfconfig6Arguments = $0
}
if let ifconfig6Arguments = optIfconfig6Arguments, ifconfig6Arguments.count == 2 {
let address6Components = ifconfig6Arguments[0].components(separatedBy: "/")
guard address6Components.count == 2 else {
throw SessionError.malformedPushReply
}
guard let addressPrefix6 = UInt8(address6Components[1]) else {
throw SessionError.malformedPushReply
}
let address6 = address6Components[0]
let defaultGateway6 = ifconfig6Arguments[1]
var routes6: [IPv6Settings.Route] = []
Regex.route6.enumerateArguments(in: message) {
let routeEntryArguments = $0
let destinationComponents = routeEntryArguments[0].components(separatedBy: "/")
guard destinationComponents.count == 2 else {
// throw SessionError.malformedPushReply
return
}
guard let prefix = UInt8(destinationComponents[1]) else {
// throw SessionError.malformedPushReply
return
}
let destination = destinationComponents[0]
let gateway: String?
if routeEntryArguments.count > 1 {
gateway = routeEntryArguments[1]
} else {
gateway = defaultGateway6
}
routes6.append(IPv6Settings.Route(destination, prefix, gateway))
}
ipv6 = IPv6Settings(
address: address6,
addressPrefixLength: addressPrefix6,
defaultGateway: defaultGateway6,
routes: routes6
)
} else {
ipv6 = nil
}
// MARK: DNS
Regex.dns.enumerateArguments(in: message) {
dnsServers.append($0[1])
}
// MARK: Compression
Regex.comp.enumerateComponents(in: message) {
switch $0[0] {
case "comp-lzo":
compressionFraming = .compLZO
if ($0.count == 2) && ($0[1] == "no") {
compressionAlgorithm = .disabled
} else {
compressionAlgorithm = .LZO
}
case "compress":
compressionFraming = .compress
if $0.count == 1 {
compressionAlgorithm = .disabled
} else if ($0.count == 2) && ($0[1] == "lzo") {
compressionAlgorithm = .LZO
} else {
compressionAlgorithm = .other
}
default:
break
}
}
// MARK: Keep-alive
Regex.ping.enumerateArguments(in: message) {
ping = Int($0[0])
}
// MARK: Authentication
Regex.authToken.enumerateArguments(in: message) {
authToken = $0[0]
}
Regex.peerId.enumerateArguments(in: message) {
peerId = UInt32($0[0])
}
// MARK: NCP
Regex.cipher.enumerateArguments(in: message) {
cipher = SessionProxy.Cipher(rawValue: $0[0].uppercased())
}
self.dnsServers = dnsServers
self.compressionFraming = compressionFraming
self.compressionAlgorithm = compressionAlgorithm
self.ping = ping
self.authToken = authToken
self.peerId = peerId
self.cipher = cipher
}
// MARK: CustomStringConvertible
var description: String {
let stripped = NSMutableString(string: original)
Regex.authToken.replaceMatches(
in: stripped,
options: [],
range: NSMakeRange(0, stripped.length),
withTemplate: "auth-token"
)
return stripped as String
}
}
}

View File

@ -0,0 +1,84 @@
//
// SessionProxy+SessionReply.swift
// TunnelKit
//
// Created by Davide De Rosa on 7/25/18.
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
//
// https://github.com/keeshux
//
// 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.
//
//
import Foundation
/// Groups the parsed reply of a successfully started session.
public protocol SessionReply {
/// The returned options.
var options: OptionsBundle { get }
}
extension SessionProxy {
// XXX: parsing is very optimistic
struct PushReply: SessionReply, CustomStringConvertible {
private static let prefix = "PUSH_REPLY,"
private let original: String
let options: OptionsBundle
init?(message: String) throws {
guard message.hasPrefix(PushReply.prefix) else {
return nil
}
guard let prefixIndex = message.range(of: PushReply.prefix)?.lowerBound else {
return nil
}
original = String(message[prefixIndex...])
let lines = original.components(separatedBy: ",")
options = try OptionsBundle(from: lines)
}
// MARK: CustomStringConvertible
var description: String {
let stripped = NSMutableString(string: original)
OptionsBundle.Regex.authToken.replaceMatches(
in: stripped,
options: [],
range: NSMakeRange(0, stripped.length),
withTemplate: "auth-token"
)
return stripped as String
}
}
}

View File

@ -86,7 +86,7 @@ public class SessionProxy {
private var keepAliveInterval: TimeInterval? {
let interval: TimeInterval?
if let negInterval = pushReply?.ping, negInterval > 0 {
if let negInterval = pushReply?.options.keepAliveSeconds, negInterval > 0 {
interval = TimeInterval(negInterval)
} else if let cfgInterval = configuration.keepAliveInterval, cfgInterval > 0.0 {
interval = cfgInterval
@ -276,7 +276,7 @@ public class SessionProxy {
- Seealso: `canRebindLink()`.
*/
public func rebindLink(_ link: LinkInterface) {
guard let _ = pushReply?.peerId else {
guard let _ = pushReply?.options.peerId else {
log.warning("Session doesn't support link rebinding!")
return
}
@ -666,7 +666,7 @@ public class SessionProxy {
negotiationKey.controlState = .preAuth
do {
authenticator = try Authenticator(credentials?.username, pushReply?.authToken ?? credentials?.password)
authenticator = try Authenticator(credentials?.username, pushReply?.options.authToken ?? credentials?.password)
try authenticator?.putAuth(into: negotiationKey.tls)
} catch let e {
deferStop(.shutdown, e)
@ -919,7 +919,7 @@ public class SessionProxy {
reply = optionalReply
log.debug("Received PUSH_REPLY: \"\(reply.maskedDescription)\"")
if let framing = reply.compressionFraming, let compression = reply.compressionAlgorithm {
if let framing = reply.options.compressionFraming, let compression = reply.options.compressionAlgorithm {
switch compression {
case .disabled:
break
@ -1036,18 +1036,18 @@ public class SessionProxy {
log.debug("Set up encryption")
}
let pushedFraming = pushReply.compressionFraming
let pushedFraming = pushReply.options.compressionFraming
if let negFraming = pushedFraming {
log.info("\tNegotiated compression framing: \(negFraming)")
}
let pushedCompression = pushReply.compressionAlgorithm
let pushedCompression = pushReply.options.compressionAlgorithm
if let negCompression = pushedCompression {
log.info("\tNegotiated compression algorithm: \(negCompression)")
}
if let negPing = pushReply.ping {
if let negPing = pushReply.options.keepAliveSeconds {
log.info("\tNegotiated keep-alive: \(negPing) seconds")
}
let pushedCipher = pushReply.cipher
let pushedCipher = pushReply.options.cipher
if let negCipher = pushedCipher {
log.info("\tNegotiated cipher: \(negCipher.rawValue)")
}
@ -1069,7 +1069,7 @@ public class SessionProxy {
negotiationKey.dataPath = DataPath(
encrypter: bridge.encrypter(),
decrypter: bridge.decrypter(),
peerId: pushReply.peerId ?? PacketPeerIdDisabled,
peerId: pushReply.options.peerId ?? PacketPeerIdDisabled,
compressionFraming: (pushedFraming ?? configuration.compressionFraming).native,
compressionAlgorithm: (pushedCompression ?? configuration.compressionAlgorithm ?? .disabled).native,
maxPackets: link?.packetBufferSize ?? 200,

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.5.3</string>
<string>1.6.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.5.3</string>
<string>1.6.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.5.3</string>
<string>1.6.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>

View File

@ -27,8 +27,6 @@ import XCTest
import TunnelKit
class ConfigurationParserTests: XCTestCase {
let base: [String] = ["<ca>", "</ca>", "remote 1.2.3.4"]
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
@ -56,30 +54,6 @@ class ConfigurationParserTests: XCTestCase {
print(stripped)
}
func testCompression() throws {
// XCTAssertNotNil(try ConfigurationParser.parsed(fromLines: base + ["comp-lzo"]).warning)
XCTAssertNil(try ConfigurationParser.parsed(fromLines: base + ["comp-lzo"]).warning)
XCTAssertNoThrow(try ConfigurationParser.parsed(fromLines: base + ["comp-lzo no"]))
XCTAssertNoThrow(try ConfigurationParser.parsed(fromLines: base + ["comp-lzo yes"]))
// XCTAssertThrowsError(try ConfigurationParser.parsed(fromLines: base + ["comp-lzo yes"]))
XCTAssertNoThrow(try ConfigurationParser.parsed(fromLines: base + ["compress"]))
XCTAssertNoThrow(try ConfigurationParser.parsed(fromLines: base + ["compress lzo"]))
}
func testDHCPOption() throws {
let lines = base + ["dhcp-option DNS 8.8.8.8", "dhcp-option DNS6 ffff::1"]
XCTAssertNoThrow(try ConfigurationParser.parsed(fromLines: lines))
let parsed = try! ConfigurationParser.parsed(fromLines: lines)
XCTAssertEqual(parsed.configuration.dnsServers, ["8.8.8.8", "ffff::1"])
}
func testConnectionBlock() throws {
let lines = base + ["<connection>", "</connection>"]
XCTAssertThrowsError(try ConfigurationParser.parsed(fromLines: lines))
}
func testEncryptedCertificateKey() throws {
try privateTestEncryptedCertificateKey(pkcs: "1")
try privateTestEncryptedCertificateKey(pkcs: "8")

View File

@ -0,0 +1,65 @@
//
// OptionsBundleTests.swift
// TunnelKitTests
//
// Created by Davide De Rosa on 4/3/19.
// Copyright (c) 2019 Davide De Rosa. All rights reserved.
//
// https://github.com/keeshux
//
// 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/>.
//
import XCTest
import TunnelKit
class OptionsBundleTests: XCTestCase {
let base: [String] = ["<ca>", "</ca>", "remote 1.2.3.4"]
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCompression() throws {
// XCTAssertNotNil(try OptionsBundle.parsed(fromLines: base + ["comp-lzo"]).warning)
XCTAssertNil(try OptionsBundle(from: base + ["comp-lzo"]).warning)
XCTAssertNoThrow(try OptionsBundle(from: base + ["comp-lzo no"]))
XCTAssertNoThrow(try OptionsBundle(from: base + ["comp-lzo yes"]))
// XCTAssertThrowsError(try OptionsBundle(from: base + ["comp-lzo yes"]))
XCTAssertNoThrow(try OptionsBundle(from: base + ["compress"]))
XCTAssertNoThrow(try OptionsBundle(from: base + ["compress lzo"]))
}
func testDHCPOption() throws {
let lines = base + ["dhcp-option DNS 8.8.8.8", "dhcp-option DNS6 ffff::1"]
XCTAssertNoThrow(try OptionsBundle(from: lines))
let parsed = try! OptionsBundle(from: lines)
XCTAssertEqual(parsed.dnsServers, ["8.8.8.8", "ffff::1"])
}
func testConnectionBlock() throws {
let lines = base + ["<connection>", "</connection>"]
XCTAssertThrowsError(try OptionsBundle(from: lines))
}
}

View File

@ -28,11 +28,11 @@ import XCTest
private extension SessionReply {
func debug() {
print("Compression framing: \(compressionFraming?.description ?? "none")")
print("Compression algorithm: \(compressionAlgorithm?.description ?? "none")")
print("IPv4: \(ipv4?.description ?? "none")")
print("IPv6: \(ipv6?.description ?? "none")")
print("DNS: \(dnsServers)")
print("Compression framing: \(options.compressionFraming?.description ?? "none")")
print("Compression algorithm: \(options.compressionAlgorithm?.description ?? "none")")
print("IPv4: \(options.ipv4?.description ?? "none")")
print("IPv6: \(options.ipv6?.description ?? "none")")
print("DNS: \(options.dnsServers)")
}
}
@ -51,10 +51,10 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.ipv4?.address, "10.5.10.6")
XCTAssertEqual(reply.ipv4?.addressMask, "255.255.255.255")
XCTAssertEqual(reply.ipv4?.defaultGateway, "10.5.10.5")
XCTAssertEqual(reply.dnsServers, ["209.222.18.222", "209.222.18.218"])
XCTAssertEqual(reply.options.ipv4?.address, "10.5.10.6")
XCTAssertEqual(reply.options.ipv4?.addressMask, "255.255.255.255")
XCTAssertEqual(reply.options.ipv4?.defaultGateway, "10.5.10.5")
XCTAssertEqual(reply.options.dnsServers, ["209.222.18.222", "209.222.18.218"])
}
func testSubnet() {
@ -62,10 +62,10 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.ipv4?.address, "10.8.0.2")
XCTAssertEqual(reply.ipv4?.addressMask, "255.255.255.0")
XCTAssertEqual(reply.ipv4?.defaultGateway, "10.8.0.1")
XCTAssertEqual(reply.dnsServers, ["8.8.8.8", "4.4.4.4"])
XCTAssertEqual(reply.options.ipv4?.address, "10.8.0.2")
XCTAssertEqual(reply.options.ipv4?.addressMask, "255.255.255.0")
XCTAssertEqual(reply.options.ipv4?.defaultGateway, "10.8.0.1")
XCTAssertEqual(reply.options.dnsServers, ["8.8.8.8", "4.4.4.4"])
}
func testRoute() {
@ -73,7 +73,7 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
let route = reply.ipv4!.routes.first!
let route = reply.options.ipv4!.routes.first!
XCTAssertEqual(route.destination, "192.168.0.0")
XCTAssertEqual(route.mask, "255.255.255.0")
@ -85,13 +85,13 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.ipv4?.address, "10.8.0.2")
XCTAssertEqual(reply.ipv4?.addressMask, "255.255.255.0")
XCTAssertEqual(reply.ipv4?.defaultGateway, "10.8.0.1")
XCTAssertEqual(reply.ipv6?.address, "fe80::601:30ff:feb7:ec01")
XCTAssertEqual(reply.ipv6?.addressPrefixLength, 64)
XCTAssertEqual(reply.ipv6?.defaultGateway, "fe80::601:30ff:feb7:dc02")
XCTAssertEqual(reply.dnsServers, ["2001:4860:4860::8888", "2001:4860:4860::8844"])
XCTAssertEqual(reply.options.ipv4?.address, "10.8.0.2")
XCTAssertEqual(reply.options.ipv4?.addressMask, "255.255.255.0")
XCTAssertEqual(reply.options.ipv4?.defaultGateway, "10.8.0.1")
XCTAssertEqual(reply.options.ipv6?.address, "fe80::601:30ff:feb7:ec01")
XCTAssertEqual(reply.options.ipv6?.addressPrefixLength, 64)
XCTAssertEqual(reply.options.ipv6?.defaultGateway, "fe80::601:30ff:feb7:dc02")
XCTAssertEqual(reply.options.dnsServers, ["2001:4860:4860::8888", "2001:4860:4860::8844"])
}
func testCompressionFraming() {
@ -99,7 +99,7 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compLZO)
XCTAssertEqual(reply.options.compressionFraming, .compLZO)
}
func testCompression() {
@ -108,28 +108,28 @@ class PushTests: XCTestCase {
reply = try! SessionProxy.PushReply(message: msg.appending(",comp-lzo no"))!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compLZO)
XCTAssertEqual(reply.compressionAlgorithm, .disabled)
XCTAssertEqual(reply.options.compressionFraming, .compLZO)
XCTAssertEqual(reply.options.compressionAlgorithm, .disabled)
reply = try! SessionProxy.PushReply(message: msg.appending(",comp-lzo"))!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compLZO)
XCTAssertEqual(reply.compressionAlgorithm, .LZO)
XCTAssertEqual(reply.options.compressionFraming, .compLZO)
XCTAssertEqual(reply.options.compressionAlgorithm, .LZO)
reply = try! SessionProxy.PushReply(message: msg.appending(",comp-lzo yes"))!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compLZO)
XCTAssertEqual(reply.compressionAlgorithm, .LZO)
XCTAssertEqual(reply.options.compressionFraming, .compLZO)
XCTAssertEqual(reply.options.compressionAlgorithm, .LZO)
reply = try! SessionProxy.PushReply(message: msg.appending(",compress"))!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compress)
XCTAssertEqual(reply.compressionAlgorithm, .disabled)
XCTAssertEqual(reply.options.compressionFraming, .compress)
XCTAssertEqual(reply.options.compressionAlgorithm, .disabled)
reply = try! SessionProxy.PushReply(message: msg.appending(",compress lz4"))!
reply.debug()
XCTAssertEqual(reply.compressionFraming, .compress)
XCTAssertEqual(reply.compressionAlgorithm, .other)
XCTAssertEqual(reply.options.compressionFraming, .compress)
XCTAssertEqual(reply.options.compressionAlgorithm, .other)
}
func testNCP() {
@ -137,7 +137,7 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.cipher, .aes256gcm)
XCTAssertEqual(reply.options.cipher, .aes256gcm)
}
func testNCPTrailing() {
@ -145,7 +145,7 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.cipher, .aes256gcm)
XCTAssertEqual(reply.options.cipher, .aes256gcm)
}
func testPing() {
@ -153,6 +153,6 @@ class PushTests: XCTestCase {
let reply = try! SessionProxy.PushReply(message: msg)!
reply.debug()
XCTAssertEqual(reply.ping, 10)
XCTAssertEqual(reply.options.keepAliveSeconds, 10)
}
}