Initial merge of rc's work.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jeroen Leenarts 2018-08-27 22:32:47 +02:00
parent 2c3a36078e
commit 2e9a12c63f
8 changed files with 169 additions and 276 deletions

View File

@ -41,7 +41,6 @@
4AC5462E2116306F00749D21 /* Tunnel+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AC5462D2116306F00749D21 /* Tunnel+Extension.swift */; };
4AC5462F211643DE00749D21 /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4A61D83420D98D25006C7A76 /* NetworkExtension.framework */; };
4AD095C820DC4190000E9CF5 /* libwg-go.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4AD0900120DC4171000E9CF5 /* libwg-go.a */; };
4AD095CC20DC42CD000E9CF5 /* WireGuardGoWrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 4AD095CB20DC42CD000E9CF5 /* WireGuardGoWrapper.m */; };
4AEAC32920F14B3B007B67AB /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AEAC32820F14B3B007B67AB /* Log.swift */; };
4AEAC32B20F14BA9007B67AB /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AEAC32A20F14BA9007B67AB /* Log.swift */; };
5FA1D4CB21249F7D00DBA2E6 /* Peer+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5FA1D4CA21249F7D00DBA2E6 /* Peer+Extension.swift */; };
@ -126,8 +125,6 @@
4AD0900120DC4171000E9CF5 /* libwg-go.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libwg-go.a"; sourceTree = "<group>"; };
4AD0900720DC4171000E9CF5 /* wireguard.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = wireguard.h; sourceTree = "<group>"; };
4AD095C920DC42CD000E9CF5 /* WireGuardNetworkExtension-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "WireGuardNetworkExtension-Bridging-Header.h"; sourceTree = "<group>"; };
4AD095CA20DC42CD000E9CF5 /* WireGuardGoWrapper.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WireGuardGoWrapper.h; sourceTree = "<group>"; };
4AD095CB20DC42CD000E9CF5 /* WireGuardGoWrapper.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = WireGuardGoWrapper.m; sourceTree = "<group>"; };
4AEAC32820F14B3B007B67AB /* Log.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = "<group>"; };
4AEAC32A20F14BA9007B67AB /* Log.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = "<group>"; };
5FA1D4CA21249F7D00DBA2E6 /* Peer+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Peer+Extension.swift"; sourceTree = "<group>"; };
@ -277,8 +274,6 @@
4A61D82820D98CE2006C7A76 /* PacketTunnelProvider.swift */,
4A61D82A20D98CE2006C7A76 /* Info.plist */,
4A61D82B20D98CE2006C7A76 /* WireGuardNetworkExtension.entitlements */,
4AD095CA20DC42CD000E9CF5 /* WireGuardGoWrapper.h */,
4AD095CB20DC42CD000E9CF5 /* WireGuardGoWrapper.m */,
4AD095C920DC42CD000E9CF5 /* WireGuardNetworkExtension-Bridging-Header.h */,
4AEAC32820F14B3B007B67AB /* Log.swift */,
);
@ -611,7 +606,6 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
4AD095CC20DC42CD000E9CF5 /* WireGuardGoWrapper.m in Sources */,
4AC086852120BCB500CEE5ED /* ProviderConfigurationKeys.swift in Sources */,
4AC086862120BD5800CEE5ED /* PacketTunnelProvider.swift in Sources */,
4A43515A2124956200261999 /* Validators.swift in Sources */,

View File

@ -2,4 +2,4 @@
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#include "x25519.h"
#import "Crypto/x25519.h"

View File

