Sources/OrgApp/CryptPassphrases.swift

9300add1d8a7e33f0fc51a6e9a6cf4969be05032
orgstar/Sources/OrgApp/CryptPassphrases.swift

230 lines · 10975 bytes

  1import CryptoKit
  2import Foundation
  3import LocalAuthentication
  4import OrgDocument
  5import Security
  6
  7/// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked.
  8/// Items are readable only on this device while it's unlocked, and only after Touch ID, Face
  9/// ID or the device's password (`.userPresence`), asked once per file while it's open. Items
 10/// earlier versions stored without that move over at their first read. A build without a
 11/// Keychain entitlement (the Developer ID Mac app) can't make such items and keeps the old kind.
 12@MainActor
 13public enum CryptPassphrases {
 14    nonisolated static let service = "sh.krz.orgstar.crypt.v2"
 15    /// Where earlier versions kept passphrases, readable without authentication.
 16    nonisolated static let legacyService = "sh.krz.orgstar.crypt"
 17    /// Whether this build can keep passphrases limited to this device: the Developer ID Mac app
 18    /// has no Keychain entitlement and keeps them in the login keychain.
 19    public static var protectsItems: Bool {
 20        #if os(macOS) && !APPSTORE
 21        false
 22        #else
 23        true
 24        #endif
 25    }
 26
 27    /// Said beside Remember in the Keychain where `protectsItems` is false.
 28    public static var caveat: String {
 29        String(localized: "This version of orgstar keeps remembered passphrases in your login keychain without limiting them to this Mac; Touch ID or your password is still asked before one is used.")
 30    }
 31
 32    /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile.
 33    struct Request: @unchecked Sendable {
 34        let query: [String: Any]
 35    }
 36
 37    /// One authentication per file while it's open; `endSession` ends it.
 38    private static var contexts: [String: LAContext] = [:]
 39
 40    static func context(for path: String) -> LAContext {
 41        if let context = contexts[path] { return context }
 42        let context = LAContext()
 43        contexts[path] = context
 44        return context
 45    }
 46
 47    /// The file closed: its authentication no longer reads its passphrase.
 48    public static func endSession(for path: String) {
 49        contexts.removeValue(forKey: path)?.invalidate()
 50    }
 51
 52    nonisolated static func query(_ path: String, service: String = service) -> [String: Any] {
 53        var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
 54        if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
 55        return query
 56    }
 57
 58    /// The new item for `passphrase`: this device only, unlocked, after user presence.
 59    nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
 60        guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
 61        var item = query(path)
 62        item[kSecValueData as String] = Data(passphrase.utf8)
 63        item[kSecAttrAccessControl as String] = access
 64        item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
 65        return item
 66    }
 67
 68    /// Adds `item`, in place of one there already.
 69    nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus {
 70        var status = SecItemAdd(item as CFDictionary, nil)
 71        if status == errSecDuplicateItem {
 72            SecItemDelete(query as CFDictionary)
 73            status = SecItemAdd(item as CFDictionary, nil)
 74        }
 75        return status
 76    }
 77
 78    /// Remembers `passphrase` for `path`. A message to show when it wasn't kept; nil otherwise.
 79    @discardableResult
 80    public static func store(_ passphrase: String, for path: String) -> String? {
 81        guard let item = newItem(passphrase, for: path) else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
 82        let status = add(item, replacing: query(path))
 83        if status == errSecSuccess {
 84            SecItemDelete(query(path, service: legacyService) as CFDictionary)
 85            return nil
 86        }
 87        guard status == errSecMissingEntitlement else { return String(localized: "The passphrase wasn't remembered: the Keychain refused it.") }
 88        var legacy = query(path, service: legacyService)
 89        legacy[kSecValueData as String] = Data(passphrase.utf8)
 90        legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
 91        guard add(legacy, replacing: query(path, service: legacyService)) == errSecSuccess else {
 92            return String(localized: "The passphrase wasn't remembered: the Keychain refused it.")
 93        }
 94        SecItemDelete(query(path) as CFDictionary)
 95        return nil
 96    }
 97
 98    public static func forget(_ path: String) {
 99        endSession(for: path)
100        SecItemDelete(query(path) as CFDictionary)
101        SecItemDelete(query(path, service: legacyService) as CFDictionary)
102    }
103
104    /// Whether an item exists, without asking for authentication.
105    nonisolated static func exists(_ query: [String: Any]) -> Bool {
106        var q = query
107        let quiet = LAContext()
108        quiet.interactionNotAllowed = true
109        q[kSecUseAuthenticationContext as String] = quiet
110        q[kSecReturnAttributes as String] = true
111        let status = SecItemCopyMatching(q as CFDictionary, nil)
112        return status == errSecSuccess || status == errSecInteractionNotAllowed
113    }
114
115    public static func hasStored(_ path: String) -> Bool {
116        exists(query(path)) || exists(query(path, service: legacyService))
117    }
118
119    /// The stored passphrase, once the person has proved who they are; nil otherwise.
120    public static func stored(for path: String) async -> String? {
121        let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
122        let context = context(for: path)
123        if exists(query(path)) {
124            var q = query(path)
125            q[kSecReturnData as String] = true
126            context.localizedReason = reason
127            q[kSecUseAuthenticationContext as String] = context
128            let request = Request(query: q)
129            // The read waits for Touch ID or the password, off the main thread.
130            return await Task.detached { () -> String? in
131                var result: AnyObject?
132                guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
133                return String(decoding: data, as: UTF8.self)
134            }.value
135        }
136        guard exists(query(path, service: legacyService)) else { return nil }
137        guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
138        var q = query(path, service: legacyService)
139        q[kSecReturnData as String] = true
140        var result: AnyObject?
141        guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
142        let passphrase = String(decoding: data, as: UTF8.self)
143        // Moved to the protected kind of item; kept as it was where that can't be made.
144        if let item = newItem(passphrase, for: path), add(item, replacing: query(path)) == errSecSuccess {
145            SecItemDelete(query(path, service: legacyService) as CFDictionary)
146        }
147        return passphrase
148    }
149}
150
151/// The key clock history hashes encrypted headings' titles with, made once and kept in the
152/// Keychain, on this device only, without asking for authentication.
153public enum ClockTitleKey {
154    static let service = "sh.krz.orgstar.clock-title-key"
155
156    static func query(dataProtection: Bool) -> [String: Any] {
157        var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: "key"]
158        if dataProtection { query[kSecUseDataProtectionKeychain as String] = true }
159        return query
160    }
161
162    /// The key, made and kept the first time; nil when the Keychain keeps none.
163    public static func loadOrCreate() -> SymmetricKey? {
164        for dataProtection in [true, false] {
165            var q = query(dataProtection: dataProtection)
166            q[kSecReturnData as String] = true
167            var result: AnyObject?
168            if SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data, data.count == 32 { return SymmetricKey(data: data) }
169        }
170        let key = SymmetricKey(size: .bits256)
171        let data = key.withUnsafeBytes { Data($0) }
172        for dataProtection in [true, false] {
173            var item = query(dataProtection: dataProtection)
174            item[kSecValueData as String] = data
175            item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
176            item[kSecAttrLabel as String] = "orgstar: clock history key"
177            if SecItemAdd(item as CFDictionary, nil) == errSecSuccess { return key }
178        }
179        return nil
180    }
181}
182
183extension CryptHold {
184    /// Whether giving the passphrase lets the file be saved.
185    public var takesPassphrase: Bool {
186        if case .blocked = self { return false }
187        return true
188    }
189
190    /// What the held file's notice says.
191    public func notice(for path: String) -> String {
192        let name = (path as NSString).lastPathComponent
193        return switch self {
194        case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
195        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
196        case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
197        case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.")
198        }
199    }
200}
201
202extension SaveError: LocalizedError {
203    public var errorDescription: String? {
204        switch self {
205        case .fileKeepsChanging: String(localized: "The file keeps changing on disk; nothing was saved.")
206        case .otherVersionRestored: String(localized: "The file changed on disk; nothing was changed.")
207        }
208    }
209}
210
211extension CryptHold: LocalizedError {
212    public var errorDescription: String? {
213        switch self {
214        case .entries(1): String(localized: "1 tagged entry isn't encrypted")
215        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
216        case .file: String(localized: "The file has no passphrase yet")
217        case .blocked(let reason): reason
218        }
219    }
220}
221
222extension CryptReadError: LocalizedError {
223    public var errorDescription: String? {
224        switch self {
225        case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
226        case .wrongPassphrase: String(localized: "Wrong passphrase")
227        case .failed(let reason): reason
228        }
229    }
230}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form