commit b546dd1c9d4abe3e9a8074d5a003167669c810f0 Author: Nate Brown Date: Mon Jul 27 15:43:58 2020 -0500 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dcc3a05 --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Web related +lib/generated_plugin_registrant.dart + +# Exceptions to above rules. +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +/nebula/local.settings +/nebula/MobileNebula.framework/ +/nebula/mobileNebula-sources.jar +/nebula/vendor/ +/android/app/src/main/libs/mobileNebula.aar +/nebula/mobileNebula.aar +/android/key.properties +/env.sh +/lib/gen.versions.dart +/lib/.gen.versions.dart diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..01d2dcb --- /dev/null +++ b/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: 0b8abb4724aa590dd0f429683339b1e045a1594d + channel: stable + +project_type: app diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..e71e2bf --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,8 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +/build/build-attribution/ diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..cc25d96 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,102 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('key.properties') +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) +} + +android { + compileSdkVersion 28 + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + lintOptions { + disable 'InvalidPackage' + } + + defaultConfig { + applicationId "net.defined.mobile_nebula" + minSdkVersion 25 + targetSdkVersion 28 + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + } + + signingConfigs { + release { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['password'] + storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + storePassword keystoreProperties['password'] + } + } + + buildTypes { + release { + signingConfig signingConfigs.release + + // We are disabling minification and proguard because it wrecks the crypto for storing keys + // Ideally we would turn these on. We had issues with gson as well but resolved those with proguardFiles + minifyEnabled false + useProguard false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +flutter { + source '../..' +} + +repositories { + flatDir { + dirs 'src/main/libs' + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation "androidx.security:security-crypto:1.0.0-rc02" + implementation 'com.google.code.gson:gson:2.8.6' + + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test:runner:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' + implementation (name:'mobileNebula', ext:'aar') { + exec { + workingDir '../../' + environment("ANDROID_NDK_HOME", android.ndkDirectory) + environment("ANDROID_HOME", android.sdkDirectory) + commandLine './gen-artifacts.sh', 'android' + } + } +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..51a9fa3 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,11 @@ +# Flutter Wrapper - this came from guidance at https://medium.com/@swav.kulinski/flutter-and-android-obfuscation-8768ac544421 +-keep class io.flutter.app.** { *; } +-keep class io.flutter.plugin.** { *; } +-keep class io.flutter.util.** { *; } +-keep class io.flutter.view.** { *; } +-keep class io.flutter.** { *; } +-keep class io.flutter.plugins.** { *; } + +# Keep our class names for gson +-keep class net.defined.mobile_nebula.** { *; } +-keep class androidx.security.crypto.** { *; } \ No newline at end of file diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..bc4f1bf --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..8e4fc32 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/net/defined/mobile_nebula/EncFile.kt b/android/app/src/main/kotlin/net/defined/mobile_nebula/EncFile.kt new file mode 100644 index 0000000..581ddbd --- /dev/null +++ b/android/app/src/main/kotlin/net/defined/mobile_nebula/EncFile.kt @@ -0,0 +1,22 @@ +package net.defined.mobile_nebula + +import android.content.Context +import androidx.security.crypto.EncryptedFile +import androidx.security.crypto.MasterKeys +import java.io.* + +class EncFile(var context: Context) { + private val scheme = EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB + private val master: String = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC) + + fun openRead(file: File): BufferedReader { + val eFile = EncryptedFile.Builder(file, context, master, scheme).build() + return eFile.openFileInput().bufferedReader() + } + + fun openWrite(file: File): BufferedWriter { + val eFile = EncryptedFile.Builder(file, context, master, scheme).build() + return eFile.openFileOutput().bufferedWriter() + } + +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/net/defined/mobile_nebula/MainActivity.kt b/android/app/src/main/kotlin/net/defined/mobile_nebula/MainActivity.kt new file mode 100644 index 0000000..051450a --- /dev/null +++ b/android/app/src/main/kotlin/net/defined/mobile_nebula/MainActivity.kt @@ -0,0 +1,402 @@ +package net.defined.mobile_nebula + +import android.app.Activity +import android.content.ComponentName +import android.content.Intent +import android.content.ServiceConnection +import android.net.VpnService +import android.os.* +import androidx.annotation.NonNull; +import com.google.gson.Gson +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugins.GeneratedPluginRegistrant + +const val TAG = "nebula" +const val VPN_PERMISSIONS_CODE = 0x0F +const val VPN_START_CODE = 0x10 +const val CHANNEL = "net.defined.mobileNebula/NebulaVpnService" + +class MainActivity: FlutterActivity() { + private var sites: Sites? = null + private var permResult: MethodChannel.Result? = null + + private var inMessenger: Messenger? = Messenger(IncomingHandler()) + private var outMessenger: Messenger? = null + + private var activeSiteId: String? = null + + override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { + //TODO: Initializing in the constructor leads to a context lacking info we need, figure out the right way to do this + sites = Sites(context, flutterEngine) + + // Bind against our service to detect which site is running on app boot + val intent = Intent(this, NebulaVpnService::class.java) + bindService(intent, connection, 0) + + GeneratedPluginRegistrant.registerWith(flutterEngine); + + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> + when(call.method) { + "android.requestPermissions" -> androidPermissions(result) + + "nebula.parseCerts" -> nebulaParseCerts(call, result) + "nebula.generateKeyPair" -> nebulaGenerateKeyPair(result) + "nebula.renderConfig" -> nebulaRenderConfig(call, result) + + "listSites" -> listSites(result) + "deleteSite" -> deleteSite(call, result) + "saveSite" -> saveSite(call, result) + "startSite" -> startSite(call, result) + "stopSite" -> stopSite() + + "active.listHostmap" -> activeListHostmap(call, result) + "active.listPendingHostmap" -> activeListPendingHostmap(call, result) + "active.getHostInfo" -> activeGetHostInfo(call, result) + "active.setRemoteForTunnel" -> activeSetRemoteForTunnel(call, result) + "active.closeTunnel" -> activeCloseTunnel(call, result) + + else -> result.notImplemented() + } + } + } + + private fun nebulaParseCerts(call: MethodCall, result: MethodChannel.Result) { + val certs = call.argument("certs") + if (certs == "") { + return result.error("required_argument", "certs is a required argument", null) + } + + return try { + val json = mobileNebula.MobileNebula.parseCerts(certs) + result.success(json) + } catch (err: Exception) { + result.error("unhandled_error", err.message, null) + } + } + + private fun nebulaGenerateKeyPair(result: MethodChannel.Result) { + val kp = mobileNebula.MobileNebula.generateKeyPair() + return result.success(kp) + } + + private fun nebulaRenderConfig(call: MethodCall, result: MethodChannel.Result) { + val config = call.arguments as String + val yaml = mobileNebula.MobileNebula.renderConfig(config, "") + return result.success(yaml) + } + + private fun listSites(result: MethodChannel.Result) { + sites!!.refreshSites(activeSiteId) + val sites = sites!!.getSites() + val gson = Gson() + val json = gson.toJson(sites) + result.success(json) + } + + private fun deleteSite(call: MethodCall, result: MethodChannel.Result) { + val id = call.arguments as String + if (activeSiteId == id) { + stopSite() + } + sites!!.deleteSite(id) + result.success(null) + } + + private fun saveSite(call: MethodCall, result: MethodChannel.Result) { + val site: IncomingSite + try { + val gson = Gson() + site = gson.fromJson(call.arguments as String, IncomingSite::class.java) + site.save(context) + + } catch (err: Exception) { + //TODO: is toString the best or .message? + return result.error("failure", err.toString(), null) + } + + val siteDir = context.filesDir.resolve("sites").resolve(site.id) + try { + // Try to render a full site, if this fails the config was bad somehow + Site(siteDir) + } catch (err: Exception) { + siteDir.deleteRecursively() + return result.error("failure", "Site config was incomplete, please review and try again", null) + } + + result.success(null) + } + + private fun startSite(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + var siteContainer: SiteContainer = sites!!.getSite(id!!) ?: return result.error("unknown_site", "No site with that id exists", null) + + siteContainer.site.connected = true + siteContainer.site.status = "Initializing..." + + val intent = VpnService.prepare(this) + if (intent != null) { + //TODO: ensure this boots the correct bit, I bet it doesn't and we need to go back to the active symlink + intent.putExtra("path", siteContainer.site.path) + intent.putExtra("id", siteContainer.site.id) + startActivityForResult(intent, VPN_START_CODE) + + } else { + val intent = Intent(this, NebulaVpnService::class.java) + intent.putExtra("path", siteContainer.site.path) + intent.putExtra("id", siteContainer.site.id) + onActivityResult(VPN_START_CODE, Activity.RESULT_OK, intent) + } + + result.success(null) + } + + private fun stopSite() { + val intent = Intent(this, NebulaVpnService::class.java) + intent.putExtra("COMMAND", "STOP") + + //This is odd but stopService goes nowhere in my tests and this is correct + // according to the official example https://android.googlesource.com/platform/development/+/master/samples/ToyVpn/src/com/example/android/toyvpn/ToyVpnClient.java#116 + startService(intent) + //TODO: why doesn't this work!?!? +// if (serviceIntent != null) { +// Log.e(TAG, "stopping ${serviceIntent.toString()}") +// stopService(serviceIntent) +// } + } + + private fun activeListHostmap(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + if (outMessenger == null || activeSiteId == null || activeSiteId != id) { + return result.success(null) + } + + var msg = Message.obtain() + msg.what = NebulaVpnService.MSG_LIST_HOSTMAP + msg.replyTo = Messenger(object: Handler() { + override fun handleMessage(msg: Message) { + result.success(msg.data.getString("data")) + } + }) + outMessenger?.send(msg) + } + + private fun activeListPendingHostmap(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + if (outMessenger == null || activeSiteId == null || activeSiteId != id) { + return result.success(null) + } + + var msg = Message.obtain() + msg.what = NebulaVpnService.MSG_LIST_PENDING_HOSTMAP + msg.replyTo = Messenger(object: Handler() { + override fun handleMessage(msg: Message) { + result.success(msg.data.getString("data")) + } + }) + outMessenger?.send(msg) + } + + private fun activeGetHostInfo(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + val vpnIp = call.argument("vpnIp") + if (vpnIp == "") { + return result.error("required_argument", "vpnIp is a required argument", null) + } + + val pending = call.argument("pending") ?: false + + if (outMessenger == null || activeSiteId == null || activeSiteId != id) { + return result.success(null) + } + + var msg = Message.obtain() + msg.what = NebulaVpnService.MSG_GET_HOSTINFO + msg.data.putString("vpnIp", vpnIp) + msg.data.putBoolean("pending", pending) + msg.replyTo = Messenger(object: Handler() { + override fun handleMessage(msg: Message) { + result.success(msg.data.getString("data")) + } + }) + outMessenger?.send(msg) + } + + private fun activeSetRemoteForTunnel(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + val vpnIp = call.argument("vpnIp") + if (vpnIp == "") { + return result.error("required_argument", "vpnIp is a required argument", null) + } + + val addr = call.argument("addr") + if (vpnIp == "") { + return result.error("required_argument", "addr is a required argument", null) + } + + if (outMessenger == null || activeSiteId == null || activeSiteId != id) { + return result.success(null) + } + + var msg = Message.obtain() + msg.what = NebulaVpnService.MSG_SET_REMOTE_FOR_TUNNEL + msg.data.putString("vpnIp", vpnIp) + msg.data.putString("addr", addr) + msg.replyTo = Messenger(object: Handler() { + override fun handleMessage(msg: Message) { + result.success(msg.data.getString("data")) + } + }) + outMessenger?.send(msg) + } + + private fun activeCloseTunnel(call: MethodCall, result: MethodChannel.Result) { + val id = call.argument("id") + if (id == "") { + return result.error("required_argument", "id is a required argument", null) + } + + val vpnIp = call.argument("vpnIp") + if (vpnIp == "") { + return result.error("required_argument", "vpnIp is a required argument", null) + } + + if (outMessenger == null || activeSiteId == null || activeSiteId != id) { + return result.success(null) + } + + var msg = Message.obtain() + msg.what = NebulaVpnService.MSG_CLOSE_TUNNEL + msg.data.putString("vpnIp", vpnIp) + msg.replyTo = Messenger(object: Handler() { + override fun handleMessage(msg: Message) { + result.success(msg.data.getBoolean("data")) + } + }) + outMessenger?.send(msg) + } + + private fun androidPermissions(result: MethodChannel.Result) { + val intent = VpnService.prepare(this) + if (intent != null) { + permResult = result + return startActivityForResult(intent, VPN_PERMISSIONS_CODE) + } + + // We already have the permission + result.success(null) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + // This is where activity results come back to us (startActivityForResult) + if (requestCode == VPN_PERMISSIONS_CODE && permResult != null) { + // We are processing a response for vpn permissions and the UI is waiting for feedback + //TODO: unlikely we ever register multiple attempts but this could be a trouble spot if we did + val result = permResult!! + permResult = null + if (resultCode == Activity.RESULT_OK) { + return result.success(null) + } + + return result.error("denied", "User did not grant permission", null) + + } else if (requestCode == VPN_START_CODE) { + // We are processing a response for permissions while starting the VPN (or reusing code in the event we already have perms) + startService(data) + if (outMessenger == null) { + bindService(data, connection, 0) + } + return + } + + // The file picker needs us to super + super.onActivityResult(requestCode, resultCode, data) + } + + /** Defines callbacks for service binding, passed to bindService() */ + val connection = object : ServiceConnection { + override fun onServiceConnected(className: ComponentName, service: IBinder) { + outMessenger = Messenger(service) + // We want to monitor the service for as long as we are connected to it. + try { + val msg = Message.obtain(null, NebulaVpnService.MSG_REGISTER_CLIENT) + msg.replyTo = inMessenger + outMessenger?.send(msg) + + } catch (e: RemoteException) { + // In this case the service has crashed before we could even + // do anything with it; we can count on soon being + // disconnected (and then reconnected if it can be restarted) + // so there is no need to do anything here. + //TODO: + } + + val msg = Message.obtain(null, NebulaVpnService.MSG_IS_RUNNING) + outMessenger?.send(msg) + } + + override fun onServiceDisconnected(arg0: ComponentName) { + outMessenger = null + if (activeSiteId != null) { + //TODO: this indicates the service died, notify that it is disconnected + } + activeSiteId = null + } + } + + // Handle and route messages coming from the vpn service + inner class IncomingHandler: Handler() { + override fun handleMessage(msg: Message) { + val id = msg.data.getString("id") + + //TODO: If the elvis hits then we had a deleted site running, which shouldn't happen + val site = sites!!.getSite(id) ?: return + + when (msg.what) { + NebulaVpnService.MSG_IS_RUNNING -> isRunning(site, msg) + NebulaVpnService.MSG_EXIT -> serviceExited(site, msg) + else -> super.handleMessage(msg) + } + } + + private fun isRunning(site: SiteContainer, msg: Message) { + var status = "Disconnected" + var connected = false + + if (msg.arg1 == 1) { + status = "Connected" + connected = true + } + + activeSiteId = site.site.id + site.updater.setState(connected, status) + } + + private fun serviceExited(site: SiteContainer, msg: Message) { + activeSiteId = null + site.updater.setState(false, "Disconnected", msg.data.getString("error")) + } + } +} diff --git a/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt b/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt new file mode 100644 index 0000000..32357e6 --- /dev/null +++ b/android/app/src/main/kotlin/net/defined/mobile_nebula/NebulaVpnService.kt @@ -0,0 +1,209 @@ +package net.defined.mobile_nebula + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.net.ConnectivityManager +import android.net.VpnService +import android.os.* +import android.util.Log +import mobileNebula.CIDR +import java.io.File + +class NebulaVpnService : VpnService() { + + companion object { + private const val TAG = "NebulaVpnService" + const val MSG_REGISTER_CLIENT = 1 + const val MSG_UNREGISTER_CLIENT = 2 + const val MSG_IS_RUNNING = 3 + const val MSG_LIST_HOSTMAP = 4 + const val MSG_LIST_PENDING_HOSTMAP = 5 + const val MSG_GET_HOSTINFO = 6 + const val MSG_SET_REMOTE_FOR_TUNNEL = 7 + const val MSG_CLOSE_TUNNEL = 8 + const val MSG_EXIT = 9 + } + + /** + * Target we publish for clients to send messages to IncomingHandler. + */ + private lateinit var messenger: Messenger + private val mClients = ArrayList() + + private var running: Boolean = false + private var site: Site? = null + private var nebula: mobileNebula.Nebula? = null + private var vpnInterface: ParcelFileDescriptor? = null + + //TODO: bindService seems to be how to do IPC + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.getStringExtra("COMMAND") == "STOP") { + stopVpn() + return Service.START_NOT_STICKY + } + + startVpn(intent?.getStringExtra("path"), intent?.getStringExtra("id")) + return super.onStartCommand(intent, flags, startId) + } + + private fun startVpn(path: String?, id: String?) { + if (running) { + return announceExit(id, "Trying to run nebula but it is already running") + } + + //TODO: if we fail to start, android will attempt a restart lacking all the intent data we need. + // Link active site config in Main to avoid this + site = Site(File(path)) + var ipNet: CIDR + + if (site!!.cert == null) { + return announceExit(id, "Site is missing a certificate") + } + + try { + ipNet = mobileNebula.MobileNebula.parseCIDR(site!!.cert!!.cert.details.ips[0]) + } catch (err: Exception) { + return announceExit(id, err.message ?: "$err") + } + + val builder = Builder() + .addAddress(ipNet.ip, ipNet.maskSize.toInt()) + .addRoute(ipNet.network, ipNet.maskSize.toInt()) + .setMtu(site!!.mtu) + .setSession(TAG) + + // Add our unsafe routes + site!!.unsafeRoutes.forEach { unsafeRoute -> + val ipNet = mobileNebula.MobileNebula.parseCIDR(unsafeRoute.route) + builder.addRoute(ipNet.network, ipNet.maskSize.toInt()) + } + + val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + cm.allNetworks.forEach { network -> + cm.getLinkProperties(network).dnsServers.forEach { builder.addDnsServer(it) } + } + + try { + vpnInterface = builder.establish() + nebula = mobileNebula.MobileNebula.newNebula(site!!.config, site!!.getKey(this), site!!.logFile, vpnInterface!!.fd.toLong()) + + } catch (e: Exception) { + Log.e(TAG, "Got an error $e") + vpnInterface?.close() + announceExit(id, e.message) + return stopSelf() + } + + nebula!!.start() + running = true + sendSimple(MSG_IS_RUNNING, if (running) 1 else 0) + } + + private fun stopVpn() { + nebula?.stop() + vpnInterface?.close() + running = false + announceExit(site?.id, null) + } + + override fun onDestroy() { + stopVpn() + //TODO: wait for the thread to exit + super.onDestroy() + } + + private fun announceExit(id: String?, err: String?) { + val msg = Message.obtain(null, MSG_EXIT) + if (err != null) { + msg.data.putString("error", err) + Log.e(TAG, "$err") + } + send(msg, id) + } + + /** + * Handler of incoming messages from clients. + */ + inner class IncomingHandler(context: Context, private val applicationContext: Context = context.applicationContext) : Handler() { + override fun handleMessage(msg: Message) { + //TODO: how do we limit what can talk to us? + //TODO: Make sure replyTo is actually a messenger + when (msg.what) { + MSG_REGISTER_CLIENT -> mClients.add(msg.replyTo) + MSG_UNREGISTER_CLIENT -> mClients.remove(msg.replyTo) + MSG_IS_RUNNING -> isRunning() + MSG_LIST_HOSTMAP -> listHostmap(msg) + MSG_LIST_PENDING_HOSTMAP -> listHostmap(msg) + MSG_GET_HOSTINFO -> getHostInfo(msg) + MSG_CLOSE_TUNNEL -> closeTunnel(msg) + MSG_SET_REMOTE_FOR_TUNNEL -> setRemoteForTunnel(msg) + else -> super.handleMessage(msg) + } + } + + private fun isRunning() { + sendSimple(MSG_IS_RUNNING, if (running) 1 else 0) + } + + private fun listHostmap(msg: Message) { + val res = nebula!!.listHostmap(msg.what == MSG_LIST_PENDING_HOSTMAP) + var m = Message.obtain(null, msg.what) + m.data.putString("data", res) + msg.replyTo.send(m) + } + + private fun getHostInfo(msg: Message) { + val res = nebula!!.getHostInfoByVpnIp(msg.data.getString("vpnIp"), msg.data.getBoolean("pending")) + var m = Message.obtain(null, msg.what) + m.data.putString("data", res) + msg.replyTo.send(m) + } + + private fun setRemoteForTunnel(msg: Message) { + val res = nebula!!.setRemoteForTunnel(msg.data.getString("vpnIp"), msg.data.getString("addr")) + var m = Message.obtain(null, msg.what) + m.data.putString("data", res) + msg.replyTo.send(m) + } + + private fun closeTunnel(msg: Message) { + val res = nebula!!.closeTunnel(msg.data.getString("vpnIp")) + var m = Message.obtain(null, msg.what) + m.data.putBoolean("data", res) + msg.replyTo.send(m) + } + } + + private fun sendSimple(type: Int, arg1: Int = 0, arg2: Int = 0) { + send(Message.obtain(null, type, arg1, arg2)) + } + + private fun sendObj(type: Int, obj: Any?) { + send(Message.obtain(null, type, obj)) + } + + private fun send(msg: Message, id: String? = null) { + msg.data.putString("id", id ?: site?.id) + mClients.forEach { m -> + try { + m.send(msg) + } catch (e: RemoteException) { + // The client is dead. Remove it from the list; + // we are going through the list from back to front + // so this is safe to do inside the loop. + //TODO: seems bad to remove in loop, double check this is ok +// mClients.remove(m) + } + } + } + + override fun onBind(intent: Intent?): IBinder? { + if (intent != null && SERVICE_INTERFACE == intent.action) { + return super.onBind(intent) + } + + messenger = Messenger(IncomingHandler(this)) + return messenger.binder + } +} \ No newline at end of file diff --git a/android/app/src/main/kotlin/net/defined/mobile_nebula/Sites.kt b/android/app/src/main/kotlin/net/defined/mobile_nebula/Sites.kt new file mode 100644 index 0000000..51e6b8e --- /dev/null +++ b/android/app/src/main/kotlin/net/defined/mobile_nebula/Sites.kt @@ -0,0 +1,267 @@ +package net.defined.mobile_nebula + +import android.content.Context +import android.util.Log +import com.google.gson.Gson +import com.google.gson.annotations.Expose +import com.google.gson.annotations.SerializedName +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.EventChannel +import java.io.File +import kotlin.collections.HashMap + +data class SiteContainer( + val site: Site, + val updater: SiteUpdater +) + +class Sites(private var context: Context, private var engine: FlutterEngine) { + private var sites: HashMap = HashMap() + + init { + refreshSites() + } + + fun refreshSites(activeSite: String? = null) { + val sitesDir = context.filesDir.resolve("sites") + if (!sitesDir.isDirectory) { + sitesDir.delete() + sitesDir.mkdir() + } + + sites = HashMap() + sitesDir.listFiles().forEach { siteDir -> + try { + val site = Site(siteDir) + + // Make sure we can load the private key + site.getKey(context) + + val updater = SiteUpdater(site, engine) + if (site.id == activeSite) { + updater.setState(true, "Connected") + } + + this.sites[site.id] = SiteContainer(site, updater) + + } catch (err: Exception) { + siteDir.deleteRecursively() + Log.e(TAG, "Deleting non conforming site ${siteDir.absolutePath}", err) + } + } + } + + fun getSites(): Map { + return sites.mapValues { it.value.site } + } + + fun deleteSite(id: String) { + sites.remove(id) + val siteDir = context.filesDir.resolve("sites").resolve(id) + siteDir.deleteRecursively() + //TODO: make sure you stop the vpn + //TODO: make sure you relink the active site if this is the active site + } + + fun getSite(id: String): SiteContainer? { + return sites[id] + } +} + +class SiteUpdater(private var site: Site, engine: FlutterEngine): EventChannel.StreamHandler { + // eventSink is how we send info back up to flutter + private var eventChannel: EventChannel = EventChannel(engine.dartExecutor.binaryMessenger, "net.defined.nebula/${site.id}") + private var eventSink: EventChannel.EventSink? = null + + fun setState(connected: Boolean, status: String, err: String? = null) { + site.connected = connected + site.status = status + val d = mapOf("connected" to site.connected, "status" to site.status) + + if (err != null) { + eventSink?.error("", err, d) + } else { + eventSink?.success(d) + } + } + + init { + eventChannel.setStreamHandler(this) + } + + // Methods for EventChannel.StreamHandler + override fun onListen(p0: Any?, p1: EventChannel.EventSink?) { + eventSink = p1 + } + + override fun onCancel(p0: Any?) { + eventSink = null + } + +} + +data class CertificateInfo( + @SerializedName("Cert") val cert: Certificate, + @SerializedName("RawCert") val rawCert: String, + @SerializedName("Validity") val validity: CertificateValidity +) + +data class Certificate( + val fingerprint: String, + val signature: String, + val details: CertificateDetails +) + +data class CertificateDetails( + val name: String, + val notBefore: String, + val notAfter: String, + val publicKey: String, + val groups: List, + val ips: List, + val subnets: List, + val isCa: Boolean, + val issuer: String +) + +data class CertificateValidity( + @SerializedName("Valid") val valid: Boolean, + @SerializedName("Reason") val reason: String +) + +class Site { + val name: String + val id: String + val staticHostmap: HashMap + val unsafeRoutes: List + var cert: CertificateInfo? = null + var ca: Array + val lhDuration: Int + val port: Int + val mtu: Int + val cipher: String + val sortKey: Int + var logVerbosity: String + var connected: Boolean? + var status: String? + val logFile: String? + var errors: ArrayList = ArrayList() + + // Path to this site on disk + @Expose(serialize = false) + val path: String + + // Strong representation of the site config + @Expose(serialize = false) + val config: String + + constructor(siteDir: File) { + val gson = Gson() + config = siteDir.resolve("config.json").readText() + val incomingSite = gson.fromJson(config, IncomingSite::class.java) + + path = siteDir.absolutePath + name = incomingSite.name + id = incomingSite.id + staticHostmap = incomingSite.staticHostmap + unsafeRoutes = incomingSite.unsafeRoutes ?: ArrayList() + lhDuration = incomingSite.lhDuration + port = incomingSite.port + mtu = incomingSite.mtu ?: 1300 + cipher = incomingSite.cipher + sortKey = incomingSite.sortKey ?: 0 + logFile = siteDir.resolve("log").absolutePath + logVerbosity = incomingSite.logVerbosity ?: "info" + + connected = false + status = "Disconnected" + + try { + val rawDetails = mobileNebula.MobileNebula.parseCerts(incomingSite.cert) + val certs = gson.fromJson(rawDetails, Array::class.java) + if (certs.isEmpty()) { + throw IllegalArgumentException("No certificate found") + } + cert = certs[0] + if (!cert!!.validity.valid) { + errors.add("Certificate is invalid: ${cert!!.validity.reason}") + } + + } catch (err: Exception) { + errors.add("Error while loading certificate: ${err.message}") + } + + try { + val rawCa = mobileNebula.MobileNebula.parseCerts(incomingSite.ca) + ca = gson.fromJson(rawCa, Array::class.java) + var hasErrors = false + ca.forEach { + if (!it.validity.valid) { + hasErrors = true + } + } + + if (hasErrors) { + errors.add("There are issues with 1 or more ca certificates") + } + + } catch (err: Exception) { + ca = arrayOf() + errors.add("Error while loading certificate authorities: ${err.message}") + } + } + + fun getKey(context: Context): String? { + val f = EncFile(context).openRead(File(path).resolve("key")) + val k = f.readText() + f.close() + return k + } +} + +data class StaticHosts( + val lighthouse: Boolean, + val destinations: List +) + +data class UnsafeRoute( + val route: String, + val via: String, + val mtu: Int? +) + +class IncomingSite( + val name: String, + val id: String, + val staticHostmap: HashMap, + val unsafeRoutes: List?, + val cert: String, + val ca: String, + val lhDuration: Int, + val port: Int, + val mtu: Int?, + val cipher: String, + val sortKey: Int?, + var logVerbosity: String?, + @Expose(serialize = false) + var key: String? +) { + + fun save(context: Context) { + val siteDir = context.filesDir.resolve("sites").resolve(id) + if (!siteDir.exists()) { + siteDir.mkdir() + } + + if (key != null) { + val f = EncFile(context).openWrite(siteDir.resolve("key")) + f.use { it.write(key) } + f.close() + } + + key = null + val gson = Gson() + val confFile = siteDir.resolve("config.json") + confFile.writeText(gson.toJson(this)) + } +} diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..00fa441 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ + + + + diff --git a/android/app/src/main/res/xml/provider_paths.xml b/android/app/src/main/res/xml/provider_paths.xml new file mode 100644 index 0000000..7f4dbfc --- /dev/null +++ b/android/app/src/main/res/xml/provider_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..bc4f1bf --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..f040383 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,31 @@ +buildscript { + ext.kotlin_version = '1.3.61' + repositories { + google() + jcenter() + } + + dependencies { + classpath 'com.android.tools.build:gradle:4.0.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..38c8d45 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx1536M +android.enableR8=true +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a6cfe7d --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Jun 05 14:55:48 CDT 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..5a2f14f --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,15 @@ +include ':app' + +def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() + +def plugins = new Properties() +def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') +if (pluginsFile.exists()) { + pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } +} + +plugins.each { name, path -> + def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() + include ":$name" + project(":$name").projectDir = pluginDirectory +} diff --git a/android/settings_aar.gradle b/android/settings_aar.gradle new file mode 100644 index 0000000..e7b4def --- /dev/null +++ b/android/settings_aar.gradle @@ -0,0 +1 @@ +include ':app' diff --git a/env.sh.example b/env.sh.example new file mode 100644 index 0000000..3f40465 --- /dev/null +++ b/env.sh.example @@ -0,0 +1,4 @@ +#!/bin/sh + +# Ensure your go and flutter bin folders are here +export PATH="$PATH:/path/to/go/bin:/path/to/flutter/bin" \ No newline at end of file diff --git a/fonts/RobotoMono-Regular.ttf b/fonts/RobotoMono-Regular.ttf new file mode 100644 index 0000000..5919b5d Binary files /dev/null and b/fonts/RobotoMono-Regular.ttf differ diff --git a/gen-artifacts.sh b/gen-artifacts.sh new file mode 100755 index 0000000..802f6ec --- /dev/null +++ b/gen-artifacts.sh @@ -0,0 +1,51 @@ +#!/bin/sh + +set -e + +. env.sh + +# Generate gomobile nebula bindings +cd nebula + +if [ "$1" = "ios" ]; then + # Build for nebula for iOS + make MobileNebula.framework + rm -rf ../ios/NebulaNetworkExtension/MobileNebula.framework + cp -r MobileNebula.framework ../ios/NebulaNetworkExtension/ + +elif [ "$1" = "android" ]; then + # Build nebula for android + make mobileNebula.aar + rm -rf ../android/app/src/main/libs/mobileNebula.aar + cp mobileNebula.aar ../android/app/src/main/libs/mobileNebula.aar + +else + echo "Error: unsupported target os $1" + exit 1 +fi + +cd .. + +# Generate version info to display in about +{ + # Get the flutter and dart versions + printf "const flutterVersion = " + flutter --version --machine + echo ";" + + # Get our current git sha + git rev-parse --short HEAD | sed -e "s/\(.*\)/const gitSha = '\1';/" + + # Get the nebula version + cd nebula + NEBULA_VERSION="$(go list -m -f "{{.Version}}" github.com/slackhq/nebula | cut -f1 -d'-' | cut -c2-)" + echo "const nebulaVersion = '$NEBULA_VERSION';" + cd .. + + # Get our golang version + echo "const goVersion = '$(go version | awk '{print $3}')';" +} > lib/.gen.versions.dart + +# Try and avoid issues with building by moving into place after we are complete +#TODO: this might be a parallel build of deps issue in kotlin, might need to solve there +mv lib/.gen.versions.dart lib/gen.versions.dart \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..d7108be --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,33 @@ +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 +/NebulaNetworkExtension/MobileNebula.framework/ diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..6b4c0f7 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 8.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..e8efba1 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..399e934 --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/NebulaNetworkExtension/Info.plist b/ios/NebulaNetworkExtension/Info.plist new file mode 100644 index 0000000..eca99a3 --- /dev/null +++ b/ios/NebulaNetworkExtension/Info.plist @@ -0,0 +1,31 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + NebulaNetworkExtension + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionPointIdentifier + com.apple.networkextension.packet-tunnel + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).PacketTunnelProvider + + + diff --git a/ios/NebulaNetworkExtension/Keychain.swift b/ios/NebulaNetworkExtension/Keychain.swift new file mode 100644 index 0000000..2be94ee --- /dev/null +++ b/ios/NebulaNetworkExtension/Keychain.swift @@ -0,0 +1,67 @@ +import Foundation + +let groupName = "group.net.defined.mobileNebula" + +class KeyChain { + class func save(key: String, data: Data) -> Bool { + let query: [String: Any] = [ + kSecClass as String : kSecClassGenericPassword as String, + kSecAttrAccount as String : key, + kSecValueData as String : data, + kSecAttrAccessGroup as String: groupName, + ] + + SecItemDelete(query as CFDictionary) + let val = SecItemAdd(query as CFDictionary, nil) + return val == 0 + } + + class func load(key: String) -> Data? { + let query: [String: Any] = [ + kSecClass as String : kSecClassGenericPassword, + kSecAttrAccount as String : key, + kSecReturnData as String : kCFBooleanTrue!, + kSecMatchLimit as String : kSecMatchLimitOne, + kSecAttrAccessGroup as String: groupName, + ] + + var dataTypeRef: AnyObject? = nil + + let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef) + + if status == noErr { + return dataTypeRef as! Data? + } else { + return nil + } + } + + class func delete(key: String) -> Bool { + let query: [String: Any] = [ + kSecClass as String : kSecClassGenericPassword, + kSecAttrAccount as String : key, + kSecReturnData as String : kCFBooleanTrue!, + kSecMatchLimit as String : kSecMatchLimitOne, + kSecAttrAccessGroup as String: groupName, + ] + + return SecItemDelete(query as CFDictionary) == 0 + } +} + +extension Data { + + init(from value: T) { + var value = value + var data = Data() + withUnsafePointer(to: &value, { (ptr: UnsafePointer) -> Void in + data = Data(buffer: UnsafeBufferPointer(start: ptr, count: 1)) + }) + self.init(data) + } + + func to(type: T.Type) -> T { + return self.withUnsafeBytes { $0.load(as: T.self) } + } +} + diff --git a/ios/NebulaNetworkExtension/NebulaNetworkExtension.entitlements b/ios/NebulaNetworkExtension/NebulaNetworkExtension.entitlements new file mode 100644 index 0000000..fe9a9e3 --- /dev/null +++ b/ios/NebulaNetworkExtension/NebulaNetworkExtension.entitlements @@ -0,0 +1,18 @@ + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + com.apple.security.application-groups + + group.net.defined.mobileNebula + + keychain-access-groups + + $(AppIdentifierPrefix)group.net.defined.mobileNebula + + + diff --git a/ios/NebulaNetworkExtension/PacketTunnelProvider.swift b/ios/NebulaNetworkExtension/PacketTunnelProvider.swift new file mode 100644 index 0000000..8781320 --- /dev/null +++ b/ios/NebulaNetworkExtension/PacketTunnelProvider.swift @@ -0,0 +1,174 @@ +import NetworkExtension +import MobileNebula +import os.log +import MMWormhole + +class PacketTunnelProvider: NEPacketTunnelProvider { + private var networkMonitor: NWPathMonitor? + private var ifname: String? + + private var site: Site? + private var _log = OSLog(subsystem: "net.defined.mobileNebula", category: "PacketTunnelProvider") + private var wormhole = MMWormhole(applicationGroupIdentifier: "group.net.defined.mobileNebula", optionalDirectory: "ipc") + private var nebula: MobileNebulaNebula? + + private func log(_ message: StaticString, _ args: CVarArg...) { + os_log(message, log: _log, args) + } + + override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { + NSKeyedUnarchiver.setClass(IPCRequest.classForKeyedUnarchiver(), forClassName: "Runner.IPCRequest") + let proto = self.protocolConfiguration as! NETunnelProviderProtocol + var config: Data + var key: String + + do { + config = proto.providerConfiguration?["config"] as! Data + site = try Site(proto: proto) + } catch { + //TODO: need a way to notify the app + log("Failed to render config from vpn object") + return completionHandler(error) + } + + let _site = site! + _log = OSLog(subsystem: "net.defined.mobileNebula:\(_site.name)", category: "PacketTunnelProvider") + + do { + key = try _site.getKey() + } catch { + wormhole.passMessageObject(IPCMessage(id: _site.id, type: "error", message: error.localizedDescription), identifier: "nebula") + return completionHandler(error) + } + + self.networkMonitor = NWPathMonitor() + self.networkMonitor!.pathUpdateHandler = self.pathUpdate + self.networkMonitor!.start(queue: DispatchQueue(label: "NetworkMonitor")) + + let fileDescriptor = (self.packetFlow.value(forKeyPath: "socket.fileDescriptor") as? Int32) ?? -1 + if fileDescriptor < 0 { + let msg = IPCMessage(id: _site.id, type: "error", message: "Starting tunnel failed: Could not determine file descriptor") + wormhole.passMessageObject(msg, identifier: "nebula") + return completionHandler(NSError()) + } + + var ifnameSize = socklen_t(IFNAMSIZ) + let ifnamePtr = UnsafeMutablePointer.allocate(capacity: Int(ifnameSize)) + ifnamePtr.initialize(repeating: 0, count: Int(ifnameSize)) + if getsockopt(fileDescriptor, 2 /* SYSPROTO_CONTROL */, 2 /* UTUN_OPT_IFNAME */, ifnamePtr, &ifnameSize) == 0 { + self.ifname = String(cString: ifnamePtr) + } + ifnamePtr.deallocate() + + // This is set to 127.0.0.1 because it has to be something.. + let tunnelNetworkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1") + + // Make sure our ip is routed to the tun device + var err: NSError? + let ipNet = MobileNebulaParseCIDR(_site.cert!.cert.details.ips[0], &err) + if (err != nil) { + let msg = IPCMessage(id: _site.id, type: "error", message: err?.localizedDescription ?? "Unknown error from go MobileNebula.ParseCIDR - certificate") + self.wormhole.passMessageObject(msg, identifier: "nebula") + return completionHandler(err) + } + tunnelNetworkSettings.ipv4Settings = NEIPv4Settings(addresses: [ipNet!.ip], subnetMasks: [ipNet!.maskCIDR]) + var routes: [NEIPv4Route] = [NEIPv4Route(destinationAddress: ipNet!.network, subnetMask: ipNet!.maskCIDR)] + + // Add our unsafe routes + _site.unsafeRoutes.forEach { unsafeRoute in + let ipNet = MobileNebulaParseCIDR(unsafeRoute.route, &err) + if (err != nil) { + let msg = IPCMessage(id: _site.id, type: "error", message: err?.localizedDescription ?? "Unknown error from go MobileNebula.ParseCIDR - unsafe routes") + self.wormhole.passMessageObject(msg, identifier: "nebula") + return completionHandler(err) + } + routes.append(NEIPv4Route(destinationAddress: ipNet!.network, subnetMask: ipNet!.maskCIDR)) + } + + tunnelNetworkSettings.ipv4Settings!.includedRoutes = routes + tunnelNetworkSettings.mtu = _site.mtu as NSNumber + + wormhole.listenForMessage(withIdentifier: "app", listener: self.wormholeListener) + self.setTunnelNetworkSettings(tunnelNetworkSettings, completionHandler: {(error:Error?) in + if (error != nil) { + let msg = IPCMessage(id: _site.id, type: "error", message: error?.localizedDescription ?? "Unknown setTunnelNetworkSettings error") + self.wormhole.passMessageObject(msg, identifier: "nebula") + return completionHandler(error) + } + + var err: NSError? + self.nebula = MobileNebulaNewNebula(String(data: config, encoding: .utf8), key, self.site!.logFile, Int(fileDescriptor), &err) + if err != nil { + let msg = IPCMessage(id: _site.id, type: "error", message: err?.localizedDescription ?? "Unknown error from go MobileNebula.Main") + self.wormhole.passMessageObject(msg, identifier: "nebula") + return completionHandler(err) + } + + self.nebula!.start() + completionHandler(nil) + }) + } + + override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { + nebula?.stop() + networkMonitor?.cancel() + networkMonitor = nil + completionHandler() + } + + private func pathUpdate(path: Network.NWPath) { + nebula?.rebind() + } + + private func wormholeListener(msg: Any?) { + guard let call = msg as? IPCRequest else { + log("Failed to decode IPCRequest from network extension") + return + } + + var error: Error? + var data: Any? + + //TODO: try catch over all this + switch call.type { + case "listHostmap": (data, error) = listHostmap(pending: false) + case "listPendingHostmap": (data, error) = listHostmap(pending: true) + case "getHostInfo": (data, error) = getHostInfo(args: call.arguments!) + case "setRemoteForTunnel": (data, error) = setRemoteForTunnel(args: call.arguments!) + case "closeTunnel": (data, error) = closeTunnel(args: call.arguments!) + + default: + error = "Unknown IPC message type \(call.type)" + } + + if (error != nil) { + self.wormhole.passMessageObject(IPCMessage(id: "", type: "error", message: error!.localizedDescription), identifier: call.callbackId) + } else { + self.wormhole.passMessageObject(IPCMessage(id: "", type: "success", message: data), identifier: call.callbackId) + } + } + + private func listHostmap(pending: Bool) -> (String?, Error?) { + var err: NSError? + let res = nebula!.listHostmap(pending, error: &err) + return (res, err) + } + + private func getHostInfo(args: Dictionary) -> (String?, Error?) { + var err: NSError? + let res = nebula!.getHostInfo(byVpnIp: args["vpnIp"] as? String, pending: args["pending"] as! Bool, error: &err) + return (res, err) + } + + private func setRemoteForTunnel(args: Dictionary) -> (String?, Error?) { + var err: NSError? + let res = nebula!.setRemoteForTunnel(args["vpnIp"] as? String, addr: args["addr"] as? String, error: &err) + return (res, err) + } + + private func closeTunnel(args: Dictionary) -> (Bool?, Error?) { + let res = nebula!.closeTunnel(args["vpnIp"] as? String) + return (res, nil) + } +} + diff --git a/ios/NebulaNetworkExtension/Site.swift b/ios/NebulaNetworkExtension/Site.swift new file mode 100644 index 0000000..8adfcb8 --- /dev/null +++ b/ios/NebulaNetworkExtension/Site.swift @@ -0,0 +1,383 @@ +import NetworkExtension +import MobileNebula + +extension String: Error {} + +class IPCMessage: NSObject, NSCoding { + var id: String + var type: String + var message: Any? + + func encode(with aCoder: NSCoder) { + aCoder.encode(id, forKey: "id") + aCoder.encode(type, forKey: "type") + aCoder.encode(message, forKey: "message") + } + + required init(coder aDecoder: NSCoder) { + id = aDecoder.decodeObject(forKey: "id") as! String + type = aDecoder.decodeObject(forKey: "type") as! String + message = aDecoder.decodeObject(forKey: "message") as Any? + } + + init(id: String, type: String, message: Any) { + self.id = id + self.type = type + self.message = message + } +} + +class IPCRequest: NSObject, NSCoding { + var type: String + var callbackId: String + var arguments: Dictionary? + + func encode(with aCoder: NSCoder) { + aCoder.encode(type, forKey: "type") + aCoder.encode(arguments, forKey: "arguments") + aCoder.encode(callbackId, forKey: "callbackId") + } + + required init(coder aDecoder: NSCoder) { + callbackId = aDecoder.decodeObject(forKey: "callbackId") as! String + type = aDecoder.decodeObject(forKey: "type") as! String + arguments = aDecoder.decodeObject(forKey: "arguments") as? Dictionary + } + + init(callbackId: String, type: String, arguments: Dictionary?) { + self.callbackId = callbackId + self.type = type + self.arguments = arguments + } + + init(callbackId: String, type: String) { + self.callbackId = callbackId + self.type = type + } +} + +struct CertificateInfo: Codable { + var cert: Certificate + var rawCert: String + var validity: CertificateValidity + + enum CodingKeys: String, CodingKey { + case cert = "Cert" + case rawCert = "RawCert" + case validity = "Validity" + } +} + +struct Certificate: Codable { + var fingerprint: String + var signature: String + var details: CertificateDetails + + /// An empty initilizer to make error reporting easier + init() { + fingerprint = "" + signature = "" + details = CertificateDetails() + } +} + +struct CertificateDetails: Codable { + var name: String + var notBefore: String + var notAfter: String + var publicKey: String + var groups: [String] + var ips: [String] + var subnets: [String] + var isCa: Bool + var issuer: String + + /// An empty initilizer to make error reporting easier + init() { + name = "" + notBefore = "" + notAfter = "" + publicKey = "" + groups = [] + ips = ["ERROR"] + subnets = [] + isCa = false + issuer = "" + } +} + +struct CertificateValidity: Codable { + var valid: Bool + var reason: String + + enum CodingKeys: String, CodingKey { + case valid = "Valid" + case reason = "Reason" + } +} + +let statusMap: Dictionary = [ + NEVPNStatus.invalid: false, + NEVPNStatus.disconnected: false, + NEVPNStatus.connecting: true, + NEVPNStatus.connected: true, + NEVPNStatus.reasserting: true, + NEVPNStatus.disconnecting: true, +] + +let statusString: Dictionary = [ + NEVPNStatus.invalid: "Invalid configuration", + NEVPNStatus.disconnected: "Disconnected", + NEVPNStatus.connecting: "Connecting...", + NEVPNStatus.connected: "Connected", + NEVPNStatus.reasserting: "Reasserting...", + NEVPNStatus.disconnecting: "Disconnecting...", +] + +// Represents a site that was pulled out of the system configuration +struct Site: Codable { + // Stored in manager + var name: String + var id: String + + // Stored in proto + var staticHostmap: Dictionary + var unsafeRoutes: [UnsafeRoute] + var cert: CertificateInfo? + var ca: [CertificateInfo] + var lhDuration: Int + var port: Int + var mtu: Int + var cipher: String + var sortKey: Int + var logVerbosity: String + var connected: Bool? + var status: String? + var logFile: String? + + // A list of error encountered when trying to rehydrate a site from config + var errors: [String] + + // We initialize to avoid an error with Codable, there is probably a better way since manager must be present for a Site but is not codable + var manager: NETunnelProviderManager = NETunnelProviderManager() + + // Creates a new site from a vpn manager instance + init(manager: NETunnelProviderManager) throws { + //TODO: Throw an error and have Sites delete the site, notify the user instead of using ! + let proto = manager.protocolConfiguration as! NETunnelProviderProtocol + try self.init(proto: proto) + self.manager = manager + self.connected = statusMap[manager.connection.status] + self.status = statusString[manager.connection.status] + } + + init(proto: NETunnelProviderProtocol) throws { + let dict = proto.providerConfiguration + let rawConfig = dict?["config"] as? Data ?? Data() + let decoder = JSONDecoder() + let incoming = try decoder.decode(IncomingSite.self, from: rawConfig) + self.init(incoming: incoming) + } + + init(incoming: IncomingSite) { + var err: NSError? + + errors = [] + name = incoming.name + id = incoming.id + staticHostmap = incoming.staticHostmap + unsafeRoutes = incoming.unsafeRoutes ?? [] + + do { + let rawCert = incoming.cert + let rawDetails = MobileNebulaParseCerts(rawCert, &err) + if (err != nil) { + throw err! + } + + var certs: [CertificateInfo] + + certs = try JSONDecoder().decode([CertificateInfo].self, from: rawDetails.data(using: .utf8)!) + if (certs.count == 0) { + throw "No certificate found" + } + cert = certs[0] + if (!cert!.validity.valid) { + errors.append("Certificate is invalid: \(cert!.validity.reason)") + } + + } catch { + errors.append("Error while loading certificate: \(error.localizedDescription)") + } + + do { + let rawCa = incoming.ca + let rawCaDetails = MobileNebulaParseCerts(rawCa, &err) + if (err != nil) { + throw err! + } + ca = try JSONDecoder().decode([CertificateInfo].self, from: rawCaDetails.data(using: .utf8)!) + + var hasErrors = false + ca.forEach { cert in + if (!cert.validity.valid) { + hasErrors = true + } + } + + if (hasErrors) { + errors.append("There are issues with 1 or more ca certificates") + } + + } catch { + ca = [] + errors.append("Error while loading certificate authorities: \(error.localizedDescription)") + } + + lhDuration = incoming.lhDuration + port = incoming.port + cipher = incoming.cipher + sortKey = incoming.sortKey ?? 0 + logVerbosity = incoming.logVerbosity ?? "info" + mtu = incoming.mtu ?? 1300 + logFile = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.net.defined.mobileNebula")?.appendingPathComponent(id).appendingPathExtension("log").path + } + + // Gets the private key from the keystore, we don't always need it in memory + func getKey() throws -> String { + guard let keyData = KeyChain.load(key: "\(id).key") else { + throw "failed to get key material from keychain" + } + + //TODO: make sure this is valid on return! + return String(decoding: keyData, as: UTF8.self) + } + + // Limits what we export to the UI + private enum CodingKeys: String, CodingKey { + case name + case id + case staticHostmap + case cert + case ca + case lhDuration + case port + case cipher + case sortKey + case connected + case status + case logFile + case unsafeRoutes + case logVerbosity + case errors + case mtu + } +} + +class StaticHosts: Codable { + var lighthouse: Bool + var destinations: [String] +} + +class UnsafeRoute: Codable { + var route: String + var via: String + var mtu: Int? +} + +// This class represents a site coming in from flutter, meant only to be saved and re-loaded as a proper Site +struct IncomingSite: Codable { + var name: String + var id: String + var staticHostmap: Dictionary + var unsafeRoutes: [UnsafeRoute]? + var cert: String + var ca: String + var lhDuration: Int + var port: Int + var mtu: Int? + var cipher: String + var sortKey: Int? + var logVerbosity: String? + var key: String? + + func save(manager: NETunnelProviderManager?, callback: @escaping (Error?) -> ()) { +#if targetEnvironment(simulator) + let fileManager = FileManager.default + let sitePath = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("sites").appendingPathComponent(self.id) + let encoder = JSONEncoder() + + do { + var config = self + config.key = nil + let rawConfig = try encoder.encode(config) + try rawConfig.write(to: sitePath) + } catch { + return callback(error) + } + + callback(nil) +#else + if (manager != nil) { + // We need to refresh our settings to properly update config + manager?.loadFromPreferences { error in + if (error != nil) { + return callback(error) + } + + return self.finish(manager: manager!, callback: callback) + } + return + } + + return finish(manager: NETunnelProviderManager(), callback: callback) +#endif + } + + private func finish(manager: NETunnelProviderManager, callback: @escaping (Error?) -> ()) { + var config = self + + // Store the private key if it was provided + if (config.key != nil) { + //TODO: should we ensure the resulting data is big enough? (conversion didn't fail) + let data = config.key!.data(using: .utf8) + if (!KeyChain.save(key: "\(config.id).key", data: data!)) { + return callback("failed to store key material in keychain") + } + } + + // Zero out the key so that we don't save it in the profile + config.key = nil + + // Stuff our details in the protocol + let proto = manager.protocolConfiguration as? NETunnelProviderProtocol ?? NETunnelProviderProtocol() + let encoder = JSONEncoder() + let rawConfig: Data + + // We tried using NSSecureCoder but that was obnoxious and didn't work so back to JSON + do { + rawConfig = try encoder.encode(config) + } catch { + return callback(error) + } + + proto.providerConfiguration = ["config": rawConfig] + + //TODO: proto is a subclass and we should probably set some settings on the parents + //TODO: set these to meaningful values, or not at all + proto.serverAddress = "TODO" + proto.username = "TEST USERNAME" + + // Finish up the manager, this is what stores everything at the system level + manager.protocolConfiguration = proto + //TODO: cert name? manager.protocolConfiguration?.username + + //TODO: This is what is shown on the vpn page. We should add more identifying details in + manager.localizedDescription = config.name + manager.isEnabled = true + + manager.saveToPreferences{ error in + return callback(error) + } + } +} diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 0000000..eaec93c --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,91 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def parse_KV_file(file, separator='=') + file_abs_path = File.expand_path(file) + if !File.exists? file_abs_path + return []; + end + generated_key_values = {} + skip_line_start_symbols = ["#", "/"] + File.foreach(file_abs_path) do |line| + next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } + plugin = line.split(pattern=separator) + if plugin.length == 2 + podname = plugin[0].strip() + path = plugin[1].strip() + podpath = File.expand_path("#{path}", file_abs_path) + generated_key_values[podname] = podpath + else + puts "Invalid plugin specification: #{line}" + end + end + generated_key_values +end + +target 'Runner' do + use_frameworks! + use_modular_headers! + + # Flutter Pod + + copied_flutter_dir = File.join(__dir__, 'Flutter') + copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') + copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') + unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) + # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. + # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. + # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. + + generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') + unless File.exist?(generated_xcode_build_settings_path) + raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) + cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; + + unless File.exist?(copied_framework_path) + FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) + end + unless File.exist?(copied_podspec_path) + FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) + end + end + + # Keep pod path relative so it can be checked into Podfile.lock. + pod 'Flutter', :path => 'Flutter' + pod 'MMWormhole', '~> 2.0.0' + + # Plugin Pods + + # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock + # referring to absolute paths on developers' machines. + system('rm -rf .symlinks') + system('mkdir -p .symlinks/plugins') + plugin_pods = parse_KV_file('../.flutter-plugins') + plugin_pods.each do |name, path| + symlink = File.join('.symlinks', 'plugins', name) + File.symlink(path, symlink) + pod name, :path => File.join(symlink, 'ios') + end +end + +# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. +install! 'cocoapods', :disable_input_output_paths => true + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + config.build_settings['ENABLE_BITCODE'] = 'NO' + end + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100644 index 0000000..716bdc5 --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,148 @@ +PODS: + - barcode_scan (0.0.1): + - Flutter + - MTBBarcodeScanner + - SwiftProtobuf + - DKImagePickerController/Core (4.3.0): + - DKImagePickerController/ImageDataManager + - DKImagePickerController/Resource + - DKImagePickerController/ImageDataManager (4.3.0) + - DKImagePickerController/PhotoGallery (4.3.0): + - DKImagePickerController/Core + - DKPhotoGallery + - DKImagePickerController/Resource (4.3.0) + - DKPhotoGallery (0.0.15): + - DKPhotoGallery/Core (= 0.0.15) + - DKPhotoGallery/Model (= 0.0.15) + - DKPhotoGallery/Preview (= 0.0.15) + - DKPhotoGallery/Resource (= 0.0.15) + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Core (0.0.15): + - DKPhotoGallery/Model + - DKPhotoGallery/Preview + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Model (0.0.15): + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Preview (0.0.15): + - DKPhotoGallery/Model + - DKPhotoGallery/Resource + - SDWebImage + - SDWebImageFLPlugin + - DKPhotoGallery/Resource (0.0.15): + - SDWebImage + - SDWebImageFLPlugin + - file_picker (0.0.1): + - DKImagePickerController/PhotoGallery + - Flutter + - FLAnimatedImage (1.0.12) + - Flutter (1.0.0) + - flutter_plugin_android_lifecycle (0.0.1): + - Flutter + - flutter_share (0.0.1): + - Flutter + - MMWormhole (2.0.0): + - MMWormhole/Core (= 2.0.0) + - MMWormhole/Core (2.0.0) + - MTBBarcodeScanner (5.0.11) + - package_info (0.0.1): + - Flutter + - path_provider (0.0.1): + - Flutter + - path_provider_linux (0.0.1): + - Flutter + - path_provider_macos (0.0.1): + - Flutter + - SDWebImage (5.8.0): + - SDWebImage/Core (= 5.8.0) + - SDWebImage/Core (5.8.0) + - SDWebImageFLPlugin (0.4.0): + - FLAnimatedImage (>= 1.0.11) + - SDWebImage/Core (~> 5.6) + - SwiftProtobuf (1.8.0) + - url_launcher (0.0.1): + - Flutter + - url_launcher_macos (0.0.1): + - Flutter + - url_launcher_web (0.0.1): + - Flutter + +DEPENDENCIES: + - barcode_scan (from `.symlinks/plugins/barcode_scan/ios`) + - file_picker (from `.symlinks/plugins/file_picker/ios`) + - Flutter (from `Flutter`) + - flutter_plugin_android_lifecycle (from `.symlinks/plugins/flutter_plugin_android_lifecycle/ios`) + - flutter_share (from `.symlinks/plugins/flutter_share/ios`) + - MMWormhole (~> 2.0.0) + - package_info (from `.symlinks/plugins/package_info/ios`) + - path_provider (from `.symlinks/plugins/path_provider/ios`) + - path_provider_linux (from `.symlinks/plugins/path_provider_linux/ios`) + - path_provider_macos (from `.symlinks/plugins/path_provider_macos/ios`) + - url_launcher (from `.symlinks/plugins/url_launcher/ios`) + - url_launcher_macos (from `.symlinks/plugins/url_launcher_macos/ios`) + - url_launcher_web (from `.symlinks/plugins/url_launcher_web/ios`) + +SPEC REPOS: + trunk: + - DKImagePickerController + - DKPhotoGallery + - FLAnimatedImage + - MMWormhole + - MTBBarcodeScanner + - SDWebImage + - SDWebImageFLPlugin + - SwiftProtobuf + +EXTERNAL SOURCES: + barcode_scan: + :path: ".symlinks/plugins/barcode_scan/ios" + file_picker: + :path: ".symlinks/plugins/file_picker/ios" + Flutter: + :path: Flutter + flutter_plugin_android_lifecycle: + :path: ".symlinks/plugins/flutter_plugin_android_lifecycle/ios" + flutter_share: + :path: ".symlinks/plugins/flutter_share/ios" + package_info: + :path: ".symlinks/plugins/package_info/ios" + path_provider: + :path: ".symlinks/plugins/path_provider/ios" + path_provider_linux: + :path: ".symlinks/plugins/path_provider_linux/ios" + path_provider_macos: + :path: ".symlinks/plugins/path_provider_macos/ios" + url_launcher: + :path: ".symlinks/plugins/url_launcher/ios" + url_launcher_macos: + :path: ".symlinks/plugins/url_launcher_macos/ios" + url_launcher_web: + :path: ".symlinks/plugins/url_launcher_web/ios" + +SPEC CHECKSUMS: + barcode_scan: a5c27959edfafaa0c771905bad0b29d6d39e4479 + DKImagePickerController: 397702a3590d4958fad336e9a77079935c500ddb + DKPhotoGallery: e880aef16c108333240e1e7327896f2ea380f4f0 + file_picker: 3e6c3790de664ccf9b882732d9db5eaf6b8d4eb1 + FLAnimatedImage: 4a0b56255d9b05f18b6dd7ee06871be5d3b89e31 + Flutter: 0e3d915762c693b495b44d77113d4970485de6ec + flutter_plugin_android_lifecycle: dc0b544e129eebb77a6bfb1239d4d1c673a60a35 + flutter_share: 4be0208963c60b537e6255ed2ce1faae61cd9ac2 + MMWormhole: 0cd3fd35a9118b2e2d762b499f54eeaace0be791 + MTBBarcodeScanner: f453b33c4b7dfe545d8c6484ed744d55671788cb + package_info: 873975fc26034f0b863a300ad47e7f1ac6c7ec62 + path_provider: abfe2b5c733d04e238b0d8691db0cfd63a27a93c + path_provider_linux: 4d630dc393e1f20364f3e3b4a2ff41d9674a84e4 + path_provider_macos: f760a3c5b04357c380e2fddb6f9db6f3015897e0 + SDWebImage: 84000f962cbfa70c07f19d2234cbfcf5d779b5dc + SDWebImageFLPlugin: 6c2295fb1242d44467c6c87dc5db6b0a13228fd8 + SwiftProtobuf: 2cbd9409689b7df170d82a92a33443c8e3e14a70 + url_launcher: 6fef411d543ceb26efce54b05a0a40bfd74cbbef + url_launcher_macos: fd7894421cd39320dce5f292fc99ea9270b2a313 + url_launcher_web: e5527357f037c87560776e36436bf2b0288b965c + +PODFILE CHECKSUM: 40eeeb97ef2165edffec94ac1ddff2d14dd420f7 + +COCOAPODS: 1.9.0 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..8b58192 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,849 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 437F72592469AAC500A0C4B9 /* Site.swift in Sources */ = {isa = PBXBuildFile; fileRef = 437F72582469AAC500A0C4B9 /* Site.swift */; }; + 437F725E2469AC5700A0C4B9 /* Keychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 437F725C2469AC5700A0C4B9 /* Keychain.swift */; }; + 437F725F2469B4B000A0C4B9 /* Site.swift in Sources */ = {isa = PBXBuildFile; fileRef = 437F72582469AAC500A0C4B9 /* Site.swift */; }; + 437F72602469B4B300A0C4B9 /* Keychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 437F725C2469AC5700A0C4B9 /* Keychain.swift */; }; + 43871C9B2444DD39004F9075 /* MobileNebula.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 43871C9A2444DD39004F9075 /* MobileNebula.framework */; }; + 43871C9D2444E2EC004F9075 /* Sites.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43871C9C2444E2EC004F9075 /* Sites.swift */; }; + 43871C9E2444E61F004F9075 /* MobileNebula.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 43871C9A2444DD39004F9075 /* MobileNebula.framework */; }; + 43AA894F2444D8BC00EDC39C /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 43AA894E2444D8BC00EDC39C /* NetworkExtension.framework */; }; + 43AA89572444DA6500EDC39C /* PacketTunnelProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43AA89562444DA6500EDC39C /* PacketTunnelProvider.swift */; }; + 43AA895C2444DA6500EDC39C /* NebulaNetworkExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 43AA89542444DA6500EDC39C /* NebulaNetworkExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 43AA89622444DAA500EDC39C /* NetworkExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 43AA894E2444D8BC00EDC39C /* NetworkExtension.framework */; }; + 4CF2F06A02A63B862C9F6F03 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 384887B4785D38431E800D3A /* Pods_Runner.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 43AA895A2444DA6500EDC39C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 43AA89532444DA6500EDC39C; + remoteInfo = NebulaNetworkExtension; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 43AA89612444DA6500EDC39C /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 43AA895C2444DA6500EDC39C /* NebulaNetworkExtension.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 384887B4785D38431E800D3A /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 437F72582469AAC500A0C4B9 /* Site.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Site.swift; sourceTree = ""; }; + 437F725C2469AC5700A0C4B9 /* Keychain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Keychain.swift; sourceTree = ""; }; + 43871C9A2444DD39004F9075 /* MobileNebula.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = MobileNebula.framework; sourceTree = ""; }; + 43871C9C2444E2EC004F9075 /* Sites.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sites.swift; sourceTree = ""; }; + 43AA894C2444D8BC00EDC39C /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + 43AA894E2444D8BC00EDC39C /* NetworkExtension.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = NetworkExtension.framework; path = System/Library/Frameworks/NetworkExtension.framework; sourceTree = SDKROOT; }; + 43AA89542444DA6500EDC39C /* NebulaNetworkExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = NebulaNetworkExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 43AA89562444DA6500EDC39C /* PacketTunnelProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PacketTunnelProvider.swift; sourceTree = ""; }; + 43AA89582444DA6500EDC39C /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 43AA89592444DA6500EDC39C /* NebulaNetworkExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NebulaNetworkExtension.entitlements; sourceTree = ""; }; + 43B66ECA245A0C8400B18C36 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; }; + 43B66ECC245A146300B18C36 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 43B828DA249C08DC00CA229C /* MMWormhole.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = MMWormhole.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6E7A71D8C71BF965D042667D /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 8E4961BE2F06B97C8C693530 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C2D5198CF6975BF93E8A6F93 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 43AA89512444DA6500EDC39C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 43AA89622444DAA500EDC39C /* NetworkExtension.framework in Frameworks */, + 43871C9B2444DD39004F9075 /* MobileNebula.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 43AA894F2444D8BC00EDC39C /* NetworkExtension.framework in Frameworks */, + 4CF2F06A02A63B862C9F6F03 /* Pods_Runner.framework in Frameworks */, + 43871C9E2444E61F004F9075 /* MobileNebula.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 43AA894D2444D8BC00EDC39C /* Frameworks */ = { + isa = PBXGroup; + children = ( + 43B828DA249C08DC00CA229C /* MMWormhole.framework */, + 43B66ECC245A146300B18C36 /* Foundation.framework */, + 43B66ECA245A0C8400B18C36 /* CoreFoundation.framework */, + 43AA894E2444D8BC00EDC39C /* NetworkExtension.framework */, + 384887B4785D38431E800D3A /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 43AA89552444DA6500EDC39C /* NebulaNetworkExtension */ = { + isa = PBXGroup; + children = ( + 437F725C2469AC5700A0C4B9 /* Keychain.swift */, + 43871C9A2444DD39004F9075 /* MobileNebula.framework */, + 43AA89562444DA6500EDC39C /* PacketTunnelProvider.swift */, + 43AA89582444DA6500EDC39C /* Info.plist */, + 43AA89592444DA6500EDC39C /* NebulaNetworkExtension.entitlements */, + 437F72582469AAC500A0C4B9 /* Site.swift */, + ); + path = NebulaNetworkExtension; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 43AA89552444DA6500EDC39C /* NebulaNetworkExtension */, + 97C146EF1CF9000F007C117D /* Products */, + 43AA894D2444D8BC00EDC39C /* Frameworks */, + 9D19B3FACD187D51D2854929 /* Pods */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 43AA89542444DA6500EDC39C /* NebulaNetworkExtension.appex */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 43AA894C2444D8BC00EDC39C /* Runner.entitlements */, + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 97C146F11CF9000F007C117D /* Supporting Files */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + 43871C9C2444E2EC004F9075 /* Sites.swift */, + ); + path = Runner; + sourceTree = ""; + }; + 97C146F11CF9000F007C117D /* Supporting Files */ = { + isa = PBXGroup; + children = ( + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 9D19B3FACD187D51D2854929 /* Pods */ = { + isa = PBXGroup; + children = ( + C2D5198CF6975BF93E8A6F93 /* Pods-Runner.debug.xcconfig */, + 6E7A71D8C71BF965D042667D /* Pods-Runner.release.xcconfig */, + 8E4961BE2F06B97C8C693530 /* Pods-Runner.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 43AA89532444DA6500EDC39C /* NebulaNetworkExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 43AA895D2444DA6500EDC39C /* Build configuration list for PBXNativeTarget "NebulaNetworkExtension" */; + buildPhases = ( + 43AA89632444DAD100EDC39C /* ShellScript */, + 43AA89502444DA6500EDC39C /* Sources */, + 43AA89512444DA6500EDC39C /* Frameworks */, + 43AA89522444DA6500EDC39C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = NebulaNetworkExtension; + productName = NebulaNetworkExtension; + productReference = 43AA89542444DA6500EDC39C /* NebulaNetworkExtension.appex */; + productType = "com.apple.product-type.app-extension"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + FF0E0EB9A684F086443A8FBA /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 43AA89612444DA6500EDC39C /* Embed App Extensions */, + 00C7A79AE88792090BDAC68B /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 43AA895B2444DA6500EDC39C /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1140; + LastUpgradeCheck = 1020; + ORGANIZATIONNAME = "The Chromium Authors"; + TargetAttributes = { + 43AA89532444DA6500EDC39C = { + CreatedOnToolsVersion = 11.4; + DevelopmentTeam = 576H3XS7FP; + ProvisioningStyle = Automatic; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + DevelopmentTeam = 576H3XS7FP; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 43AA89532444DA6500EDC39C /* NebulaNetworkExtension */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 43AA89522444DA6500EDC39C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 00C7A79AE88792090BDAC68B /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed\n/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin\n"; + }; + 43AA89632444DAD100EDC39C /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "cd ..\n./gen-artifacts.sh ios\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build\n"; + }; + FF0E0EB9A684F086443A8FBA /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 43AA89502444DA6500EDC39C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 43AA89572444DA6500EDC39C /* PacketTunnelProvider.swift in Sources */, + 437F72592469AAC500A0C4B9 /* Site.swift in Sources */, + 437F725E2469AC5700A0C4B9 /* Keychain.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 43871C9D2444E2EC004F9075 /* Sites.swift in Sources */, + 437F725F2469B4B000A0C4B9 /* Site.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 437F72602469B4B300A0C4B9 /* Keychain.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 43AA895B2444DA6500EDC39C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 43AA89532444DA6500EDC39C /* NebulaNetworkExtension */; + targetProxy = 43AA895A2444DA6500EDC39C /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + INFOPLIST_FILE = Runner/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + MARKETING_VERSION = 0.0.30; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 43AA895E2444DA6500EDC39C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = NebulaNetworkExtension/NebulaNetworkExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + GCC_C_LANGUAGE_STANDARD = gnu11; + INFOPLIST_FILE = NebulaNetworkExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + MARKETING_VERSION = 0.0.30; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula.NebulaNetworkExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 43AA895F2444DA6500EDC39C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = NebulaNetworkExtension/NebulaNetworkExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + GCC_C_LANGUAGE_STANDARD = gnu11; + INFOPLIST_FILE = NebulaNetworkExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + MARKETING_VERSION = 0.0.30; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula.NebulaNetworkExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 43AA89602444DA6500EDC39C /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_ENTITLEMENTS = NebulaNetworkExtension/NebulaNetworkExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + GCC_C_LANGUAGE_STANDARD = gnu11; + INFOPLIST_FILE = NebulaNetworkExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + MARKETING_VERSION = 0.0.30; + MTL_FAST_MATH = YES; + OTHER_LDFLAGS = ""; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula.NebulaNetworkExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + INFOPLIST_FILE = Runner/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + MARKETING_VERSION = 0.0.30; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 576H3XS7FP; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + "$(PROJECT_DIR)/NebulaNetworkExtension", + ); + INFOPLIST_FILE = Runner/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.2; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); + MARKETING_VERSION = 0.0.30; + PRODUCT_BUNDLE_IDENTIFIER = net.defined.mobileNebula; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 43AA895D2444DA6500EDC39C /* Build configuration list for PBXNativeTarget "NebulaNetworkExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 43AA895E2444DA6500EDC39C /* Debug */, + 43AA895F2444DA6500EDC39C /* Release */, + 43AA89602444DA6500EDC39C /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..a28140c --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..64f1601 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,316 @@ +import UIKit +import Flutter +import MobileNebula +import NetworkExtension +import MMWormhole + +enum ChannelName { + static let vpn = "net.defined.mobileNebula/NebulaVpnService" +} + +func MissingArgumentError(message: String, details: Any?) -> FlutterError { + return FlutterError(code: "missing_argument", message: message, details: details) +} + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + private var sites: Sites? + private var wormhole = MMWormhole(applicationGroupIdentifier: "group.net.defined.mobileNebula", optionalDirectory: "ipc") + + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + + guard let controller = window?.rootViewController as? FlutterViewController else { + fatalError("rootViewController is not type FlutterViewController") + } + + sites = Sites(messenger: controller.binaryMessenger) + let channel = FlutterMethodChannel(name: ChannelName.vpn, binaryMessenger: controller.binaryMessenger) + + NSKeyedUnarchiver.setClass(IPCMessage.classForKeyedUnarchiver(), forClassName: "NebulaNetworkExtension.IPCMessage") + wormhole.listenForMessage(withIdentifier: "nebula", listener: self.wormholeListener) + + channel.setMethodCallHandler({(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in + switch call.method { + case "nebula.parseCerts": return self.nebulaParseCerts(call: call, result: result) + case "nebula.generateKeyPair": return self.nebulaGenerateKeyPair(result: result) + case "nebula.renderConfig": return self.nebulaRenderConfig(call: call, result: result) + + case "listSites": return self.listSites(result: result) + case "deleteSite": return self.deleteSite(call: call, result: result) + case "saveSite": return self.saveSite(call: call, result: result) + case "startSite": return self.startSite(call: call, result: result) + case "stopSite": return self.stopSite(call: call, result: result) + + case "active.listHostmap": self.activeListHostmap(call: call, result: result) + case "active.listPendingHostmap": self.activeListPendingHostmap(call: call, result: result) + case "active.getHostInfo": self.activeGetHostInfo(call: call, result: result) + case "active.setRemoteForTunnel": self.activeSetRemoteForTunnel(call: call, result: result) + case "active.closeTunnel": self.activeCloseTunnel(call: call, result: result) + + default: + result(FlutterMethodNotImplemented) + } + }) + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func nebulaParseCerts(call: FlutterMethodCall, result: FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let certs = args["certs"] else { return result(MissingArgumentError(message: "certs is a required argument")) } + + var err: NSError? + let json = MobileNebulaParseCerts(certs, &err) + if (err != nil) { + return result(CallFailedError(message: "Error while parsing certificate(s)", details: err!.localizedDescription)) + } + + return result(json) + } + + func nebulaGenerateKeyPair(result: FlutterResult) { + var err: NSError? + let kp = MobileNebulaGenerateKeyPair(&err) + if (err != nil) { + return result(CallFailedError(message: "Error while generating key pairs", details: err!.localizedDescription)) + } + + return result(kp) + } + + func nebulaRenderConfig(call: FlutterMethodCall, result: FlutterResult) { + guard let config = call.arguments as? String else { return result(NoArgumentsError()) } + + var err: NSError? + print(config) + let yaml = MobileNebulaRenderConfig(config, "", &err) + if (err != nil) { + return result(CallFailedError(message: "Error while rendering config", details: err!.localizedDescription)) + } + + return result(yaml) + } + + func listSites(result: @escaping FlutterResult) { + self.sites?.loadSites { (sites, err) -> () in + if (err != nil) { + return result(CallFailedError(message: "Failed to load site list", details: err!.localizedDescription)) + } + + let encoder = JSONEncoder() + let data = try! encoder.encode(sites) + let ret = String(data: data, encoding: .utf8) + result(ret) + } + } + + func deleteSite(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let id = call.arguments as? String else { return result(NoArgumentsError()) } + //TODO: stop the site if its running currently + self.sites?.deleteSite(id: id) { error in + if (error != nil) { + result(CallFailedError(message: "Failed to delete site", details: error!.localizedDescription)) + } + + result(nil) + } + } + + func saveSite(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let json = call.arguments as? String else { return result(NoArgumentsError()) } + guard let data = json.data(using: .utf8) else { return result(NoArgumentsError()) } + + guard let site = try? JSONDecoder().decode(IncomingSite.self, from: data) else { + return result(NoArgumentsError()) + } + + let oldSite = self.sites?.getSite(id: site.id) + site.save(manager: oldSite?.manager) { error in + if (error != nil) { + return result(CallFailedError(message: "Failed to save site", details: error!.localizedDescription)) + } + + result(nil) + } + } + + func startSite(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } +#if targetEnvironment(simulator) + let updater = self.sites?.getUpdater(id: id) + updater?.update(connected: true) + +#else + let manager = self.sites?.getSite(id: id)?.manager + manager?.loadFromPreferences{ error in + //TODO: Handle load error + // This is silly but we need to enable the site each time to avoid situations where folks have multiple sites + manager?.isEnabled = true + manager?.saveToPreferences{ error in + //TODO: Handle load error + manager?.loadFromPreferences{ error in + //TODO: Handle load error + do { + try manager?.connection.startVPNTunnel() + } catch { + return result(CallFailedError(message: "Could not start site", details: error.localizedDescription)) + } + + return result(nil) + } + } + } +#endif + } + + func stopSite(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } +#if targetEnvironment(simulator) + let updater = self.sites?.getUpdater(id: id) + updater?.update(connected: false) + +#else + let manager = self.sites?.getSite(id: id)?.manager + manager?.loadFromPreferences{ error in + //TODO: Handle load error + + manager?.connection.stopVPNTunnel() + return result(nil) + } +#endif + } + + func activeListHostmap(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } + //TODO: match id for safety? + wormholeRequestWithCallback(type: "listHostmap", arguments: nil) { (data, err) -> () in + if (err != nil) { + return result(CallFailedError(message: err!.localizedDescription)) + } + + result(data) + } + } + + func activeListPendingHostmap(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } + //TODO: match id for safety? + wormholeRequestWithCallback(type: "listPendingHostmap", arguments: nil) { (data, err) -> () in + if (err != nil) { + return result(CallFailedError(message: err!.localizedDescription)) + } + + result(data) + } + } + + func activeGetHostInfo(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] as? String else { return result(MissingArgumentError(message: "id is a required argument")) } + guard let vpnIp = args["vpnIp"] as? String else { return result(MissingArgumentError(message: "vpnIp is a required argument")) } + let pending = args["pending"] as? Bool ?? false + + //TODO: match id for safety? + wormholeRequestWithCallback(type: "getHostInfo", arguments: ["vpnIp": vpnIp, "pending": pending]) { (data, err) -> () in + if (err != nil) { + return result(CallFailedError(message: err!.localizedDescription)) + } + + result(data) + } + } + + func activeSetRemoteForTunnel(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } + guard let vpnIp = args["vpnIp"] else { return result(MissingArgumentError(message: "vpnIp is a required argument")) } + guard let addr = args["addr"] else { return result(MissingArgumentError(message: "addr is a required argument")) } + + //TODO: match id for safety? + wormholeRequestWithCallback(type: "setRemoteForTunnel", arguments: ["vpnIp": vpnIp, "addr": addr]) { (data, err) -> () in + if (err != nil) { + return result(CallFailedError(message: err!.localizedDescription)) + } + + result(data) + } + } + + func activeCloseTunnel(call: FlutterMethodCall, result: @escaping FlutterResult) { + guard let args = call.arguments as? Dictionary else { return result(NoArgumentsError()) } + guard let id = args["id"] else { return result(MissingArgumentError(message: "id is a required argument")) } + guard let vpnIp = args["vpnIp"] else { return result(MissingArgumentError(message: "vpnIp is a required argument")) } + + //TODO: match id for safety? + wormholeRequestWithCallback(type: "closeTunnel", arguments: ["vpnIp": vpnIp]) { (data, err) -> () in + if (err != nil) { + return result(CallFailedError(message: err!.localizedDescription)) + } + + result(data as? Bool ?? false) + } + } + + func wormholeListener(msg: Any?) { + guard let call = msg as? IPCMessage else { + print("Failed to decode IPCMessage from network extension") + return + } + + switch call.type { + case "error": + guard let updater = self.sites?.getUpdater(id: call.id) else { + return print("Could not find site to deliver error to \(call.id): \(String(describing: call.message))") + } + updater.setError(err: call.message as! String) + + default: + print("Unknown IPC message type \(call.type)") + } + } + + func wormholeRequestWithCallback(type: String, arguments: Dictionary?, completion: @escaping (Any?, Error?) -> ()) { + let uuid = UUID().uuidString + + wormhole.listenForMessage(withIdentifier: uuid) { msg -> () in + self.wormhole.stopListeningForMessage(withIdentifier: uuid) + + guard let call = msg as? IPCMessage else { + completion("", "Failed to decode IPCMessage callback from network extension") + return + } + + switch call.type { + case "error": + completion("", call.message as? String ?? "Failed to convert error") + case "success": + completion(call.message, nil) + + default: + completion("", "Unknown IPC message type \(call.type)") + } + } + + wormhole.passMessageObject(IPCRequest(callbackId: uuid, type: type, arguments: arguments), identifier: "app") + } +} + +func MissingArgumentError(message: String, details: Error? = nil) -> FlutterError { + return FlutterError(code: "missingArgument", message: message, details: details) +} + +func NoArgumentsError(message: String? = "no arguments were provided or could not be deserialized", details: Error? = nil) -> FlutterError { + return FlutterError(code: "noArguments", message: message, details: details) +} + +func CallFailedError(message: String, details: String? = "") -> FlutterError { + return FlutterError(code: "callFailed", message: message, details: details) +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..28c6bf0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..f091b6b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cde121 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..d0ef06e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..dcdc230 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..c8f9ed8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..75b2d16 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..c4df70d Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..6a84f41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..d0e1f58 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..8adf96b --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,51 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + nebula + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + ITSAppUsesNonExemptEncryption + + LSRequiresIPhoneOS + + NSCameraUsageDescription + Camera permission is required for qr code scanning. + NSPhotoLibraryUsageDescription + Just in case you store a nebula certificate as a photo, we aren't interested in your photos but a file picker might come across them + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..7335fdf --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" \ No newline at end of file diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements new file mode 100644 index 0000000..fe9a9e3 --- /dev/null +++ b/ios/Runner/Runner.entitlements @@ -0,0 +1,18 @@ + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + com.apple.security.application-groups + + group.net.defined.mobileNebula + + keychain-access-groups + + $(AppIdentifierPrefix)group.net.defined.mobileNebula + + + diff --git a/ios/Runner/Sites.swift b/ios/Runner/Sites.swift new file mode 100644 index 0000000..b653147 --- /dev/null +++ b/ios/Runner/Sites.swift @@ -0,0 +1,163 @@ +import NetworkExtension +import MobileNebula + +class SiteContainer { + var site: Site + var updater: SiteUpdater + + init(site: Site, updater: SiteUpdater) { + self.site = site + self.updater = updater + } +} + +class Sites { + private var sites = [String: SiteContainer]() + private var messenger: FlutterBinaryMessenger? + + init(messenger: FlutterBinaryMessenger?) { + self.messenger = messenger + } + + func loadSites(completion: @escaping ([String: Site]?, Error?) -> ()) { +#if targetEnvironment(simulator) + let fileManager = FileManager.default + let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("sites") + var configPaths: [URL] + + do { + if (!fileManager.fileExists(atPath: documentsURL.absoluteString)) { + try fileManager.createDirectory(at: documentsURL, withIntermediateDirectories: true) + } + configPaths = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil) + } catch { + return completion(nil, error) + } + + configPaths.forEach { path in + do { + let config = try Data(contentsOf: path) + let decoder = JSONDecoder() + let incoming = try decoder.decode(IncomingSite.self, from: config) + let site = try Site(incoming: incoming) + let updater = SiteUpdater(messenger: self.messenger!, site: site) + self.sites[site.id] = SiteContainer(site: site, updater: updater) + } catch { + print(error) + // try? fileManager.removeItem(at: path) + print("Deleted non conforming site \(path)") + } + } + + let justSites = self.sites.mapValues { + return $0.site + } + completion(justSites, nil) + +#else + NETunnelProviderManager.loadAllFromPreferences() { newManagers, err in + if (err != nil) { + return completion(nil, err) + } + + newManagers?.forEach { manager in + do { + let site = try Site(manager: manager) + // Load the private key to make sure we can + _ = try site.getKey() + let updater = SiteUpdater(messenger: self.messenger!, site: site) + self.sites[site.id] = SiteContainer(site: site, updater: updater) + } catch { + //TODO: notify the user about this + print("Deleted non conforming site \(manager) \(error)") + manager.removeFromPreferences() + } + } + + let justSites = self.sites.mapValues { + return $0.site + } + completion(justSites, nil) + } +#endif + } + + func deleteSite(id: String, callback: @escaping (Error?) -> ()) { + if let site = self.sites.removeValue(forKey: id) { +#if targetEnvironment(simulator) + let fileManager = FileManager.default + let sitePath = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("sites").appendingPathComponent(site.site.id) + try? fileManager.removeItem(at: sitePath) +#else + _ = KeyChain.delete(key: site.site.id) + site.site.manager.removeFromPreferences(completionHandler: callback) +#endif + } + + // Nothing to remove + callback(nil) + } + + func getSite(id: String) -> Site? { + return self.sites[id]?.site + } + + func getUpdater(id: String) -> SiteUpdater? { + return self.sites[id]?.updater + } +} + +class SiteUpdater: NSObject, FlutterStreamHandler { + private var eventSink: FlutterEventSink?; + private var eventChannel: FlutterEventChannel; + private var site: Site + private var notification: Any? + + init(messenger: FlutterBinaryMessenger, site: Site) { + eventChannel = FlutterEventChannel(name: "net.defined.nebula/\(site.id)", binaryMessenger: messenger) + self.site = site + super.init() + eventChannel.setStreamHandler(self) + } + + func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { + eventSink = events; + + self.notification = NotificationCenter.default.addObserver(forName: NSNotification.Name.NEVPNStatusDidChange, object: site.manager.connection , queue: nil) { _ in + + self.site.status = statusString[self.site.manager.connection.status] + self.site.connected = statusMap[self.site.manager.connection.status] + + let d: Dictionary = [ + "connected": self.site.connected!, + "status": self.site.status!, + ] + self.eventSink?(d) + } + + return nil + } + + func setError(err: String) { + let d: Dictionary = [ + "connected": self.site.connected!, + "status": self.site.status!, + ] + self.eventSink?(FlutterError(code: "", message: err, details: d)) + } + + func onCancel(withArguments arguments: Any?) -> FlutterError? { + if (self.notification != nil) { + NotificationCenter.default.removeObserver(self.notification!) + } + return nil + } + + func update(connected: Bool) { + let d: Dictionary = [ + "connected": connected, + "status": connected ? "Connected" : "Disconnected", + ] + self.eventSink?(d) + } +} diff --git a/lib/components/CIDRField.dart b/lib/components/CIDRField.dart new file mode 100644 index 0000000..50e3972 --- /dev/null +++ b/lib/components/CIDRField.dart @@ -0,0 +1,102 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SpecialTextField.dart'; +import 'package:mobile_nebula/models/CIDR.dart'; +import '../services/utils.dart'; +import 'IPField.dart'; + +//TODO: Support initialValue +class CIDRField extends StatefulWidget { + const CIDRField({ + Key key, + this.ipHelp = "ip address", + this.autoFocus = false, + this.focusNode, + this.nextFocusNode, + this.onChanged, + this.textInputAction, + this.ipController, + this.bitsController, + }) : super(key: key); + + final String ipHelp; + final bool autoFocus; + final FocusNode focusNode; + final FocusNode nextFocusNode; + final ValueChanged onChanged; + final TextInputAction textInputAction; + final TextEditingController ipController; + final TextEditingController bitsController; + + @override + _CIDRFieldState createState() => _CIDRFieldState(); +} + +//TODO: if the keyboard is open on the port field and you switch to dark mode, it crashes +//TODO: maybe add in a next/done step for numeric keyboards +//TODO: rig up focus node and next node +//TODO: rig up textInputAction +class _CIDRFieldState extends State { + final bitsFocus = FocusNode(); + final cidr = CIDR(); + + @override + void initState() { + //TODO: this won't track external controller changes appropriately + cidr.ip = widget.ipController?.text ?? ""; + cidr.bits = int.tryParse(widget.bitsController?.text ?? ""); + super.initState(); + } + + @override + Widget build(BuildContext context) { + var textStyle = CupertinoTheme.of(context).textTheme.textStyle; + + return Container( + child: Row(children: [ + Expanded( + child: Padding( + padding: EdgeInsets.fromLTRB(6, 6, 2, 6), + child: IPField( + help: widget.ipHelp, + ipOnly: true, + textPadding: EdgeInsets.all(0), + textInputAction: TextInputAction.next, + textAlign: TextAlign.end, + focusNode: widget.focusNode, + nextFocusNode: bitsFocus, + onChanged: (val) { + cidr.ip = val; + widget.onChanged(cidr); + }, + controller: widget.ipController, + ))), + Text("/"), + Container( + width: Utils.textSize("bits", textStyle).width + 12, + padding: EdgeInsets.fromLTRB(2, 6, 6, 6), + child: SpecialTextField( + keyboardType: TextInputType.number, + focusNode: bitsFocus, + nextFocusNode: widget.nextFocusNode, + controller: widget.bitsController, + onChanged: (val) { + cidr.bits = int.tryParse(val ?? ""); + widget.onChanged(cidr); + }, + maxLength: 2, + inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], + textInputAction: widget.textInputAction ?? TextInputAction.done, + placeholder: 'bits', + )) + ])); + } + + @override + void dispose() { + bitsFocus.dispose(); + super.dispose(); + } +} diff --git a/lib/components/CIDRFormField.dart b/lib/components/CIDRFormField.dart new file mode 100644 index 0000000..1101f3b --- /dev/null +++ b/lib/components/CIDRFormField.dart @@ -0,0 +1,170 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/CIDRField.dart'; +import 'package:mobile_nebula/models/CIDR.dart'; +import 'package:mobile_nebula/validators/ipValidator.dart'; + +class CIDRFormField extends FormField { + //TODO: onSaved, validator, autovalidate, enabled? + CIDRFormField({ + Key key, + autoFocus = false, + focusNode, + nextFocusNode, + ValueChanged onChanged, + FormFieldSetter onSaved, + textInputAction, + CIDR initialValue, + this.ipController, + this.bitsController, + }) : super( + key: key, + initialValue: initialValue, + onSaved: onSaved, + validator: (cidr) { + if (cidr == null) { + return "Please fill out this field"; + } + + if (!ipValidator(cidr.ip)) { + return 'Please enter a valid ip address'; + } + + if (cidr.bits == null || cidr.bits > 32 || cidr.bits < 0) { + return "Please enter a valid number of bits"; + } + + return null; + }, + builder: (FormFieldState field) { + final _CIDRFormField state = field; + + void onChangedHandler(CIDR value) { + if (onChanged != null) { + onChanged(value); + } + field.didChange(value); + } + + return Column(crossAxisAlignment: CrossAxisAlignment.end, children: [ + CIDRField( + autoFocus: autoFocus, + focusNode: focusNode, + nextFocusNode: nextFocusNode, + onChanged: onChangedHandler, + textInputAction: textInputAction, + ipController: state._effectiveIPController, + bitsController: state._effectiveBitsController, + ), + field.hasError + ? Text(field.errorText, + style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), + textAlign: TextAlign.end) + : Container(height: 0) + ]); + }); + + final TextEditingController ipController; + final TextEditingController bitsController; + + @override + _CIDRFormField createState() => _CIDRFormField(); +} + +class _CIDRFormField extends FormFieldState { + TextEditingController _ipController; + TextEditingController _bitsController; + + TextEditingController get _effectiveIPController => widget.ipController ?? _ipController; + TextEditingController get _effectiveBitsController => widget.bitsController ?? _bitsController; + + @override + CIDRFormField get widget => super.widget; + + @override + void initState() { + super.initState(); + if (widget.ipController == null) { + _ipController = TextEditingController(text: widget.initialValue.ip); + } else { + widget.ipController.addListener(_handleControllerChanged); + } + + if (widget.bitsController == null) { + _bitsController = TextEditingController(text: widget.initialValue?.bits?.toString() ?? ""); + } else { + widget.bitsController.addListener(_handleControllerChanged); + } + } + + @override + void didUpdateWidget(CIDRFormField oldWidget) { + super.didUpdateWidget(oldWidget); + var update = CIDR(ip: widget.ipController?.text, bits: int.tryParse(widget.bitsController?.text ?? "") ?? null); + bool shouldUpdate = false; + + if (widget.ipController != oldWidget.ipController) { + oldWidget.ipController?.removeListener(_handleControllerChanged); + widget.ipController?.addListener(_handleControllerChanged); + + if (oldWidget.ipController != null && widget.ipController == null) { + _ipController = TextEditingController.fromValue(oldWidget.ipController.value); + } + + if (widget.ipController != null) { + shouldUpdate = true; + update.ip = widget.ipController.text; + if (oldWidget.ipController == null) _ipController = null; + } + } + + if (widget.bitsController != oldWidget.bitsController) { + oldWidget.bitsController?.removeListener(_handleControllerChanged); + widget.bitsController?.addListener(_handleControllerChanged); + + if (oldWidget.bitsController != null && widget.bitsController == null) { + _bitsController = TextEditingController.fromValue(oldWidget.bitsController.value); + } + + if (widget.bitsController != null) { + shouldUpdate = true; + update.bits = int.parse(widget.bitsController.text); + if (oldWidget.bitsController == null) _bitsController = null; + } + } + + if (shouldUpdate) { + setValue(update); + } + } + + @override + void dispose() { + widget.ipController?.removeListener(_handleControllerChanged); + widget.bitsController?.removeListener(_handleControllerChanged); + super.dispose(); + } + + @override + void reset() { + super.reset(); + setState(() { + _effectiveIPController.text = widget.initialValue.ip; + _effectiveBitsController.text = widget.initialValue.bits.toString(); + }); + } + + void _handleControllerChanged() { + // Suppress changes that originated from within this class. + // + // In the case where a controller has been passed in to this widget, we + // register this change listener. In these cases, we'll also receive change + // notifications for changes originating from within this class -- for + // example, the reset() method. In such cases, the FormField value will + // already have been set. + final effectiveBits = int.parse(_effectiveBitsController.text); + if (_effectiveIPController.text != value.ip || effectiveBits != value.bits) { + didChange(CIDR(ip: _effectiveIPController.text, bits: effectiveBits)); + } + } +} diff --git a/lib/components/FormPage.dart b/lib/components/FormPage.dart new file mode 100644 index 0000000..73cbad1 --- /dev/null +++ b/lib/components/FormPage.dart @@ -0,0 +1,95 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +/// SimplePage with a form and built in validation and confirmation to discard changes if any are made +class FormPage extends StatefulWidget { + const FormPage( + {Key key, this.title, @required this.child, @required this.onSave, @required this.changed, this.hideSave = false}) + : super(key: key); + + final String title; + final Function onSave; + final Widget child; + + /// If you need the page to progress to a certain point before saving, control it here + final bool hideSave; + + /// Useful if you have a non form field that can change, overrides the internal changed state if true + final bool changed; + + @override + _FormPageState createState() => _FormPageState(); +} + +class _FormPageState extends State { + var changed = false; + final _formKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + changed = widget.changed || changed; + + return WillPopScope( + onWillPop: () { + if (!changed) { + return Future.value(true); + } + + var completer = Completer(); + + Utils.confirmDelete(context, 'Discard changes?', () { + completer.complete(true); + }, deleteLabel: 'Yes', cancelLabel: 'No'); + + return completer.future; + }, + child: SimplePage( + leadingAction: _buildLeader(context), + trailingActions: _buildTrailer(context), + title: widget.title, + child: Form( + key: _formKey, + onChanged: () => setState(() { + changed = true; + }), + child: widget.child), + )); + } + + Widget _buildLeader(BuildContext context) { + return Utils.leadingBackWidget(context, label: changed ? 'Cancel' : 'Back', onPressed: () { + if (changed) { + Utils.confirmDelete(context, 'Discard changes?', () { + changed = false; + Navigator.pop(context); + }, deleteLabel: 'Yes', cancelLabel: 'No'); + } else { + Navigator.pop(context); + } + }); + } + + List _buildTrailer(BuildContext context) { + if (!changed || widget.hideSave) { + return []; + } + + return [ + Utils.trailingSaveWidget( + context, + () { + if (!_formKey.currentState.validate()) { + return; + } + + _formKey.currentState.save(); + widget.onSave(); + }, + ) + ]; + } +} diff --git a/lib/components/IPAndPortField.dart b/lib/components/IPAndPortField.dart new file mode 100644 index 0000000..7b78367 --- /dev/null +++ b/lib/components/IPAndPortField.dart @@ -0,0 +1,108 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SpecialTextField.dart'; +import 'package:mobile_nebula/models/IPAndPort.dart'; +import '../services/utils.dart'; +import 'IPField.dart'; + +//TODO: Support initialValue +class IPAndPortField extends StatefulWidget { + const IPAndPortField({ + Key key, + this.ipOnly = false, + this.ipHelp = "ip address", + this.autoFocus = false, + this.focusNode, + this.nextFocusNode, + this.onChanged, + this.textInputAction, + this.noBorder = false, + this.ipTextAlign, + this.ipController, + this.portController, + }) : super(key: key); + + final String ipHelp; + final bool ipOnly; + final bool autoFocus; + final FocusNode focusNode; + final FocusNode nextFocusNode; + final ValueChanged onChanged; + final TextInputAction textInputAction; + final bool noBorder; + final TextAlign ipTextAlign; + final TextEditingController ipController; + final TextEditingController portController; + + @override + _IPAndPortFieldState createState() => _IPAndPortFieldState(); +} + +//TODO: if the keyboard is open on the port field and you switch to dark mode, it crashes +//TODO: maybe add in a next/done step for numeric keyboards +//TODO: rig up focus node and next node +//TODO: rig up textInputAction +class _IPAndPortFieldState extends State { + final _portFocus = FocusNode(); + final _ipAndPort = IPAndPort(); + + @override + void initState() { + //TODO: this won't track external controller changes appropriately + _ipAndPort.ip = widget.ipController?.text ?? ""; + _ipAndPort.port = int.tryParse(widget.portController?.text ?? ""); + super.initState(); + } + + @override + Widget build(BuildContext context) { + var textStyle = CupertinoTheme.of(context).textTheme.textStyle; + + return Container( + child: Row(children: [ + Expanded( + child: Padding( + padding: EdgeInsets.fromLTRB(6, 6, 2, 6), + child: IPField( + help: widget.ipHelp, + ipOnly: widget.ipOnly, + nextFocusNode: _portFocus, + textPadding: EdgeInsets.all(0), + textInputAction: TextInputAction.next, + focusNode: widget.focusNode, + onChanged: (val) { + _ipAndPort.ip = val; + widget.onChanged(_ipAndPort); + }, + textAlign: widget.ipTextAlign, + controller: widget.ipController, + ))), + Text(":"), + Container( + width: Utils.textSize("00000", textStyle).width + 12, + padding: EdgeInsets.fromLTRB(2, 6, 6, 6), + child: SpecialTextField( + keyboardType: TextInputType.number, + focusNode: _portFocus, + nextFocusNode: widget.nextFocusNode, + controller: widget.portController, + onChanged: (val) { + _ipAndPort.port = int.tryParse(val ?? ""); + widget.onChanged(_ipAndPort); + }, + maxLength: 5, + inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], + textInputAction: TextInputAction.done, + placeholder: 'port', + )) + ])); + } + + @override + void dispose() { + _portFocus.dispose(); + super.dispose(); + } +} diff --git a/lib/components/IPAndPortFormField.dart b/lib/components/IPAndPortFormField.dart new file mode 100644 index 0000000..30db081 --- /dev/null +++ b/lib/components/IPAndPortFormField.dart @@ -0,0 +1,180 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/models/IPAndPort.dart'; +import 'package:mobile_nebula/validators/dnsValidator.dart'; +import 'package:mobile_nebula/validators/ipValidator.dart'; + +import 'IPAndPortField.dart'; + +class IPAndPortFormField extends FormField { + //TODO: onSaved, validator, autovalidate, enabled? + IPAndPortFormField({ + Key key, + ipOnly = false, + ipHelp = "ip address", + autoFocus = false, + focusNode, + nextFocusNode, + ValueChanged onChanged, + FormFieldSetter onSaved, + textInputAction, + IPAndPort initialValue, + noBorder, + ipTextAlign = TextAlign.center, + this.ipController, + this.portController, + }) : super( + key: key, + initialValue: initialValue, + onSaved: onSaved, + validator: (ipAndPort) { + if (ipAndPort == null) { + return "Please fill out this field"; + } + + if (!ipValidator(ipAndPort.ip) && (!ipOnly && !dnsValidator(ipAndPort.ip))) { + return ipOnly ? 'Please enter a valid ip address' : 'Please enter a valid ip address or dns name'; + } + + if (ipAndPort.port == null || ipAndPort.port > 65535 || ipAndPort.port < 0) { + return "Please enter a valid port"; + } + + return null; + }, + builder: (FormFieldState field) { + final _IPAndPortFormField state = field; + + void onChangedHandler(IPAndPort value) { + if (onChanged != null) { + onChanged(value); + } + field.didChange(value); + } + + return Column(children: [ + IPAndPortField( + ipOnly: ipOnly, + ipHelp: ipHelp, + autoFocus: autoFocus, + focusNode: focusNode, + nextFocusNode: nextFocusNode, + onChanged: onChangedHandler, + textInputAction: textInputAction, + ipController: state._effectiveIPController, + portController: state._effectivePortController, + noBorder: noBorder, + ipTextAlign: ipTextAlign, + ), + field.hasError + ? Text(field.errorText, + style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13)) + : Container(height: 0) + ]); + }); + + final TextEditingController ipController; + final TextEditingController portController; + + @override + _IPAndPortFormField createState() => _IPAndPortFormField(); +} + +class _IPAndPortFormField extends FormFieldState { + TextEditingController _ipController; + TextEditingController _portController; + + TextEditingController get _effectiveIPController => widget.ipController ?? _ipController; + TextEditingController get _effectivePortController => widget.portController ?? _portController; + + @override + IPAndPortFormField get widget => super.widget; + + @override + void initState() { + super.initState(); + if (widget.ipController == null) { + _ipController = TextEditingController(text: widget.initialValue.ip); + } else { + widget.ipController.addListener(_handleControllerChanged); + } + + if (widget.portController == null) { + _portController = TextEditingController(text: widget.initialValue?.port?.toString() ?? ""); + } else { + widget.portController.addListener(_handleControllerChanged); + } + } + + @override + void didUpdateWidget(IPAndPortFormField oldWidget) { + super.didUpdateWidget(oldWidget); + var update = + IPAndPort(ip: widget.ipController?.text, port: int.tryParse(widget.portController?.text ?? "") ?? null); + bool shouldUpdate = false; + + if (widget.ipController != oldWidget.ipController) { + oldWidget.ipController?.removeListener(_handleControllerChanged); + widget.ipController?.addListener(_handleControllerChanged); + + if (oldWidget.ipController != null && widget.ipController == null) { + _ipController = TextEditingController.fromValue(oldWidget.ipController.value); + } + + if (widget.ipController != null) { + shouldUpdate = true; + update.ip = widget.ipController.text; + if (oldWidget.ipController == null) _ipController = null; + } + } + + if (widget.portController != oldWidget.portController) { + oldWidget.portController?.removeListener(_handleControllerChanged); + widget.portController?.addListener(_handleControllerChanged); + + if (oldWidget.portController != null && widget.portController == null) { + _portController = TextEditingController.fromValue(oldWidget.portController.value); + } + + if (widget.portController != null) { + shouldUpdate = true; + update.port = int.parse(widget.portController.text); + if (oldWidget.portController == null) _portController = null; + } + } + + if (shouldUpdate) { + setValue(update); + } + } + + @override + void dispose() { + widget.ipController?.removeListener(_handleControllerChanged); + widget.portController?.removeListener(_handleControllerChanged); + super.dispose(); + } + + @override + void reset() { + super.reset(); + setState(() { + _effectiveIPController.text = widget.initialValue.ip; + _effectivePortController.text = widget.initialValue.port.toString(); + }); + } + + void _handleControllerChanged() { + // Suppress changes that originated from within this class. + // + // In the case where a controller has been passed in to this widget, we + // register this change listener. In these cases, we'll also receive change + // notifications for changes originating from within this class -- for + // example, the reset() method. In such cases, the FormField value will + // already have been set. + final effectivePort = int.parse(_effectivePortController.text); + if (_effectiveIPController.text != value.ip || effectivePort != value.port) { + didChange(IPAndPort(ip: _effectiveIPController.text, port: effectivePort)); + } + } +} diff --git a/lib/components/IPField.dart b/lib/components/IPField.dart new file mode 100644 index 0000000..d71a1c7 --- /dev/null +++ b/lib/components/IPField.dart @@ -0,0 +1,59 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SpecialTextField.dart'; +import '../services/utils.dart'; + +class IPField extends StatelessWidget { + final String help; + final bool ipOnly; + final bool autoFocus; + final FocusNode focusNode; + final FocusNode nextFocusNode; + final ValueChanged onChanged; + final EdgeInsetsGeometry textPadding; + final TextInputAction textInputAction; + final controller; + final textAlign; + + const IPField( + {Key key, + this.ipOnly = false, + this.help = "ip address", + this.autoFocus = false, + this.focusNode, + this.nextFocusNode, + this.onChanged, + this.textPadding = const EdgeInsets.all(6.0), + this.textInputAction, + this.controller, + this.textAlign = TextAlign.center}) + : super(key: key); + + @override + Widget build(BuildContext context) { + var textStyle = CupertinoTheme.of(context).textTheme.textStyle; + final double ipWidth = ipOnly ? Utils.textSize("000000000000000", textStyle).width + 12 : null; + + return SizedBox( + width: ipWidth, + child: SpecialTextField( + keyboardType: ipOnly ? TextInputType.numberWithOptions(decimal: true) : null, + textAlign: textAlign, + autofocus: autoFocus, + focusNode: focusNode, + nextFocusNode: nextFocusNode, + controller: controller, + onChanged: onChanged, + maxLength: ipOnly ? 15 : null, + maxLengthEnforced: ipOnly ? true : false, + inputFormatters: ipOnly + ? [WhitelistingTextInputFormatter(RegExp(r'[\d\.]+'))] + : [WhitelistingTextInputFormatter(RegExp(r'[^\s]+'))], + textInputAction: this.textInputAction, + placeholder: help, + )); + } +} diff --git a/lib/components/IPFormField.dart b/lib/components/IPFormField.dart new file mode 100644 index 0000000..4cbe129 --- /dev/null +++ b/lib/components/IPFormField.dart @@ -0,0 +1,140 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/validators/dnsValidator.dart'; +import 'package:mobile_nebula/validators/ipValidator.dart'; + +import 'IPField.dart'; + +//TODO: reset doesn't update the ui but clears the field + +class IPFormField extends FormField { + //TODO: validator, autovalidate, enabled? + IPFormField({ + Key key, + ipOnly = false, + help = "ip address", + autoFocus = false, + focusNode, + nextFocusNode, + ValueChanged onChanged, + FormFieldSetter onSaved, + textPadding = const EdgeInsets.all(6.0), + textInputAction, + initialValue, + this.controller, + crossAxisAlignment = CrossAxisAlignment.center, + textAlign = TextAlign.center, + }) : super( + key: key, + initialValue: initialValue, + onSaved: onSaved, + validator: (ip) { + if (ip == null || ip == "") { + return "Please fill out this field"; + } + + if (!ipValidator(ip) || (!ipOnly && !dnsValidator(ip))) { + print(ip); + return ipOnly ? 'Please enter a valid ip address' : 'Please enter a valid ip address or dns name'; + } + + return null; + }, + builder: (FormFieldState field) { + final _IPFormField state = field; + + void onChangedHandler(String value) { + if (onChanged != null) { + onChanged(value); + } + field.didChange(value); + } + + return Column(crossAxisAlignment: crossAxisAlignment, children: [ + IPField( + ipOnly: ipOnly, + help: help, + autoFocus: autoFocus, + focusNode: focusNode, + nextFocusNode: nextFocusNode, + onChanged: onChangedHandler, + textPadding: textPadding, + textInputAction: textInputAction, + controller: state._effectiveController, + textAlign: textAlign), + field.hasError + ? Text( + field.errorText, + style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), + textAlign: textAlign, + ) + : Container(height: 0) + ]); + }); + + final TextEditingController controller; + + @override + _IPFormField createState() => _IPFormField(); +} + +class _IPFormField extends FormFieldState { + TextEditingController _controller; + + TextEditingController get _effectiveController => widget.controller ?? _controller; + + @override + IPFormField get widget => super.widget; + + @override + void initState() { + super.initState(); + if (widget.controller == null) { + _controller = TextEditingController(text: widget.initialValue); + } else { + widget.controller.addListener(_handleControllerChanged); + } + } + + @override + void didUpdateWidget(IPFormField oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.controller != oldWidget.controller) { + oldWidget.controller?.removeListener(_handleControllerChanged); + widget.controller?.addListener(_handleControllerChanged); + + if (oldWidget.controller != null && widget.controller == null) + _controller = TextEditingController.fromValue(oldWidget.controller.value); + if (widget.controller != null) { + setValue(widget.controller.text); + if (oldWidget.controller == null) _controller = null; + } + } + } + + @override + void dispose() { + widget.controller?.removeListener(_handleControllerChanged); + super.dispose(); + } + + @override + void reset() { + super.reset(); + setState(() { + _effectiveController.text = widget.initialValue; + }); + } + + void _handleControllerChanged() { + // Suppress changes that originated from within this class. + // + // In the case where a controller has been passed in to this widget, we + // register this change listener. In these cases, we'll also receive change + // notifications for changes originating from within this class -- for + // example, the reset() method. In such cases, the FormField value will + // already have been set. + if (_effectiveController.text != value) didChange(_effectiveController.text); + } +} diff --git a/lib/components/PlatformTextFormField.dart b/lib/components/PlatformTextFormField.dart new file mode 100644 index 0000000..78ded7b --- /dev/null +++ b/lib/components/PlatformTextFormField.dart @@ -0,0 +1,150 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SpecialTextField.dart'; +//TODO: reset doesn't update the ui but clears the field + +class PlatformTextFormField extends FormField { + //TODO: autovalidate, enabled? + PlatformTextFormField( + {Key key, + widgetKey, + this.controller, + focusNode, + nextFocusNode, + TextInputType keyboardType, + textInputAction, + List inputFormatters, + textAlign, + autofocus, + maxLines = 1, + maxLength, + maxLengthEnforced, + onChanged, + keyboardAppearance, + minLines, + expands, + suffix, + textAlignVertical, + String initialValue, + String placeholder, + FormFieldValidator validator, + ValueChanged onSaved}) + : super( + key: key, + initialValue: controller != null ? controller.text : (initialValue ?? ''), + onSaved: onSaved, + validator: (str) { + if (validator != null) { + return validator(str); + } + + return null; + }, + builder: (FormFieldState field) { + final _PlatformTextFormFieldState state = field; + + void onChangedHandler(String value) { + if (onChanged != null) { + onChanged(value); + } + field.didChange(value); + } + + return Column(crossAxisAlignment: CrossAxisAlignment.end, children: [ + SpecialTextField( + key: widgetKey, + controller: state._effectiveController, + focusNode: focusNode, + nextFocusNode: nextFocusNode, + keyboardType: keyboardType, + textInputAction: textInputAction, + textAlign: textAlign, + autofocus: autofocus, + maxLines: maxLines, + maxLength: maxLength, + maxLengthEnforced: maxLengthEnforced, + onChanged: onChangedHandler, + keyboardAppearance: keyboardAppearance, + minLines: minLines, + expands: expands, + textAlignVertical: textAlignVertical, + placeholder: placeholder, + inputFormatters: inputFormatters, + suffix: suffix), + field.hasError + ? Text( + field.errorText, + style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(field.context), fontSize: 13), + textAlign: textAlign, + ) + : Container(height: 0) + ]); + }); + + final TextEditingController controller; + + @override + _PlatformTextFormFieldState createState() => _PlatformTextFormFieldState(); +} + +class _PlatformTextFormFieldState extends FormFieldState { + TextEditingController _controller; + + TextEditingController get _effectiveController => widget.controller ?? _controller; + + @override + PlatformTextFormField get widget => super.widget; + + @override + void initState() { + super.initState(); + if (widget.controller == null) { + _controller = TextEditingController(text: widget.initialValue); + } else { + widget.controller.addListener(_handleControllerChanged); + } + } + + @override + void didUpdateWidget(PlatformTextFormField oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.controller != oldWidget.controller) { + oldWidget.controller?.removeListener(_handleControllerChanged); + widget.controller?.addListener(_handleControllerChanged); + + if (oldWidget.controller != null && widget.controller == null) + _controller = TextEditingController.fromValue(oldWidget.controller.value); + if (widget.controller != null) { + setValue(widget.controller.text); + if (oldWidget.controller == null) _controller = null; + } + } + } + + @override + void dispose() { + widget.controller?.removeListener(_handleControllerChanged); + super.dispose(); + } + + @override + void reset() { + super.reset(); + setState(() { + _effectiveController.text = widget.initialValue; + }); + } + + void _handleControllerChanged() { + // Suppress changes that originated from within this class. + // + // In the case where a controller has been passed in to this widget, we + // register this change listener. In these cases, we'll also receive change + // notifications for changes originating from within this class -- for + // example, the reset() method. In such cases, the FormField value will + // already have been set. + if (_effectiveController.text != value) didChange(_effectiveController.text); + } +} diff --git a/lib/components/SimplePage.dart b/lib/components/SimplePage.dart new file mode 100644 index 0000000..ade5700 --- /dev/null +++ b/lib/components/SimplePage.dart @@ -0,0 +1,105 @@ +import 'package:flutter/cupertino.dart' as cupertino; +import 'package:flutter/material.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:pull_to_refresh/pull_to_refresh.dart'; + +enum SimpleScrollable { + none, + vertical, + horizontal, + both, +} + +class SimplePage extends StatelessWidget { + const SimplePage( + {Key key, + this.title, + @required this.child, + this.leadingAction, + this.trailingActions = const [], + this.scrollable = SimpleScrollable.vertical, + this.scrollbar = true, + this.scrollController, + this.bottomBar, + this.onRefresh, + this.onLoading, + this.refreshController}) + : super(key: key); + + final String title; + final Widget child; + final SimpleScrollable scrollable; + final ScrollController scrollController; + + /// Set this to true to force draw a scrollbar without a scroll view, this is helpful for pages with Reorderable listviews + /// This is set to true if you have any scrollable other than none + final bool scrollbar; + final Widget bottomBar; + + /// If no leading action is provided then a default "Back" widget than pops the page will be provided + final Widget leadingAction; + final List trailingActions; + + final VoidCallback onRefresh; + final VoidCallback onLoading; + final RefreshController refreshController; + + + @override + Widget build(BuildContext context) { + Widget realChild = child; + var addScrollbar = this.scrollbar; + + if (scrollable == SimpleScrollable.vertical || scrollable == SimpleScrollable.both) { + realChild = SingleChildScrollView(scrollDirection: Axis.vertical, child: realChild, controller: refreshController == null ? scrollController : null); + addScrollbar = true; + } + + if (scrollable == SimpleScrollable.horizontal || scrollable == SimpleScrollable.both) { + realChild = SingleChildScrollView(scrollDirection: Axis.horizontal, child: realChild); + addScrollbar = true; + } + + if (refreshController != null) { + realChild = RefreshConfiguration( + headerTriggerDistance: 100, + footerTriggerDistance: -100, + maxUnderScrollExtent: 100, + child: SmartRefresher( + scrollController: scrollController, + onRefresh: onRefresh, + onLoading: onLoading, + controller: refreshController, + child: realChild, + enablePullUp: onLoading != null, + enablePullDown: onRefresh != null, + footer: ClassicFooter(loadStyle: LoadStyle.ShowWhenLoading), + )); + addScrollbar = true; + } + + if (addScrollbar) { + realChild = Scrollbar(child: realChild); + } + + if (bottomBar != null) { + realChild = Column(children: [ + Expanded(child: realChild), + bottomBar, + ]); + } + + return PlatformScaffold( + backgroundColor: cupertino.CupertinoColors.systemGroupedBackground.resolveFrom(context), + appBar: PlatformAppBar( + title: Text(title), + leading: leadingAction != null ? leadingAction : Utils.leadingBackWidget(context), + trailingActions: trailingActions, + ios: (_) => CupertinoNavigationBarData( + transitionBetweenRoutes: false, + ), + ), + body: SafeArea(child: realChild)); + } +} diff --git a/lib/components/SiteItem.dart b/lib/components/SiteItem.dart new file mode 100644 index 0000000..60150a6 --- /dev/null +++ b/lib/components/SiteItem.dart @@ -0,0 +1,51 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/components/SpecialButton.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class SiteItem extends StatelessWidget { + const SiteItem({Key key, this.site, this.onPressed}) : super(key: key); + + final Site site; + final onPressed; + + @override + Widget build(BuildContext context) { + final borderColor = site.errors.length > 0 + ? CupertinoColors.systemRed.resolveFrom(context) + : site.connected + ? CupertinoColors.systemGreen.resolveFrom(context) + : CupertinoColors.systemGrey2.resolveFrom(context); + final border = BorderSide(color: borderColor, width: 10); + + return Container( + margin: EdgeInsets.symmetric(vertical: 6), + decoration: BoxDecoration(border: Border(left: border)), + child: _buildContent(context)); + } + + Widget _buildContent(BuildContext context) { + final border = BorderSide(color: Utils.configSectionBorder(context)); + var ip = "Error"; + if (site.cert != null) { + ip = site.cert.cert.details.ips[0]; + } + + return SpecialButton( + decoration: + BoxDecoration(border: Border(top: border, bottom: border), color: Utils.configItemBackground(context)), + onPressed: onPressed, + child: Padding( + padding: EdgeInsets.fromLTRB(10, 10, 5, 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text(site.name, style: TextStyle(fontWeight: FontWeight.bold)), + Expanded(child: Text(ip, textAlign: TextAlign.end)), + Padding(padding: EdgeInsets.only(right: 10)), + Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18) + ], + ))); + } +} diff --git a/lib/components/SpecialButton.dart b/lib/components/SpecialButton.dart new file mode 100644 index 0000000..cd04346 --- /dev/null +++ b/lib/components/SpecialButton.dart @@ -0,0 +1,145 @@ +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +// This is a button that pushes the bare minimum onto you, it doesn't even respect button themes - unless you tell it to +class SpecialButton extends StatefulWidget { + const SpecialButton({Key key, this.child, this.color, this.onPressed, this.useButtonTheme = false, this.decoration}) : super(key: key); + + final Widget child; + final Color color; + final bool useButtonTheme; + final BoxDecoration decoration; + + final Function onPressed; + + @override + _SpecialButtonState createState() => _SpecialButtonState(); +} + +class _SpecialButtonState extends State with SingleTickerProviderStateMixin { + @override + Widget build(BuildContext context) { + return Platform.isAndroid ? _buildAndroid() : _buildGeneric(); + } + + Widget _buildAndroid() { + var textStyle; + if (widget.useButtonTheme) { + textStyle = Theme.of(context).textTheme.button; + } + + return Material( + textStyle: textStyle, + child: Ink( + decoration: widget.decoration, + color: widget.color, + child: InkWell( + child: widget.child, + onTap: widget.onPressed, + ))); + } + + Widget _buildGeneric() { + var textStyle = CupertinoTheme.of(context).textTheme.textStyle; + if (widget.useButtonTheme) { + textStyle = CupertinoTheme.of(context).textTheme.actionTextStyle; + } + + return Container( + decoration: widget.decoration, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: _handleTapDown, + onTapUp: _handleTapUp, + onTapCancel: _handleTapCancel, + onTap: widget.onPressed, + child: Semantics( + button: true, + child: FadeTransition( + opacity: _opacityAnimation, + child: DefaultTextStyle(style: textStyle, child: Container(child: widget.child, color: widget.color)), + ), + ), + ) + ); + } + + // Eyeballed values. Feel free to tweak. + static const Duration kFadeOutDuration = Duration(milliseconds: 10); + static const Duration kFadeInDuration = Duration(milliseconds: 100); + final Tween _opacityTween = Tween(begin: 1.0); + + AnimationController _animationController; + Animation _opacityAnimation; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: const Duration(milliseconds: 200), + value: 0.0, + vsync: this, + ); + _opacityAnimation = _animationController.drive(CurveTween(curve: Curves.decelerate)).drive(_opacityTween); + _setTween(); + } + + @override + void didUpdateWidget(SpecialButton old) { + super.didUpdateWidget(old); + _setTween(); + } + + void _setTween() { + _opacityTween.end = 0.4; + } + + @override + void dispose() { + _animationController.dispose(); + _animationController = null; + super.dispose(); + } + + bool _buttonHeldDown = false; + + void _handleTapDown(TapDownDetails event) { + if (!_buttonHeldDown) { + _buttonHeldDown = true; + _animate(); + } + } + + void _handleTapUp(TapUpDetails event) { + if (_buttonHeldDown) { + _buttonHeldDown = false; + _animate(); + } + } + + void _handleTapCancel() { + if (_buttonHeldDown) { + _buttonHeldDown = false; + _animate(); + } + } + + void _animate() { + if (_animationController.isAnimating) { + return; + } + + final bool wasHeldDown = _buttonHeldDown; + final TickerFuture ticker = _buttonHeldDown + ? _animationController.animateTo(1.0, duration: kFadeOutDuration) + : _animationController.animateTo(0.0, duration: kFadeInDuration); + + ticker.then((void value) { + if (mounted && wasHeldDown != _buttonHeldDown) { + _animate(); + } + }); + } +} diff --git a/lib/components/SpecialTextField.dart b/lib/components/SpecialTextField.dart new file mode 100644 index 0000000..ac5deca --- /dev/null +++ b/lib/components/SpecialTextField.dart @@ -0,0 +1,199 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; + +/// A normal TextField or CupertinoTextField that watches for copy, paste, cut, or select all keyboard actions +class SpecialTextField extends StatefulWidget { + const SpecialTextField( + {Key key, + this.placeholder, + this.suffix, + this.controller, + this.focusNode, + this.nextFocusNode, + this.autocorrect, + this.minLines, + this.maxLines, + this.maxLength, + this.maxLengthEnforced, + this.style, + this.keyboardType, + this.textInputAction, + this.textCapitalization, + this.textAlign, + this.autofocus, + this.onChanged, + this.expands, + this.keyboardAppearance, + this.textAlignVertical, + this.inputFormatters}) + : super(key: key); + + final String placeholder; + final TextEditingController controller; + final FocusNode focusNode; + final FocusNode nextFocusNode; + final bool autocorrect; + final int minLines; + final int maxLines; + final int maxLength; + final bool maxLengthEnforced; + final Widget suffix; + final TextStyle style; + final TextInputType keyboardType; + final Brightness keyboardAppearance; + + final TextInputAction textInputAction; + final TextCapitalization textCapitalization; + final TextAlign textAlign; + final TextAlignVertical textAlignVertical; + + final bool autofocus; + final ValueChanged onChanged; + final List inputFormatters; + final bool expands; + + @override + _SpecialTextFieldState createState() => _SpecialTextFieldState(); +} + +class _SpecialTextFieldState extends State { + FocusNode _focusNode = FocusNode(); + List formatters; + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } + + @override + void initState() { + formatters = widget.inputFormatters; + if (formatters == null || formatters.length == 0) { + formatters = [WhitelistingTextInputFormatter(RegExp(r'[^\t]'))]; + } + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return RawKeyboardListener( + focusNode: _focusNode, + onKey: _onKey, + child: PlatformTextField( + autocorrect: widget.autocorrect, + minLines: widget.minLines, + maxLines: widget.maxLines, + maxLength: widget.maxLength, + maxLengthEnforced: widget.maxLengthEnforced, + keyboardType: widget.keyboardType, + keyboardAppearance: widget.keyboardAppearance, + textInputAction: widget.textInputAction, + textCapitalization: widget.textCapitalization, + textAlign: widget.textAlign, + textAlignVertical: widget.textAlignVertical, + autofocus: widget.autofocus, + focusNode: widget.focusNode, + onChanged: widget.onChanged, + onSubmitted: (_) { + if (widget.nextFocusNode != null) { + FocusScope.of(context).requestFocus(widget.nextFocusNode); + } + }, + expands: widget.expands, + inputFormatters: formatters, + android: (_) => MaterialTextFieldData( + decoration: InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.zero, + isDense: true, + hintText: widget.placeholder, + counterText: '', + suffix: widget.suffix)), + ios: (_) => CupertinoTextFieldData( + decoration: BoxDecoration(), + padding: EdgeInsets.zero, + placeholder: widget.placeholder, + suffix: widget.suffix), + style: widget.style, + controller: widget.controller)); + } + + _onKey(RawKeyEvent event) { + // We don't care about key up events + if (event is RawKeyUpEvent) { + return; + } + + if (event.logicalKey == LogicalKeyboardKey.tab) { + // Handle tab to the next node + if (widget.nextFocusNode != null) { + FocusScope.of(context).requestFocus(widget.nextFocusNode); + } + return; + } + + // Handle special keyboard events with control key + if (event.data.isControlPressed) { + // Handle paste + if (event.logicalKey == LogicalKeyboardKey.keyV) { + Clipboard.getData("text/plain").then((data) { + // Adjust our clipboard entry to confirm with the leftover space if we have maxLength + var text = data.text; + if (widget.maxLength != null && widget.maxLength > 0) { + var leftover = widget.maxLength - widget.controller.text.length; + if (leftover < data.text.length) { + text = text.substring(0, leftover); + } + } + + // If maxLength took us to 0 then bail + if (text.length == 0) { + return; + } + + var end = widget.controller.selection.end; + var start = widget.controller.selection.start; + + // Insert our paste buffer into the selection, which can be 0 selected text (normal caret) + widget.controller.text = widget.controller.selection.textBefore(widget.controller.text) + + text + + widget.controller.selection.textAfter(widget.controller.text); + + // Adjust our caret to be at the end of the pasted contents, need to take into account the size of the selection + // We may want runes instead of + end += text.length - (end - start); + widget.controller.selection = TextSelection(baseOffset: end, extentOffset: end); + }); + + return; + } + + // Handle select all + if (event.logicalKey == LogicalKeyboardKey.keyA) { + widget.controller.selection = TextSelection(baseOffset: 0, extentOffset: widget.controller.text.length); + return; + } + + // Handle copy + if (event.logicalKey == LogicalKeyboardKey.keyC) { + Clipboard.setData(ClipboardData(text: widget.controller.selection.textInside(widget.controller.text))); + return; + } + + // Handle cut + if (event.logicalKey == LogicalKeyboardKey.keyX) { + Clipboard.setData(ClipboardData(text: widget.controller.selection.textInside(widget.controller.text))); + + var start = widget.controller.selection.start; + widget.controller.text = widget.controller.selection.textBefore(widget.controller.text) + + widget.controller.selection.textAfter(widget.controller.text); + widget.controller.selection = TextSelection(baseOffset: start, extentOffset: start); + return; + } + } + } +} diff --git a/lib/components/config/ConfigButtonItem.dart b/lib/components/config/ConfigButtonItem.dart new file mode 100644 index 0000000..c0c9b0b --- /dev/null +++ b/lib/components/config/ConfigButtonItem.dart @@ -0,0 +1,41 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SpecialButton.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +// A config item that detects tapping and calls back on a tap +class ConfigButtonItem extends StatelessWidget { + const ConfigButtonItem({Key key, this.content, this.onPressed}) : super(key: key); + + final Widget content; + final onPressed; + + @override + Widget build(BuildContext context) { + return SpecialButton( + color: Utils.configItemBackground(context), + onPressed: onPressed, + useButtonTheme: true, + child: Container( + constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity), + child: Center(child: content), + )); + + return Container( + color: Utils.configItemBackground(context), + constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity), + child: PlatformButton( + androidFlat: (_) => MaterialFlatButtonData( + textTheme: ButtonTextTheme.normal, padding: EdgeInsets.zero, shape: RoundedRectangleBorder()), + ios: (_) => CupertinoButtonData(padding: EdgeInsets.zero, borderRadius: BorderRadius.zero), + padding: EdgeInsets.symmetric(vertical: 7), + child: content, + onPressed: () { + if (onPressed != null) { + onPressed(); + } + }, + )); + } +} diff --git a/lib/components/config/ConfigCheckboxItem.dart b/lib/components/config/ConfigCheckboxItem.dart new file mode 100644 index 0000000..ce7bc86 --- /dev/null +++ b/lib/components/config/ConfigCheckboxItem.dart @@ -0,0 +1,46 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/components/SpecialButton.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class ConfigCheckboxItem extends StatelessWidget { + const ConfigCheckboxItem({Key key, this.label, this.content, this.labelWidth = 100, this.onChanged, this.checked}) + : super(key: key); + + final Widget label; + final Widget content; + final double labelWidth; + final bool checked; + final Function onChanged; + + @override + Widget build(BuildContext context) { + Widget item = Container( + padding: EdgeInsets.only(left: 15), + constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + label != null ? Container(width: labelWidth, child: label) : Container(), + Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))), + checked + ? Icon(CupertinoIcons.check_mark, color: CupertinoColors.systemBlue.resolveFrom(context), size: 34) + : Container() + ], + )); + + if (onChanged != null) { + return SpecialButton( + color: Utils.configItemBackground(context), + child: item, + onPressed: () { + if (onChanged != null) { + onChanged(); + } + }, + ); + } else { + return item; + } + } +} diff --git a/lib/components/config/ConfigHeader.dart b/lib/components/config/ConfigHeader.dart new file mode 100644 index 0000000..3a51fb4 --- /dev/null +++ b/lib/components/config/ConfigHeader.dart @@ -0,0 +1,30 @@ +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +TextStyle basicTextStyle(BuildContext context) => + Platform.isIOS ? CupertinoTheme.of(context).textTheme.textStyle : Theme.of(context).textTheme.subhead; + +const double _headerFontSize = 13.0; + +class ConfigHeader extends StatelessWidget { + const ConfigHeader({Key key, this.label, this.color}) : super(key: key); + + final String label; + final Color color; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.only(left: 10.0, top: 30.0, bottom: 5.0, right: 10.0), + child: Text( + label, + style: basicTextStyle(context).copyWith( + color: color ?? CupertinoColors.secondaryLabel.resolveFrom(context), + fontSize: _headerFontSize, + ), + ), + ); + } +} diff --git a/lib/components/config/ConfigItem.dart b/lib/components/config/ConfigItem.dart new file mode 100644 index 0000000..f4fef54 --- /dev/null +++ b/lib/components/config/ConfigItem.dart @@ -0,0 +1,29 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class ConfigItem extends StatelessWidget { + const ConfigItem( + {Key key, this.label, this.content, this.labelWidth = 100, this.crossAxisAlignment = CrossAxisAlignment.center}) + : super(key: key); + + final Widget label; + final Widget content; + final double labelWidth; + final CrossAxisAlignment crossAxisAlignment; + + @override + Widget build(BuildContext context) { + return Container( + color: Utils.configItemBackground(context), + padding: EdgeInsets.only(top: 2, bottom: 2, left: 15, right: 10), + constraints: BoxConstraints(minHeight: Utils.minInteractiveSize), + child: Row( + crossAxisAlignment: crossAxisAlignment, + children: [ + Container(width: labelWidth, child: label), + Expanded(child: content), + ], + )); + } +} diff --git a/lib/components/config/ConfigPageItem.dart b/lib/components/config/ConfigPageItem.dart new file mode 100644 index 0000000..09a7c68 --- /dev/null +++ b/lib/components/config/ConfigPageItem.dart @@ -0,0 +1,58 @@ +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/components/SpecialButton.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class ConfigPageItem extends StatelessWidget { + const ConfigPageItem( + {Key key, + this.label, + this.content, + this.labelWidth = 100, + this.onPressed, + this.crossAxisAlignment = CrossAxisAlignment.center}) + : super(key: key); + + final Widget label; + final Widget content; + final double labelWidth; + final CrossAxisAlignment crossAxisAlignment; + final onPressed; + + @override + Widget build(BuildContext context) { + var theme; + + if (Platform.isAndroid) { + final origTheme = Theme.of(context); + theme = origTheme.copyWith( + textTheme: + origTheme.textTheme.copyWith(button: origTheme.textTheme.button.copyWith(fontWeight: FontWeight.normal))); + return Theme(data: theme, child: _buildContent(context)); + } else { + final origTheme = CupertinoTheme.of(context); + theme = origTheme.copyWith(primaryColor: CupertinoColors.label.resolveFrom(context)); + return CupertinoTheme(data: theme, child: _buildContent(context)); + } + } + + Widget _buildContent(BuildContext context) { + return SpecialButton( + onPressed: onPressed, + color: Utils.configItemBackground(context), + child: Container( + padding: EdgeInsets.only(left: 15), + constraints: BoxConstraints(minHeight: Utils.minInteractiveSize, minWidth: double.infinity), + child: Row( + crossAxisAlignment: crossAxisAlignment, + children: [ + label != null ? Container(width: labelWidth, child: label) : Container(), + Expanded(child: Container(child: content, padding: EdgeInsets.only(right: 10))), + Icon(CupertinoIcons.forward, color: CupertinoColors.placeholderText.resolveFrom(context), size: 18) + ], + )), + ); + } +} diff --git a/lib/components/config/ConfigSection.dart b/lib/components/config/ConfigSection.dart new file mode 100644 index 0000000..6a2edc1 --- /dev/null +++ b/lib/components/config/ConfigSection.dart @@ -0,0 +1,45 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +import 'ConfigHeader.dart'; + +class ConfigSection extends StatelessWidget { + const ConfigSection({Key key, this.label, this.children, this.borderColor, this.labelColor}) : super(key: key); + + final List children; + final String label; + final Color borderColor; + final Color labelColor; + + @override + Widget build(BuildContext context) { + final border = BorderSide(color: borderColor ?? Utils.configSectionBorder(context)); + + List _children = []; + final len = children.length; + + for (var i = 0; i < len; i++) { + _children.add(children[i]); + + if (i < len - 1) { + double pad = 15; + if (children[i + 1].runtimeType.toString() == 'ConfigButtonItem') { + pad = 0; + } + _children.add(Padding( + child: Divider(height: 1, color: Utils.configSectionBorder(context)), padding: EdgeInsets.only(left: pad))); + } + } + + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + label != null ? ConfigHeader(label: label, color: labelColor) : Container(height: 20), + Container( + decoration: + BoxDecoration(border: Border(top: border, bottom: border), color: Utils.configItemBackground(context)), + child: Column( + children: _children, + )) + ]); + } +} diff --git a/lib/components/config/ConfigTextItem.dart b/lib/components/config/ConfigTextItem.dart new file mode 100644 index 0000000..aa6e975 --- /dev/null +++ b/lib/components/config/ConfigTextItem.dart @@ -0,0 +1,25 @@ +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/components/SpecialTextField.dart'; + +class ConfigTextItem extends StatelessWidget { + const ConfigTextItem({Key key, this.placeholder, this.controller}) : super(key: key); + + final String placeholder; + final TextEditingController controller; + + @override + Widget build(BuildContext context) { + return Padding( + padding: Platform.isAndroid ? EdgeInsets.all(5) : EdgeInsets.zero, + child: SpecialTextField( + autocorrect: false, + minLines: 3, + maxLines: 10, + placeholder: placeholder, + style: TextStyle(fontFamily: 'RobotoMono'), + controller: controller)); + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..329d8c1 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,100 @@ +import 'package:flutter/cupertino.dart' show CupertinoThemeData, DefaultCupertinoLocalizations; +import 'package:flutter/material.dart' + show BottomSheetThemeData, Colors, DefaultMaterialLocalizations, Theme, ThemeData, ThemeMode; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/screens/MainScreen.dart'; +import 'package:mobile_nebula/services/settings.dart'; + +//TODO: EventChannel might be better than the streamcontroller we are using now + +void main() => runApp(Main()); + +class Main extends StatelessWidget { + // This widget is the root of your application. + @override + Widget build(BuildContext context) => App(); +} + +class App extends StatefulWidget { + @override + _AppState createState() => _AppState(); +} + +class _AppState extends State { + final settings = Settings(); + Brightness brightness = SchedulerBinding.instance.window.platformBrightness; + + @override + void initState() { + //TODO: wait until settings is ready? + settings.onChange().listen((_) { + setState(() { + if (!settings.useSystemColors) { + brightness = settings.darkMode ? Brightness.dark : Brightness.light; + } + }); + }); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + final ThemeData lightTheme = ThemeData( + brightness: Brightness.light, + primarySwatch: Colors.blueGrey, + primaryColor: Colors.blueGrey[900], + primaryColorBrightness: Brightness.dark, + accentColor: Colors.cyan[600], + accentColorBrightness: Brightness.dark, + fontFamily: 'PublicSans', + //scaffoldBackgroundColor: Colors.grey[100], + scaffoldBackgroundColor: Colors.white, + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: Colors.blueGrey[50], + ), + ); + + final ThemeData darkTheme = ThemeData( + brightness: Brightness.dark, + primarySwatch: Colors.grey, + primaryColor: Colors.grey[900], + primaryColorBrightness: Brightness.dark, + accentColor: Colors.cyan[600], + accentColorBrightness: Brightness.dark, + fontFamily: 'PublicSans', + scaffoldBackgroundColor: Colors.grey[800], + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: Colors.grey[850], + ), + ); + + // This theme is required since icons light/dark mode will look for it + return Theme( + data: brightness == Brightness.light ? lightTheme : darkTheme, + child: PlatformProvider( + //initialPlatform: initialPlatform, + builder: (context) => PlatformApp( + localizationsDelegates: >[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + DefaultCupertinoLocalizations.delegate, + ], + title: 'Nebula', + android: (_) { + return new MaterialAppData( + themeMode: brightness == Brightness.light ? ThemeMode.light : ThemeMode.dark, + ); + }, + ios: (_) => CupertinoAppData( + theme: CupertinoThemeData(brightness: brightness), + ), + home: MainScreen(), + ), + ), + ); + } +} diff --git a/lib/models/CIDR.dart b/lib/models/CIDR.dart new file mode 100644 index 0000000..788805e --- /dev/null +++ b/lib/models/CIDR.dart @@ -0,0 +1,25 @@ +class CIDR { + CIDR({this.ip, this.bits}); + + String ip; + int bits; + + @override + String toString() { + return '$ip/$bits'; + } + + String toJson() { + return toString(); + } + + CIDR.fromString(String val) { + final parts = val.split('/'); + if (parts.length != 2) { + throw 'Invalid CIDR string'; + } + + ip = parts[0]; + bits = int.parse(parts[1]); + } +} diff --git a/lib/models/Certificate.dart b/lib/models/Certificate.dart new file mode 100644 index 0000000..64bffc2 --- /dev/null +++ b/lib/models/Certificate.dart @@ -0,0 +1,83 @@ +class CertificateInfo { + Certificate cert; + String rawCert; + CertificateValidity validity; + + CertificateInfo.debug({this.rawCert = ""}) + : this.cert = Certificate.debug(), + this.validity = CertificateValidity.debug(); + + CertificateInfo.fromJson(Map json) + : cert = Certificate.fromJson(json['Cert']), + rawCert = json['RawCert'], + validity = CertificateValidity.fromJson(json['Validity']); + + CertificateInfo({this.cert, this.rawCert, this.validity}); + + static List fromJsonList(List list) { + return list.map((v) => CertificateInfo.fromJson(v)); + } +} + +class Certificate { + CertificateDetails details; + String fingerprint; + String signature; + + Certificate.debug() + : this.details = CertificateDetails.debug(), + this.fingerprint = "DEBUG", + this.signature = "DEBUG"; + + Certificate.fromJson(Map json) + : details = CertificateDetails.fromJson(json['details']), + fingerprint = json['fingerprint'], + signature = json['signature']; +} + +class CertificateDetails { + String name; + DateTime notBefore; + DateTime notAfter; + String publicKey; + List groups; + List ips; + List subnets; + bool isCa; + String issuer; + + CertificateDetails.debug() + : this.name = "DEBUG", + notBefore = DateTime.now(), + notAfter = DateTime.now(), + publicKey = "", + groups = [], + ips = [], + subnets = [], + isCa = false, + issuer = "DEBUG"; + + CertificateDetails.fromJson(Map json) + : name = json['name'], + notBefore = DateTime.tryParse(json['notBefore']), + notAfter = DateTime.tryParse(json['notAfter']), + publicKey = json['publicKey'], + groups = List.from(json['groups']), + ips = List.from(json['ips']), + subnets = List.from(json['subnets']), + isCa = json['isCa'], + issuer = json['issuer']; +} + +class CertificateValidity { + bool valid; + String reason; + + CertificateValidity.debug() + : this.valid = true, + this.reason = ""; + + CertificateValidity.fromJson(Map json) + : valid = json['Valid'], + reason = json['Reason']; +} diff --git a/lib/models/HostInfo.dart b/lib/models/HostInfo.dart new file mode 100644 index 0000000..32f008f --- /dev/null +++ b/lib/models/HostInfo.dart @@ -0,0 +1,49 @@ +import 'package:mobile_nebula/models/Certificate.dart'; + +class HostInfo { + String vpnIp; + int localIndex; + int remoteIndex; + List remoteAddresses; + int cachedPackets; + Certificate cert; + UDPAddress currentRemote; + int messageCounter; + + HostInfo.fromJson(Map json) { + vpnIp = json['vpnIp']; + localIndex = json['localIndex']; + remoteIndex = json['remoteIndex']; + cachedPackets = json['cachedPackets']; + + if (json['currentRemote'] != null) { + currentRemote = UDPAddress.fromJson(json['currentRemote']); + } + + if (json['cert'] != null) { + cert = Certificate.fromJson(json['cert']); + } + + List addrs = json['remoteAddrs']; + remoteAddresses = []; + addrs?.forEach((val) { + remoteAddresses.add(UDPAddress.fromJson(val)); + }); + + messageCounter = json['messageCounter']; + } +} + +class UDPAddress { + String ip; + int port; + + @override + String toString() { + return '$ip:$port'; + } + + UDPAddress.fromJson(Map json) + : ip = json['IP'], + port = json['Port']; +} diff --git a/lib/models/Hostmap.dart b/lib/models/Hostmap.dart new file mode 100644 index 0000000..f30cdd6 --- /dev/null +++ b/lib/models/Hostmap.dart @@ -0,0 +1,9 @@ +import 'IPAndPort.dart'; + +class Hostmap { + String nebulaIp; + List destinations; + bool lighthouse; + + Hostmap({this.nebulaIp, this.destinations, this.lighthouse}); +} diff --git a/lib/models/IPAndPort.dart b/lib/models/IPAndPort.dart new file mode 100644 index 0000000..a1aa044 --- /dev/null +++ b/lib/models/IPAndPort.dart @@ -0,0 +1,25 @@ +class IPAndPort { + IPAndPort({this.ip, this.port}); + + String ip; + int port; + + @override + String toString() { + return '$ip:$port'; + } + + String toJson() { + return toString(); + } + + IPAndPort.fromString(String val) { + final parts = val.split(':'); + if (parts.length != 2) { + throw 'Invalid IPAndPort string'; + } + + ip = parts[0]; + port = int.parse(parts[1]); + } +} diff --git a/lib/models/Site.dart b/lib/models/Site.dart new file mode 100644 index 0000000..11a0877 --- /dev/null +++ b/lib/models/Site.dart @@ -0,0 +1,305 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:mobile_nebula/models/HostInfo.dart'; +import 'package:mobile_nebula/models/UnsafeRoute.dart'; +import 'package:uuid/uuid.dart'; +import 'Certificate.dart'; +import 'StaticHosts.dart'; + +var uuid = Uuid(); + +class Site { + static const platform = MethodChannel('net.defined.mobileNebula/NebulaVpnService'); + EventChannel _updates; + + /// Signals that something about this site has changed. onError is called with an error string if there was an error + StreamController _change = StreamController.broadcast(); + + // Identifiers + String name; + String id; + + // static_host_map + Map staticHostmap; + List unsafeRoutes; + + // pki fields + List ca; + CertificateInfo cert; + String key; + + // lighthouse options + int lhDuration; // in seconds + + // listen settings + int port; + int mtu; + + String cipher; + int sortKey; + bool connected; + String status; + String logFile; + String logVerbosity; + + // A list of errors encountered while loading the site + List errors; + + Site( + {this.name, + id, + staticHostmap, + ca, + this.cert, + this.lhDuration = 0, + this.port = 0, + this.cipher = "aes", + this.sortKey, + this.mtu, + this.connected, + this.status, + this.logFile, + this.logVerbosity, + errors, + unsafeRoutes}) + : staticHostmap = staticHostmap ?? {}, + unsafeRoutes = unsafeRoutes ?? [], + errors = errors ?? [], + ca = ca ?? [], + id = id ?? uuid.v4(); + + Site.fromJson(Map json) { + name = json['name']; + id = json['id']; + + Map rawHostmap = json['staticHostmap']; + staticHostmap = {}; + rawHostmap.forEach((key, val) { + staticHostmap[key] = StaticHost.fromJson(val); + }); + + List rawUnsafeRoutes = json['unsafeRoutes']; + unsafeRoutes = []; + if (rawUnsafeRoutes != null) { + rawUnsafeRoutes.forEach((val) { + unsafeRoutes.add(UnsafeRoute.fromJson(val)); + }); + } + + List rawCA = json['ca']; + ca = []; + rawCA.forEach((val) { + ca.add(CertificateInfo.fromJson(val)); + }); + + if (json['cert'] != null) { + cert = CertificateInfo.fromJson(json['cert']); + } + + lhDuration = json['lhDuration']; + port = json['port']; + mtu = json['mtu']; + cipher = json['cipher']; + sortKey = json['sortKey']; + logFile = json['logFile']; + logVerbosity = json['logVerbosity']; + connected = json['connected'] ?? false; + status = json['status'] ?? ""; + + errors = []; + List rawErrors = json["errors"]; + rawErrors.forEach((error) { + errors.add(error); + }); + + _updates = EventChannel('net.defined.nebula/$id'); + _updates.receiveBroadcastStream().listen((d) { + try { + this.status = d['status']; + this.connected = d['connected']; + _change.add(null); + } catch (err) { + //TODO: handle the error + print(err); + } + }, onError: (err) { + var error = err as PlatformException; + this.status = error.details['status']; + this.connected = error.details['connected']; + _change.addError(error.message); + }); + } + + Stream onChange() { + return _change.stream; + } + + Map toJson() { + return { + 'name': name, + 'id': id, + 'staticHostmap': staticHostmap, + 'unsafeRoutes': unsafeRoutes, + 'ca': ca?.map((cert) { + return cert.rawCert; + })?.join('\n') ?? + "", + 'cert': cert?.rawCert, + 'key': key, + 'lhDuration': lhDuration, + 'port': port, + 'mtu': mtu, + 'cipher': cipher, + 'sortKey': sortKey, + 'logVerbosity': logVerbosity, + }; + } + + save() async { + try { + var raw = jsonEncode(this); + await platform.invokeMethod("saveSite", raw); + } on PlatformException catch (err) { + //TODO: fix this message + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future renderConfig() async { + try { + var raw = jsonEncode(this); + return await platform.invokeMethod("nebula.renderConfig", raw); + } on PlatformException catch (err) { + //TODO: fix this message + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + start() async { + try { + await platform.invokeMethod("startSite", {"id": id}); + } on PlatformException catch (err) { + //TODO: fix this message + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + stop() async { + try { + await platform.invokeMethod("stopSite", {"id": id}); + } on PlatformException catch (err) { + //TODO: fix this message + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future> listHostmap() async { + try { + var ret = await platform.invokeMethod("active.listHostmap", {"id": id}); + + List f = jsonDecode(ret); + List hosts = []; + f.forEach((v) { + hosts.add(HostInfo.fromJson(v)); + }); + + return hosts; + + } on PlatformException catch (err) { + //TODO: fix this message + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future> listPendingHostmap() async { + try { + var ret = await platform.invokeMethod("active.listPendingHostmap", {"id": id}); + + List f = jsonDecode(ret); + List hosts = []; + f.forEach((v) { + hosts.add(HostInfo.fromJson(v)); + }); + + return hosts; + + } on PlatformException catch (err) { + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future>> listAllHostmaps() async { + try { + var res = await Future.wait([this.listHostmap(), this.listPendingHostmap()]); + return {"active": res[0], "pending": res[1]}; + + } on PlatformException catch (err) { + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + void dispose() { + _change.close(); + } + + Future getHostInfo(String vpnIp, bool pending) async { + try { + var ret = await platform.invokeMethod("active.getHostInfo", {"id": id, "vpnIp": vpnIp, "pending": pending}); + final h = jsonDecode(ret); + if (h == null) { + return null; + } + + return HostInfo.fromJson(h); + + } on PlatformException catch (err) { + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future setRemoteForTunnel(String vpnIp, String addr) async { + try { + var ret = await platform.invokeMethod("active.setRemoteForTunnel", {"id": id, "vpnIp": vpnIp, "addr": addr}); + final h = jsonDecode(ret); + if (h == null) { + return null; + } + + return HostInfo.fromJson(h); + + } on PlatformException catch (err) { + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } + + Future closeTunnel(String vpnIp) async { + try { + return await platform.invokeMethod("active.closeTunnel", {"id": id, "vpnIp": vpnIp}); + + } on PlatformException catch (err) { + throw err.details ?? err.message ?? err.toString(); + } catch (err) { + throw err.toString(); + } + } +} diff --git a/lib/models/StaticHosts.dart b/lib/models/StaticHosts.dart new file mode 100644 index 0000000..a55dc0f --- /dev/null +++ b/lib/models/StaticHosts.dart @@ -0,0 +1,28 @@ +import 'IPAndPort.dart'; + +class StaticHost { + bool lighthouse; + List destinations; + + StaticHost({this.lighthouse, this.destinations}); + + StaticHost.fromJson(Map json) { + lighthouse = json['lighthouse']; + + var list = json['destinations'] as List; + var result = List(); + + list.forEach((item) { + result.add(IPAndPort.fromString(item)); + }); + + destinations = result; + } + + Map toJson() { + return { + 'lighthouse': lighthouse, + 'destinations': destinations, + }; + } +} diff --git a/lib/models/UnsafeRoute.dart b/lib/models/UnsafeRoute.dart new file mode 100644 index 0000000..bb53166 --- /dev/null +++ b/lib/models/UnsafeRoute.dart @@ -0,0 +1,18 @@ +class UnsafeRoute { + String route; + String via; + + UnsafeRoute({this.route, this.via}); + + UnsafeRoute.fromJson(Map json) { + route = json['route']; + via = json['via']; + } + + Map toJson() { + return { + 'route': route, + 'via': via, + }; + } +} \ No newline at end of file diff --git a/lib/screens/AboutScreen.dart b/lib/screens/AboutScreen.dart new file mode 100644 index 0000000..6880ea0 --- /dev/null +++ b/lib/screens/AboutScreen.dart @@ -0,0 +1,70 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/gen.versions.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:package_info/package_info.dart'; + +class AboutScreen extends StatefulWidget { + const AboutScreen({Key key}) : super(key: key); + + @override + _AboutScreenState createState() => _AboutScreenState(); +} + +class _AboutScreenState extends State { + bool ready = false; + PackageInfo packageInfo; + + @override + void initState() { + PackageInfo.fromPlatform().then((PackageInfo info) { + packageInfo = info; + setState(() { + ready = true; + }); + }); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + if (!ready) { + return Center( + child: PlatformCircularProgressIndicator(ios: (_) { + return CupertinoProgressIndicatorData(radius: 50); + }), + ); + } + + return SimplePage( + title: 'About', + child: Column(children: [ + ConfigSection(children: [ + ConfigItem(label: Text('App version'), labelWidth: 150, content: _buildText('${packageInfo.version}-${packageInfo.buildNumber} (sha: $gitSha)')), + ConfigItem(label: Text('Nebula version'), labelWidth: 150, content: _buildText('$nebulaVersion ($goVersion)')), + ConfigItem(label: Text('Flutter version'), labelWidth: 150, content: _buildText(flutterVersion['frameworkVersion'])), + ConfigItem(label: Text('Dart version'), labelWidth: 150, content: _buildText(flutterVersion['dartSdkVersion'])), + ]), + ConfigSection(children: [ + ConfigPageItem(label: Text('Changelog'), labelWidth: 300, onPressed: () => Utils.launchUrl('https://defined.net/mobile/changelog', context)), + ConfigPageItem(label: Text('Privacy policy'), labelWidth: 300, onPressed: () => Utils.launchUrl('https://defined.net/mobile/privacy-policy', context)), + ConfigPageItem(label: Text('Licenses'), labelWidth: 300, onPressed: () => Utils.launchUrl('https://defined.net/mobile/license', context)), + ]), + Padding(padding: EdgeInsets.only(top: 20), child: Text('Copyright © 2020 Defined Networking, Inc', textAlign: TextAlign.center,)), + ]), + ); + } + + _buildText(String str) { + return Align(alignment: AlignmentDirectional.centerEnd, child: SelectableText(str)); + } +} \ No newline at end of file diff --git a/lib/screens/HostInfoScreen.dart b/lib/screens/HostInfoScreen.dart new file mode 100644 index 0000000..50cab7a --- /dev/null +++ b/lib/screens/HostInfoScreen.dart @@ -0,0 +1,191 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigCheckboxItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Certificate.dart'; +import 'package:mobile_nebula/models/HostInfo.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/screens/siteConfig/CertificateDetailsScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:pull_to_refresh/pull_to_refresh.dart'; + +class HostInfoScreen extends StatefulWidget { + const HostInfoScreen({Key key, this.hostInfo, this.isLighthouse, this.pending, this.onChanged, this.site}) + : super(key: key); + + final bool isLighthouse; + final bool pending; + final HostInfo hostInfo; + final Function onChanged; + final Site site; + + @override + _HostInfoScreenState createState() => _HostInfoScreenState(); +} + +//TODO: have a config option to refresh hostmaps on a cadence (applies to 3 screens so far) + +class _HostInfoScreenState extends State { + HostInfo hostInfo; + RefreshController refreshController = RefreshController(initialRefresh: false); + + @override + void initState() { + _setHostInfo(widget.hostInfo); + super.initState(); + } + + @override + Widget build(BuildContext context) { + final title = widget.pending ? 'Pending' : 'Active'; + + return SimplePage( + title: '$title Host Info', + refreshController: refreshController, + onRefresh: () async { + await _getHostInfo(); + refreshController.refreshCompleted(); + }, + leadingAction: Utils.leadingBackWidget(context, onPressed: () { + Navigator.pop(context); + }), + child: Column( + children: [_buildMain(), _buildDetails(), _buildRemotes(), !widget.pending ? _buildClose() : Container()])); + } + + Widget _buildMain() { + return ConfigSection(children: [ + ConfigItem(label: Text('VPN IP'), labelWidth: 150, content: SelectableText(hostInfo.vpnIp)), + hostInfo.cert != null + ? ConfigPageItem( + label: Text('Certificate'), + labelWidth: 150, + content: Text(hostInfo.cert.details.name), + onPressed: () => Utils.openPage( + context, (context) => CertificateDetailsScreen(certificate: CertificateInfo(cert: hostInfo.cert)))) + : Container(), + ]); + } + + Widget _buildDetails() { + return ConfigSection(children: [ + ConfigItem( + label: Text('Lighthouse'), labelWidth: 150, content: SelectableText(widget.isLighthouse ? 'Yes' : 'No')), + ConfigItem(label: Text('Local Index'), labelWidth: 150, content: SelectableText('${hostInfo.localIndex}')), + ConfigItem(label: Text('Remote Index'), labelWidth: 150, content: SelectableText('${hostInfo.remoteIndex}')), + ConfigItem( + label: Text('Message Counter'), labelWidth: 150, content: SelectableText('${hostInfo.messageCounter}')), + ConfigItem(label: Text('Cached Packets'), labelWidth: 150, content: SelectableText('${hostInfo.cachedPackets}')), + ]); + } + + Widget _buildRemotes() { + if (hostInfo.remoteAddresses.length == 0) { + return ConfigSection(label: 'REMOTES', children: [ConfigItem(content: Text('No remote addresses yet'), labelWidth: 0)]); + } + + return widget.pending ? _buildStaticRemotes() : _buildEditRemotes(); + } + + Widget _buildEditRemotes() { + List items = []; + final currentRemote = hostInfo.currentRemote.toString(); + final double ipWidth = + Utils.textSize("000.000.000.000:000000", CupertinoTheme.of(context).textTheme.textStyle).width; + + hostInfo.remoteAddresses.forEach((remoteObj) { + String remote = remoteObj.toString(); + items.add(ConfigCheckboxItem( + key: Key(remote), + label: Text(remote), + labelWidth: ipWidth, + checked: currentRemote == remote, + onChanged: () async { + if (remote == currentRemote) { + return; + } + + try { + final h = await widget.site.setRemoteForTunnel(hostInfo.vpnIp, remote); + if (h != null) { + _setHostInfo(h); + } + } catch (err) { + Utils.popError(context, 'Error while changing the remote', err); + } + }, + )); + }); + + return ConfigSection(label: items.length > 0 ? 'Tap to change the active address' : null, children: items); + } + + Widget _buildStaticRemotes() { + List items = []; + final currentRemote = hostInfo.currentRemote.toString(); + final double ipWidth = + Utils.textSize("000.000.000.000:000000", CupertinoTheme.of(context).textTheme.textStyle).width; + + hostInfo.remoteAddresses.forEach((remoteObj) { + String remote = remoteObj.toString(); + items.add(ConfigCheckboxItem( + key: Key(remote), + label: Text(remote), + labelWidth: ipWidth, + checked: currentRemote == remote, + )); + }); + + return ConfigSection(label: items.length > 0 ? 'REMOTES' : null, children: items); + } + + Widget _buildClose() { + return Padding( + padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), + child: SizedBox( + width: double.infinity, + child: PlatformButton( + child: Text('Close Tunnel'), + color: CupertinoColors.systemRed.resolveFrom(context), + onPressed: () => Utils.confirmDelete(context, 'Close Tunnel?', () async { + try { + await widget.site.closeTunnel(hostInfo.vpnIp); + if (widget.onChanged != null) { + widget.onChanged(); + } + Navigator.pop(context); + } catch (err) { + Utils.popError(context, 'Error while trying to close the tunnel', err); + } + }, deleteLabel: 'Close')))); + } + + _getHostInfo() async { + try { + final h = await widget.site.getHostInfo(hostInfo.vpnIp, widget.pending); + if (h == null) { + return Utils.popError(context, '', 'The tunnel for this host no longer exists'); + } + + _setHostInfo(h); + } catch (err) { + Utils.popError(context, 'Failed to refresh host info', err); + } + } + + _setHostInfo(HostInfo h) { + h.remoteAddresses.sort((a, b) { + final diff = Utils.ip2int(a.ip) - Utils.ip2int(b.ip); + return diff == 0 ? a.port - b.port : diff; + }); + + setState(() { + hostInfo = h; + }); + } +} diff --git a/lib/screens/MainScreen.dart b/lib/screens/MainScreen.dart new file mode 100644 index 0000000..d8bc08e --- /dev/null +++ b/lib/screens/MainScreen.dart @@ -0,0 +1,244 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/SiteItem.dart'; +import 'package:mobile_nebula/models/Certificate.dart'; +import 'package:mobile_nebula/models/IPAndPort.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/models/StaticHosts.dart'; +import 'package:mobile_nebula/models/UnsafeRoute.dart'; +import 'package:mobile_nebula/screens/SettingsScreen.dart'; +import 'package:mobile_nebula/screens/SiteDetailScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/SiteConfigScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:uuid/uuid.dart'; + +//TODO: add refresh + +class MainScreen extends StatefulWidget { + const MainScreen({Key key}) : super(key: key); + + @override + _MainScreenState createState() => _MainScreenState(); +} + +class _MainScreenState extends State { + bool ready = false; + List sites; + + static const platform = MethodChannel('net.defined.mobileNebula/NebulaVpnService'); + + @override + void initState() { + _loadSites(); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return SimplePage( + title: 'Nebula', + scrollable: SimpleScrollable.none, + leadingAction: PlatformIconButton( + padding: EdgeInsets.zero, + icon: Icon(Icons.add, size: 28.0), + onPressed: () => Utils.openPage(context, (context) { + return SiteConfigScreen(onSave: (_) { + _loadSites(); + }); + }), + ), + trailingActions: [ + PlatformIconButton( + padding: EdgeInsets.zero, + icon: Icon(Icons.menu, size: 28.0), + onPressed: () => Utils.openPage(context, (_) => SettingsScreen()), + ), + ], + bottomBar: kDebugMode ? _debugSave() : null, + child: _buildBody(), + ); + } + + Widget _buildBody() { + if (!ready) { + return Center( + child: PlatformCircularProgressIndicator(ios: (_) { + return CupertinoProgressIndicatorData(radius: 50); + }), + ); + } + + if (sites == null || sites.length == 0) { + return _buildNoSites(); + } + + return _buildSites(); + } + + Widget _buildNoSites() { + return Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(0, 8.0, 0, 8.0), + child: Text('Welcome to Nebula!', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)), + ), + Text('You don\'t have any site configurations installed yet. Hit the plus button above to get started.', + textAlign: TextAlign.center), + ], + ), + ); + } + + Widget _buildSites() { + List items = []; + sites.forEach((site) { + items.add(SiteItem( + key: Key(site.id), + site: site, + onPressed: () { + Utils.openPage(context, (context) { + return SiteDetailScreen(site: site, onChanged: () => _loadSites()); + }); + })); + }); + + Widget child = ReorderableListView( + padding: EdgeInsets.symmetric(vertical: 5), + children: items, + onReorder: (oldI, newI) async { + if (oldI < newI) { + // removing the item at oldIndex will shorten the list by 1. + newI -= 1; + } + + setState(() { + final Site moved = sites.removeAt(oldI); + sites.insert(newI, moved); + }); + + for (var i = min(oldI, newI); i <= max(oldI, newI); i++) { + sites[i].sortKey = i; + try { + await sites[i].save(); + } catch (err) { + //TODO: display error at the end + print('ERR ${sites[i].name} - $err'); + } + } + + _loadSites(); + }); + + if (Platform.isIOS) { + child = CupertinoTheme(child: child, data: CupertinoTheme.of(context)); + } + + // The theme here is to remove the hardcoded canvas border reordering forces on us + return Theme( + data: Theme.of(context).copyWith(canvasColor: Colors.transparent), + child: child + ); + } + + Widget _debugSave() { + return CupertinoButton( + key: Key('debug-save'), + child: Text("DEBUG SAVE"), + onPressed: () async { + var uuid = Uuid(); + + var cert = '''-----BEGIN NEBULA CERTIFICATE----- +CmMKBnBpeGVsNBIJiYCEUID+//8PKLqMivcFMKTzjoYGOiB4iANINzCjLdlQJSj/ +vJDd080yggfLgW9hT4a/bhGZekog+W+YEJiV36evX4MueQ+npDzJd3zGg5gialu4 +UNGYBP0SQL5bjEyafC0YtETEbrraSfwuFHMvUoi1Kc4XRzTPPvHsEaq3hNNTZtD7 +Pt3sjH83zTMZfnD/Du3ahsvV0rAXUgc= +-----END NEBULA CERTIFICATE-----'''; + + var ca = '''-----BEGIN NEBULA CERTIFICATE----- +CjkKB3Rlc3QgY2EopYyK9wUwpfOOhgY6IHj4yrtHbq+rt4hXTYGrxuQOS0412uKT +4wi5wL503+SAQAESQPhWXuVGjauHS1Qqd3aNA3DY+X8CnAweXNEoJKAN/kjH+BBv +mUOcsdFcCZiXrj7ryQIG1+WfqA46w71A/lV4nAc= +-----END NEBULA CERTIFICATE-----'''; + + var s = Site( + name: "DEBUG TEST", + id: uuid.v4(), + staticHostmap: { + "10.1.0.1": StaticHost(lighthouse: true, destinations: [IPAndPort(ip: '10.1.1.53', port: 4242)]) + }, + ca: [CertificateInfo.debug(rawCert: ca)], + cert: CertificateInfo.debug(rawCert: cert), + unsafeRoutes: [UnsafeRoute(route: '10.3.3.3/32', via: '10.1.0.1')] + ); + + s.key = "-----BEGIN NEBULA X25519 PRIVATE KEY-----\ndYgPb04Bb1xzfgdCfVsKGZrCYe+u5tDWNXKipQBVZ44=\n-----END NEBULA X25519 PRIVATE KEY-----"; + + var err = await s.save(); + if (err != null) { + Utils.popError(context, "Failed to save the site", err); + } else { + _loadSites(); + } + }, + ); + } + + _loadSites() async { + if (Platform.isAndroid) { + await platform.invokeMethod("android.requestPermissions"); + } + + //TODO: This can throw, we need to show an error dialog + Map rawSites = jsonDecode(await platform.invokeMethod('listSites')); + bool hasErrors = false; + + sites = []; + rawSites.values.forEach((rawSite) { + try { + var site = Site.fromJson(rawSite); + if (site.errors.length > 0) { + hasErrors = true; + } + + //TODO: we need to cancel change listeners when we rebuild + site.onChange().listen((_) { + setState(() {}); + }, onError: (err) { + setState(() {}); + if (ModalRoute.of(context).isCurrent) { + Utils.popError(context, "${site.name} Error", err); + } + }); + + sites.add(site); + } catch (err) { + //TODO: handle error + print(err); + } + }); + + if (hasErrors) { + Utils.popError(context, "Site Error(s)", "1 or more sites have errors and need your attention, problem sites have a red border."); + } + + sites.sort((a, b) { + return a.sortKey - b.sortKey; + }); + + setState(() { + ready = true; + }); + } +} diff --git a/lib/screens/SettingsScreen.dart b/lib/screens/SettingsScreen.dart new file mode 100644 index 0000000..75e6985 --- /dev/null +++ b/lib/screens/SettingsScreen.dart @@ -0,0 +1,76 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/services/settings.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +import 'AboutScreen.dart'; + +class SettingsScreen extends StatefulWidget { + @override + _SettingsScreenState createState() { + return _SettingsScreenState(); + } +} + +class _SettingsScreenState extends State { + var settings = Settings(); + + @override + void initState() { + //TODO: we need to unregister on dispose? + settings.onChange().listen((_) { + if (this.mounted) { + setState(() {}); + } + }); + super.initState(); + } + + @override + Widget build(BuildContext context) { + List colorSection = []; + + colorSection.add(ConfigItem( + label: Text('Use system colors'), + labelWidth: 200, + content: Align( + alignment: Alignment.centerRight, + child: Switch.adaptive( + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onChanged: (value) { + settings.useSystemColors = value; + }, + value: settings.useSystemColors, + )), + )); + + if (!settings.useSystemColors) { + colorSection.add(ConfigItem( + label: Text('Dark mode'), + content: Align( + alignment: Alignment.centerRight, + child: Switch.adaptive( + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onChanged: (value) { + settings.darkMode = value; + }, + value: settings.darkMode, + )), + )); + } + + List items = []; + items.add(ConfigSection(children: colorSection)); + items.add(ConfigSection(children: [ConfigPageItem(label: Text('About'), onPressed: () => Utils.openPage(context, (context) => AboutScreen()),)])); + + return SimplePage( + title: 'Settings', + child: Column(children: items), + ); + } +} diff --git a/lib/screens/SiteDetailScreen.dart b/lib/screens/SiteDetailScreen.dart new file mode 100644 index 0000000..160bfb1 --- /dev/null +++ b/lib/screens/SiteDetailScreen.dart @@ -0,0 +1,275 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/HostInfo.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/screens/SiteLogsScreen.dart'; +import 'package:mobile_nebula/screens/SiteTunnelsScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/SiteConfigScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:pull_to_refresh/pull_to_refresh.dart'; + +//TODO: If the site isn't active, don't respond to reloads on hostmaps +//TODO: ios is now the problem with connecting screwing our ability to query the hostmap (its a race) + +class SiteDetailScreen extends StatefulWidget { + const SiteDetailScreen({Key key, this.site, this.onChanged}) : super(key: key); + + final Site site; + final Function onChanged; + + @override + _SiteDetailScreenState createState() => _SiteDetailScreenState(); +} + +class _SiteDetailScreenState extends State { + Site site; + StreamSubscription onChange; + static const platform = MethodChannel('net.defined.mobileNebula/NebulaVpnService'); + bool changed = false; + List activeHosts; + List pendingHosts; + RefreshController refreshController = RefreshController(initialRefresh: false); + bool lastState; + + @override + void initState() { + site = widget.site; + lastState = site.connected; + if (site.connected) { + _listHostmap(); + } + + onChange = site.onChange().listen((_) { + setState(() {}); + if (lastState != site.connected) { + //TODO: connected is set before the nebula object exists leading to a crash race, waiting for "Connected" status is a gross hack but keeps it alive + if (site.status == 'Connected') { + lastState = site.connected; + _listHostmap(); + } else { + lastState = site.connected; + activeHosts = null; + pendingHosts = null; + } + } + }, onError: (err) { + setState(() {}); + Utils.popError(context, "Error", err); + }); + + super.initState(); + } + + @override + void dispose() { + onChange.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SimplePage( + title: site.name, + leadingAction: Utils.leadingBackWidget(context, onPressed: () { + if (changed && widget.onChanged != null) { + widget.onChanged(); + } + Navigator.pop(context); + }), + refreshController: refreshController, + onRefresh: () async { + if (site.connected) { + await _listHostmap(); + } + refreshController.refreshCompleted(); + }, + child: Column(children: [ + _buildErrors(), + _buildConfig(), + site.connected ? _buildHosts() : Container(), + _buildSiteDetails(), + _buildDelete(), + ])); + } + + Widget _buildErrors() { + if (site.errors.length == 0) { + return Container(); + } + + List items = []; + site.errors.forEach((error) { + items.add(ConfigItem( + labelWidth: 0, content: Padding(padding: EdgeInsets.symmetric(vertical: 10), child: SelectableText(error)))); + }); + + return ConfigSection( + label: 'ERRORS', + borderColor: CupertinoColors.systemRed.resolveFrom(context), + labelColor: CupertinoColors.systemRed.resolveFrom(context), + children: items, + ); + } + + Widget _buildConfig() { + return ConfigSection(children: [ + ConfigItem( + label: Text('Status'), + content: Row(mainAxisAlignment: MainAxisAlignment.end, children: [ + Padding( + padding: EdgeInsets.only(right: 5), + child: Text(widget.site.status, + style: TextStyle(color: CupertinoColors.secondaryLabel.resolveFrom(context)))), + Switch.adaptive( + value: widget.site.connected, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onChanged: (v) async { + try { + if (v) { + await widget.site.start(); + } else { + await widget.site.stop(); + } + } catch (error) { + var action = v ? 'start' : 'stop'; + Utils.popError(context, 'Failed to $action the site', error.toString()); + } + }, + ) + ])), + ConfigPageItem( + label: Text('Logs'), + onPressed: () { + Utils.openPage(context, (context) { + return SiteLogsScreen(site: widget.site); + }); + }, + ), + ]); + } + + Widget _buildHosts() { + Widget active, pending; + + if (activeHosts == null) { + active = SizedBox(height: 20, width: 20, child: PlatformCircularProgressIndicator()); + } else { + active = Text(Utils.itemCountFormat(activeHosts.length, singleSuffix: "tunnel", multiSuffix: "tunnels")); + } + + if (pendingHosts == null) { + pending = SizedBox(height: 20, width: 20, child: PlatformCircularProgressIndicator()); + } else { + pending = Text(Utils.itemCountFormat(pendingHosts.length, singleSuffix: "tunnel", multiSuffix: "tunnels")); + } + + return ConfigSection( + label: "TUNNELS", + children: [ + ConfigPageItem( + onPressed: () { + Utils.openPage( + context, + (context) => SiteTunnelsScreen( + pending: false, + tunnels: activeHosts, + site: site, + onChanged: (hosts) { + setState(() { + activeHosts = hosts; + }); + })); + }, + label: Text("Active"), + content: Container(alignment: Alignment.centerRight, child: active)), + ConfigPageItem( + onPressed: () { + Utils.openPage( + context, + (context) => SiteTunnelsScreen( + pending: true, + tunnels: pendingHosts, + site: site, + onChanged: (hosts) { + setState(() { + pendingHosts = hosts; + }); + })); + }, + label: Text("Pending"), + content: Container(alignment: Alignment.centerRight, child: pending)) + ], + ); + } + + Widget _buildSiteDetails() { + return ConfigSection(children: [ + ConfigPageItem( + crossAxisAlignment: CrossAxisAlignment.center, + content: Text('Configuration'), + onPressed: () { + Utils.openPage(context, (context) { + return SiteConfigScreen( + site: widget.site, + onSave: (site) async { + changed = true; + }); + }); + }, + ), + ]); + } + + Widget _buildDelete() { + return Padding( + padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), + child: SizedBox( + width: double.infinity, + child: PlatformButton( + child: Text('Delete'), + color: CupertinoColors.systemRed.resolveFrom(context), + onPressed: () => Utils.confirmDelete(context, 'Delete Site?', () async { + if (await _deleteSite()) { + Navigator.of(context).pop(); + } + })))); + } + + _listHostmap() async { + try { + var maps = await site.listAllHostmaps(); + activeHosts = maps["active"]; + pendingHosts = maps["pending"]; + setState(() {}); + } catch (err) { + Utils.popError(context, 'Error while fetching hostmaps', err); + } + } + + Future _deleteSite() async { + try { + var err = await platform.invokeMethod("deleteSite", widget.site.id); + if (err != null) { + Utils.popError(context, 'Failed to delete the site', err); + return false; + } + } catch (err) { + Utils.popError(context, 'Failed to delete the site', err.toString()); + return false; + } + + if (widget.onChanged != null) { + widget.onChanged(); + } + return true; + } +} diff --git a/lib/screens/SiteLogsScreen.dart b/lib/screens/SiteLogsScreen.dart new file mode 100644 index 0000000..faefc8a --- /dev/null +++ b/lib/screens/SiteLogsScreen.dart @@ -0,0 +1,123 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:flutter_share/flutter_share.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:pull_to_refresh/pull_to_refresh.dart'; + +class SiteLogsScreen extends StatefulWidget { + const SiteLogsScreen({Key key, this.site}) : super(key: key); + + final Site site; + + @override + _SiteLogsScreenState createState() => _SiteLogsScreenState(); +} + +class _SiteLogsScreenState extends State { + String logs = ''; + ScrollController controller = ScrollController(); + RefreshController refreshController = RefreshController(initialRefresh: false); + + @override + void initState() { + loadLogs(); + super.initState(); + } + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SimplePage( + title: widget.site.name, + scrollable: SimpleScrollable.both, + scrollController: controller, + onRefresh: () async { + await loadLogs(); + refreshController.refreshCompleted(); + }, + onLoading: () async { + await loadLogs(); + refreshController.loadComplete(); + }, + refreshController: refreshController, + child: Container( + padding: EdgeInsets.all(5), + constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width), + child: SelectableText(logs.trim(), style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14))), + bottomBar: _buildBottomBar(), + ); + } + + Widget _buildBottomBar() { + var borderSide = BorderSide( + color: CupertinoColors.separator, + style: BorderStyle.solid, + width: 0.0, + ); + + var padding = Platform.isAndroid ? EdgeInsets.fromLTRB(0, 20, 0, 30) : EdgeInsets.all(10); + + return Container( + decoration: BoxDecoration( + border: Border(top: borderSide), + ), + child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + Expanded( + child: PlatformIconButton( + padding: padding, + icon: Icon(context.platformIcons.share, size: 30), + onPressed: () { + FlutterShare.shareFile(title: '${widget.site.name} logs', filePath: widget.site.logFile); + }, + )), + Expanded( + child: PlatformIconButton( + padding: padding, + icon: Icon(context.platformIcons.delete, size: Platform.isIOS ? 38 : 30), + onPressed: () { + Utils.confirmDelete(context, 'Are you sure you want to clear all logs?', () => deleteLogs()); + }, + )), + Expanded( + child: PlatformIconButton( + padding: padding, + icon: Icon(context.platformIcons.downArrow, size: 30), + onPressed: () async { + controller.animateTo(controller.position.maxScrollExtent, + duration: const Duration(milliseconds: 500), curve: Curves.linearToEaseOut); + }, + )), + ])); + } + + loadLogs() async { + var file = File(widget.site.logFile); + try { + final v = await file.readAsString(); + + setState(() { + logs = v; + }); + } catch (err) { + Utils.popError(context, 'Error while reading logs', err.toString()); + } + } + + deleteLogs() async { + var file = File(widget.site.logFile); + await file.writeAsBytes([]); + await loadLogs(); + } +} diff --git a/lib/screens/SiteTunnelsScreen.dart b/lib/screens/SiteTunnelsScreen.dart new file mode 100644 index 0000000..d863306 --- /dev/null +++ b/lib/screens/SiteTunnelsScreen.dart @@ -0,0 +1,132 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/HostInfo.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/screens/HostInfoScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:pull_to_refresh/pull_to_refresh.dart'; + +class SiteTunnelsScreen extends StatefulWidget { + const SiteTunnelsScreen({Key key, this.site, this.tunnels, this.pending, this.onChanged}) : super(key: key); + + final Site site; + final List tunnels; + final bool pending; + final Function(List) onChanged; + + @override + _SiteTunnelsScreenState createState() => _SiteTunnelsScreenState(); +} + +class _SiteTunnelsScreenState extends State { + Site site; + List tunnels; + RefreshController refreshController = RefreshController(initialRefresh: false); + + @override + void initState() { + site = widget.site; + tunnels = widget.tunnels; + _sortTunnels(); + super.initState(); + } + + @override + void dispose() { + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32; + + List children = []; + tunnels.forEach((hostInfo) { + Widget icon; + + final isLh = site.staticHostmap[hostInfo.vpnIp]?.lighthouse ?? false; + if (isLh) { + icon = Icon(Icons.lightbulb_outline, color: CupertinoColors.placeholderText.resolveFrom(context)); + } else { + icon = Icon(Icons.computer, color: CupertinoColors.placeholderText.resolveFrom(context)); + } + + children.add(ConfigPageItem( + onPressed: () => Utils.openPage( + context, + (context) => HostInfoScreen( + isLighthouse: isLh, + hostInfo: hostInfo, + pending: widget.pending, + site: widget.site, + onChanged: () { + _listHostmap(); + })), + label: Row(children: [Padding(child: icon, padding: EdgeInsets.only(right: 10)), Text(hostInfo.vpnIp)]), + labelWidth: ipWidth, + content: Container(alignment: Alignment.centerRight, child: Text(hostInfo.cert?.details?.name ?? "")), + )); + }); + + Widget child; + if (children.length == 0) { + child = Center(child: Padding(child: Text('No tunnels to show'), padding: EdgeInsets.only(top: 30))); + } else { + child = ConfigSection(children: children); + } + + final title = widget.pending ? 'Pending' : 'Active'; + + return SimplePage( + title: "$title Tunnels", + leadingAction: Utils.leadingBackWidget(context, onPressed: () { + Navigator.pop(context); + }), + refreshController: refreshController, + onRefresh: () async { + await _listHostmap(); + refreshController.refreshCompleted(); + }, + child: child); + } + + _sortTunnels() { + tunnels.sort((a, b) { + final aLh = _isLighthouse(a.vpnIp), bLh = _isLighthouse(b.vpnIp); + + if (aLh && !bLh) { + return -1; + } else if (!aLh && bLh) { + return 1; + } + + return Utils.ip2int(a.vpnIp) - Utils.ip2int(b.vpnIp); + }); + } + + bool _isLighthouse(String vpnIp) { + return site.staticHostmap[vpnIp]?.lighthouse ?? false; + } + + _listHostmap() async { + try { + if (widget.pending) { + tunnels = await site.listPendingHostmap(); + } else { + tunnels = await site.listHostmap(); + } + + _sortTunnels(); + if (widget.onChanged != null) { + widget.onChanged(tunnels); + } + setState(() {}); + } catch (err) { + Utils.popError(context, 'Error while fetching hostmap', err); + } + } +} diff --git a/lib/screens/siteConfig/AdvancedScreen.dart b/lib/screens/siteConfig/AdvancedScreen.dart new file mode 100644 index 0000000..5e825fa --- /dev/null +++ b/lib/screens/siteConfig/AdvancedScreen.dart @@ -0,0 +1,186 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/PlatformTextFormField.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/models/UnsafeRoute.dart'; +import 'package:mobile_nebula/screens/siteConfig/CipherScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/LogVerbosityScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/RenderedConfigScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +import 'UnsafeRoutesScreen.dart'; + +//TODO: form validation (seconds and port) +//TODO: wire up the focus nodes, add a done/next/prev to the keyboard +//TODO: fingerprint blacklist +//TODO: show site id here + +class Advanced { + int lhDuration; + int port; + String cipher; + String verbosity; + List unsafeRoutes; + int mtu; +} + +class AdvancedScreen extends StatefulWidget { + const AdvancedScreen({Key key, this.site, @required this.onSave}) : super(key: key); + + final Site site; + final ValueChanged onSave; + + @override + _AdvancedScreenState createState() => _AdvancedScreenState(); +} + +class _AdvancedScreenState extends State { + var settings = Advanced(); + var changed = false; + + @override + void initState() { + settings.lhDuration = widget.site.lhDuration; + settings.port = widget.site.port; + settings.cipher = widget.site.cipher; + settings.verbosity = widget.site.logVerbosity; + settings.unsafeRoutes = widget.site.unsafeRoutes; + settings.mtu = widget.site.mtu; + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: 'Advanced Settings', + changed: changed, + onSave: () { + Navigator.pop(context); + widget.onSave(settings); + }, + child: Column(children: [ + ConfigSection( + children: [ + ConfigItem( + label: Text("Lighthouse interval"), + labelWidth: 200, + //TODO: Auto select on focus? + content: PlatformTextFormField( + initialValue: settings.lhDuration.toString(), + keyboardType: TextInputType.number, + suffix: Text("seconds"), + textAlign: TextAlign.right, + maxLength: 5, + inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], + onSaved: (val) { + setState(() { + settings.lhDuration = int.parse(val); + }); + }, + )), + ConfigItem( + label: Text("Listen port"), + labelWidth: 150, + //TODO: Auto select on focus? + content: PlatformTextFormField( + initialValue: settings.port.toString(), + keyboardType: TextInputType.number, + textAlign: TextAlign.right, + maxLength: 5, + inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], + onSaved: (val) { + setState(() { + settings.port = int.parse(val); + }); + }, + )), + ConfigItem( + label: Text("MTU"), + labelWidth: 150, + content: PlatformTextFormField( + initialValue: settings.mtu.toString(), + keyboardType: TextInputType.number, + textAlign: TextAlign.right, + maxLength: 5, + inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], + onSaved: (val) { + setState(() { + settings.mtu = int.parse(val); + }); + }, + )), + ConfigPageItem( + label: Text('Cipher'), + labelWidth: 150, + content: Text(settings.cipher, textAlign: TextAlign.end), + onPressed: () { + Utils.openPage(context, (context) { + return CipherScreen( + cipher: settings.cipher, + onSave: (cipher) { + setState(() { + settings.cipher = cipher; + changed = true; + }); + }); + }); + }), + ConfigPageItem( + label: Text('Log verbosity'), + labelWidth: 150, + content: Text(settings.verbosity, textAlign: TextAlign.end), + onPressed: () { + Utils.openPage(context, (context) { + return LogVerbosityScreen( + verbosity: settings.verbosity, + onSave: (verbosity) { + setState(() { + settings.verbosity = verbosity; + changed = true; + }); + }); + }); + }), + ConfigPageItem( + label: Text('Unsafe routes'), + labelWidth: 150, + content: Text(Utils.itemCountFormat(settings.unsafeRoutes.length), textAlign: TextAlign.end), + onPressed: () { + Utils.openPage(context, (context) { + return UnsafeRoutesScreen(unsafeRoutes: settings.unsafeRoutes, onSave: (routes) { + setState(() { + settings.unsafeRoutes = routes; + changed = true; + }); + }); + }); + }, + ) + ], + ), + ConfigSection( + children: [ + ConfigPageItem( + content: Text('View rendered config'), + onPressed: () async { + try { + var config = await widget.site.renderConfig(); + Utils.openPage(context, (context) { + return RenderedConfigScreen(config: config); + }); + } catch (err) { + Utils.popError(context, 'Failed to render the site config', err); + } + }, + ) + ], + ) + ])); + } +} diff --git a/lib/screens/siteConfig/CAListScreen.dart b/lib/screens/siteConfig/CAListScreen.dart new file mode 100644 index 0000000..37762ec --- /dev/null +++ b/lib/screens/siteConfig/CAListScreen.dart @@ -0,0 +1,233 @@ +import 'dart:convert'; + +import 'package:barcode_scan/barcode_scan.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigButtonItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/components/config/ConfigTextItem.dart'; +import 'package:mobile_nebula/models/Certificate.dart'; +import 'package:mobile_nebula/screens/siteConfig/CertificateDetailsScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +//TODO: wire up the focus nodes, add a done/next/prev to the keyboard +//TODO: you left off at providing the signed cert back. You need to verify it has your public key in it. You likely want to present the cert details before they can save +//TODO: In addition you will want to think about re-generation while the site is still active (This means storing multiple keys in secure storage) + +class CAListScreen extends StatefulWidget { + const CAListScreen({Key key, this.cas, @required this.onSave}) : super(key: key); + + final List cas; + final ValueChanged> onSave; + + @override + _CAListScreenState createState() => _CAListScreenState(); +} + +class _CAListScreenState extends State { + Map cas = {}; + bool changed = false; + var inputType = "paste"; + final pasteController = TextEditingController(); + static const platform = MethodChannel('net.defined.mobileNebula/NebulaVpnService'); + var error = ""; + + @override + void initState() { + widget.cas.forEach((ca) { + cas[ca.cert.fingerprint] = ca; + }); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + List items = []; + final caItems = _buildCAs(); + + if (caItems.length > 0) { + items.add(ConfigSection(children: caItems)); + } + + items.addAll(_addCA()); + return FormPage( + title: 'Certificate Authorities', + changed: changed, + onSave: () { + if (widget.onSave != null) { + Navigator.pop(context); + widget.onSave(cas.values.map((ca) { + return ca; + }).toList()); + } + }, + child: Column(children: items)); + } + + List _buildCAs() { + List items = []; + cas.forEach((key, ca) { + items.add(ConfigPageItem( + content: Text(ca.cert.details.name), + onPressed: () { + Utils.openPage(context, (context) { + return CertificateDetailsScreen( + certificate: ca, + onDelete: () { + setState(() { + changed = true; + cas.remove(key); + }); + }); + }); + }, + )); + }); + + return items; + } + + _addCAEntry(String ca, ValueChanged callback) async { + String error; + + //TODO: show an error popup + try { + var rawCerts = await platform.invokeMethod("nebula.parseCerts", {"certs": ca}); + List certs = jsonDecode(rawCerts); + certs.forEach((rawCert) { + final info = CertificateInfo.fromJson(rawCert); + cas[info.cert.fingerprint] = info; + }); + + changed = true; + } on PlatformException catch (err) { + //TODO: fix this message + error = err.details ?? err.message; + } + + if (callback != null) { + callback(error); + } + } + + List _addCA() { + List items = [ + Padding( + padding: EdgeInsets.fromLTRB(10, 25, 10, 0), + child: CupertinoSlidingSegmentedControl( + groupValue: inputType, + onValueChanged: (v) { + setState(() { + inputType = v; + }); + }, + children: { + 'paste': Text('Copy/Paste'), + 'file': Text('File'), + 'qr': Text('QR Code'), + }, + )) + ]; + + if (inputType == 'paste') { + items.addAll(_addPaste()); + } else if (inputType == 'file') { + items.addAll(_addFile()); + } else { + items.addAll(_addQr()); + } + + return items; + } + + List _addPaste() { + return [ + ConfigSection( + children: [ + ConfigTextItem( + placeholder: 'CA PEM contents', + controller: pasteController, + ), + ConfigButtonItem( + content: Text('Load CA'), + onPressed: () { + _addCAEntry(pasteController.text, (err) { + print(err); + if (err != null) { + return Utils.popError(context, 'Failed to parse CA content', err); + } + + pasteController.text = ''; + setState(() {}); + }); + }), + ], + ) + ]; + } + + List _addFile() { + return [ + ConfigSection( + children: [ + ConfigButtonItem( + content: Text('Choose a file'), + onPressed: () async { + final file = await FilePicker.getFile(); + if (file == null) { + return; + } + + var content = ""; + try { + content = file.readAsStringSync(); + } catch (err) { + return Utils.popError(context, 'Failed to load CA file', err.toString()); + } + + _addCAEntry(content, (err) { + if (err != null) { + Utils.popError(context, 'Error loading CA file', err); + } else { + setState(() {}); + } + }); + }) + ], + ) + ]; + } + + List _addQr() { + return [ + ConfigSection( + children: [ + ConfigButtonItem( + content: Text('Scan a QR code'), + onPressed: () async { + var options = ScanOptions( + restrictFormat: [BarcodeFormat.qr], + ); + + var result = await BarcodeScanner.scan(options: options); + if (result.rawContent != "") { + _addCAEntry(result.rawContent, (err) { + if (err != null) { + Utils.popError(context, 'Error loading CA content', err); + } else { + setState(() {}); + } + }); + } + }) + ], + ) + ]; + } +} diff --git a/lib/screens/siteConfig/CertificateDetailsScreen.dart b/lib/screens/siteConfig/CertificateDetailsScreen.dart new file mode 100644 index 0000000..8a4e33f --- /dev/null +++ b/lib/screens/siteConfig/CertificateDetailsScreen.dart @@ -0,0 +1,131 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Certificate.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +/// Displays the details of a CertificateInfo object. Respects incomplete objects (missing validity or rawCert) +class CertificateDetailsScreen extends StatefulWidget { + const CertificateDetailsScreen({Key key, this.certificate, this.onDelete}) : super(key: key); + + final CertificateInfo certificate; + final Function onDelete; + + @override + _CertificateDetailsScreenState createState() => _CertificateDetailsScreenState(); +} + +class _CertificateDetailsScreenState extends State { + @override + Widget build(BuildContext context) { + return SimplePage( + title: 'Certificate Details', + child: Column(children: [ + _buildID(), + _buildFilters(), + _buildValid(), + _buildAdvanced(), + _buildDelete(), + ]), + ); + } + + Widget _buildID() { + return ConfigSection(children: [ + ConfigItem(label: Text('Name'), content: SelectableText(widget.certificate.cert.details.name)), + ConfigItem( + label: Text('Type'), + content: Text(widget.certificate.cert.details.isCa ? 'CA certificate' : 'Client certificate')), + ]); + } + + Widget _buildValid() { + var valid = Text('yes'); + if (widget.certificate.validity != null && !widget.certificate.validity.valid) { + valid = Text(widget.certificate.validity.valid ? 'yes' : widget.certificate.validity.reason, + style: TextStyle(color: CupertinoColors.systemRed.resolveFrom(context))); + } + return ConfigSection( + label: 'VALIDITY', + children: [ + ConfigItem(label: Text('Valid?'), content: valid), + ConfigItem( + label: Text('Created'), + content: SelectableText(widget.certificate.cert.details.notBefore.toLocal().toString())), + ConfigItem( + label: Text('Expires'), + content: SelectableText(widget.certificate.cert.details.notAfter.toLocal().toString())), + ], + ); + } + + Widget _buildFilters() { + List items = []; + if (widget.certificate.cert.details.groups.length > 0) { + items.add(ConfigItem( + label: Text('Groups'), content: SelectableText(widget.certificate.cert.details.groups.join(', ')))); + } + + if (widget.certificate.cert.details.ips.length > 0) { + items + .add(ConfigItem(label: Text('IPs'), content: SelectableText(widget.certificate.cert.details.ips.join(', ')))); + } + + if (widget.certificate.cert.details.subnets.length > 0) { + items.add(ConfigItem( + label: Text('Subnets'), content: SelectableText(widget.certificate.cert.details.subnets.join(', ')))); + } + + return items.length > 0 + ? ConfigSection(label: widget.certificate.cert.details.isCa ? 'FILTERS' : 'DETAILS', children: items) + : Container(); + } + + Widget _buildAdvanced() { + return ConfigSection( + children: [ + ConfigItem( + label: Text('Fingerprint'), + content: SelectableText(widget.certificate.cert.fingerprint, + style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), + crossAxisAlignment: CrossAxisAlignment.start), + ConfigItem( + label: Text('Public Key'), + content: SelectableText(widget.certificate.cert.details.publicKey, + style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), + crossAxisAlignment: CrossAxisAlignment.start), + widget.certificate.rawCert != null + ? ConfigItem( + label: Text('PEM Format'), + content: SelectableText(widget.certificate.rawCert, + style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), + crossAxisAlignment: CrossAxisAlignment.start) + : Container(), + ], + ); + } + + Widget _buildDelete() { + if (widget.onDelete == null) { + return Container(); + } + + var title = widget.certificate.cert.details.isCa ? 'Delete CA?' : 'Delete cert?'; + + return Padding( + padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), + child: SizedBox( + width: double.infinity, + child: PlatformButton( + child: Text('Delete'), + color: CupertinoColors.systemRed.resolveFrom(context), + onPressed: () => Utils.confirmDelete(context, title, () async { + Navigator.pop(context); + widget.onDelete(); + })))); + } +} diff --git a/lib/screens/siteConfig/CertificateScreen.dart b/lib/screens/siteConfig/CertificateScreen.dart new file mode 100644 index 0000000..8e2ebf5 --- /dev/null +++ b/lib/screens/siteConfig/CertificateScreen.dart @@ -0,0 +1,293 @@ +import 'dart:convert'; + +import 'package:barcode_scan/barcode_scan.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_share/flutter_share.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigButtonItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/components/config/ConfigTextItem.dart'; +import 'package:mobile_nebula/models/Certificate.dart'; +import 'package:mobile_nebula/screens/siteConfig/CertificateDetailsScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class CertificateResult { + CertificateInfo cert; + String key; + + CertificateResult({this.cert, this.key}); +} + +class CertificateScreen extends StatefulWidget { + const CertificateScreen({Key key, this.cert, this.onSave}) : super(key: key); + + final CertificateInfo cert; + final ValueChanged onSave; + + @override + _CertificateScreenState createState() => _CertificateScreenState(); +} + +class _CertificateScreenState extends State { + String pubKey; + String privKey; + bool changed = false; + + CertificateInfo cert; + + String inputType = 'paste'; + bool shared = false; + + final pasteController = TextEditingController(); + static const platform = MethodChannel('net.defined.mobileNebula/NebulaVpnService'); + + @override + void initState() { + cert = widget.cert; + super.initState(); + } + + @override + Widget build(BuildContext context) { + List items = []; + bool hideSave = true; + + if (cert == null) { + if (pubKey == null) { + items = _buildGenerate(); + } else { + items.addAll(_buildShare()); + items.addAll(_buildLoadCert()); + } + } else { + items.addAll(_buildCertList()); + hideSave = false; + } + + return FormPage( + title: 'Certificate', + changed: changed, + hideSave: hideSave, + onSave: () { + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(CertificateResult(cert: cert, key: privKey)); + } + }, + child: Column(children: items)); + } + + _buildCertList() { + //TODO: generate a full list + return [ + ConfigSection( + children: [ + ConfigPageItem( + content: Text(cert.cert.details.name), + onPressed: () { + Utils.openPage(context, (context) { + //TODO: wire on delete + return CertificateDetailsScreen(certificate: cert); + }); + }, + ) + ], + ) + ]; + } + + List _buildGenerate() { + return [ + ConfigSection(label: 'Please generate a new public and private key', children: [ + ConfigButtonItem( + content: Text('Generate Keys'), + onPressed: () => _generateKeys(), + ) + ]) + ]; + } + + _generateKeys() async { + try { + var kp = await platform.invokeMethod("nebula.generateKeyPair"); + Map keyPair = jsonDecode(kp); + + setState(() { + changed = true; + pubKey = keyPair['PublicKey']; + privKey = keyPair['PrivateKey']; + }); + } on PlatformException catch (err) { + Utils.popError(context, 'Failed to generate key pair', err.details ?? err.message); + } + } + + List _buildShare() { + return [ + ConfigSection( + label: 'Share your public key with a nebula CA so they can sign and return a certificate', + children: [ + ConfigItem( + labelWidth: 0, + content: SelectableText(pubKey, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14)), + ), + ConfigButtonItem( + content: Text('Share Public Key'), + onPressed: () async { + await FlutterShare.share(title: 'Please sign and return a certificate', text: pubKey); + setState(() { + shared = true; + }); + }, + ), + ]) + ]; + } + + List _buildLoadCert() { + List items = [ + Padding( + padding: EdgeInsets.fromLTRB(10, 25, 10, 0), + child: CupertinoSlidingSegmentedControl( + groupValue: inputType, + onValueChanged: (v) { + setState(() { + inputType = v; + }); + }, + children: { + 'paste': Text('Copy/Paste'), + 'file': Text('File'), + 'qr': Text('QR Code'), + }, + )) + ]; + + if (inputType == 'paste') { + items.addAll(_addPaste()); + } else if (inputType == 'file') { + items.addAll(_addFile()); + } else { + items.addAll(_addQr()); + } + + return items; + } + + List _addPaste() { + return [ + ConfigSection( + children: [ + ConfigTextItem( + placeholder: 'Certificate PEM Contents', + controller: pasteController, + ), + ConfigButtonItem( + content: Center(child: Text('Load Certificate')), + onPressed: () { + _addCertEntry(pasteController.text, (err) { + if (err != null) { + return Utils.popError(context, 'Failed to parse certificate content', err); + } + + pasteController.text = ''; + setState(() {}); + }); + }), + ], + ) + ]; + } + + List _addFile() { + return [ + ConfigSection( + children: [ + ConfigButtonItem( + content: Center(child: Text('Choose a file')), + onPressed: () async { + var file; + try { + await FilePicker.clearTemporaryFiles(); + file = await FilePicker.getFile(); + + if (file == null) { + print('GOT A NULL'); + return; + } + } catch (err) { + print('HEY $err'); + } + + var content = ""; + try { + content = file.readAsStringSync(); + } catch (err) { + print('CAUGH IN READ ${file}'); + return Utils.popError(context, 'Failed to load CA file', err.toString()); + } + + _addCertEntry(content, (err) { + if (err != null) { + Utils.popError(context, 'Error loading certificate file', err); + } else { + setState(() {}); + } + }); + }) + ], + ) + ]; + } + + List _addQr() { + return [ + ConfigSection( + children: [ + ConfigButtonItem( + content: Text('Scan a QR code'), + onPressed: () async { + var options = ScanOptions( + restrictFormat: [BarcodeFormat.qr], + ); + + var result = await BarcodeScanner.scan(options: options); + if (result.rawContent != "") { + _addCertEntry(result.rawContent, (err) { + if (err != null) { + Utils.popError(context, 'Error loading certificate content', err); + } else { + setState(() {}); + } + }); + } + }), + ], + ) + ]; + } + + _addCertEntry(String rawCert, ValueChanged callback) async { + String error; + + try { + var rawCerts = await platform.invokeMethod("nebula.parseCerts", {"certs": rawCert}); + List certs = jsonDecode(rawCerts); + if (certs.length > 0) { + cert = CertificateInfo.fromJson(certs.first); + } + } on PlatformException catch (err) { + error = err.details ?? err.message; + } + + if (callback != null) { + callback(error); + } + } +} diff --git a/lib/screens/siteConfig/CipherScreen.dart b/lib/screens/siteConfig/CipherScreen.dart new file mode 100644 index 0000000..9904b5a --- /dev/null +++ b/lib/screens/siteConfig/CipherScreen.dart @@ -0,0 +1,70 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigCheckboxItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class CipherScreen extends StatefulWidget { + const CipherScreen({Key key, this.cipher, @required this.onSave}) : super(key: key); + + final String cipher; + final ValueChanged onSave; + + @override + _CipherScreenState createState() => _CipherScreenState(); +} + +class _CipherScreenState extends State { + String cipher; + bool changed = false; + + @override + void initState() { + cipher = widget.cipher; + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: 'Cipher Selection', + changed: changed, + onSave: () { + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(cipher); + } + }, + child: Column( + children: [ + ConfigSection(children: [ + ConfigCheckboxItem( + label: Text("aes"), + labelWidth: 150, + checked: cipher == "aes", + onChanged: () { + setState(() { + changed = true; + cipher = "aes"; + }); + }, + ), + ConfigCheckboxItem( + label: Text("chachapoly"), + labelWidth: 150, + checked: cipher == "chachapoly", + onChanged: () { + setState(() { + changed = true; + cipher = "chachapoly"; + }); + }, + ) + ]) + ], + )); + } +} diff --git a/lib/screens/siteConfig/LogVerbosityScreen.dart b/lib/screens/siteConfig/LogVerbosityScreen.dart new file mode 100644 index 0000000..d229b25 --- /dev/null +++ b/lib/screens/siteConfig/LogVerbosityScreen.dart @@ -0,0 +1,68 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigCheckboxItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class LogVerbosityScreen extends StatefulWidget { + const LogVerbosityScreen({Key key, this.verbosity, @required this.onSave}) : super(key: key); + + final String verbosity; + final ValueChanged onSave; + + @override + _LogVerbosityScreenState createState() => _LogVerbosityScreenState(); +} + +class _LogVerbosityScreenState extends State { + String verbosity; + bool changed = false; + + @override + void initState() { + verbosity = widget.verbosity; + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: 'Log Verbosity', + changed: changed, + onSave: () { + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(verbosity); + } + }, + child: Column( + children: [ + ConfigSection(children: [ + _buildEntry('debug'), + _buildEntry('info'), + _buildEntry('warning'), + _buildEntry('error'), + _buildEntry('fatal'), + _buildEntry('panic'), + ]) + ], + )); + } + + Widget _buildEntry(String title) { + return ConfigCheckboxItem( + label: Text(title), + labelWidth: 150, + checked: verbosity == title, + onChanged: () { + setState(() { + changed = true; + verbosity = title; + }); + }, + ); + } +} diff --git a/lib/screens/siteConfig/RenderedConfigScreen.dart b/lib/screens/siteConfig/RenderedConfigScreen.dart new file mode 100644 index 0000000..8a11942 --- /dev/null +++ b/lib/screens/siteConfig/RenderedConfigScreen.dart @@ -0,0 +1,21 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:mobile_nebula/components/SimplePage.dart'; + +class RenderedConfigScreen extends StatelessWidget { + final String config; + + RenderedConfigScreen({Key key, this.config}) : super(key: key); + + @override + Widget build(BuildContext context) { + return SimplePage( + title: 'Rendered Site Config', + scrollable: SimpleScrollable.both, + child: Container( + padding: EdgeInsets.all(5), + constraints: BoxConstraints(minWidth: MediaQuery.of(context).size.width), + child: SelectableText(config, style: TextStyle(fontFamily: 'RobotoMono', fontSize: 14))), + ); + } +} diff --git a/lib/screens/siteConfig/SiteConfigScreen.dart b/lib/screens/siteConfig/SiteConfigScreen.dart new file mode 100644 index 0000000..c88b20f --- /dev/null +++ b/lib/screens/siteConfig/SiteConfigScreen.dart @@ -0,0 +1,229 @@ +import 'dart:convert'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/PlatformTextFormField.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Site.dart'; +import 'package:mobile_nebula/screens/siteConfig/AdvancedScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/CAListScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/CertificateScreen.dart'; +import 'package:mobile_nebula/screens/siteConfig/StaticHostsScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +//TODO: Add a config test mechanism + +class SiteConfigScreen extends StatefulWidget { + const SiteConfigScreen({Key key, this.site, this.onSave}) : super(key: key); + + final Site site; + + // This is called after the target OS has saved the configuration + final ValueChanged onSave; + + @override + _SiteConfigScreenState createState() => _SiteConfigScreenState(); +} + +class _SiteConfigScreenState extends State { + bool changed = false; + bool newSite = false; + bool debug = false; + Site site; + + final nameController = TextEditingController(); + + @override + void initState() { + if (widget.site == null) { + newSite = true; + site = Site(); + } else { + site = widget.site; + nameController.text = site.name; + } + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: newSite ? 'New Site' : 'Edit Site', + changed: changed, + onSave: () async { + site.name = nameController.text; + try { + await site.save(); + } catch (error) { + return Utils.popError(context, 'Failed to save the site configuration', error.toString()); + } + + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(site); + } + }, + child: Column( + children: [ + _main(), + _keys(), + _hosts(), + _advanced(), + kDebugMode ? _debugConfig() : Container(height: 0), + ], + )); + } + + Widget _debugConfig() { + var data = ""; + try { + final encoder = new JsonEncoder.withIndent(' '); + data = encoder.convert(site); + } catch (err) { + data = err.toString(); + } + + return ConfigSection(label: 'DEBUG', children: [ConfigItem(labelWidth: 0, content: SelectableText(data))]); + } + + Widget _main() { + return ConfigSection(children: [ + ConfigItem( + label: Text("Name"), + content: PlatformTextFormField( + placeholder: 'Required', + controller: nameController, + )) + ]); + } + + Widget _keys() { + final certError = site.cert == null || !site.cert.validity.valid; + var caError = site.ca.length == 0; + if (!caError) { + site.ca.forEach((ca) { + if (!ca.validity.valid) { + caError = true; + } + }); + } + + return ConfigSection( + label: "IDENTITY", + children: [ + ConfigPageItem( + label: Text('Certificate'), + content: Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: [ + certError + ? Padding( + child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), + padding: EdgeInsets.only(right: 5)) + : Container(), + certError ? Text('Needs attention') : Text(site.cert.cert.details.name) + ]), + onPressed: () { + Utils.openPage(context, (context) { + return CertificateScreen( + cert: site.cert, + onSave: (result) { + setState(() { + changed = true; + site.cert = result.cert; + site.key = result.key; + }); + }); + }); + }, + ), + ConfigPageItem( + label: Text("CA"), + content: + Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: [ + caError + ? Padding( + child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), + padding: EdgeInsets.only(right: 5)) + : Container(), + caError ? Text('Needs attention') : Text(Utils.itemCountFormat(site.ca.length)) + ]), + onPressed: () { + Utils.openPage(context, (context) { + return CAListScreen( + cas: site.ca, + onSave: (ca) { + setState(() { + changed = true; + site.ca = ca; + }); + }); + }); + }) + ], + ); + } + + Widget _hosts() { + return ConfigSection( + label: "Set up static hosts and lighthouses", + children: [ + ConfigPageItem( + label: Text('Hosts'), + content: Wrap(alignment: WrapAlignment.end, crossAxisAlignment: WrapCrossAlignment.center, children: [ + site.staticHostmap.length == 0 + ? Padding( + child: Icon(Icons.error, color: CupertinoColors.systemRed.resolveFrom(context), size: 20), + padding: EdgeInsets.only(right: 5)) + : Container(), + site.staticHostmap.length == 0 + ? Text('Needs attention') + : Text(Utils.itemCountFormat(site.staticHostmap.length)) + ]), + onPressed: () { + Utils.openPage(context, (context) { + return StaticHostsScreen( + hostmap: site.staticHostmap, + onSave: (map) { + setState(() { + changed = true; + site.staticHostmap = map; + }); + }); + }); + }, + ), + ], + ); + } + + Widget _advanced() { + return ConfigSection( + children: [ + ConfigPageItem( + label: Text('Advanced'), + onPressed: () { + Utils.openPage(context, (context) { + return AdvancedScreen( + site: site, + onSave: (settings) { + setState(() { + changed = true; + site.cipher = settings.cipher; + site.lhDuration = settings.lhDuration; + site.port = settings.port; + site.logVerbosity = settings.verbosity; + site.unsafeRoutes = settings.unsafeRoutes; + site.mtu = settings.mtu; + }); + }); + }); + }) + ], + ); + } +} diff --git a/lib/screens/siteConfig/StaticHostmapScreen.dart b/lib/screens/siteConfig/StaticHostmapScreen.dart new file mode 100644 index 0000000..4124e01 --- /dev/null +++ b/lib/screens/siteConfig/StaticHostmapScreen.dart @@ -0,0 +1,197 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/IPAndPortFormField.dart'; +import 'package:mobile_nebula/components/IPFormField.dart'; +import 'package:mobile_nebula/components/config/ConfigButtonItem.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Hostmap.dart'; +import 'package:mobile_nebula/models/IPAndPort.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class _IPAndPort { + final FocusNode focusNode; + IPAndPort destination; + + _IPAndPort({this.focusNode, this.destination}); +} + +class StaticHostmapScreen extends StatefulWidget { + const StaticHostmapScreen( + {Key key, this.nebulaIp, this.destinations, this.lighthouse = false, this.onDelete, @required this.onSave}) + : super(key: key); + + final List destinations; + final String nebulaIp; + final bool lighthouse; + final ValueChanged onSave; + final Function onDelete; + + @override + _StaticHostmapScreenState createState() => _StaticHostmapScreenState(); +} + +class _StaticHostmapScreenState extends State { + Map _destinations = {}; + String _nebulaIp; + bool _lighthouse; + bool changed = false; + + @override + void initState() { + _nebulaIp = widget.nebulaIp; + _lighthouse = widget.lighthouse; + widget.destinations?.forEach((dest) { + _destinations[UniqueKey()] = _IPAndPort(focusNode: FocusNode(), destination: dest); + }); + + if (_destinations.length == 0) { + _addDestination(); + } + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: widget.onDelete == null ? 'New Static Host' : 'Edit Static Host', + changed: changed, + onSave: _onSave, + child: Column(children: [ + ConfigSection(label: 'Maps a nebula ip address to multiple real world addresses', children: [ + ConfigItem( + label: Text('Nebula IP'), + labelWidth: 200, + content: IPFormField( + help: "Required", + initialValue: _nebulaIp, + ipOnly: true, + textAlign: TextAlign.end, + crossAxisAlignment: CrossAxisAlignment.end, + textInputAction: TextInputAction.next, + onSaved: (v) { + _nebulaIp = v; + })), + ConfigItem( + label: Text('Lighthouse'), + labelWidth: 200, + content: Container( + alignment: Alignment.centerRight, + child: Switch.adaptive( + value: _lighthouse, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + onChanged: (v) { + setState(() { + changed = true; + _lighthouse = v; + }); + })), + ), + ]), + ConfigSection( + label: 'List of public ips or dns names where for this host', + children: _buildHosts(), + ), + widget.onDelete != null + ? Padding( + padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), + child: SizedBox( + width: double.infinity, + child: PlatformButton( + child: Text('Delete'), + color: CupertinoColors.systemRed.resolveFrom(context), + onPressed: () => Utils.confirmDelete(context, 'Delete host map?', () { + Navigator.of(context).pop(); + widget.onDelete(); + }), + ))) + : Container() + ])); + } + + _onSave() { + Navigator.pop(context); + if (widget.onSave != null) { + var map = Hostmap(nebulaIp: _nebulaIp, destinations: [], lighthouse: _lighthouse); + + _destinations.forEach((_, dest) { + map.destinations.add(dest.destination); + }); + + widget.onSave(map); + } + } + + List _buildHosts() { + List items = []; + + _destinations.forEach((key, dest) { + items.add(ConfigItem( + key: key, + label: Align( + alignment: Alignment.centerLeft, + child: PlatformIconButton( + padding: EdgeInsets.zero, + icon: Icon(Icons.remove_circle, color: CupertinoColors.systemRed.resolveFrom(context)), + onPressed: () => setState(() { + _removeDestination(key); + _dismissKeyboard(); + }))), + labelWidth: 70, + content: Row(children: [ + Expanded( + child: IPAndPortFormField( + ipHelp: 'public ip or name', + ipTextAlign: TextAlign.end, + noBorder: true, + initialValue: dest.destination, + onSaved: (v) { + dest.destination = v; + }, + )), + ]), + )); + }); + + items.add(ConfigButtonItem( + content: Text('Add another'), + onPressed: () => setState(() { + _addDestination(); + _dismissKeyboard(); + }))); + + return items; + } + + _addDestination() { + changed = true; + _destinations[UniqueKey()] = _IPAndPort(focusNode: FocusNode(), destination: IPAndPort()); + // We can't onChanged here because it causes rendering issues on first build due to ensuring there is a single destination + } + + _removeDestination(Key key) { + changed = true; + _destinations.remove(key); + } + + _dismissKeyboard() { + FocusScopeNode currentFocus = FocusScope.of(context); + + if (!currentFocus.hasPrimaryFocus) { + currentFocus.unfocus(); + } + } + + @override + void dispose() { + _destinations.forEach((key, dest) { + dest.focusNode.dispose(); + }); + + super.dispose(); + } +} diff --git a/lib/screens/siteConfig/StaticHostsScreen.dart b/lib/screens/siteConfig/StaticHostsScreen.dart new file mode 100644 index 0000000..5c2f7c3 --- /dev/null +++ b/lib/screens/siteConfig/StaticHostsScreen.dart @@ -0,0 +1,142 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigButtonItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/Hostmap.dart'; +import 'package:mobile_nebula/models/IPAndPort.dart'; +import 'package:mobile_nebula/models/StaticHosts.dart'; +import 'package:mobile_nebula/screens/siteConfig/StaticHostMapScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +//TODO: wire up the focus nodes, add a done/next/prev to the keyboard + +class _Hostmap { + final FocusNode focusNode; + String nebulaIp; + List destinations; + bool lighthouse; + + _Hostmap({this.focusNode, this.nebulaIp, destinations, this.lighthouse}) + : destinations = destinations ?? List(); +} + +class StaticHostsScreen extends StatefulWidget { + const StaticHostsScreen({Key key, @required this.hostmap, @required this.onSave}) : super(key: key); + + final Map hostmap; + final ValueChanged> onSave; + + @override + _StaticHostsScreenState createState() => _StaticHostsScreenState(); +} + +class _StaticHostsScreenState extends State { + Map _hostmap = {}; + bool changed = false; + + @override + void initState() { + widget.hostmap?.forEach((key, map) { + _hostmap[UniqueKey()] = + _Hostmap(focusNode: FocusNode(), nebulaIp: key, destinations: map.destinations, lighthouse: map.lighthouse); + }); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: 'Static Hosts', + changed: changed, + onSave: _onSave, + child: ConfigSection( + children: _buildHosts(), + )); + } + + _onSave() { + Navigator.pop(context); + if (widget.onSave != null) { + Map map = {}; + _hostmap.forEach((_, host) { + map[host.nebulaIp] = StaticHost(destinations: host.destinations, lighthouse: host.lighthouse); + }); + + widget.onSave(map); + } + } + + List _buildHosts() { + final double ipWidth = Utils.textSize("000.000.000.000", CupertinoTheme.of(context).textTheme.textStyle).width + 32; + List items = []; + _hostmap.forEach((key, host) { + items.add(ConfigPageItem( + label: Row(children: [ + Padding( + child: Icon(host.lighthouse ? Icons.lightbulb_outline : Icons.computer, + color: CupertinoColors.placeholderText.resolveFrom(context)), + padding: EdgeInsets.only(right: 10)), + Text(host.nebulaIp), + ]), + labelWidth: ipWidth, + content: Text(host.destinations.length.toString() + ' items', textAlign: TextAlign.end), + onPressed: () { + Utils.openPage(context, (context) { + return StaticHostmapScreen( + nebulaIp: host.nebulaIp, + destinations: host.destinations, + lighthouse: host.lighthouse, + onSave: (map) { + setState(() { + changed = true; + host.nebulaIp = map.nebulaIp; + host.destinations = map.destinations; + host.lighthouse = map.lighthouse; + }); + }, + onDelete: () { + setState(() { + changed = true; + _hostmap.remove(key); + }); + }); + }); + }, + )); + }); + + items.add(ConfigButtonItem( + content: Text('Add a new entry'), + onPressed: () { + Utils.openPage(context, (context) { + return StaticHostmapScreen(onSave: (map) { + setState(() { + changed = true; + _addHostmap(map); + }); + }); + }); + }, + )); + + return items; + } + + _addHostmap(Hostmap map) { + _hostmap[UniqueKey()] = (_Hostmap( + focusNode: FocusNode(), nebulaIp: map.nebulaIp, destinations: map.destinations, lighthouse: map.lighthouse)); + } + + @override + void dispose() { + _hostmap.forEach((key, host) { + host.focusNode.dispose(); + }); + + super.dispose(); + } +} diff --git a/lib/screens/siteConfig/UnsafeRouteScreen.dart b/lib/screens/siteConfig/UnsafeRouteScreen.dart new file mode 100644 index 0000000..97c3a44 --- /dev/null +++ b/lib/screens/siteConfig/UnsafeRouteScreen.dart @@ -0,0 +1,115 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:mobile_nebula/components/CIDRFormField.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/IPFormField.dart'; +import 'package:mobile_nebula/components/PlatformTextFormField.dart'; +import 'package:mobile_nebula/components/config/ConfigItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/CIDR.dart'; +import 'package:mobile_nebula/models/UnsafeRoute.dart'; +import 'package:mobile_nebula/services/utils.dart'; +import 'package:mobile_nebula/validators/mtuValidator.dart'; + +class UnsafeRouteScreen extends StatefulWidget { + const UnsafeRouteScreen({Key key, this.route, this.onDelete, @required this.onSave}) : super(key: key); + + final UnsafeRoute route; + final ValueChanged onSave; + final Function onDelete; + + @override + _UnsafeRouteScreenState createState() => _UnsafeRouteScreenState(); +} + +class _UnsafeRouteScreenState extends State { + UnsafeRoute route; + bool changed = false; + + FocusNode routeFocus = FocusNode(); + FocusNode viaFocus = FocusNode(); + FocusNode mtuFocus = FocusNode(); + + @override + void initState() { + route = widget.route; + super.initState(); + } + + @override + Widget build(BuildContext context) { + var routeCIDR = route?.route == null ? CIDR() : CIDR.fromString(route?.route); + + return FormPage( + title: widget.onDelete == null ? 'New Unsafe Route' : 'Edit Unsafe Route', + changed: changed, + onSave: _onSave, + child: Column(children: [ + ConfigSection(children: [ + ConfigItem( + label: Text('Route'), + content: CIDRFormField( + initialValue: routeCIDR, + textInputAction: TextInputAction.next, + focusNode: routeFocus, + nextFocusNode: viaFocus, + onSaved: (v) { + route.route = v.toString(); + })), + ConfigItem( + label: Text('Via'), + content: IPFormField( + initialValue: route?.via ?? "", + ipOnly: true, + help: 'nebula ip', + textAlign: TextAlign.end, + crossAxisAlignment: CrossAxisAlignment.end, + textInputAction: TextInputAction.next, + focusNode: viaFocus, + nextFocusNode: mtuFocus, + onSaved: (v) { + route.via = v; + })), +//TODO: Android doesn't appear to support route based MTU, figure this out +// ConfigItem( +// label: Text('MTU'), +// content: PlatformTextFormField( +// placeholder: "", +// validator: mtuValidator(false), +// keyboardType: TextInputType.number, +// inputFormatters: [WhitelistingTextInputFormatter.digitsOnly], +// initialValue: route?.mtu.toString(), +// textAlign: TextAlign.end, +// textInputAction: TextInputAction.done, +// focusNode: mtuFocus, +// onSaved: (v) { +// route.mtu = int.tryParse(v); +// })), + ]), + widget.onDelete != null + ? Padding( + padding: EdgeInsets.only(top: 50, bottom: 10, left: 10, right: 10), + child: SizedBox( + width: double.infinity, + child: PlatformButton( + child: Text('Delete'), + color: CupertinoColors.systemRed.resolveFrom(context), + onPressed: () => Utils.confirmDelete(context, 'Delete unsafe route?', () { + Navigator.of(context).pop(); + widget.onDelete(); + }), + ))) + : Container() + ])); + } + + _onSave() { + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(route); + } + } +} diff --git a/lib/screens/siteConfig/UnsafeRoutesScreen.dart b/lib/screens/siteConfig/UnsafeRoutesScreen.dart new file mode 100644 index 0000000..af5fda7 --- /dev/null +++ b/lib/screens/siteConfig/UnsafeRoutesScreen.dart @@ -0,0 +1,98 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:mobile_nebula/components/FormPage.dart'; +import 'package:mobile_nebula/components/config/ConfigButtonItem.dart'; +import 'package:mobile_nebula/components/config/ConfigPageItem.dart'; +import 'package:mobile_nebula/components/config/ConfigSection.dart'; +import 'package:mobile_nebula/models/UnsafeRoute.dart'; +import 'package:mobile_nebula/screens/siteConfig/UnsafeRouteScreen.dart'; +import 'package:mobile_nebula/services/utils.dart'; + +class UnsafeRoutesScreen extends StatefulWidget { + const UnsafeRoutesScreen({Key key, @required this.unsafeRoutes, @required this.onSave}) : super(key: key); + + final List unsafeRoutes; + final ValueChanged> onSave; + + @override + _UnsafeRoutesScreenState createState() => _UnsafeRoutesScreenState(); +} + +class _UnsafeRoutesScreenState extends State { + Map unsafeRoutes = {}; + bool changed = false; + + @override + void initState() { + widget.unsafeRoutes.forEach((route) { + unsafeRoutes[UniqueKey()] = route; + }); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return FormPage( + title: 'Unsafe Routes', + changed: changed, + onSave: _onSave, + child: ConfigSection( + children: _buildRoutes(), + )); + } + + _onSave() { + Navigator.pop(context); + if (widget.onSave != null) { + widget.onSave(unsafeRoutes.values.toList()); + } + } + + List _buildRoutes() { + final double ipWidth = Utils.textSize("000.000.000.000/00", CupertinoTheme.of(context).textTheme.textStyle).width; + List items = []; + unsafeRoutes.forEach((key, route) { + items.add(ConfigPageItem( + label: Text(route.route), + labelWidth: ipWidth, + content: Text('via ${route.via}', textAlign: TextAlign.end), + onPressed: () { + Utils.openPage(context, (context) { + return UnsafeRouteScreen( + route: route, + onSave: (route) { + setState(() { + changed = true; + unsafeRoutes[key] = route; + }); + }, + onDelete: () { + setState(() { + changed = true; + unsafeRoutes.remove(key); + }); + }); + }); + }, + )); + }); + + items.add(ConfigButtonItem( + content: Text('Add a new route'), + onPressed: () { + Utils.openPage(context, (context) { + return UnsafeRouteScreen(route: UnsafeRoute(), onSave: (route) { + setState(() { + changed = true; + unsafeRoutes[UniqueKey()] = route; + }); + }); + }); + }, + )); + + return items; + } +} diff --git a/lib/services/settings.dart b/lib/services/settings.dart new file mode 100644 index 0000000..2ee09f7 --- /dev/null +++ b/lib/services/settings.dart @@ -0,0 +1,88 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:mobile_nebula/services/storage.dart'; + +class Settings { + final _storage = Storage(); + StreamController _change = StreamController.broadcast(); + var _ready = Completer(); + var _settings = Map(); + + bool get useSystemColors { + return _getBool('systemDarkMode', true); + } + + set useSystemColors(bool enabled) { + if (!enabled) { + // Clear the dark mode to let the default system config take over, user can override from there + _settings.remove('darkMode'); + } + _set('systemDarkMode', enabled); + } + + bool get darkMode { + return _getBool('darkMode', SchedulerBinding.instance.window.platformBrightness == Brightness.dark); + } + + set darkMode(bool enabled) { + _set('darkMode', enabled); + } + + String _getString(String key, String defaultValue) { + final val = _settings[key]; + if (val is String) { + return val; + } + return defaultValue; + } + + bool _getBool(String key, bool defaultValue) { + final val = _settings[key]; + if (val is bool) { + return val; + } + return defaultValue; + } + + void _set(String key, dynamic value) { + _settings[key] = value; + _save(); + } + + Stream onChange() { + return _change.stream; + } + + void _save() { + final content = jsonEncode(_settings); + //TODO: handle errors + _storage.writeFile("config.json", content).then((_) { + _change.add(null); + }); + } + + static final Settings _instance = Settings._internal(); + + factory Settings() { + return _instance; + } + + Settings._internal() { + _ready = Completer(); + + _storage.readFile("config.json").then((rawConfig) { + if (rawConfig != null) { + _settings = jsonDecode(rawConfig); + } + + _ready.complete(); + _change.add(null); + }); + } + + void dispose() { + _change.close(); + } +} diff --git a/lib/services/storage.dart b/lib/services/storage.dart new file mode 100644 index 0000000..7abbb33 --- /dev/null +++ b/lib/services/storage.dart @@ -0,0 +1,67 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:path_provider/path_provider.dart'; +import 'package:path/path.dart' as p; + +class Storage { + Future mkdir(String path) async { + final parent = await localPath; + return Directory(p.join(parent, path)).create(recursive: true); + } + + Future> listDir(String path) async { + List list = []; + var parent = await localPath; + + if (path != '') { + parent = p.join(parent, path); + } + + var completer = Completer>(); + + Directory(parent).list().listen((FileSystemEntity entity) { + list.add(entity); + }).onDone(() { + completer.complete(list); + }); + + return completer.future; + } + + Future get localPath async { + final directory = await getApplicationDocumentsDirectory(); + return directory.path; + } + + Future readFile(String path) async { + try { + final parent = await localPath; + final file = File(p.join(parent, path)); + + // Read the file + return await file.readAsString(); + } catch (e) { + // If encountering an error, return 0 + return null; + } + } + + Future writeFile(String path, String contents) async { + final parent = await localPath; + final file = File(p.join(parent, path)); + + // Write the file + return file.writeAsString(contents); + } + + Future delete(String path) async { + var parent = await localPath; + return File(p.join(parent, path)).delete(recursive: true); + } + + Future getFullPath(String path) async { + var parent = await localPath; + return p.join(parent, path); + } +} diff --git a/lib/services/utils.dart b/lib/services/utils.dart new file mode 100644 index 0000000..c09f771 --- /dev/null +++ b/lib/services/utils.dart @@ -0,0 +1,166 @@ +import 'dart:io'; +import 'dart:ui'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class Utils { + /// Minimum size (width or height) of a interactive component + static const double minInteractiveSize = 44; + + /// The background color for a page, this is the furthest back color + static Color pageBackground(BuildContext context) { + return CupertinoColors.systemGroupedBackground.resolveFrom(context); + } + + /// The background color for a config item + static Color configItemBackground(BuildContext context) { + return CupertinoColors.secondarySystemGroupedBackground.resolveFrom(context); + } + + /// The top and bottom border color of a config section + static Color configSectionBorder(BuildContext context) { + return CupertinoColors.secondarySystemFill.resolveFrom(context); + } + + static Size textSize(String text, TextStyle style) { + final TextPainter textPainter = + TextPainter(text: TextSpan(text: text, style: style), maxLines: 1, textDirection: TextDirection.ltr) + ..layout(minWidth: 0, maxWidth: double.infinity); + return textPainter.size; + } + + static openPage(BuildContext context, WidgetBuilder pageToDisplayBuilder) { + Navigator.push( + context, + platformPageRoute( + context: context, + builder: pageToDisplayBuilder, + ), + ); + } + + static String itemCountFormat(int items, {singleSuffix = "item", multiSuffix = "items"}) { + if (items == 1) { + return items.toString() + " " + singleSuffix; + } + + return items.toString() + " " + multiSuffix; + } + + /// Builds a simple leading widget that pops the current screen. + /// Provide your own onPressed to override that behavior, just remember you have to pop + static Widget leadingBackWidget(BuildContext context, {label = 'Back', Function onPressed}) { + if (Platform.isAndroid) { + return IconButton( + padding: EdgeInsets.zero, + icon: Icon(context.platformIcons.back), + tooltip: label, + onPressed: () { + if (onPressed == null) { + Navigator.pop(context); + } else { + onPressed(); + } + }, + ); + } + + return CupertinoButton( + child: Row(children: [Icon(context.platformIcons.back), Text(label)]), + padding: EdgeInsets.zero, + onPressed: () { + if (onPressed == null) { + Navigator.pop(context); + } else { + onPressed(); + } + }, + ); + } + + static Widget trailingSaveWidget(BuildContext context, Function onPressed) { + return CupertinoButton( + child: Text('Save', style: TextStyle(fontWeight: FontWeight.bold)), + padding: Platform.isAndroid ? null : EdgeInsets.zero, + onPressed: () => onPressed()); + } + + /// Simple cross platform delete confirmation dialog - can also be used to confirm throwing away a change by swapping the deleteLabel + static confirmDelete(BuildContext context, String title, Function onConfirm, + {String deleteLabel = 'Delete', String cancelLabel = 'Cancel'}) { + showDialog( + context: context, + barrierDismissible: false, + builder: (context) { + return PlatformAlertDialog( + title: Text(title), + actions: [ + PlatformDialogAction( + child: Text(deleteLabel, + style: + TextStyle(fontWeight: FontWeight.bold, color: CupertinoColors.systemRed.resolveFrom(context))), + onPressed: () { + Navigator.pop(context); + onConfirm(); + }, + ), + PlatformDialogAction( + child: Text(cancelLabel), + onPressed: () { + Navigator.of(context).pop(); + }, + ) + ], + ); + }); + } + + static popError(BuildContext context, String title, String error) { + showDialog( + context: context, + barrierDismissible: false, + builder: (context) { + if (Platform.isAndroid) { + return AlertDialog(title: Text(title), content: Text(error), actions: [ + FlatButton( + child: Text('Ok'), + onPressed: () { + Navigator.of(context).pop(); + }, + ) + ]); + } + + return CupertinoAlertDialog( + title: Text(title), + content: Text(error), + actions: [ + CupertinoDialogAction( + child: Text('Ok'), + onPressed: () { + Navigator.of(context).pop(); + }, + ) + ], + ); + }); + } + + static launchUrl(String url, BuildContext context) async { + if (await canLaunch(url)) { + await launch(url); + } else { + Utils.popError(context, 'Error', 'Could not launch web view'); + } + } + + static int ip2int(String ip) { + final parts = ip.split('.'); + return int.parse(parts[3]) | int.parse(parts[2]) << 8 | int.parse(parts[1]) << 16 | int.parse(parts[0]) << 24; + } +} diff --git a/lib/validators/dnsValidator.dart b/lib/validators/dnsValidator.dart new file mode 100644 index 0000000..a19a6a2 --- /dev/null +++ b/lib/validators/dnsValidator.dart @@ -0,0 +1,34 @@ +// Inspired by https://github.com/suragch/string_validator/blob/master/lib/src/validator.dart + +bool dnsValidator(str, {requireTld = true, allowUnderscore = false}) { + if (str == null) { + return false; + } + + List parts = str.split('.'); + if (requireTld) { + var tld = parts.removeLast(); + if (parts.isEmpty || !RegExp(r'^[a-z]{2,}$').hasMatch(tld)) { + return false; + } + } + + for (var part, i = 0; i < parts.length; i++) { + part = parts[i]; + if (allowUnderscore) { + if (part.indexOf('__') >= 0) { + return false; + } + } + + if (!RegExp(r'^[a-z\\u00a1-\\uffff0-9-]+$').hasMatch(part)) { + return false; + } + + if (part[0] == '-' || part[part.length - 1] == '-' || part.indexOf('---') >= 0) { + return false; + } + } + + return true; +} diff --git a/lib/validators/ipValidator.dart b/lib/validators/ipValidator.dart new file mode 100644 index 0000000..9a819d7 --- /dev/null +++ b/lib/validators/ipValidator.dart @@ -0,0 +1,17 @@ +// Inspired by https://github.com/suragch/string_validator/blob/master/lib/src/validator.dart + +final _ipv4 = RegExp(r'^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$'); + +bool ipValidator(str) { + if (str == null) { + return false; + } + + if (!_ipv4.hasMatch(str)) { + return false; + } + + var parts = str.split('.'); + parts.sort((a, b) => int.parse(a) - int.parse(b)); + return int.parse(parts[3]) <= 255; +} diff --git a/lib/validators/mtuValidator.dart b/lib/validators/mtuValidator.dart new file mode 100644 index 0000000..9683334 --- /dev/null +++ b/lib/validators/mtuValidator.dart @@ -0,0 +1,14 @@ +Function mtuValidator(bool required) { + return (String str) { + if (str == null || str == "") { + return required ? 'Please fill out this field' : null; + } + + var mtu = int.tryParse(str); + if (mtu == null || mtu < 0 || mtu > 65535) { + return 'Please enter a valid mtu'; + } + + return null; + }; +} diff --git a/nebula/Makefile b/nebula/Makefile new file mode 100644 index 0000000..a643127 --- /dev/null +++ b/nebula/Makefile @@ -0,0 +1,12 @@ +111MODULE = on +export GO111MODULE + +mobileNebula.aar: *.go + gomobile bind -trimpath -v --target=android + +MobileNebula.framework: *.go + gomobile bind -trimpath -v --target=ios + +.DEFAULT_GOAL := mobileNebula.aar + +all: mobileNebula.aar MobileNebula.framework diff --git a/nebula/config.go b/nebula/config.go new file mode 100644 index 0000000..f448c50 --- /dev/null +++ b/nebula/config.go @@ -0,0 +1,204 @@ +package mobileNebula + +type config struct { + PKI configPKI `yaml:"pki"` + StaticHostmap map[string][]string `yaml:"static_host_map"` + Lighthouse configLighthouse `yaml:"lighthouse"` + Listen configListen `yaml:"listen"` + Punchy configPunchy `yaml:"punchy"` + Cipher string `yaml:"cipher"` + LocalRange string `yaml:"local_range"` + SSHD configSSHD `yaml:"sshd"` + Tun configTun `yaml:"tun"` + Logging configLogging `yaml:"logging"` + Stats configStats `yaml:"stats"` + Handshakes configHandshakes `yaml:"handshakes"` + Firewall configFirewall `yaml:"firewall"` +} + +func newConfig() *config { + mtu := 1300 + return &config{ + PKI: configPKI{ + Blacklist: []string{}, + }, + StaticHostmap: map[string][]string{}, + Lighthouse: configLighthouse{ + DNS: configDNS{}, + Interval: 60, + Hosts: []string{}, + RemoteAllowList: map[string]bool{}, + LocalAllowList: map[string]interface{}{}, + }, + Listen: configListen{ + Host: "0.0.0.0", + Port: 4242, + Batch: 64, + }, + Punchy: configPunchy{ + Punch: true, + Delay: "1s", + }, + Cipher: "aes", + SSHD: configSSHD{ + AuthorizedUsers: []configAuthorizedUser{}, + }, + Tun: configTun{ + Dev: "tun1", + DropLocalbroadcast: true, + DropMulticast: true, + TxQueue: 500, + MTU: &mtu, + Routes: []configRoute{}, + UnsafeRoutes: []configUnsafeRoute{}, + }, + Logging: configLogging{ + Level: "info", + Format: "text", + }, + Stats: configStats{}, + Handshakes: configHandshakes{ + TryInterval: "100ms", + Retries: 20, + WaitRotation: 5, + }, + Firewall: configFirewall{ + Conntrack: configConntrack{ + TcpTimeout: "120h", + UdpTimeout: "3m", + DefaultTimeout: "10m", + MaxConnections: 100000, + }, + Outbound: []configFirewallRule{ + { + Port: "any", + Proto: "any", + Host: "any", + }, + }, + Inbound: []configFirewallRule{}, + }, + } +} + +type configPKI struct { + CA string `yaml:"ca"` + Cert string `yaml:"cert"` + Key string `yaml:"key"` + Blacklist []string `yaml:"blacklist"` +} + +type configLighthouse struct { + AmLighthouse bool `yaml:"am_lighthouse"` + ServeDNS bool `yaml:"serve_dns"` + DNS configDNS `yaml:"dns"` + Interval int `yaml:"interval"` + Hosts []string `yaml:"hosts"` + RemoteAllowList map[string]bool `yaml:"remote_allow_list"` + LocalAllowList map[string]interface{} `yaml:"local_allow_list"` // This can be a special "interfaces" object or a bool +} + +type configDNS struct { + Host string `yaml:"host"` + Port int `yaml:"port"` +} + +type configListen struct { + Host string `yaml:"host"` + Port int `yaml:"port"` + Batch int `yaml:"batch"` + ReadBuffer int64 `yaml:"read_buffer"` + WriteBuffer int64 `yaml:"write_buffer"` +} + +type configPunchy struct { + Punch bool `yaml:"punch"` + Respond bool `yaml:"respond"` + Delay string `yaml:"delay"` +} + +type configSSHD struct { + Enabled bool `yaml:"enabled"` + Listen string `yaml:"listen"` + HostKey string `yaml:"host_key"` + AuthorizedUsers []configAuthorizedUser `yaml:"authorized_users"` +} + +type configAuthorizedUser struct { + Name string `yaml:"name"` + Keys []string `yaml:"keys"` +} + +type configTun struct { + Dev string `yaml:"dev"` + DropLocalbroadcast bool `yaml:"drop_local_broadcast"` + DropMulticast bool `yaml:"drop_multicast"` + TxQueue int `yaml:"tx_queue"` + MTU *int `yaml:"mtu,omitempty"` + Routes []configRoute `yaml:"routes"` + UnsafeRoutes []configUnsafeRoute `yaml:"unsafe_routes"` +} + +type configRoute struct { + MTU int `yaml:"mtu"` + Route string `yaml:"route"` +} + +type configUnsafeRoute struct { + MTU *int `yaml:"mtu,omitempty"` + Route string `yaml:"route"` + Via string `yaml:"via"` +} + +type configLogging struct { + Level string `yaml:"level"` + Format string `yaml:"format"` + TimestampFormat string `yaml:"timestamp_format,omitempty"` +} + +type configStats struct { + Type string `yaml:"type"` + Interval string `yaml:"interval"` + + // Graphite settings + Prefix string `yaml:"prefix"` + Protocol string `yaml:"protocol"` + Host string `yaml:"host"` + + // Prometheus settings + Listen string `yaml:"listen"` + Path string `yaml:"path"` + Namespace string `yaml:"namespace"` + Subsystem string `yaml:"subsystem"` +} + +type configHandshakes struct { + TryInterval string `yaml:"try_interval"` + Retries int `yaml:"retries"` + WaitRotation int `yaml:"wait_rotation"` +} + +type configFirewall struct { + Conntrack configConntrack `yaml:"conntrack"` + Outbound []configFirewallRule `yaml:"outbound"` + Inbound []configFirewallRule `yaml:"inbound"` +} + +type configConntrack struct { + TcpTimeout string `yaml:"tcp_timeout"` + UdpTimeout string `yaml:"udp_timeout"` + DefaultTimeout string `yaml:"default_timeout"` + MaxConnections int `yaml:"max_connections"` +} + +type configFirewallRule struct { + Port string `yaml:"port,omitempty"` + Code string `yaml:"code,omitempty"` + Proto string `yaml:"proto,omitempty"` + Host string `yaml:"host,omitempty"` + Group string `yaml:"group,omitempty"` + Groups []string `yaml:"groups,omitempty"` + CIDR string `yaml:"cidr,omitempty"` + CASha string `yaml:"ca_sha,omitempty"` + CAName string `yaml:"ca_name,omitempty"` +} diff --git a/nebula/control.go b/nebula/control.go new file mode 100644 index 0000000..0f27afe --- /dev/null +++ b/nebula/control.go @@ -0,0 +1,116 @@ +package mobileNebula + +import ( + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "net" + "os" + "runtime/debug" + + "github.com/sirupsen/logrus" + "github.com/slackhq/nebula" +) + +type Nebula struct { + c *nebula.Control + l *logrus.Logger +} + +func NewNebula(configData string, key string, logFile string, tunFd int) (*Nebula, error) { + // GC more often, largely for iOS due to extension 15mb limit + debug.SetGCPercent(20) + + yamlConfig, err := RenderConfig(configData, key) + if err != nil { + return nil, err + } + + config := nebula.NewConfig() + err = config.LoadString(yamlConfig) + if err != nil { + return nil, fmt.Errorf("failed to load config: %s", err) + } + + l := logrus.New() + f, err := os.OpenFile(logFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + return nil, err + } + l.SetOutput(f) + + //TODO: inject our version + c, err := nebula.Main(config, false, "", l, &tunFd) + if err != nil { + switch v := err.(type) { + case nebula.ContextualError: + return nil, v.RealError + default: + return nil, err + } + } + + return &Nebula{c, l}, nil +} + +func (n *Nebula) Start() { + n.c.Start() +} + +func (n *Nebula) ShutdownBlock() { + n.c.ShutdownBlock() +} + +func (n *Nebula) Stop() { + n.c.Stop() +} + +func (n *Nebula) Rebind() { + n.c.RebindUDPServer() +} + +func (n *Nebula) ListHostmap(pending bool) (string, error) { + hosts := n.c.ListHostmap(pending) + b, err := json.Marshal(hosts) + if err != nil { + return "", err + } + + return string(b), nil +} + +func (n *Nebula) GetHostInfoByVpnIp(vpnIp string, pending bool) (string, error) { + b, err := json.Marshal(n.c.GetHostInfoByVpnIp(stringIpToInt(vpnIp), pending)) + if err != nil { + return "", err + } + + return string(b), nil +} + +func (n *Nebula) CloseTunnel(vpnIp string) bool { + return n.c.CloseTunnel(stringIpToInt(vpnIp), false) +} + +func (n *Nebula) SetRemoteForTunnel(vpnIp string, addr string) (string, error) { + udpAddr := nebula.NewUDPAddrFromString(addr) + if udpAddr == nil { + return "", errors.New("could not parse udp address") + } + + b, err := json.Marshal(n.c.SetRemoteForTunnel(stringIpToInt(vpnIp), *udpAddr)) + if err != nil { + return "", err + } + + return string(b), nil +} + +func stringIpToInt(ip string) uint32 { + n := net.ParseIP(ip) + if len(n) == 16 { + return binary.BigEndian.Uint32(n[12:16]) + } + return binary.BigEndian.Uint32(n) +} \ No newline at end of file diff --git a/nebula/go.mod b/nebula/go.mod new file mode 100644 index 0000000..52593e6 --- /dev/null +++ b/nebula/go.mod @@ -0,0 +1,14 @@ +module github.com/DefinedNet/mobile_nebula/nebula + +go 1.14 + +replace github.com/slackhq/nebula => /Users/nate/src/github.com/slackhq/nebula + +require ( + github.com/prometheus/common v0.7.0 + github.com/sirupsen/logrus v1.4.2 + github.com/slackhq/nebula v1.1.1-0.20200303203524-6cdc17c01d30 + golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 + golang.org/x/mobile v0.0.0-20200329125638-4c31acba0007 // indirect + gopkg.in/yaml.v2 v2.2.7 +) diff --git a/nebula/go.sum b/nebula/go.sum new file mode 100644 index 0000000..14674ae --- /dev/null +++ b/nebula/go.sum @@ -0,0 +1,158 @@ +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafoB+tBA3gMyHYHrpOtNuDiK/uB5uXxq5wM= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4 h1:Hs82Z41s6SdL1CELW+XaDYmOH4hkBN4/N9og/AsOv7E= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.1.0/go.mod h1:dgIUBU3pDso/gPgZ1osOZ0iQf77oPR28Tjxl5dIMyVM= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432 h1:M5QgkYacWj0Xs8MhpIK/5uwU02icXpEoSo9sM2aRCps= +github.com/cyberdelia/go-metrics-graphite v0.0.0-20161219230853-39f87cc3b432/go.mod h1:xwIwAxMvYnVrGJPe2FKx5prTrnAjGOD8zvDOnxnrrkM= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6 h1:u/UEqS66A5ckRmS4yNpjmVH56sVtS/RfclBAYocb4as= +github.com/flynn/noise v0.0.0-20180327030543-2492fe189ae6/go.mod h1:1i71OnUq3iUe1ma7Lr6yG6/rjvM3emb6yoL7xLFzcVQ= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/imdario/mergo v0.3.8 h1:CGgOkSJeqMRmt0D9XLWExdT4m4F1vd3FV3VPt+0VxkQ= +github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kardianos/service v1.0.0/go.mod h1:8CzDhVuCuugtsHyZoTvsOBuvonN/UDBvl0kH+BUxvbo= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.1.25 h1:dFwPR6SfLtrSwgDcIq2bcU/gVutB4sNApq2HBdqcakg= +github.com/miekg/dns v1.1.25/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/nbrownus/go-metrics-prometheus v0.0.0-20180622211546-6e6d5173d99c h1:G/mfx/MWYuaaGlHkZQBBXFAJiYnRt/GaOVxnRHjlxg4= +github.com/nbrownus/go-metrics-prometheus v0.0.0-20180622211546-6e6d5173d99c/go.mod h1:1yMri853KAI2pPAUnESjaqZj9JeImOUM+6A4GuuPmTs= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.2.1 h1:JnMpQc6ppsNgw9QPAGF6Dod479itz7lvlsMzzNayLOI= +github.com/prometheus/client_golang v1.2.1/go.mod h1:XMU6Z2MjaRKVu/dC1qupJI9SiNkDYzz3xecMgSW/F+U= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20191202183732-d1d2010b5bee h1:iBZPTYkGLvdu6+A5TsMUJQkQX9Ad4aCEnSQtdxPuTCQ= +github.com/prometheus/client_model v0.0.0-20191202183732-d1d2010b5bee/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.7.0 h1:L+1lyG48J1zAQXA3RBX/nG/B3gjlHq0zTt2tlbJLyCY= +github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLkt8= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563 h1:dY6ETXrvDG7Sa4vE8ZQG4yqWg6UnOcbqTAahkV813vQ= +github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/slackhq/nebula v1.1.1-0.20200303203524-6cdc17c01d30 h1:7DovgM4NDqKj966SMS0+Hz2gXl7JeRZQ9+9g9Kg/G18= +github.com/slackhq/nebula v1.1.1-0.20200303203524-6cdc17c01d30/go.mod h1:zwkf6kct+HA8sYMNzI5/iEKRAKBa50TXOoRzmuGIRCA= +github.com/slackhq/nebula v1.2.0 h1:44U4G86Ek/5XDVlH3iFtrPoZ0aNP2k/E1RT0daXQaIM= +github.com/slackhq/nebula v1.2.0/go.mod h1:zwkf6kct+HA8sYMNzI5/iEKRAKBa50TXOoRzmuGIRCA= +github.com/songgao/water v0.0.0-20190725173103-fd331bda3f4b h1:+y4hCMc/WKsDbAPsOQZgBSaSZ26uh2afyaWeVg/3s/c= +github.com/songgao/water v0.0.0-20190725173103-fd331bda3f4b/go.mod h1:P5HUIBuIWKbyjl083/loAegFkfbFNx5i2qEP4CNbm7E= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/vishvananda/netlink v1.0.1-0.20190522153524-00009fb8606a h1:Bt1IVPhiCDMqwGrc2nnbIN4QKvJGx6SK2NzWBmW00ao= +github.com/vishvananda/netlink v1.0.1-0.20190522153524-00009fb8606a/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= +github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df h1:OviZH7qLw/7ZovXvuNyL3XQl8UFofeikI1NW1Gypu7k= +github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 h1:/Tl7pH94bvbAAHBdZJT947M/+gp0+CqQXDtMRC0fseo= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20200329125638-4c31acba0007 h1:JxsyO7zPDWn1rBZW8FV5RFwCKqYeXnyaS/VQPLpXu6I= +golang.org/x/mobile v0.0.0-20200329125638-4c31acba0007/go.mod h1:skQtrUTUwhdJvXM/2KKJzY8pDgNr9I/FOMqDVRPBUS4= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191209134235-331c550502dd/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553 h1:efeOvDhwQ29Dj3SdAV/MJf8oukgn+8D8WgaCaRMchF8= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191210023423-ac6580df4449 h1:gSbV7h1NRL2G1xTg/owz62CST1oJBmxy4QpMMregXVQ= +golang.org/x/sys v0.0.0-20191210023423-ac6580df4449/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69 h1:yBHHx+XZqXJBm6Exke3N7V9gnlsyXxoCPEb1yVenjfk= +golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/alecthomas/kingpin.v2 v2.2.6 h1:jMFz6MfLP0/4fUyZle81rXUoxOBFi19VUFKVDOQfozc= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= +gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/nebula/mobileNebula.go b/nebula/mobileNebula.go new file mode 100644 index 0000000..06fc365 --- /dev/null +++ b/nebula/mobileNebula.go @@ -0,0 +1,212 @@ +package mobileNebula + +import ( + "crypto/rand" + "encoding/json" + "fmt" + "io" + "net" + "strings" + "time" + + "github.com/slackhq/nebula" + "github.com/slackhq/nebula/cert" + "golang.org/x/crypto/curve25519" + "gopkg.in/yaml.v2" +) + +type m map[string]interface{} + +type CIDR struct { + Ip string + MaskCIDR string + MaskSize int + Network string +} + +type Validity struct { + Valid bool + Reason string +} + +type RawCert struct { + RawCert string + Cert *cert.NebulaCertificate + Validity Validity +} + +type KeyPair struct { + PublicKey string + PrivateKey string +} + +func RenderConfig(configData string, key string) (string, error) { + config := newConfig() + var d m + + err := json.Unmarshal([]byte(configData), &d) + if err != nil { + return "", err + } + + config.PKI.CA, _ = d["ca"].(string) + config.PKI.Cert, _ = d["cert"].(string) + config.PKI.Key = key + + i, _ := d["port"].(float64) + config.Listen.Port = int(i) + + config.Cipher, _ = d["cipher"].(string) + // Log verbosity is not required + if val, _ := d["logVerbosity"].(string); val != "" { + config.Logging.Level = val + } + + i, _ = d["lhDuration"].(float64) + config.Lighthouse.Interval = int(i) + + if i, ok := d["mtu"].(float64); ok { + mtu := int(i) + config.Tun.MTU = &mtu + } + + config.Lighthouse.Hosts = make([]string, 0) + staticHostmap := d["staticHostmap"].(map[string]interface{}) + for nebIp, mapping := range staticHostmap { + def := mapping.(map[string]interface{}) + + isLh := def["lighthouse"].(bool) + if isLh { + config.Lighthouse.Hosts = append(config.Lighthouse.Hosts, nebIp) + } + + hosts := def["destinations"].([]interface{}) + realHosts := make([]string, len(hosts)) + + for i, h := range hosts { + realHosts[i] = h.(string) + } + + config.StaticHostmap[nebIp] = realHosts + } + + if unsafeRoutes, ok := d["unsafeRoutes"].([]interface{}); ok { + config.Tun.UnsafeRoutes = make([]configUnsafeRoute, len(unsafeRoutes)) + for i, r := range unsafeRoutes { + rawRoute := r.(map[string]interface{}) + route := &config.Tun.UnsafeRoutes[i] + route.Route = rawRoute["route"].(string) + route.Via = rawRoute["via"].(string) + } + } + + finalConfig, err := yaml.Marshal(config) + if err != nil { + return "", err + } + + return string(finalConfig), nil +} + +func GetConfigSetting(configData string, setting string) string { + config := nebula.NewConfig() + config.LoadString(configData) + return config.GetString(setting, "") +} + +func ParseCIDR(cidr string) (*CIDR, error) { + ip, ipNet, err := net.ParseCIDR(cidr) + if err != nil { + return nil, err + } + size, _ := ipNet.Mask.Size() + + return &CIDR{ + Ip: ip.String(), + MaskCIDR: fmt.Sprintf("%d.%d.%d.%d", ipNet.Mask[0], ipNet.Mask[1], ipNet.Mask[2], ipNet.Mask[3]), + MaskSize: size, + Network: ipNet.IP.String(), + }, nil +} + +// Returns a JSON representation of 1 or more certificates +func ParseCerts(rawStringCerts string) (string, error) { + var certs []RawCert + var c *cert.NebulaCertificate + var err error + rawCerts := []byte(rawStringCerts) + + for { + c, rawCerts, err = cert.UnmarshalNebulaCertificateFromPEM(rawCerts) + if err != nil { + return "", err + } + + rawCert, err := c.MarshalToPEM() + if err != nil { + return "", err + } + + rc := RawCert{ + RawCert: string(rawCert), + Cert: c, + Validity: Validity{ + Valid: true, + }, + } + + if c.Expired(time.Now()) { + rc.Validity.Valid = false + rc.Validity.Reason = "Certificate is expired" + } + + if rc.Validity.Valid && c.Details.IsCA && !c.CheckSignature(c.Details.PublicKey) { + rc.Validity.Valid = false + rc.Validity.Reason = "Certificate signature did not match" + } + + certs = append(certs, rc) + + if rawCerts == nil || strings.TrimSpace(string(rawCerts)) == "" { + break + } + } + + rawJson, err := json.Marshal(certs) + if err != nil { + return "", err + } + + return string(rawJson), nil +} + +func GenerateKeyPair() (string, error) { + pub, priv, err := x25519Keypair() + if err != nil { + return "", err + } + + kp := KeyPair{} + kp.PublicKey = string(cert.MarshalX25519PublicKey(pub)) + kp.PrivateKey = string(cert.MarshalX25519PrivateKey(priv)) + + rawJson, err := json.Marshal(kp) + if err != nil { + return "", err + } + + return string(rawJson), nil +} + +func x25519Keypair() ([]byte, []byte, error) { + var pubkey, privkey [32]byte + if _, err := io.ReadFull(rand.Reader, privkey[:]); err != nil { + return nil, nil, err + } + curve25519.ScalarBaseMult(&pubkey, &privkey) + return pubkey[:], privkey[:], nil +} + +//func VerifyCertAndKey(cert string, key string) (string, error) { +// +//} diff --git a/nebula/mobileNebula_test.go b/nebula/mobileNebula_test.go new file mode 100644 index 0000000..977ba15 --- /dev/null +++ b/nebula/mobileNebula_test.go @@ -0,0 +1,50 @@ +package mobileNebula + +import ( + "testing" + + "github.com/slackhq/nebula" +) + +func TestParseCerts(t *testing.T) { + jsonConfig := `{ + "name": "Debug Test - unsafe", + "id": "be9d6756-4099-4b25-a901-9d3b773e7d1a", + "staticHostmap": { + "10.1.0.1": { + "lighthouse": true, + "destinations": [ + "10.1.1.53:4242" + ] + } + }, + "unsafeRoutes": [ + { + "route": "10.3.3.3/32", + "via": "10.1.0.1", + "mtu": null + }, + { + "route": "1.1.1.2/32", + "via": "10.1.0.1", + "mtu": null + } + ], + "ca": "-----BEGIN NEBULA CERTIFICATE-----\nCpEBCg9EZWZpbmVkIHJvb3QgMDISE4CAhFCA/v//D4CCoIUMgID8/w8aE4CAgFCA\n/v//D4CAoIUMgID8/w8iBHRlc3QiBmxhcHRvcCIFcGhvbmUiCGVtcGxveWVlIgVh\nZG1pbiiI05z1BTCIuqGEBjogV/nxuQ1/kN12IrYs/H1cpZr3agQUnRs9FqWdJcOa\nJSlAARJA4H1wI3hdfVpIy8Y9IZHqIlMIFObCu5ceM4aELiTKsEGv+g7u8Dn1VY8g\nQPNsuOsqJB3ma8PntddPYn5QgH+qDA==\n-----END NEBULA CERTIFICATE-----\n", + "cert": "-----BEGIN NEBULA CERTIFICATE-----\nCmcKCmNocm9tZWJvb2sSCYmAhFCA/v//DyiR1Zf2BTCHuqGEBjogqtoJL9WKGKLp\nb3BIgTEZnTTusSJOiswuf1DS7jPjMzFKIIstsyPnnccgEYkNflwrYBvZFMCOtgmN\nuc5Jpc5lbzM9EkBACYP3VMFYHk2h5AcpURcG6QwS4iYOgHET7lMbM7WSMj4ZnzLR\ni2HhX58vSTr6evgvKuSPaA23hLUqR65QNRQD\n-----END NEBULA CERTIFICATE-----\n", + "key": null, + "lhDuration": 7200, + "port": 4242, + "mtu": 1300, + "cipher": "aes", + "sortKey": 3, + "logVerbosity": "info" +}` + s, err := RenderConfig(jsonConfig, "") + + config := nebula.NewConfig() + err = config.LoadString(s) + + t.Log(err) + return +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..6465d2c --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,376 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.13" + args: + dependency: transitive + description: + name: args + url: "https://pub.dartlang.org" + source: hosted + version: "1.6.0" + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.1" + barcode_scan: + dependency: "direct main" + description: + name: barcode_scan + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.3" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.14.12" + convert: + dependency: transitive + description: + name: convert + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + crypto: + dependency: transitive + description: + name: crypto + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.4" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.3" + file: + dependency: transitive + description: + name: file + url: "https://pub.dartlang.org" + source: hosted + version: "5.1.0" + file_picker: + dependency: "direct main" + description: + name: file_picker + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + fixnum: + dependency: transitive + description: + name: fixnum + url: "https://pub.dartlang.org" + source: hosted + version: "0.10.11" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_platform_widgets: + dependency: "direct main" + description: + name: flutter_platform_widgets + url: "https://pub.dartlang.org" + source: hosted + version: "0.41.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.8" + flutter_share: + dependency: "direct main" + description: + name: flutter_share + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2+1" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + image: + dependency: transitive + description: + name: image + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.12" + intl: + dependency: transitive + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.16.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.6" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.8" + package_info: + dependency: "direct main" + description: + name: package_info + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.1" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.6.4" + path_provider: + dependency: "direct main" + description: + name: path_provider + url: "https://pub.dartlang.org" + source: hosted + version: "1.6.10" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.1+1" + path_provider_macos: + dependency: transitive + description: + name: path_provider_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.4+3" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + petitparser: + dependency: transitive + description: + name: petitparser + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.0" + platform: + dependency: transitive + description: + name: platform + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.1" + platform_detect: + dependency: transitive + description: + name: platform_detect + url: "https://pub.dartlang.org" + source: hosted + version: "1.4.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + process: + dependency: transitive + description: + name: process + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.13" + protobuf: + dependency: transitive + description: + name: protobuf + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + url: "https://pub.dartlang.org" + source: hosted + version: "1.4.4" + pull_to_refresh: + dependency: "direct main" + description: + name: pull_to_refresh + url: "https://pub.dartlang.org" + source: hosted + version: "1.6.0" + quiver: + dependency: transitive + description: + name: quiver + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.3" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.5" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.15" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.6" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + url: "https://pub.dartlang.org" + source: hosted + version: "5.4.10" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.1+7" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.7" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.1+6" + uuid: + dependency: "direct main" + description: + name: uuid + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.8" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0" + xml: + dependency: transitive + description: + name: xml + url: "https://pub.dartlang.org" + source: hosted + version: "3.6.1" +sdks: + dart: ">=2.6.0 <3.0.0" + flutter: ">=1.17.0 <2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..17a81cd --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,85 @@ +name: mobile_nebula +description: Mobile Nebula Client + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +version: 1.0.0+30 + +environment: + sdk: ">=2.1.0 <3.0.0" + +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^0.1.2 + flutter_platform_widgets: ^0.41.0 + path_provider: ^1.6.0 + file_picker: ^1.9.0 + barcode_scan: ^3.0.1 + flutter_share: ^1.0.2 + uuid: ^2.0.4 + package_info: '>=0.4.1 <2.0.0' + url_launcher: ^5.4.10 + pull_to_refresh: ^1.6.0 + +dev_dependencies: + flutter_test: + sdk: flutter + + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware. + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages + fonts: + - family: RobotoMono + fonts: + - asset: fonts/RobotoMono-Regular.ttf \ No newline at end of file