@ -18,13 +18,13 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
// MARK: Properties
/// A reference to the WireGuard wrapper object.
let wireGuardWrapper = WireGuardGoWrapper()
var wgHandle: Int32?
var wgContext: WireGuardContext?
// MARK: NEPacketTunnelProvider
/// Begin the process of establishing the tunnel.
override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) {
override func startTunnel(options: [String: NSObject]?, completionHandler startTunnelCompletionHandler: @escaping (Error?) -> Void) {
os_log("Starting tunnel", log: Log.general, type: .info)
let config = self.protocolConfiguration as! NETunnelProviderProtocol // swiftlint:disable:this force_cast
@ -37,57 +37,120 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
let validatedEndpoints = endpoints.commaSeparatedToArray().compactMap { try? Endpoint(endpointString: String($0)) }.compactMap {$0}
let validatedAddresses = addresses.compactMap { try? CIDRAddress(stringRepresentation: String($0)) }.compactMap { $0 }
if let firstEndpoint = validatedEndpoints.first, wireGuardWrapper.turnOn(withInterfaceName: interfaceName, settingsString: settings) {
// We use the first endpoint for the ipAddress
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: firstEndpoint.ipAddress)
newSettings.tunnelOverheadBytes = 80
guard let firstEndpoint = validatedEndpoints.first else {
startTunnelCompletionHandler(PacketTunnelProviderError.tunnelSetupFailed)
return
// IPv4 settings
let validatedIPv4Addresses = validatedAddresses.filter { $0.addressType == .IPv4}
if validatedIPv4Addresses.count > 0 {
let ipv4Settings = NEIPv4Settings(addresses: validatedIPv4Addresses.map { $0.ipAddress }, subnetMasks: validatedIPv4Addresses.map { $0.subnetString })
ipv4Settings.includedRoutes = [NEIPv4Route.default()]
ipv4Settings.excludedRoutes = validatedEndpoints.filter { $0.addressType == .IPv4}.map {
NEIPv4Route(destinationAddress: $0.ipAddress, subnetMask: "255.255.255.255")}
}
newSettings.ipv4Settings = ipv4Settings
wgSetLogger { (level, tagCStr, msgCStr) in
let tag = (tagCStr != nil) ? String(cString: tagCStr!) : ""
let msg = (msgCStr != nil) ? String(cString: msgCStr!) : ""
NSLog("wg log: \(level): \(tag): \(msg)")
}
wgContext = WireGuardContext(packetFlow: self.packetFlow)
let handle = withStringsAsGoStrings(interfaceName, settings) { (nameGoStr, settingsGoStr) -> Int32 in
return withUnsafeMutablePointer(to: &wgContext) { (wgCtxPtr) -> Int32 in
return wgTurnOn(nameGoStr, settingsGoStr,
// read_fn: Read from the TUN interface and pass it on to WireGuard
{ (wgCtxPtr, buf, len) -> Int in
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
},
// write_fn: Receive packets from WireGuard and write to the TUN interface
{ (wgCtxPtr, buf, len) -> Int in
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
},
wgCtxPtr)
}
}
// IPv6 settings
let validatedIPv6Addresses = validatedAddresses.filter { $0.addressType == .IPv6}
if validatedIPv6Addresses.count > 0 {
let ipv6Settings = NEIPv6Settings(addresses: validatedIPv6Addresses.map { $0.ipAddress }, networkPrefixLengths: validatedIPv6Addresses.map { NSNumber(value: $0.subnet) })
ipv6Settings.includedRoutes = [NEIPv6Route.default()]
ipv6Settings.excludedRoutes = validatedEndpoints.filter { $0.addressType == .IPv6}.map { NEIPv6Route(destinationAddress: $0.ipAddress, networkPrefixLength: 0)}
if handle < 0 {
startTunnelCompletionHandler(PacketTunnelProviderError.tunnelSetupFailed)
return
}
newSettings.ipv6Settings = ipv6Settings
wgHandle = handle
// We use the first endpoint for the ipAddress
let newSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: firstEndpoint.ipAddress)
newSettings.tunnelOverheadBytes = 80
// IPv4 settings
let validatedIPv4Addresses = validatedAddresses.filter { $0.addressType == .IPv4}
if validatedIPv4Addresses.count > 0 {
let ipv4Settings = NEIPv4Settings(addresses: validatedIPv4Addresses.map { $0.ipAddress }, subnetMasks: validatedIPv4Addresses.map { $0.subnetString })
ipv4Settings.includedRoutes = [NEIPv4Route.default()]
ipv4Settings.excludedRoutes = validatedEndpoints.filter { $0.addressType == .IPv4}.map {
NEIPv4Route(destinationAddress: $0.ipAddress, subnetMask: "255.255.255.255")}
newSettings.ipv4Settings = ipv4Settings
}
// IPv6 settings
let validatedIPv6Addresses = validatedAddresses.filter { $0.addressType == .IPv6}
if validatedIPv6Addresses.count > 0 {
let ipv6Settings = NEIPv6Settings(addresses: validatedIPv6Addresses.map { $0.ipAddress }, networkPrefixLengths: validatedIPv6Addresses.map { NSNumber(value: $0.subnet) })
ipv6Settings.includedRoutes = [NEIPv6Route.default()]
ipv6Settings.excludedRoutes = validatedEndpoints.filter { $0.addressType == .IPv6}.map { NEIPv6Route(destinationAddress: $0.ipAddress, networkPrefixLength: 0)}
newSettings.ipv6Settings = ipv6Settings
}
if let dns = config.providerConfiguration?[PCKeys.dns.rawValue] as? String {
newSettings.dnsSettings = NEDNSSettings(servers: dns.commaSeparatedToArray())
}
if let mtu = mtu, mtu.intValue > 0 {
newSettings.mtu = mtu
}
setTunnelNetworkSettings(newSettings) { (error) in
if let error = error {
NSLog("Error setting network settings: \(error)")
startTunnelCompletionHandler(PacketTunnelProviderError.tunnelSetupFailed)
} else {
startTunnelCompletionHandler(nil /* No errors */)
}
if let dns = config.providerConfiguration?[PCKeys.dns.rawValue] as? String {
newSettings.dnsSettings = NEDNSSettings(servers: dns.commaSeparatedToArray())
}
if let mtu = mtu, mtu.intValue > 0 {
newSettings.mtu = mtu
}
setTunnelNetworkSettings(newSettings) { [weak self](error) in
self?.wireGuardWrapper.packetFlow = self?.packetFlow
self?.wireGuardWrapper.configured = true
self?.wireGuardWrapper.startReadingPackets()
completionHandler(error)
}
} else {
completionHandler(PacketTunnelProviderError.tunnelSetupFailed)
wireGuardWrapper.configured = false
}
}
/// Begin the process of stopping the tunnel.
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
os_log("Stopping tunnel", log: Log.general, type: .info)
wireGuardWrapper.turnOff()
if let handle = wgHandle {
wgTurnOff(handle)
}
wgContext?.closeTunnel()
completionHandler()
}
@ -104,3 +167,60 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
completionHandler?(responseData)
}
}
class WireGuardContext {
private var packetFlow: NEPacketTunnelFlow
private var outboundPackets: [NEPacket] = []
private var isTunnelClosed: Bool = false
private let readPacketCondition = NSCondition()
init(packetFlow: NEPacketTunnelFlow) {
self.packetFlow = packetFlow
}
func closeTunnel() {
isTunnelClosed = true
readPacketCondition.signal()
}
func readPacket(isTunnelClosed: inout Bool) -> NEPacket? {
if outboundPackets.isEmpty {
let readPacketCondition = NSCondition()
readPacketCondition.lock()
var packetsObtained: [NEPacket]?
packetFlow.readPacketObjects { (packets: [NEPacket]) in
packetsObtained = packets
readPacketCondition.signal()
}
// Wait till the completion handler of packetFlow.readPacketObjects() finishes
while packetsObtained == nil && !self.isTunnelClosed {
readPacketCondition.wait()
}
if let packetsObtained = packetsObtained {
outboundPackets = packetsObtained
}
readPacketCondition.unlock()
}
isTunnelClosed = self.isTunnelClosed
if outboundPackets.isEmpty {
return nil
} else {
return outboundPackets.removeFirst()
}
}
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)
}
}
}

