Improve VPN video routing, profile storage and authorization reuse
This commit is contained in:
@@ -21,6 +21,7 @@
|
||||
/* End PBXAggregateTarget section */
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = A137C030AA00000000000002 /* LocalProfileStore.swift */; };
|
||||
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
|
||||
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
|
||||
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
|
||||
@@ -62,6 +63,7 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
A137C030AA00000000000002 /* LocalProfileStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalProfileStore.swift; sourceTree = "<group>"; };
|
||||
092517D44FE622E53982B8F7 /* 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 = "<group>"; };
|
||||
0C42A6D1E91FCC75A8FFACCD /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
|
||||
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -177,6 +179,7 @@
|
||||
children = (
|
||||
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
|
||||
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
|
||||
A137C030AA00000000000002 /* LocalProfileStore.swift */,
|
||||
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
|
||||
33E51914231749380026EE4D /* Release.entitlements */,
|
||||
33CC11242044D66E0003C045 /* Resources */,
|
||||
@@ -420,6 +423,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
|
||||
A137C030AA00000000000001 /* LocalProfileStore.swift in Sources */,
|
||||
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
|
||||
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import Foundation
|
||||
import Security
|
||||
import Darwin
|
||||
import LocalAuthentication
|
||||
|
||||
enum StoredProfile: CaseIterable {
|
||||
case proxy, network
|
||||
var fileName: String { self == .proxy ? "proxy-profile.json" : "network-profile.toml" }
|
||||
var service: String { self == .proxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile" }
|
||||
var account: String { self == .proxy ? "last-proxy" : "last-network" }
|
||||
}
|
||||
|
||||
final class LocalProfileStore {
|
||||
typealias LegacyReader = (StoredProfile, Bool) throws -> Data?
|
||||
let root: URL
|
||||
private let legacyReader: LegacyReader
|
||||
private let fm = FileManager.default
|
||||
private let limit = 65536
|
||||
|
||||
init(root: URL = FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Application Support/MeshPort", isDirectory: true),
|
||||
legacyReader: @escaping LegacyReader = LocalProfileStore.readKeychain) {
|
||||
self.root = root
|
||||
self.legacyReader = legacyReader
|
||||
}
|
||||
|
||||
private func failure(_ message: String) -> NSError {
|
||||
NSError(domain: "MeshPort.LocalProfile", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
|
||||
}
|
||||
private func verify(_ url: URL, directory: Bool = false) throws {
|
||||
let attrs = try fm.attributesOfItem(atPath: url.path)
|
||||
guard attrs[.type] as? FileAttributeType == (directory ? .typeDirectory : .typeRegular),
|
||||
(attrs[.ownerAccountID] as? NSNumber)?.uint32Value == getuid() else {
|
||||
throw failure("Configuration path must be owned by the current user and cannot be a symbolic link")
|
||||
}
|
||||
try fm.setAttributes([.posixPermissions: directory ? 0o700 : 0o600], ofItemAtPath: url.path)
|
||||
}
|
||||
private func prepare() throws {
|
||||
if !fm.fileExists(atPath: root.path) {
|
||||
try fm.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
}
|
||||
try verify(root, directory: true)
|
||||
}
|
||||
private func marker(_ kind: StoredProfile, _ suffix: String) -> URL {
|
||||
root.appendingPathComponent(".\(kind.fileName).\(suffix)")
|
||||
}
|
||||
private func exists(_ url: URL) -> Bool {
|
||||
// Attributes also detect dangling symlinks, which fileExists follows.
|
||||
(try? fm.attributesOfItem(atPath: url.path)) != nil
|
||||
}
|
||||
private func atomicWrite(_ data: Data, to target: URL) throws {
|
||||
try prepare()
|
||||
if exists(target) { try verify(target) }
|
||||
var template = Array(root.appendingPathComponent(".profile-XXXXXX").path.utf8CString)
|
||||
let fd = mkstemp(&template)
|
||||
guard fd >= 0 else { throw failure("Cannot create private configuration file") }
|
||||
let temporary = String(cString: template)
|
||||
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
||||
defer { try? handle.close(); unlink(temporary) }
|
||||
guard fchmod(fd, 0o600) == 0 else { throw failure("Cannot protect configuration file") }
|
||||
try handle.write(contentsOf: data)
|
||||
try handle.synchronize()
|
||||
guard rename(temporary, target.path) == 0 else { throw failure("Cannot replace configuration file") }
|
||||
}
|
||||
private func finishMigration(_ kind: StoredProfile) throws {
|
||||
try atomicWrite(Data(), to: marker(kind, "migrated"))
|
||||
let pending = marker(kind, "migration-pending")
|
||||
if exists(pending) { try verify(pending); try fm.removeItem(at: pending) }
|
||||
}
|
||||
func save(_ text: String, kind: StoredProfile) throws {
|
||||
guard let data = text.data(using: .utf8), data.count <= limit else {
|
||||
throw failure("Configuration exceeds storage limit")
|
||||
}
|
||||
try atomicWrite(data, to: root.appendingPathComponent(kind.fileName))
|
||||
try finishMigration(kind)
|
||||
}
|
||||
func load(_ kind: StoredProfile) throws -> String? {
|
||||
try prepare()
|
||||
let file = root.appendingPathComponent(kind.fileName)
|
||||
if exists(file) {
|
||||
try verify(file)
|
||||
let size = (try fm.attributesOfItem(atPath: file.path)[.size] as? NSNumber)?.intValue ?? limit + 1
|
||||
guard size <= limit, let text = String(data: try Data(contentsOf: file), encoding: .utf8) else {
|
||||
throw failure("Invalid local configuration")
|
||||
}
|
||||
return text
|
||||
}
|
||||
if exists(marker(kind, "migrated")) || exists(marker(kind, "migration-pending")) { return nil }
|
||||
// Never show a Keychain dialog during automatic startup migration.
|
||||
do { return try migrate(kind, interactive: false) }
|
||||
catch {
|
||||
try atomicWrite(Data(), to: marker(kind, "migration-pending"))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
private func migrate(_ kind: StoredProfile, interactive: Bool) throws -> String? {
|
||||
guard let data = try legacyReader(kind, interactive) else {
|
||||
try finishMigration(kind)
|
||||
return nil
|
||||
}
|
||||
guard data.count <= limit, let text = String(data: data, encoding: .utf8) else {
|
||||
throw failure("Invalid legacy configuration")
|
||||
}
|
||||
try save(text, kind: kind)
|
||||
return text
|
||||
}
|
||||
func migratePending() throws {
|
||||
try prepare()
|
||||
for kind in StoredProfile.allCases where exists(marker(kind, "migration-pending")) {
|
||||
// Never overwrite local edits with the legacy backup.
|
||||
if exists(root.appendingPathComponent(kind.fileName)) { try finishMigration(kind) }
|
||||
else { _ = try migrate(kind, interactive: true) }
|
||||
}
|
||||
}
|
||||
func migrationPending() throws -> Bool {
|
||||
try prepare()
|
||||
return StoredProfile.allCases.contains { exists(marker($0, "migration-pending")) }
|
||||
}
|
||||
func delete(_ kind: StoredProfile) throws {
|
||||
try prepare()
|
||||
let file = root.appendingPathComponent(kind.fileName)
|
||||
if exists(file) { try verify(file); try fm.removeItem(at: file) }
|
||||
// A deleted profile must not reappear from the old Keychain backup.
|
||||
try finishMigration(kind)
|
||||
}
|
||||
static func readKeychain(_ kind: StoredProfile, _ interactive: Bool) throws -> Data? {
|
||||
var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: kind.service, kSecAttrAccount as String: kind.account,
|
||||
kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]
|
||||
let authentication = LAContext()
|
||||
authentication.interactionNotAllowed = !interactive
|
||||
query[kSecUseAuthenticationContext as String] = authentication
|
||||
var value: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &value)
|
||||
if status == errSecItemNotFound { return nil }
|
||||
guard status == errSecSuccess, let data = value as? Data else {
|
||||
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
|
||||
}
|
||||
return data
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ class MainFlutterWindow: NSWindow {
|
||||
private var vpnChannel: FlutterMethodChannel?
|
||||
private var qrScanner: MeshQRScanner?
|
||||
private var importing = false
|
||||
private let profileStore = LocalProfileStore()
|
||||
private let profileQueue = DispatchQueue(label: "com.meshport.local-profiles")
|
||||
|
||||
override func close() {
|
||||
// Hiding keeps the Flutter engine, drafts and active network sessions alive.
|
||||
@@ -33,40 +35,32 @@ class MainFlutterWindow: NSWindow {
|
||||
guard let self = self else { result(FlutterError(code:"WINDOW_CLOSED",message:"Window closed",details:nil)); return }
|
||||
if self.handleCapabilities(call, result:result) { return }
|
||||
let profileMethod = call.method.replacingOccurrences(of: "_proxy_profile", with: "_profile")
|
||||
let isProxy = call.method.contains("_proxy_profile")
|
||||
let profileQuery: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: isProxy ? "MeshPort.Lab.ProxyProfile" : "MeshPort.Lab.NetworkProfile",
|
||||
kSecAttrAccount as String: isProxy ? "last-proxy" : "last-network"
|
||||
]
|
||||
if profileMethod == "save_profile", let config = call.arguments as? String,
|
||||
config.utf8.count <= 65536, let data = config.data(using: .utf8) {
|
||||
let attributes = [kSecValueData as String: data]
|
||||
var status = SecItemUpdate(profileQuery as CFDictionary, attributes as CFDictionary)
|
||||
if status == errSecItemNotFound {
|
||||
var item = profileQuery
|
||||
item[kSecValueData as String] = data
|
||||
status = SecItemAdd(item as CFDictionary, nil)
|
||||
if ["save_profile", "load_profile", "delete_profile", "profile_storage_status", "migrate_profiles"].contains(profileMethod) {
|
||||
let kind: StoredProfile = call.method.contains("_proxy_profile") ? .proxy : .network
|
||||
self.profileQueue.async {
|
||||
do {
|
||||
let value: Any?
|
||||
switch profileMethod {
|
||||
case "save_profile":
|
||||
guard let text = call.arguments as? String else {
|
||||
throw NSError(domain: "MeshPort.LocalProfile", code: 1)
|
||||
}
|
||||
try self.profileStore.save(text, kind: kind)
|
||||
value = nil
|
||||
case "load_profile": value = try self.profileStore.load(kind)
|
||||
case "delete_profile": try self.profileStore.delete(kind); value = nil
|
||||
case "migrate_profiles": try self.profileStore.migratePending(); value = nil
|
||||
default:
|
||||
value = ["path": self.profileStore.root.path,
|
||||
"migration_pending": try self.profileStore.migrationPending()]
|
||||
}
|
||||
DispatchQueue.main.async { result(value) }
|
||||
} catch {
|
||||
DispatchQueue.main.async {
|
||||
result(FlutterError(code: "PROFILE_STORAGE", message: "Could not read, save or migrate local configuration", details: (error as NSError).code))
|
||||
}
|
||||
}
|
||||
}
|
||||
if status == errSecSuccess { result(nil) }
|
||||
else { result(FlutterError(code: "KEYCHAIN_SAVE", message: "Could not save network profile to Keychain", details: status)) }
|
||||
return
|
||||
}
|
||||
if profileMethod == "load_profile" {
|
||||
var query = profileQuery
|
||||
query[kSecReturnData as String] = true
|
||||
query[kSecMatchLimit as String] = kSecMatchLimitOne
|
||||
var value: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &value)
|
||||
if status == errSecItemNotFound { result(nil) }
|
||||
else if status == errSecSuccess, let data = value as? Data { result(String(data: data, encoding: .utf8)) }
|
||||
else { result(FlutterError(code: "KEYCHAIN_LOAD", message: "Could not read network profile", details: status)) }
|
||||
return
|
||||
}
|
||||
if profileMethod == "delete_profile" {
|
||||
let status = SecItemDelete(profileQuery as CFDictionary)
|
||||
if status == errSecSuccess || status == errSecItemNotFound { result(nil) }
|
||||
else { result(FlutterError(code: "KEYCHAIN_DELETE", message: "Could not delete network profile", details: status)) }
|
||||
return
|
||||
}
|
||||
guard call.method == "launch", let args = call.arguments as? [String: Any],
|
||||
|
||||
Reference in New Issue
Block a user