142 lines
6.2 KiB
Swift
142 lines
6.2 KiB
Swift
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
|
|
}
|
|
}
|