View File

@ -1,24 +0,0 @@
//
// WireGuardGoWrapper.h
// WireGuardNetworkExtension
//
// Created by Jeroen Leenarts on 21-06-18.
// Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <NetworkExtension/NetworkExtension.h>
@interface WireGuardGoWrapper : NSObject
@property (nonatomic, strong) NEPacketTunnelFlow *packetFlow;
@property (nonatomic, assign) BOOL configured;
- (BOOL) turnOnWithInterfaceName: (NSString *)interfaceName settingsString: (NSString *)settingsString;
- (void) turnOff;
- (void) startReadingPackets;
+ (NSString *)versionWireGuardGo;
@end

View File

@ -1,197 +0,0 @@
//
// WireGuardGoWrapper.m
// WireGuardNetworkExtension
//
// Created by Jeroen Leenarts on 21-06-18.
// Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All rights reserved.
//
#include <os/log.h>
#include "wireguard.h"
#import "WireGuardGoWrapper.h"
/// Trampoline function
static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len);
/// Trampoline function
static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len);
/// Trampoline function
static void do_log(int level, const char *tag, const char *msg);
@interface WireGuardGoWrapper ()
@property (nonatomic, assign) int handle;
@property (nonatomic, assign) BOOL isClosed;
@property (nonatomic, strong) NSMutableArray<NSData *> *packets;
@property (nonatomic, strong) NSMutableArray<NSNumber *> *protocols;
@property (nonatomic, strong) dispatch_queue_t dispatchQueue;
@property (nonatomic, strong) NSCondition *condition;
@end
@implementation WireGuardGoWrapper
- (instancetype)init
{
self = [super init];
if (self) {
self.packets = [[NSMutableArray alloc]initWithCapacity:100];
self.handle = -1;
self.configured = false;
self.condition = [NSCondition new];
self.dispatchQueue = dispatch_queue_create("manager", NULL);
}
return self;
}
- (BOOL) turnOnWithInterfaceName: (NSString *)interfaceName settingsString: (NSString *)settingsString
{
os_log([WireGuardGoWrapper log], "WireGuard Go Version %{public}s", wgVersion());
wgSetLogger(do_log);
const char * ifName = [interfaceName UTF8String];
const char * settings = [settingsString UTF8String];
self.handle = wgTurnOn((gostring_t){ .p = ifName, .n = interfaceName.length }, (gostring_t){ .p = settings, .n = settingsString.length }, do_read, do_write, (__bridge void *)(self));
return self.handle >= 0;
}
- (void) turnOff
{
self.isClosed = YES;
self.configured = NO;
wgTurnOff(self.handle);
self.handle = -1;
}
- (void) startReadingPackets {
[self readPackets];
}
- (void) readPackets {
dispatch_async(self.dispatchQueue, ^{
if (self.isClosed || self.handle < 0 || !self.configured ) {
[self readPackets];
return;
}
os_log_debug([WireGuardGoWrapper log], "readPackets - read call - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
[self.packetFlow readPacketsWithCompletionHandler:^(NSArray<NSData *> * _Nonnull packets, NSArray<NSNumber *> * _Nonnull protocols) {
[self.condition lock];
@synchronized(self.packets) {
[self.packets addObjectsFromArray:packets];
[self.protocols addObjectsFromArray:protocols];
}
os_log_debug([WireGuardGoWrapper log], "readPackets - signal - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
[self.condition signal];
[self.condition unlock];
[self readPackets];
}];
});
}
+ (NSString *)versionWireGuardGo {
return [NSString stringWithUTF8String:wgVersion()];
}
+ (os_log_t)log {
static os_log_t subLog = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
subLog = os_log_create("com.wireguard.ios.WireGuard.WireGuardNetworkExtension", "WireGuard-Go");
});
return subLog;
}
@end
static ssize_t do_read(const void *ctx, const unsigned char *buf, size_t len)
{
@autoreleasepool {
os_log_debug([WireGuardGoWrapper log], "do_read - start - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
if (wrapper.isClosed) return -1;
if (wrapper.handle < 0 || !wrapper.configured ) {
os_log_debug([WireGuardGoWrapper log], "do_read - early - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
return 0;
}
NSData * __block packet = nil;
// NSNumber *protocol = nil;
dispatch_sync(wrapper.dispatchQueue, ^{
[wrapper.condition lock];
@synchronized(wrapper.packets) {
if (wrapper.packets.count == 0) {
os_log_debug([WireGuardGoWrapper log], "do_read - no packet - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
return;
}
packet = [wrapper.packets objectAtIndex:0];
// protocol = [wrapper.protocols objectAtIndex:0];
[wrapper.packets removeObjectAtIndex:0];
[wrapper.protocols removeObjectAtIndex:0];
}
});
if (packet == nil) {
os_log_debug([WireGuardGoWrapper log], "do_read - wait - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
[wrapper.condition wait];
[wrapper.condition unlock];
return 0;
} else {
[wrapper.condition unlock];
}
NSUInteger packetLength = [packet length];
if (packetLength > len) {
// The packet will be dropped when we end up here.
os_log_debug([WireGuardGoWrapper log], "do_read - drop - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
return 0;
}
memcpy(buf, [packet bytes], packetLength);
os_log_debug([WireGuardGoWrapper log], "do_read - packet - on thread \"%{public}@\" - %d", NSThread.currentThread.name, (int)NSThread.currentThread);
return packetLength;
}
}
static ssize_t do_write(const void *ctx, const unsigned char *buf, size_t len)
{
@autoreleasepool {
os_log_debug([WireGuardGoWrapper log], "do_write - start");
WireGuardGoWrapper *wrapper = (__bridge WireGuardGoWrapper *)ctx;
//determine IPv4 or IPv6 status.
NSInteger ipVersionBits = (buf[0] & 0xf0) >> 4;
NSNumber *ipVersion = NSDecimalNumber.zero;
if (ipVersionBits == 4) {
ipVersion = @AF_INET;
} else if (ipVersionBits == 6) {
ipVersion = @AF_INET6;
} else {
return 0;
}
NSData *packet = [[NSData alloc] initWithBytes:buf length:len];
[wrapper.packetFlow writePackets:@[packet] withProtocols:@[ipVersion]];
return len;
}
}
static void do_log(int level, const char *tag, const char *msg)
{
@autoreleasepool {
// TODO Get some details on the log level and distribute to matching log levels.
os_log([WireGuardGoWrapper log], "Log level %d for %{public}s: %{public}s", level, tag, msg);
}
}

View File

@ -2,5 +2,5 @@
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "WireGuardGoWrapper.h"
#include "wireguard.h"
#import "../wireguard-go-bridge/wireguard.h"

View File

@ -8,11 +8,11 @@
</array>
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.wireguard.ios.WireGuard</string>
<string>group.appforce1.test.com.wireguard.ios.WireGuard</string>
</array>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)com.wireguard.ios.WireGuard</string>
<string>$(AppIdentifierPrefix)appforce1.test.com.wireguard.ios.WireGuard</string>
</array>
</dict>
</plist>

View File

@ -9,11 +9,11 @@
#include <sys/types.h>
typedef struct { const char *p; size_t n; } gostring_t;
typedef ssize_t(*read_write_fn_t)(const void *ctx, const unsigned char *buf, size_t len);
typedef ssize_t(*read_write_fn_t)(void *ctx, unsigned char *buf, size_t len);
typedef void(*logger_fn_t)(int level, const char *tag, const char *msg);
extern void wgSetLogger(logger_fn_t logger_fn);
extern int wgTurnOn(gostring_t ifname, gostring_t settings, read_write_fn_t read_fn, read_write_fn_t write_fn, void *ctx);
extern void wgTurnOff(int handle);
extern char *wgVersion(void);
extern char *wgVersion();
#endif