2018-06-22 06:23:39 +00:00
|
|
|
//
|
2018-10-30 02:57:35 +00:00
|
|
|
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
|
2018-06-22 06:23:39 +00:00
|
|
|
//
|
|
|
|
|
|
|
|
import NetworkExtension
|
2018-07-07 20:54:44 +00:00
|
|
|
import os.log
|
2018-06-22 06:23:39 +00:00
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
enum PacketTunnelProviderError: Error {
|
2018-10-27 09:32:32 +00:00
|
|
|
case invalidOptions
|
|
|
|
case couldNotStartWireGuard
|
|
|
|
case coultNotSetNetworkSettings
|
2018-08-03 20:24:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A packet tunnel provider object.
|
2018-06-22 06:23:39 +00:00
|
|
|
class PacketTunnelProvider: NEPacketTunnelProvider {
|
2018-08-03 20:24:41 +00:00
|
|
|
|
|
|
|
// MARK: Properties
|
|
|
|
|
2018-09-26 09:22:54 +00:00
|
|
|
private var wgHandle: Int32?
|
|
|
|
private var wgContext: WireGuardContext?
|
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
// MARK: NEPacketTunnelProvider
|
2018-06-22 06:23:39 +00:00
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
/// Begin the process of establishing the tunnel.
|
2018-10-27 09:32:32 +00:00
|
|
|
override func startTunnel(options: [String: NSObject]?,
|
|
|
|
completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
|
|
|
|
os_log("Starting tunnel", log: OSLog.default, type: .info)
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
guard let options = options else {
|
2018-10-30 11:24:16 +00:00
|
|
|
os_log("Starting tunnel failed: No options passed", log: OSLog.default, type: .error)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.invalidOptions)
|
2018-08-27 20:32:47 +00:00
|
|
|
return
|
|
|
|
}
|
2018-08-16 19:26:24 +00:00
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
guard let interfaceName = options[.interfaceName] as? String,
|
|
|
|
let wireguardSettings = options[.wireguardSettings] as? String,
|
|
|
|
let remoteAddress = options[.remoteAddress] as? String,
|
|
|
|
let dnsServers = options[.dnsServers] as? [String],
|
|
|
|
let mtu = options[.mtu] as? NSNumber,
|
|
|
|
|
|
|
|
// IPv4 settings
|
|
|
|
let ipv4Addresses = options[.ipv4Addresses] as? [String],
|
|
|
|
let ipv4SubnetMasks = options[.ipv4SubnetMasks] as? [String],
|
|
|
|
let ipv4IncludedRouteAddresses = options[.ipv4IncludedRouteAddresses] as? [String],
|
|
|
|
let ipv4IncludedRouteSubnetMasks = options[.ipv4IncludedRouteSubnetMasks] as? [String],
|
|
|
|
let ipv4ExcludedRouteAddresses = options[.ipv4ExcludedRouteAddresses] as? [String],
|
|
|
|
let ipv4ExcludedRouteSubnetMasks = options[.ipv4ExcludedRouteSubnetMasks] as? [String],
|
|
|
|
|
|
|
|
// IPv6 settings
|
|
|
|
let ipv6Addresses = options[.ipv6Addresses] as? [String],
|
|
|
|
let ipv6NetworkPrefixLengths = options[.ipv6NetworkPrefixLengths] as? [NSNumber],
|
|
|
|
let ipv6IncludedRouteAddresses = options[.ipv6IncludedRouteAddresses] as? [String],
|
|
|
|
let ipv6IncludedRouteNetworkPrefixLengths = options[.ipv6IncludedRouteNetworkPrefixLengths] as? [NSNumber],
|
|
|
|
let ipv6ExcludedRouteAddresses = options[.ipv6ExcludedRouteAddresses] as? [String],
|
|
|
|
let ipv6ExcludedRouteNetworkPrefixLengths = options[.ipv6ExcludedRouteNetworkPrefixLengths] as? [NSNumber]
|
|
|
|
|
|
|
|
else {
|
2018-10-30 11:24:16 +00:00
|
|
|
os_log("Starting tunnel failed: Invalid options passed", log: OSLog.default, type: .error)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.invalidOptions)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-08-28 12:03:53 +00:00
|
|
|
configureLogger()
|
2018-09-02 21:23:30 +00:00
|
|
|
wgContext = WireGuardContext(packetFlow: self.packetFlow)
|
2018-08-27 20:32:47 +00:00
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
let handle = connect(interfaceName: interfaceName, settings: wireguardSettings, mtu: mtu.uint16Value)
|
2018-08-05 20:58:48 +00:00
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
if handle < 0 {
|
2018-10-30 11:24:16 +00:00
|
|
|
os_log("Starting tunnel failed: Could not start WireGuard", log: OSLog.default, type: .error)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotStartWireGuard)
|
2018-08-27 20:32:47 +00:00
|
|
|
return
|
|
|
|
}
|
2018-08-15 20:57:40 +00:00
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
wgHandle = handle
|
2018-08-15 20:57:40 +00:00
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
// Network settings
|
|
|
|
let networkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress)
|
2018-08-12 19:44:53 +00:00
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
// IPv4 settings
|
2018-10-27 09:32:32 +00:00
|
|
|
let ipv4Settings = NEIPv4Settings(addresses: ipv4Addresses, subnetMasks: ipv4SubnetMasks)
|
|
|
|
assert(ipv4IncludedRouteAddresses.count == ipv4IncludedRouteSubnetMasks.count)
|
|
|
|
ipv4Settings.includedRoutes = zip(ipv4IncludedRouteAddresses, ipv4IncludedRouteSubnetMasks).map {
|
|
|
|
NEIPv4Route(destinationAddress: $0.0, subnetMask: $0.1)
|
|
|
|
}
|
|
|
|
assert(ipv4ExcludedRouteAddresses.count == ipv4ExcludedRouteSubnetMasks.count)
|
|
|
|
ipv4Settings.excludedRoutes = zip(ipv4ExcludedRouteAddresses, ipv4ExcludedRouteSubnetMasks).map {
|
|
|
|
NEIPv4Route(destinationAddress: $0.0, subnetMask: $0.1)
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-10-27 09:32:32 +00:00
|
|
|
networkSettings.ipv4Settings = ipv4Settings
|
2018-08-27 20:32:47 +00:00
|
|
|
|
|
|
|
// IPv6 settings
|
2018-10-27 09:32:32 +00:00
|
|
|
let ipv6Settings = NEIPv6Settings(addresses: ipv6Addresses, networkPrefixLengths: ipv6NetworkPrefixLengths)
|
|
|
|
assert(ipv6IncludedRouteAddresses.count == ipv6IncludedRouteNetworkPrefixLengths.count)
|
|
|
|
ipv6Settings.includedRoutes = zip(ipv6IncludedRouteAddresses, ipv6IncludedRouteNetworkPrefixLengths).map {
|
|
|
|
NEIPv6Route(destinationAddress: $0.0, networkPrefixLength: $0.1)
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-10-27 09:32:32 +00:00
|
|
|
assert(ipv6ExcludedRouteAddresses.count == ipv6ExcludedRouteNetworkPrefixLengths.count)
|
|
|
|
ipv6Settings.excludedRoutes = zip(ipv6ExcludedRouteAddresses, ipv6ExcludedRouteNetworkPrefixLengths).map {
|
|
|
|
NEIPv6Route(destinationAddress: $0.0, networkPrefixLength: $0.1)
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
2018-10-27 09:32:32 +00:00
|
|
|
networkSettings.ipv6Settings = ipv6Settings
|
|
|
|
|
|
|
|
// DNS
|
|
|
|
networkSettings.dnsSettings = NEDNSSettings(servers: dnsServers)
|
|
|
|
|
|
|
|
// MTU
|
|
|
|
if (mtu == 0) {
|
|
|
|
// 0 imples automatic MTU, where we set overhead as 95 bytes,
|
|
|
|
// 80 for WireGuard and the 15 to make sure WireGuard's padding will work.
|
|
|
|
networkSettings.tunnelOverheadBytes = 95
|
|
|
|
} else {
|
|
|
|
networkSettings.mtu = mtu
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
setTunnelNetworkSettings(networkSettings) { (error) in
|
2018-08-27 20:32:47 +00:00
|
|
|
if let error = error {
|
2018-10-30 11:24:16 +00:00
|
|
|
os_log("Starting tunnel failed: Error setting network settings: %s", log: OSLog.default, type: .error, error.localizedDescription)
|
2018-10-27 09:32:32 +00:00
|
|
|
startTunnelCompletionHandler(PacketTunnelProviderError.coultNotSetNetworkSettings)
|
2018-08-27 20:32:47 +00:00
|
|
|
} else {
|
|
|
|
startTunnelCompletionHandler(nil /* No errors */)
|
|
|
|
}
|
2018-07-07 20:54:44 +00:00
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
|
|
|
|
2018-08-03 20:24:41 +00:00
|
|
|
/// Begin the process of stopping the tunnel.
|
2018-06-22 06:23:39 +00:00
|
|
|
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
|
2018-10-27 09:32:32 +00:00
|
|
|
os_log("Stopping tunnel", log: OSLog.default, type: .info)
|
2018-08-27 20:32:47 +00:00
|
|
|
if let handle = wgHandle {
|
|
|
|
wgTurnOff(handle)
|
|
|
|
}
|
|
|
|
wgContext?.closeTunnel()
|
2018-06-22 06:23:39 +00:00
|
|
|
completionHandler()
|
|
|
|
}
|
|
|
|
|
2018-08-28 12:03:53 +00:00
|
|
|
private func configureLogger() {
|
|
|
|
wgSetLogger { (level, tagCStr, msgCStr) in
|
|
|
|
let logType: OSLogType
|
|
|
|
switch level {
|
|
|
|
case 0:
|
|
|
|
logType = .debug
|
|
|
|
case 1:
|
|
|
|
logType = .info
|
|
|
|
case 2:
|
|
|
|
logType = .error
|
|
|
|
default:
|
|
|
|
logType = .default
|
|
|
|
}
|
|
|
|
let tag = (tagCStr != nil) ? String(cString: tagCStr!) : ""
|
|
|
|
let msg = (msgCStr != nil) ? String(cString: msgCStr!) : ""
|
2018-10-27 09:32:32 +00:00
|
|
|
os_log("wg log: %{public}s: %{public}s", log: OSLog.default, type: logType, tag, msg)
|
2018-08-28 12:03:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-27 09:32:32 +00:00
|
|
|
private func connect(interfaceName: String, settings: String, mtu: UInt16) -> Int32 { // swiftlint:disable:this cyclomatic_complexity
|
2018-08-28 12:04:38 +00:00
|
|
|
return withStringsAsGoStrings(interfaceName, settings) { (nameGoStr, settingsGoStr) -> Int32 in
|
|
|
|
return withUnsafeMutablePointer(to: &wgContext) { (wgCtxPtr) -> Int32 in
|
2018-10-27 09:32:32 +00:00
|
|
|
return wgTurnOn(nameGoStr, settingsGoStr, mtu, { (wgCtxPtr, buf, len) -> Int in
|
2018-09-25 00:35:01 +00:00
|
|
|
autoreleasepool {
|
2018-09-16 20:43:40 +00:00
|
|
|
// read_fn: Read from the TUN interface and pass it on to WireGuard
|
2018-08-28 12:04:38 +00:00
|
|
|
guard let wgCtxPtr = wgCtxPtr else { return 0 }
|
|
|
|
guard let buf = buf else { return 0 }
|
|
|
|
let wgContext = wgCtxPtr.bindMemory(to: WireGuardContext.self, capacity: 1).pointee
|
|
|
|
var isTunnelClosed = false
|
|
|
|
guard let packet = wgContext.readPacket(isTunnelClosed: &isTunnelClosed) else { return 0 }
|
|
|
|
if isTunnelClosed { return -1 }
|
|
|
|
let packetData = packet.data
|
|
|
|
if packetData.count <= len {
|
|
|
|
packetData.copyBytes(to: buf, count: packetData.count)
|
|
|
|
return packetData.count
|
|
|
|
}
|
|
|
|
return 0
|
2018-09-25 00:35:01 +00:00
|
|
|
}
|
2018-09-18 19:47:43 +00:00
|
|
|
}, { (wgCtxPtr, buf, len) -> Int in
|
2018-09-25 00:35:01 +00:00
|
|
|
autoreleasepool {
|
2018-09-16 20:43:40 +00:00
|
|
|
// write_fn: Receive packets from WireGuard and write to the TUN interface
|
2018-08-28 12:04:38 +00:00
|
|
|
guard let wgCtxPtr = wgCtxPtr else { return 0 }
|
|
|
|
guard let buf = buf else { return 0 }
|
|
|
|
guard len > 0 else { return 0 }
|
|
|
|
let wgContext = wgCtxPtr.bindMemory(to: WireGuardContext.self, capacity: 1).pointee
|
|
|
|
let ipVersionBits = (buf[0] & 0xf0) >> 4
|
|
|
|
let ipVersion: sa_family_t? = {
|
|
|
|
if ipVersionBits == 4 { return sa_family_t(AF_INET) } // IPv4
|
|
|
|
if ipVersionBits == 6 { return sa_family_t(AF_INET6) } // IPv6
|
|
|
|
return nil
|
|
|
|
}()
|
|
|
|
guard let protocolFamily = ipVersion else { fatalError("Unknown IP version") }
|
|
|
|
let packet = NEPacket(data: Data(bytes: buf, count: len), protocolFamily: protocolFamily)
|
|
|
|
var isTunnelClosed = false
|
|
|
|
let isWritten = wgContext.writePacket(packet: packet, isTunnelClosed: &isTunnelClosed)
|
|
|
|
if isTunnelClosed { return -1 }
|
|
|
|
if isWritten {
|
|
|
|
return len
|
|
|
|
}
|
|
|
|
return 0
|
2018-09-25 00:35:01 +00:00
|
|
|
}
|
2018-08-28 12:04:38 +00:00
|
|
|
},
|
|
|
|
wgCtxPtr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-06-22 06:23:39 +00:00
|
|
|
}
|
2018-08-27 20:32:47 +00:00
|
|
|
|
|
|
|
class WireGuardContext {
|
|
|
|
private var packetFlow: NEPacketTunnelFlow
|
|
|
|
private var outboundPackets: [NEPacket] = []
|
|
|
|
private var isTunnelClosed: Bool = false
|
2018-09-24 01:08:18 +00:00
|
|
|
private var readPacketCondition = NSCondition()
|
2018-08-27 20:32:47 +00:00
|
|
|
|
|
|
|
init(packetFlow: NEPacketTunnelFlow) {
|
|
|
|
self.packetFlow = packetFlow
|
|
|
|
}
|
|
|
|
|
|
|
|
func closeTunnel() {
|
|
|
|
isTunnelClosed = true
|
|
|
|
readPacketCondition.signal()
|
|
|
|
}
|
|
|
|
|
2018-09-22 02:10:31 +00:00
|
|
|
func packetsRead(packets: [NEPacket]) {
|
2018-09-24 01:08:18 +00:00
|
|
|
readPacketCondition.lock()
|
2018-09-22 02:10:31 +00:00
|
|
|
outboundPackets.append(contentsOf: packets)
|
2018-09-24 01:08:18 +00:00
|
|
|
readPacketCondition.unlock()
|
2018-09-22 02:10:31 +00:00
|
|
|
readPacketCondition.signal()
|
|
|
|
}
|
|
|
|
|
2018-08-27 20:32:47 +00:00
|
|
|
func readPacket(isTunnelClosed: inout Bool) -> NEPacket? {
|
|
|
|
if outboundPackets.isEmpty {
|
|
|
|
readPacketCondition.lock()
|
2018-09-22 02:10:31 +00:00
|
|
|
packetFlow.readPacketObjects(completionHandler: packetsRead)
|
|
|
|
while outboundPackets.isEmpty && !self.isTunnelClosed {
|
2018-08-27 20:32:47 +00:00
|
|
|
readPacketCondition.wait()
|
|
|
|
}
|
|
|
|
readPacketCondition.unlock()
|
|
|
|
}
|
|
|
|
isTunnelClosed = self.isTunnelClosed
|
2018-09-25 00:35:01 +00:00
|
|
|
if !outboundPackets.isEmpty {
|
2018-08-27 20:32:47 +00:00
|
|
|
return outboundPackets.removeFirst()
|
|
|
|
}
|
2018-09-25 00:35:01 +00:00
|
|
|
return nil
|
2018-08-27 20:32:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func writePacket(packet: NEPacket, isTunnelClosed: inout Bool) -> Bool {
|
|
|
|
isTunnelClosed = self.isTunnelClosed
|
|
|
|
return packetFlow.writePacketObjects([packet])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func withStringsAsGoStrings<R>(_ str1: String, _ str2: String, closure: (gostring_t, gostring_t) -> R) -> R {
|
|
|
|
return str1.withCString { (s1cStr) -> R in
|
|
|
|
let gstr1 = gostring_t(p: s1cStr, n: str1.utf8.count)
|
|
|
|
return str2.withCString { (s2cStr) -> R in
|
|
|
|
let gstr2 = gostring_t(p: s2cStr, n: str2.utf8.count)
|
|
|
|
return closure(gstr1, gstr2)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|